2 * This document is a part of the source code and related artifacts for
3 * CollectionSpace, an open source collections management system for museums and
4 * related institutions:
6 * http://www.collectionspace.org http://wiki.collectionspace.org
8 * Copyright 2009 University of California at Berkeley
10 * Licensed under the Educational Community License (ECL), Version 2.0. You may
11 * not use this file except in compliance with this License.
13 * You may obtain a copy of the ECL 2.0 License at
15 * https://source.collectionspace.org/collection-space/LICENSE.txt
17 package org.collectionspace.services.nuxeo.client.java;
19 import java.io.Serializable;
20 import java.sql.Connection;
21 import java.sql.PreparedStatement;
22 import java.sql.ResultSet;
23 import java.sql.SQLException;
24 import java.sql.Statement;
25 import java.util.ArrayList;
26 import java.util.Collections;
27 import java.util.Comparator;
28 import java.util.HashSet;
29 import java.util.Hashtable;
30 import java.util.Iterator;
31 import java.util.List;
34 import java.util.UUID;
35 import javax.sql.rowset.CachedRowSet;
37 import javax.ws.rs.WebApplicationException;
38 import javax.ws.rs.core.MultivaluedMap;
40 import org.collectionspace.services.client.CollectionSpaceClient;
41 import org.collectionspace.services.client.IQueryManager;
42 import org.collectionspace.services.client.PoxPayloadIn;
43 import org.collectionspace.services.client.PoxPayloadOut;
44 import org.collectionspace.services.client.Profiler;
45 import org.collectionspace.services.client.workflow.WorkflowClient;
46 import org.collectionspace.services.common.context.ServiceContext;
47 import org.collectionspace.services.common.query.QueryContext;
48 import org.collectionspace.services.common.repository.RepositoryClient;
49 import org.collectionspace.services.common.storage.JDBCTools;
50 import org.collectionspace.services.common.storage.PreparedStatementSimpleBuilder;
51 import org.collectionspace.services.lifecycle.TransitionDef;
52 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
54 import org.collectionspace.services.common.document.BadRequestException;
55 import org.collectionspace.services.common.document.DocumentException;
56 import org.collectionspace.services.common.document.DocumentFilter;
57 import org.collectionspace.services.common.document.DocumentHandler;
58 import org.collectionspace.services.common.document.DocumentNotFoundException;
59 import org.collectionspace.services.common.document.DocumentHandler.Action;
60 import org.collectionspace.services.common.document.DocumentWrapper;
61 import org.collectionspace.services.common.document.DocumentWrapperImpl;
62 import org.collectionspace.services.common.document.TransactionException;
63 import org.collectionspace.services.config.tenant.RepositoryDomainType;
65 import org.nuxeo.common.utils.IdUtils;
66 import org.nuxeo.ecm.core.api.ClientException;
67 import org.nuxeo.ecm.core.api.DocumentModel;
68 import org.nuxeo.ecm.core.api.DocumentModelList;
69 import org.nuxeo.ecm.core.api.IterableQueryResult;
70 import org.nuxeo.ecm.core.api.VersioningOption;
71 import org.nuxeo.ecm.core.api.impl.DocumentModelListImpl;
72 import org.nuxeo.ecm.core.api.DocumentRef;
73 import org.nuxeo.ecm.core.api.IdRef;
74 import org.nuxeo.ecm.core.api.PathRef;
75 import org.nuxeo.ecm.core.api.repository.RepositoryInstance;
76 import org.nuxeo.runtime.transaction.TransactionRuntimeException;
79 // CSPACE-5036 - How to make CMISQL queries from Nuxeo
81 import org.apache.chemistry.opencmis.commons.server.CallContext;
82 import org.apache.chemistry.opencmis.server.impl.CallContextImpl;
83 import org.collectionspace.services.common.ServiceMain;
84 import org.collectionspace.services.common.api.Tools;
85 import org.collectionspace.services.common.config.ConfigUtils;
86 import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl;
87 import org.collectionspace.services.common.config.TenantBindingUtils;
88 import org.collectionspace.services.config.tenant.TenantBindingType;
89 import org.nuxeo.ecm.core.opencmis.impl.server.NuxeoCmisService;
90 import org.nuxeo.ecm.core.opencmis.impl.server.NuxeoRepository;
92 import org.slf4j.Logger;
93 import org.slf4j.LoggerFactory;
96 * RepositoryJavaClient is used to perform CRUD operations on documents in Nuxeo
97 * repository using Remote Java APIs. It uses
99 * @see DocumentHandler as IOHandler with the client.
101 * $LastChangedRevision: $ $LastChangedDate: $
103 public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn, PoxPayloadOut> {
108 private final Logger logger = LoggerFactory.getLogger(RepositoryJavaClientImpl.class);
109 // private final Logger profilerLogger = LoggerFactory.getLogger("remperf");
110 // private String foo = Profiler.createLogger();
111 public static final String NUXEO_CORE_TYPE_DOMAIN = "Domain";
112 public static final String NUXEO_CORE_TYPE_WORKSPACEROOT = "WorkspaceRoot";
115 * Instantiates a new repository java client impl.
117 public RepositoryJavaClientImpl() {
121 public void assertWorkflowState(ServiceContext ctx,
122 DocumentModel docModel) throws DocumentNotFoundException, ClientException {
123 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
124 if (queryParams != null) {
126 // Look for the workflow "delete" query param and see if we need to assert that the
127 // docModel is in a non-deleted workflow state.
129 String currentState = docModel.getCurrentLifeCycleState();
130 String includeDeletedStr = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_NONDELETED);
131 boolean includeDeleted = includeDeletedStr == null ? true : Boolean.parseBoolean(includeDeletedStr);
132 if (includeDeleted == false) {
134 // We don't wanted soft-deleted object, so throw an exception if this one is soft-deleted.
136 if (currentState.equalsIgnoreCase(WorkflowClient.WORKFLOWSTATE_DELETED)) {
137 String msg = "The GET assertion that docModel not be in 'deleted' workflow state failed.";
139 throw new DocumentNotFoundException(msg);
146 * create document in the Nuxeo repository
148 * @param ctx service context under which this method is invoked
149 * @param handler should be used by the caller to provide and transform the
151 * @return id in repository of the newly created document
152 * @throws BadRequestException
153 * @throws TransactionException
154 * @throws DocumentException
157 public String create(ServiceContext ctx,
158 DocumentHandler handler) throws BadRequestException,
159 TransactionException, DocumentException {
161 String docType = NuxeoUtils.getTenantQualifiedDocType(ctx); //ctx.getDocumentType();
162 if (docType == null) {
163 throw new IllegalArgumentException(
164 "RepositoryJavaClient.create: docType is missing");
167 if (handler == null) {
168 throw new IllegalArgumentException(
169 "RepositoryJavaClient.create: handler is missing");
171 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
172 if (nuxeoWspaceId == null) {
173 throw new DocumentNotFoundException(
174 "Unable to find workspace for service " + ctx.getServiceName()
175 + " check if the workspace exists in the Nuxeo repository");
178 RepositoryInstance repoSession = null;
180 handler.prepare(Action.CREATE);
181 repoSession = getRepositorySession(ctx);
182 DocumentRef nuxeoWspace = new IdRef(nuxeoWspaceId);
183 DocumentModel wspaceDoc = repoSession.getDocument(nuxeoWspace);
184 String wspacePath = wspaceDoc.getPathAsString();
185 //give our own ID so PathRef could be constructed later on
186 String id = IdUtils.generateId(UUID.randomUUID().toString());
187 // create document model
188 DocumentModel doc = repoSession.createDocumentModel(wspacePath, id, docType);
189 /* Check for a versioned document, and check In and Out before we proceed.
190 * This does not work as we do not have the uid schema on our docs.
191 if(((DocumentModelHandler) handler).supportsVersioning()) {
192 doc.setProperty("uid","major_version",1);
193 doc.setProperty("uid","minor_version",0);
196 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
197 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
198 handler.handle(Action.CREATE, wrapDoc);
199 // create document with documentmodel
200 doc = repoSession.createDocument(doc);
202 // TODO for sub-docs need to call into the handler to let it deal with subitems. Pass in the id,
203 // and assume the handler has the state it needs (doc fragments).
204 handler.complete(Action.CREATE, wrapDoc);
206 } catch (BadRequestException bre) {
208 } catch (Exception e) {
209 logger.error("Caught exception ", e);
210 throw new DocumentException(e);
212 if (repoSession != null) {
213 releaseRepositorySession(ctx, repoSession);
220 * get document from the Nuxeo repository
222 * @param ctx service context under which this method is invoked
223 * @param id of the document to retrieve
224 * @param handler should be used by the caller to provide and transform the
226 * @throws DocumentNotFoundException if the document cannot be found in the
228 * @throws TransactionException
229 * @throws DocumentException
232 public void get(ServiceContext ctx, String id, DocumentHandler handler)
233 throws DocumentNotFoundException, TransactionException, DocumentException {
235 if (handler == null) {
236 throw new IllegalArgumentException(
237 "RepositoryJavaClient.get: handler is missing");
240 RepositoryInstance repoSession = null;
242 handler.prepare(Action.GET);
243 repoSession = getRepositorySession(ctx);
244 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
245 DocumentModel docModel = null;
247 docModel = repoSession.getDocument(docRef);
248 assertWorkflowState(ctx, docModel);
249 } catch (ClientException ce) {
250 String msg = logException(ce, "Could not find document with CSID=" + id);
251 throw new DocumentNotFoundException(msg, ce);
254 // Set repository session to handle the document
256 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
257 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(docModel);
258 handler.handle(Action.GET, wrapDoc);
259 handler.complete(Action.GET, wrapDoc);
260 } catch (IllegalArgumentException iae) {
262 } catch (DocumentException de) {
264 } catch (Exception e) {
265 if (logger.isDebugEnabled()) {
266 logger.debug("Caught exception ", e);
268 throw new DocumentException(e);
270 if (repoSession != null) {
271 releaseRepositorySession(ctx, repoSession);
277 * get a document from the Nuxeo repository, using the docFilter params.
279 * @param ctx service context under which this method is invoked
280 * @param handler should be used by the caller to provide and transform the
281 * document. Handler must have a docFilter set to return a single item.
282 * @throws DocumentNotFoundException if the document cannot be found in the
284 * @throws TransactionException
285 * @throws DocumentException
288 public void get(ServiceContext ctx, DocumentHandler handler)
289 throws DocumentNotFoundException, TransactionException, DocumentException {
290 QueryContext queryContext = new QueryContext(ctx, handler);
291 RepositoryInstance repoSession = null;
294 handler.prepare(Action.GET);
295 repoSession = getRepositorySession(ctx);
297 DocumentModelList docList = null;
298 // force limit to 1, and ignore totalSize
299 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
300 docList = repoSession.query(query, null, 1, 0, false);
301 if (docList.size() != 1) {
302 throw new DocumentNotFoundException("No document found matching filter params: " + query);
304 DocumentModel doc = docList.get(0);
306 if (logger.isDebugEnabled()) {
307 logger.debug("Executed NXQL query: " + query);
310 //set reposession to handle the document
311 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
312 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
313 handler.handle(Action.GET, wrapDoc);
314 handler.complete(Action.GET, wrapDoc);
315 } catch (IllegalArgumentException iae) {
317 } catch (DocumentException de) {
319 } catch (Exception e) {
320 if (logger.isDebugEnabled()) {
321 logger.debug("Caught exception ", e);
323 throw new DocumentException(e);
325 if (repoSession != null) {
326 releaseRepositorySession(ctx, repoSession);
331 public DocumentWrapper<DocumentModel> getDoc(
332 RepositoryInstance repoSession,
333 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
334 String csid) throws DocumentNotFoundException, DocumentException {
335 DocumentWrapper<DocumentModel> wrapDoc = null;
338 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
339 DocumentModel doc = null;
341 doc = repoSession.getDocument(docRef);
342 } catch (ClientException ce) {
343 String msg = logException(ce, "Could not find document with CSID=" + csid);
344 throw new DocumentNotFoundException(msg, ce);
346 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
347 } catch (IllegalArgumentException iae) {
349 } catch (DocumentException de) {
357 * Get wrapped documentModel from the Nuxeo repository. The search is
358 * restricted to the workspace of the current context.
360 * @param ctx service context under which this method is invoked
361 * @param csid of the document to retrieve
362 * @throws DocumentNotFoundException
363 * @throws TransactionException
364 * @throws DocumentException
365 * @return a wrapped documentModel
368 public DocumentWrapper<DocumentModel> getDoc(
369 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
370 String csid) throws DocumentNotFoundException, TransactionException, DocumentException {
371 RepositoryInstance repoSession = null;
372 DocumentWrapper<DocumentModel> wrapDoc = null;
375 // Open a new repository session
376 repoSession = getRepositorySession(ctx);
377 wrapDoc = getDoc(repoSession, ctx, csid);
378 } catch (IllegalArgumentException iae) {
380 } catch (DocumentException de) {
382 } catch (Exception e) {
383 if (logger.isDebugEnabled()) {
384 logger.debug("Caught exception ", e);
386 throw new DocumentException(e);
388 if (repoSession != null) {
389 releaseRepositorySession(ctx, repoSession);
393 if (logger.isWarnEnabled() == true) {
394 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
399 public DocumentWrapper<DocumentModel> findDoc(
400 RepositoryInstance repoSession,
401 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
403 throws DocumentNotFoundException, DocumentException {
404 DocumentWrapper<DocumentModel> wrapDoc = null;
407 QueryContext queryContext = new QueryContext(ctx, whereClause);
408 DocumentModelList docList = null;
409 // force limit to 1, and ignore totalSize
410 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
411 docList = repoSession.query(query,
416 if (docList.size() != 1) {
417 if (logger.isDebugEnabled()) {
418 logger.debug("findDoc: Query found: " + docList.size() + " items.");
419 logger.debug(" Query: " + query);
421 throw new DocumentNotFoundException("No document found matching filter params: " + query);
423 DocumentModel doc = docList.get(0);
424 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
425 } catch (IllegalArgumentException iae) {
427 } catch (DocumentException de) {
429 } catch (Exception e) {
430 if (logger.isDebugEnabled()) {
431 logger.debug("Caught exception ", e);
433 throw new DocumentException(e);
440 * find wrapped documentModel from the Nuxeo repository
442 * @param ctx service context under which this method is invoked
443 * @param whereClause where NXQL where clause to get the document
444 * @throws DocumentNotFoundException
445 * @throws TransactionException
446 * @throws DocumentException
447 * @return a wrapped documentModel retrieved by the repository query
450 public DocumentWrapper<DocumentModel> findDoc(
451 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
453 throws DocumentNotFoundException, TransactionException, DocumentException {
454 RepositoryInstance repoSession = null;
455 DocumentWrapper<DocumentModel> wrapDoc = null;
458 repoSession = getRepositorySession(ctx);
459 wrapDoc = findDoc(repoSession, ctx, whereClause);
460 } catch (Exception e) {
461 throw new DocumentException("Unable to create a Nuxeo repository session.", e);
463 if (repoSession != null) {
464 releaseRepositorySession(ctx, repoSession);
468 if (logger.isWarnEnabled() == true) {
469 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
476 * find doc and return CSID from the Nuxeo repository
479 * @param ctx service context under which this method is invoked
480 * @param whereClause where NXQL where clause to get the document
481 * @throws DocumentNotFoundException
482 * @throws TransactionException
483 * @throws DocumentException
484 * @return the CollectionSpace ID (CSID) of the requested document
487 public String findDocCSID(RepositoryInstance repoSession,
488 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String whereClause)
489 throws DocumentNotFoundException, TransactionException, DocumentException {
491 boolean releaseSession = false;
493 if (repoSession == null) {
494 repoSession = this.getRepositorySession(ctx);
495 releaseSession = true;
497 DocumentWrapper<DocumentModel> wrapDoc = findDoc(repoSession, ctx, whereClause);
498 DocumentModel docModel = wrapDoc.getWrappedObject();
499 csid = NuxeoUtils.getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
500 } catch (DocumentNotFoundException dnfe) {
502 } catch (IllegalArgumentException iae) {
504 } catch (DocumentException de) {
506 } catch (Exception e) {
507 if (logger.isDebugEnabled()) {
508 logger.debug("Caught exception ", e);
510 throw new DocumentException(e);
512 if (releaseSession && (repoSession != null)) {
513 this.releaseRepositorySession(ctx, repoSession);
519 public DocumentWrapper<DocumentModelList> findDocs(
520 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
521 RepositoryInstance repoSession,
522 List<String> docTypes,
524 String orderByClause,
527 boolean computeTotal)
528 throws DocumentNotFoundException, DocumentException {
529 DocumentWrapper<DocumentModelList> wrapDoc = null;
532 if (docTypes == null || docTypes.size() < 1) {
533 throw new DocumentNotFoundException(
534 "The findDocs() method must specify at least one DocumentType.");
536 DocumentModelList docList = null;
537 QueryContext queryContext = new QueryContext(ctx, whereClause, orderByClause);
538 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
539 if (logger.isDebugEnabled()) {
540 logger.debug("findDocs() NXQL: " + query);
542 docList = repoSession.query(query, null, pageSize, pageSize * pageNum, computeTotal);
543 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
544 } catch (IllegalArgumentException iae) {
546 } catch (Exception e) {
547 if (logger.isDebugEnabled()) {
548 logger.debug("Caught exception ", e);
550 throw new DocumentException(e);
556 protected static String buildInListForDocTypes(List<String> docTypes) {
557 StringBuilder sb = new StringBuilder();
559 boolean first = true;
560 for (String docType : docTypes) {
571 return sb.toString();
574 public DocumentWrapper<DocumentModelList> findDocs(
575 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
576 DocumentHandler handler,
577 RepositoryInstance repoSession,
578 List<String> docTypes)
579 throws DocumentNotFoundException, DocumentException {
580 DocumentWrapper<DocumentModelList> wrapDoc = null;
582 DocumentFilter filter = handler.getDocumentFilter();
583 String oldOrderBy = filter.getOrderByClause();
584 if (isClauseEmpty(oldOrderBy) == true) {
585 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
587 QueryContext queryContext = new QueryContext(ctx, handler);
590 if (docTypes == null || docTypes.size() < 1) {
591 throw new DocumentNotFoundException(
592 "The findDocs() method must specify at least one DocumentType.");
594 DocumentModelList docList = null;
595 if (handler.isCMISQuery() == true) {
596 String inList = buildInListForDocTypes(docTypes);
597 ctx.getQueryParams().add(IQueryManager.SEARCH_RELATED_MATCH_OBJ_DOCTYPES, inList);
598 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
600 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
601 if (logger.isDebugEnabled()) {
602 logger.debug("findDocs() NXQL: " + query);
604 docList = repoSession.query(query, null, filter.getPageSize(), filter.getOffset(), true);
606 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
607 } catch (IllegalArgumentException iae) {
609 } catch (Exception e) {
610 if (logger.isDebugEnabled()) {
611 logger.debug("Caught exception ", e);
613 throw new DocumentException(e);
620 * Find a list of documentModels from the Nuxeo repository
622 * @param docTypes a list of DocType names to match
623 * @param whereClause where the clause to qualify on
624 * @throws DocumentNotFoundException
625 * @throws TransactionException
626 * @throws DocumentException
627 * @return a list of documentModels
630 public DocumentWrapper<DocumentModelList> findDocs(
631 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
632 List<String> docTypes,
634 int pageSize, int pageNum, boolean computeTotal)
635 throws DocumentNotFoundException, TransactionException, DocumentException {
636 RepositoryInstance repoSession = null;
637 DocumentWrapper<DocumentModelList> wrapDoc = null;
640 repoSession = getRepositorySession(ctx);
641 wrapDoc = findDocs(ctx, repoSession, docTypes, whereClause, null,
642 pageSize, pageNum, computeTotal);
643 } catch (IllegalArgumentException iae) {
645 } catch (Exception e) {
646 if (logger.isDebugEnabled()) {
647 logger.debug("Caught exception ", e);
649 throw new DocumentException(e);
651 if (repoSession != null) {
652 releaseRepositorySession(ctx, repoSession);
656 if (logger.isWarnEnabled() == true) {
657 logger.warn("Returned DocumentModelList instance was created with a repository session that is now closed.");
664 * @see org.collectionspace.services.common.storage.StorageClient#get(org.collectionspace.services.common.context.ServiceContext, java.util.List, org.collectionspace.services.common.document.DocumentHandler)
667 public void get(ServiceContext ctx, List<String> csidList, DocumentHandler handler)
668 throws DocumentNotFoundException, TransactionException, DocumentException {
669 if (handler == null) {
670 throw new IllegalArgumentException(
671 "RepositoryJavaClient.getAll: handler is missing");
674 RepositoryInstance repoSession = null;
676 handler.prepare(Action.GET_ALL);
677 repoSession = getRepositorySession(ctx);
678 DocumentModelList docModelList = new DocumentModelListImpl();
679 //FIXME: Should be using NuxeoUtils.createPathRef for security reasons
680 for (String csid : csidList) {
681 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
682 DocumentModel docModel = repoSession.getDocument(docRef);
683 docModelList.add(docModel);
686 //set reposession to handle the document
687 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
688 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docModelList);
689 handler.handle(Action.GET_ALL, wrapDoc);
690 handler.complete(Action.GET_ALL, wrapDoc);
691 } catch (DocumentException de) {
693 } catch (Exception e) {
694 if (logger.isDebugEnabled()) {
695 logger.debug("Caught exception ", e);
697 throw new DocumentException(e);
699 if (repoSession != null) {
700 releaseRepositorySession(ctx, repoSession);
706 * getAll get all documents for an entity entity service from the Nuxeo
709 * @param ctx service context under which this method is invoked
710 * @param handler should be used by the caller to provide and transform the
712 * @throws DocumentNotFoundException
713 * @throws TransactionException
714 * @throws DocumentException
717 public void getAll(ServiceContext ctx, DocumentHandler handler)
718 throws DocumentNotFoundException, TransactionException, DocumentException {
719 if (handler == null) {
720 throw new IllegalArgumentException(
721 "RepositoryJavaClient.getAll: handler is missing");
723 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
724 if (nuxeoWspaceId == null) {
725 throw new DocumentNotFoundException(
726 "Unable to find workspace for service "
727 + ctx.getServiceName()
728 + " check if the workspace exists in the Nuxeo repository.");
731 RepositoryInstance repoSession = null;
733 handler.prepare(Action.GET_ALL);
734 repoSession = getRepositorySession(ctx);
735 DocumentRef wsDocRef = new IdRef(nuxeoWspaceId);
736 DocumentModelList docList = repoSession.getChildren(wsDocRef);
737 //set reposession to handle the document
738 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
739 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
740 handler.handle(Action.GET_ALL, wrapDoc);
741 handler.complete(Action.GET_ALL, wrapDoc);
742 } catch (DocumentException de) {
744 } catch (Exception e) {
745 if (logger.isDebugEnabled()) {
746 logger.debug("Caught exception ", e);
748 throw new DocumentException(e);
750 if (repoSession != null) {
751 releaseRepositorySession(ctx, repoSession);
756 private boolean isClauseEmpty(String theString) {
757 boolean result = true;
758 if (theString != null && !theString.isEmpty()) {
764 public DocumentWrapper<DocumentModel> getDocFromCsid(
765 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
766 RepositoryInstance repoSession,
769 DocumentWrapper<DocumentModel> result = null;
771 result = new DocumentWrapperImpl(NuxeoUtils.getDocFromCsid(ctx, repoSession, csid));
777 * A method to find a CollectionSpace document (of any type) given just a service context and
778 * its CSID. A search across *all* service workspaces (within a given tenant context) is performed to find
781 * This query searches Nuxeo's Hierarchy table where our CSIDs are stored in the "name" column.
784 public DocumentWrapper<DocumentModel> getDocFromCsid(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
787 DocumentWrapper<DocumentModel> result = null;
788 RepositoryInstance repoSession = null;
790 repoSession = getRepositorySession(ctx);
791 result = getDocFromCsid(ctx, repoSession, csid);
793 if (repoSession != null) {
794 releaseRepositorySession(ctx, repoSession);
798 if (logger.isWarnEnabled() == true) {
799 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
806 * Returns a URI value for a document in the Nuxeo repository
808 * @param wrappedDoc a wrapped documentModel
809 * @throws ClientException
810 * @return a document URI
813 public String getDocURI(DocumentWrapper<DocumentModel> wrappedDoc) throws ClientException {
814 DocumentModel docModel = wrappedDoc.getWrappedObject();
815 String uri = (String) docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
816 CollectionSpaceClient.COLLECTIONSPACE_CORE_URI);
821 * See CSPACE-5036 - How to make CMISQL queries from Nuxeo
823 private IterableQueryResult makeCMISQLQuery(RepositoryInstance repoSession, String query, QueryContext queryContext) {
824 IterableQueryResult result = null;
826 // the NuxeoRepository should be constructed only once, then cached
827 // (its construction is expensive)
829 NuxeoRepository repo = new NuxeoRepository(
830 repoSession.getRepositoryName(), repoSession
831 .getRootDocument().getId());
832 logger.debug("Repository ID:" + repo.getId() + " Root folder:"
833 + repo.getRootFolderId());
835 CallContextImpl callContext = new CallContextImpl(
836 CallContext.BINDING_LOCAL, repo.getId(), false);
837 callContext.put(CallContext.USERNAME, repoSession.getPrincipal()
839 NuxeoCmisService cmisService = new NuxeoCmisService(repo,
840 callContext, repoSession);
842 result = repoSession.queryAndFetch(query, "CMISQL", cmisService);
843 } catch (ClientException e) {
844 // TODO Auto-generated catch block
845 logger.error("Encounter trouble making the following CMIS query: " + query, e);
852 * getFiltered get all documents for an entity service from the Document
853 * repository, given filter parameters specified by the handler.
855 * @param ctx service context under which this method is invoked
856 * @param handler should be used by the caller to provide and transform the
858 * @throws DocumentNotFoundException if workspace not found
859 * @throws TransactionException
860 * @throws DocumentException
863 public void getFiltered(ServiceContext ctx, DocumentHandler handler)
864 throws DocumentNotFoundException, TransactionException, DocumentException {
866 DocumentFilter filter = handler.getDocumentFilter();
867 String oldOrderBy = filter.getOrderByClause();
868 if (isClauseEmpty(oldOrderBy) == true) {
869 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
871 QueryContext queryContext = new QueryContext(ctx, handler);
873 RepositoryInstance repoSession = null;
875 handler.prepare(Action.GET_ALL);
876 repoSession = getRepositorySession(ctx); //Keeps a refcount here for the repository session so you need to release this when finished
878 DocumentModelList docList = null;
879 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
881 if (logger.isDebugEnabled()) {
882 logger.debug("Executing NXQL query: " + query.toString());
885 // If we have limit and/or offset, then pass true to get totalSize
886 // in returned DocumentModelList.
887 Profiler profiler = new Profiler(this, 2);
888 profiler.log("Executing NXQL query: " + query.toString());
890 if (handler.isJDBCQuery() == true) {
891 docList = getFilteredJDBC(repoSession, ctx, handler, queryContext);
892 } else if (handler.isCMISQuery() == true) {
893 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext); //FIXME: REM - Need to deal with paging info in CMIS query
894 } else if ((queryContext.getDocFilter().getOffset() > 0) || (queryContext.getDocFilter().getPageSize() > 0)) {
895 docList = repoSession.query(query, null,
896 queryContext.getDocFilter().getPageSize(), queryContext.getDocFilter().getOffset(), true);
898 docList = repoSession.query(query);
902 //set repoSession to handle the document
903 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
904 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
905 handler.handle(Action.GET_ALL, wrapDoc);
906 handler.complete(Action.GET_ALL, wrapDoc);
907 } catch (DocumentException de) {
909 } catch (Exception e) {
910 if (logger.isDebugEnabled()) {
911 logger.debug("Caught exception ", e);
913 throw new DocumentException(e);
915 if (repoSession != null) {
916 releaseRepositorySession(ctx, repoSession);
921 private DocumentModelList getFilteredJDBC(RepositoryInstance repoSession, ServiceContext ctx,
922 DocumentHandler handler, QueryContext queryContext) throws Exception {
923 DocumentModelList result = new DocumentModelListImpl();
925 // FIXME: Get all of the following values from appropriate external constants.
927 // At present, the two constants below are duplicated in both RepositoryJavaClientImpl
928 // and in AuthorityItemDocumentModelHandler.
929 final String TERM_GROUP_LIST_NAME = "TERM_GROUP_LIST_NAME";
930 final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
931 final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
932 // Get this from a constant in AuthorityResource or equivalent
933 final String PARENT_WILDCARD = "_ALL_";
935 // Start with the default query
936 String selectStatement =
937 "SELECT DISTINCT hierarchy_termgroup.parentid as id"
938 + " FROM " + handler.getJDBCQueryParams().get(TERM_GROUP_TABLE_NAME_PARAM) + " termgroup";
941 " INNER JOIN hierarchy hierarchy_termgroup"
942 + " ON hierarchy_termgroup.id = termgroup.id";
945 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
946 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
947 // If the value of the partial term query parameter is blank ('pt='),
948 // return all records, subject to restriction by any limit clause
949 if (Tools.isBlank(partialTerm)) {
952 // Otherwise, return records that match the supplied partial term
954 " WHERE (termgroup.termdisplayname ILIKE ?)";
957 // At present, results are ordered in code, below, rather than in SQL,
958 // and the orderByClause below is thus intentionally blank.
960 // To implement the orderByClause below in SQL; e.g. via
961 // 'ORDER BY termgroup.termdisplayname', the relevant column
962 // must be returned by the SELECT statement.
963 String orderByClause = "";
966 TenantBindingConfigReaderImpl tReader =
967 ServiceMain.getInstance().getTenantBindingConfigReader();
968 TenantBindingType tenantBinding = tReader.getTenantBinding(ctx.getTenantId());
969 String maxListItemsLimit = TenantBindingUtils.getPropertyValue(tenantBinding,
970 IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES);
972 " LIMIT " + getMaxItemsLimitOnJdbcQueries(maxListItemsLimit); // implicit int-to-String conversion
974 List<String> params = new ArrayList<>();
976 // Read tenant bindings configuration to determine whether
977 // to automatically insert leading, as well as trailing, wildcards
978 // into the term matching string.
979 String usesStartingWildcard = TenantBindingUtils.getPropertyValue(tenantBinding,
980 IQueryManager.TENANT_USES_STARTING_WILDCARD_FOR_PARTIAL_TERM);
981 // Handle user-provided leading wildcard characters, in the
982 // configuration where a leading wildcard is not automatically inserted.
983 // (The user-provided wildcard must be in the first, or "starting"
984 // character position in the partial term value.)
985 if (Tools.notBlank(usesStartingWildcard) && usesStartingWildcard.equalsIgnoreCase(Boolean.FALSE.toString())) {
986 partialTerm = handleProvidedStartingWildcard(partialTerm);
987 // Otherwise, automatically insert a leading wildcard
989 partialTerm = JDBCTools.SQL_WILDCARD + partialTerm;
991 // Automatically insert a trailing wildcard
992 params.add(partialTerm + JDBCTools.SQL_WILDCARD); // Value for replaceable parameter 1 in the query
994 // Restrict the query to filter out deleted records, if requested
995 String includeDeleted = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_NONDELETED);
996 if (includeDeleted != null && includeDeleted.equalsIgnoreCase(Boolean.FALSE.toString())) {
997 joinClauses = joinClauses
999 + " ON misc.id = hierarchy_termgroup.parentid";
1000 whereClause = whereClause
1001 + " AND (misc.lifecyclestate <> '" + WorkflowClient.WORKFLOWSTATE_DELETED + "')";
1004 // If a particular authority is specified, restrict the query further
1005 // to return only records within that authority
1006 String inAuthorityValue = (String) handler.getJDBCQueryParams().get(IN_AUTHORITY_PARAM);
1007 if (Tools.notBlank(inAuthorityValue)) {
1008 // Handle the '_ALL_' case for inAuthority
1009 if (inAuthorityValue.equals(PARENT_WILDCARD)) {
1010 // Add nothing to the query here if it should match within all authorities
1012 joinClauses = joinClauses
1013 + " INNER JOIN " + handler.getServiceContext().getCommonPartLabel() + " commonschema"
1014 + " ON commonschema.id = hierarchy_termgroup.parentid";
1015 whereClause = whereClause
1016 + " AND (commonschema.inauthority = ?)";
1017 params.add(inAuthorityValue); // Value for replaceable parameter 2 in the query
1021 // Restrict the query further to return only records pertaining to
1022 // the current tenant, unless:
1023 // * Data for this service, in this tenant, is stored in its own,
1024 // separate repository, rather than being intermingled with other
1025 // tenants' data in the default repository; or
1026 // * Restriction by tenant ID in JDBC queries has been disabled,
1027 // via configuration for this tenant,
1028 if (restrictJDBCQueryByTenantID(tenantBinding, ctx)) {
1029 joinClauses = joinClauses
1030 + " INNER JOIN collectionspace_core core"
1031 + " ON core.id = hierarchy_termgroup.parentid";
1032 whereClause = whereClause
1033 + " AND (core.tenantid = ?)";
1034 params.add(ctx.getTenantId()); // Value for replaceable parameter 3 in the query
1037 // Piece together the SQL query from its parts
1038 String sql = selectStatement + joinClauses + whereClause + orderByClause + limitClause;
1040 // Note: PostgreSQL 9.2 introduced a change that may improve performance
1041 // of certain queries using JDBC PreparedStatements. See comments on
1042 // CSPACE-5943 for details.
1043 PreparedStatementSimpleBuilder jdbcFilterQueryBuilder = new PreparedStatementSimpleBuilder(sql, params);
1044 String dataSourceName = JDBCTools.NUXEO_DATASOURCE_NAME;
1045 String repositoryName = ctx.getRepositoryName();
1046 Set<String> docIds = new HashSet<>();
1047 try (CachedRowSet crs = JDBCTools.executePreparedQuery(jdbcFilterQueryBuilder,
1048 dataSourceName, repositoryName, sql)) {
1050 // If the response to the query is null or contains zero rows,
1051 // return an empty list of document models
1056 if (crs.getRow() == 0) {
1057 return result; // empty list of document models
1060 // Otherwise, get the document IDs from the results of the query
1063 while (crs.next()) {
1064 id = crs.getString(1);
1065 if (Tools.notBlank(id)) {
1069 } catch (SQLException sqle) {
1070 logger.warn("Could not obtain document IDs via SQL query '" + sql + "': " + sqle.getMessage());
1071 return result; // return an empty list of document models
1074 // Get a list of document models, using the IDs obtained from the query
1075 DocumentModel docModel;
1076 for (String docId : docIds) {
1077 docModel = NuxeoUtils.getDocumentModel(repoSession, docId);
1078 if (docModel == null) {
1079 logger.warn("Could not obtain document model for document with ID " + docId);
1081 result.add(NuxeoUtils.getDocumentModel(repoSession, docId));
1085 // Order the results
1086 final String COMMON_PART_SCHEMA = handler.getServiceContext().getCommonPartLabel();
1087 final String DISPLAY_NAME_XPATH =
1088 "//" + handler.getJDBCQueryParams().get(TERM_GROUP_LIST_NAME) + "/[0]/termDisplayName";
1089 Collections.sort(result, new Comparator<DocumentModel>() {
1091 public int compare(DocumentModel doc1, DocumentModel doc2) {
1092 String termDisplayName1 = (String) NuxeoUtils.getXPathValue(doc1, COMMON_PART_SCHEMA, DISPLAY_NAME_XPATH);
1093 String termDisplayName2 = (String) NuxeoUtils.getXPathValue(doc2, COMMON_PART_SCHEMA, DISPLAY_NAME_XPATH);
1094 return termDisplayName1.compareTo(termDisplayName2);
1102 private DocumentModelList getFilteredCMIS(RepositoryInstance repoSession, ServiceContext ctx, DocumentHandler handler, QueryContext queryContext)
1103 throws DocumentNotFoundException, DocumentException {
1105 DocumentModelList result = new DocumentModelListImpl();
1107 String query = handler.getCMISQuery(queryContext);
1109 DocumentFilter docFilter = handler.getDocumentFilter();
1110 int pageSize = docFilter.getPageSize();
1111 int offset = docFilter.getOffset();
1112 if (logger.isDebugEnabled()) {
1113 logger.debug("Executing CMIS query: " + query.toString()
1114 + "with pageSize: " + pageSize + " at offset: " + offset);
1117 // If we have limit and/or offset, then pass true to get totalSize
1118 // in returned DocumentModelList.
1119 Profiler profiler = new Profiler(this, 2);
1120 profiler.log("Executing CMIS query: " + query.toString());
1123 IterableQueryResult queryResult = makeCMISQLQuery(repoSession, query, queryContext);
1125 int totalSize = (int) queryResult.size();
1126 ((DocumentModelListImpl) result).setTotalSize(totalSize);
1127 // Skip the rows before our offset
1129 queryResult.skipTo(offset);
1132 for (Map<String, Serializable> row : queryResult) {
1133 if (logger.isTraceEnabled()) {
1134 logger.trace(" Hierarchy Table ID is:" + row.get(IQueryManager.CMIS_TARGET_NUXEO_ID)
1135 + " nuxeo:pathSegment is: " + row.get(IQueryManager.CMIS_TARGET_NAME));
1137 String nuxeoId = (String) row.get(IQueryManager.CMIS_TARGET_NUXEO_ID);
1138 DocumentModel docModel = NuxeoUtils.getDocumentModel(repoSession, nuxeoId);
1139 result.add(docModel);
1141 if (nRows >= pageSize && pageSize != 0) { // A page size of zero means that they want all of them
1142 logger.debug("Got page full of items - quitting");
1147 queryResult.close();
1152 } catch (Exception e) {
1153 if (logger.isDebugEnabled()) {
1154 logger.debug("Caught exception ", e);
1156 throw new DocumentException(e);
1160 // Since we're not supporting paging yet for CMIS queries, we need to perform
1161 // a workaround for the paging information we return in our list of results
1164 if (result != null) {
1165 docFilter.setStartPage(0);
1166 if (totalSize > docFilter.getPageSize()) {
1167 docFilter.setPageSize(totalSize);
1168 ((DocumentModelListImpl)result).setTotalSize(totalSize);
1176 private String logException(Exception e, String msg) {
1177 String result = null;
1179 String exceptionMessage = e.getMessage();
1180 exceptionMessage = exceptionMessage != null ? exceptionMessage : "<No details provided>";
1181 result = msg = msg + ". Caught exception:" + exceptionMessage;
1183 if (logger.isTraceEnabled() == true) {
1184 logger.error(msg, e);
1193 * update given document in the Nuxeo repository
1195 * @param ctx service context under which this method is invoked
1196 * @param csid of the document
1197 * @param handler should be used by the caller to provide and transform the
1199 * @throws BadRequestException
1200 * @throws DocumentNotFoundException
1201 * @throws TransactionException if the transaction times out or otherwise
1202 * cannot be successfully completed
1203 * @throws DocumentException
1206 public void update(ServiceContext ctx, String csid, DocumentHandler handler)
1207 throws BadRequestException, DocumentNotFoundException, TransactionException,
1209 if (handler == null) {
1210 throw new IllegalArgumentException(
1211 "RepositoryJavaClient.update: document handler is missing.");
1214 RepositoryInstance repoSession = null;
1216 handler.prepare(Action.UPDATE);
1217 repoSession = getRepositorySession(ctx);
1218 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
1219 DocumentModel doc = null;
1221 doc = repoSession.getDocument(docRef);
1222 } catch (ClientException ce) {
1223 String msg = logException(ce, "Could not find document to update with CSID=" + csid);
1224 throw new DocumentNotFoundException(msg, ce);
1226 // Check for a versioned document, and check In and Out before we proceed.
1227 if (((DocumentModelHandler) handler).supportsVersioning()) {
1228 /* Once we advance to 5.5 or later, we can add this.
1229 * See also https://jira.nuxeo.com/browse/NXP-8506
1230 if(!doc.isVersionable()) {
1231 throw new DocumentException("Configuration for: "
1232 +handler.getServiceContextPath()+" supports versioning, but Nuxeo config does not!");
1235 /* Force a version number - Not working. Apparently we need to configure the uid schema??
1236 if(doc.getProperty("uid","major_version") == null) {
1237 doc.setProperty("uid","major_version",1);
1239 if(doc.getProperty("uid","minor_version") == null) {
1240 doc.setProperty("uid","minor_version",0);
1243 doc.checkIn(VersioningOption.MINOR, null);
1248 // Set reposession to handle the document
1250 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1251 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
1252 handler.handle(Action.UPDATE, wrapDoc);
1253 repoSession.saveDocument(doc);
1255 handler.complete(Action.UPDATE, wrapDoc);
1256 } catch (BadRequestException bre) {
1258 } catch (DocumentException de) {
1260 } catch (WebApplicationException wae) {
1262 } catch (Exception e) {
1263 if (logger.isDebugEnabled()) {
1264 logger.debug("Caught exception ", e);
1266 throw new DocumentException(e);
1268 if (repoSession != null) {
1269 releaseRepositorySession(ctx, repoSession);
1275 * Save a documentModel to the Nuxeo repository.
1277 * @param ctx service context under which this method is invoked
1278 * @param repoSession
1279 * @param docModel the document to save
1280 * @param fSaveSession if TRUE, will call CoreSession.save() to save
1281 * accumulated changes.
1282 * @throws ClientException
1283 * @throws DocumentException
1285 public void saveDocWithoutHandlerProcessing(
1286 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1287 RepositoryInstance repoSession,
1288 DocumentModel docModel,
1289 boolean fSaveSession)
1290 throws ClientException, DocumentException {
1293 repoSession.saveDocument(docModel);
1297 } catch (ClientException ce) {
1299 } catch (Exception e) {
1300 if (logger.isDebugEnabled()) {
1301 logger.debug("Caught exception ", e);
1303 throw new DocumentException(e);
1308 * Save a list of documentModels to the Nuxeo repository.
1310 * @param ctx service context under which this method is invoked
1311 * @param repoSession a repository session
1312 * @param docModelList a list of document models
1313 * @param fSaveSession if TRUE, will call CoreSession.save() to save
1314 * accumulated changes.
1315 * @throws ClientException
1316 * @throws DocumentException
1318 public void saveDocListWithoutHandlerProcessing(
1319 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1320 RepositoryInstance repoSession,
1321 DocumentModelList docList,
1322 boolean fSaveSession)
1323 throws ClientException, DocumentException {
1325 DocumentModel[] docModelArray = new DocumentModel[docList.size()];
1326 repoSession.saveDocuments(docList.toArray(docModelArray));
1330 } catch (ClientException ce) {
1332 } catch (Exception e) {
1333 logger.error("Caught exception ", e);
1334 throw new DocumentException(e);
1339 * delete a document from the Nuxeo repository
1341 * @param ctx service context under which this method is invoked
1342 * @param id of the document
1343 * @throws DocumentException
1346 public void delete(ServiceContext ctx, String id, DocumentHandler handler) throws DocumentNotFoundException,
1347 DocumentException, TransactionException {
1349 throw new IllegalArgumentException(
1350 "delete(ctx, ix, handler): ctx is missing");
1352 if (handler == null) {
1353 throw new IllegalArgumentException(
1354 "delete(ctx, ix, handler): handler is missing");
1356 if (logger.isDebugEnabled()) {
1357 logger.debug("Deleting document with CSID=" + id);
1359 RepositoryInstance repoSession = null;
1361 handler.prepare(Action.DELETE);
1362 repoSession = getRepositorySession(ctx);
1363 DocumentWrapper<DocumentModel> wrapDoc = null;
1365 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
1366 wrapDoc = new DocumentWrapperImpl<DocumentModel>(repoSession.getDocument(docRef));
1367 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1368 handler.handle(Action.DELETE, wrapDoc);
1369 repoSession.removeDocument(docRef);
1370 } catch (ClientException ce) {
1371 String msg = logException(ce, "Could not find document to delete with CSID=" + id);
1372 throw new DocumentNotFoundException(msg, ce);
1375 handler.complete(Action.DELETE, wrapDoc);
1376 } catch (DocumentException de) {
1378 } catch (Exception e) {
1379 if (logger.isDebugEnabled()) {
1380 logger.debug("Caught exception ", e);
1382 throw new DocumentException(e);
1384 if (repoSession != null) {
1385 releaseRepositorySession(ctx, repoSession);
1391 * @see org.collectionspace.services.common.storage.StorageClient#delete(org.collectionspace.services.common.context.ServiceContext, java.lang.String, org.collectionspace.services.common.document.DocumentHandler)
1395 public void delete(@SuppressWarnings("rawtypes") ServiceContext ctx, String id)
1396 throws DocumentNotFoundException, DocumentException {
1397 throw new UnsupportedOperationException();
1398 // Use the other delete instead
1402 public Hashtable<String, String> retrieveWorkspaceIds(RepositoryDomainType repoDomain) throws Exception {
1403 return NuxeoConnectorEmbedded.getInstance().retrieveWorkspaceIds(repoDomain);
1407 public String createDomain(RepositoryDomainType repositoryDomain) throws Exception {
1408 RepositoryInstance repoSession = null;
1409 String domainId = null;
1412 // Open a connection to the domain's repo/db
1414 String repoName = repositoryDomain.getRepositoryName();
1415 repoSession = getRepositorySession(repoName); // domainName=storageName=repoName=databaseName
1417 // First create the top-level domain directory
1419 String domainName = repositoryDomain.getStorageName();
1420 DocumentRef parentDocRef = new PathRef("/");
1421 DocumentModel parentDoc = repoSession.getDocument(parentDocRef);
1422 DocumentModel domainDoc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1423 domainName, NUXEO_CORE_TYPE_DOMAIN);
1424 domainDoc.setPropertyValue("dc:title", domainName);
1425 domainDoc.setPropertyValue("dc:description", "A CollectionSpace domain "
1427 domainDoc = repoSession.createDocument(domainDoc);
1428 domainId = domainDoc.getId();
1431 // Next, create a "Workspaces" root directory to contain the workspace folders for the individual service documents
1433 DocumentModel workspacesRoot = repoSession.createDocumentModel(domainDoc.getPathAsString(),
1434 NuxeoUtils.Workspaces, NUXEO_CORE_TYPE_WORKSPACEROOT);
1435 workspacesRoot.setPropertyValue("dc:title", NuxeoUtils.Workspaces);
1436 workspacesRoot.setPropertyValue("dc:description", "A CollectionSpace workspaces directory for "
1437 + domainDoc.getPathAsString());
1438 workspacesRoot = repoSession.createDocument(workspacesRoot);
1439 String workspacesRootId = workspacesRoot.getId();
1442 if (logger.isDebugEnabled()) {
1443 logger.debug("Created tenant domain name=" + domainName
1444 + " id=" + domainId + " "
1445 + NuxeoUtils.Workspaces + " id=" + workspacesRootId);
1446 logger.debug("Path to Domain: " + domainDoc.getPathAsString());
1447 logger.debug("Path to Workspaces root: " + workspacesRoot.getPathAsString());
1449 } catch (Exception e) {
1450 if (logger.isDebugEnabled()) {
1451 logger.debug("Could not create tenant domain name=" + repositoryDomain.getStorageName() + " caught exception ", e);
1455 if (repoSession != null) {
1456 releaseRepositorySession(null, repoSession);
1464 public String getDomainId(RepositoryDomainType repositoryDomain) throws Exception {
1465 String domainId = null;
1466 RepositoryInstance repoSession = null;
1468 String repoName = repositoryDomain.getRepositoryName();
1469 String domainStorageName = repositoryDomain.getStorageName();
1470 if (domainStorageName != null && !domainStorageName.isEmpty()) {
1472 repoSession = getRepositorySession(repoName);
1473 DocumentRef docRef = new PathRef("/" + domainStorageName);
1474 DocumentModel domain = repoSession.getDocument(docRef);
1475 domainId = domain.getId();
1476 } catch (Exception e) {
1477 if (logger.isTraceEnabled()) {
1478 logger.trace("Caught exception ", e); // The document doesn't exist, this let's us know we need to create it
1480 //there is no way to identify if document does not exist due to
1481 //lack of typed exception for getDocument method
1484 if (repoSession != null) {
1485 releaseRepositorySession(null, repoSession);
1494 * Returns the workspaces root directory for a given domain.
1496 private DocumentModel getWorkspacesRoot(RepositoryInstance repoSession,
1497 String domainName) throws Exception {
1498 DocumentModel result = null;
1500 String domainPath = "/" + domainName;
1501 DocumentRef parentDocRef = new PathRef(domainPath);
1502 DocumentModelList domainChildrenList = repoSession.getChildren(
1504 Iterator<DocumentModel> witer = domainChildrenList.iterator();
1505 while (witer.hasNext()) {
1506 DocumentModel childNode = witer.next();
1507 if (NuxeoUtils.Workspaces.equalsIgnoreCase(childNode.getName())) {
1509 logger.trace("Found workspaces directory at: " + result.getPathAsString());
1514 if (result == null) {
1515 throw new ClientException("Could not find workspace root directory in: "
1523 * @see org.collectionspace.services.common.repository.RepositoryClient#createWorkspace(java.lang.String, java.lang.String)
1526 public String createWorkspace(RepositoryDomainType repositoryDomain, String workspaceName) throws Exception {
1527 RepositoryInstance repoSession = null;
1528 String workspaceId = null;
1530 String repoName = repositoryDomain.getRepositoryName();
1531 repoSession = getRepositorySession(repoName);
1533 String domainStorageName = repositoryDomain.getStorageName();
1534 DocumentModel parentDoc = getWorkspacesRoot(repoSession, domainStorageName);
1535 if (logger.isTraceEnabled()) {
1536 for (String facet : parentDoc.getFacets()) {
1537 logger.trace("Facet: " + facet);
1541 DocumentModel doc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1542 workspaceName, NuxeoUtils.WORKSPACE_DOCUMENT_TYPE);
1543 doc.setPropertyValue("dc:title", workspaceName);
1544 doc.setPropertyValue("dc:description", "A CollectionSpace workspace for "
1546 doc = repoSession.createDocument(doc);
1547 workspaceId = doc.getId();
1549 if (logger.isDebugEnabled()) {
1550 logger.debug("Created workspace name=" + workspaceName
1551 + " id=" + workspaceId);
1553 } catch (Exception e) {
1554 if (logger.isDebugEnabled()) {
1555 logger.debug("createWorkspace caught exception ", e);
1559 if (repoSession != null) {
1560 releaseRepositorySession(null, repoSession);
1567 * @see org.collectionspace.services.common.repository.RepositoryClient#getWorkspaceId(java.lang.String, java.lang.String)
1571 public String getWorkspaceId(String tenantDomain, String workspaceName) throws Exception {
1572 String workspaceId = null;
1574 RepositoryInstance repoSession = null;
1576 repoSession = getRepositorySession((ServiceContext) null);
1577 DocumentRef docRef = new PathRef(
1579 + "/" + NuxeoUtils.Workspaces
1580 + "/" + workspaceName);
1581 DocumentModel workspace = repoSession.getDocument(docRef);
1582 workspaceId = workspace.getId();
1583 } catch (DocumentException de) {
1585 } catch (Exception e) {
1586 if (logger.isDebugEnabled()) {
1587 logger.debug("Caught exception ", e);
1589 throw new DocumentException(e);
1591 if (repoSession != null) {
1592 releaseRepositorySession(null, repoSession);
1599 public RepositoryInstance getRepositorySession(ServiceContext ctx) throws Exception {
1600 return getRepositorySession(ctx, ctx.getRepositoryName());
1603 public RepositoryInstance getRepositorySession(String repoName) throws Exception {
1604 return getRepositorySession(null, repoName);
1608 * Gets the repository session. - Package access only. If the 'ctx' param is
1609 * null then the repo name must be non-mull and vice-versa
1611 * @return the repository session
1612 * @throws Exception the exception
1614 public RepositoryInstance getRepositorySession(ServiceContext ctx, String repoName) throws Exception {
1615 RepositoryInstance repoSession = null;
1617 Profiler profiler = new Profiler("getRepositorySession():", 2);
1620 // To get a connection to the Nuxeo repo, we need either a valid ServiceContext instance or a repository name
1623 repoName = ctx.getRepositoryName(); // Notice we are overriding the passed in 'repoName' since we have a valid service context passed in to us
1624 repoSession = (RepositoryInstance) ctx.getCurrentRepositorySession(); // Look to see if one exists in the context before creating one
1625 } else if (repoName == null || repoName.trim().isEmpty()) {
1626 String errMsg = String.format("We can't get a connection to the Nuxeo repo because the service context passed in was null and no repository name was passed in either.");
1627 logger.error(errMsg);
1628 throw new Exception(errMsg);
1631 // If we couldn't find a repoSession from the service context (or the context was null) then we need to create a new one using
1632 // just the repo name
1634 if (repoSession == null) {
1635 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1636 repoSession = client.openRepository(repoName);
1638 if (logger.isDebugEnabled() == true) {
1639 logger.warn("Reusing the current context's repository session.");
1643 if (logger.isTraceEnabled()) {
1644 logger.trace("Testing call to getRepository() repository root: " + repoSession.getRootDocument());
1650 ctx.setCurrentRepositorySession(repoSession); // For reusing, save the repository session in the current service context
1657 * Release repository session. - Package access only.
1659 * @param repoSession the repo session
1661 public void releaseRepositorySession(ServiceContext ctx, RepositoryInstance repoSession) throws TransactionException {
1663 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1666 ctx.clearCurrentRepositorySession(); //clear the current context of the now closed repo session
1667 if (ctx.getCurrentRepositorySession() == null) {
1668 client.releaseRepository(repoSession); //release the repo session if the service context's ref count is zeo.
1671 client.releaseRepository(repoSession); //repo session was acquired without a service context
1673 } catch (TransactionRuntimeException tre) {
1674 TransactionException te = new TransactionException(tre);
1675 logger.error(te.getMessage(), tre); // Log the standard transaction exception message, plus an exception-specific stack trace
1677 } catch (Exception e) {
1678 logger.error("Could not close the repository session", e);
1679 // no need to throw this service specific exception
1684 public void doWorkflowTransition(ServiceContext ctx, String id,
1685 DocumentHandler handler, TransitionDef transitionDef)
1686 throws BadRequestException, DocumentNotFoundException,
1688 // This is a placeholder for when we change the StorageClient interface to treat workflow transitions as 1st class operations like 'get', 'create', 'update, 'delete', etc
1691 private String handleProvidedStartingWildcard(String partialTerm) {
1692 if (Tools.notBlank(partialTerm)) {
1693 // FIXME: Get this value from an existing constant, if available
1694 final String USER_SUPPLIED_WILDCARD = "*";
1695 if (partialTerm.substring(0, 1).equals(USER_SUPPLIED_WILDCARD)) {
1696 StringBuffer buffer = new StringBuffer(partialTerm);
1697 buffer.setCharAt(0, JDBCTools.SQL_WILDCARD.charAt(0));
1698 partialTerm = buffer.toString();
1704 private int getMaxItemsLimitOnJdbcQueries(String maxListItemsLimit) {
1705 final int DEFAULT_ITEMS_LIMIT = 40;
1708 itemsLimit = Integer.parseInt(maxListItemsLimit);
1709 if (itemsLimit < 1) {
1710 logger.warn("Value of configuration setting "
1711 + IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES
1712 + " must be a positive integer; current value is " + maxListItemsLimit);
1713 itemsLimit = DEFAULT_ITEMS_LIMIT;
1715 } catch (NumberFormatException nfe) {
1716 logger.warn("Value of configuration setting "
1717 + IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES
1718 + " must be a positive integer; current value is " + maxListItemsLimit);
1719 itemsLimit = DEFAULT_ITEMS_LIMIT;
1725 * Identifies whether a restriction on tenant ID - to return only records
1726 * pertaining to the current tenant - is required in a JDBC query.
1728 * @param tenantBinding a tenant binding configuration.
1729 * @param ctx a service context.
1730 * @return true if a restriction on tenant ID is required in the query;
1731 * false if a restriction is not required.
1733 private boolean restrictJDBCQueryByTenantID(TenantBindingType tenantBinding, ServiceContext ctx) {
1734 boolean restrict = true;
1735 // If data for the current service, in the current tenant, is isolated
1736 // within its own separate, per-tenant repository, as contrasted with
1737 // being intermingled with other tenants' data in the default repository,
1738 // no restriction on Tenant ID is required in the query.
1739 String repositoryDomainName = ConfigUtils.getRepositoryName(tenantBinding, ctx.getRepositoryDomainName());
1740 if (!(repositoryDomainName.equals(ConfigUtils.DEFAULT_NUXEO_REPOSITORY_NAME))) {
1743 // If a configuration setting for this tenant identifies that JDBC
1744 // queries should not be restricted by tenant ID (perhaps because
1745 // there is always expected to be only one tenant's data present in
1746 // the system), no restriction on Tenant ID is required in the query.
1747 String queriesRestrictedByTenantId = TenantBindingUtils.getPropertyValue(tenantBinding,
1748 IQueryManager.JDBC_QUERIES_ARE_TENANT_ID_RESTRICTED);
1749 if (Tools.notBlank(queriesRestrictedByTenantId) &&
1750 queriesRestrictedByTenantId.equalsIgnoreCase(Boolean.FALSE.toString())) {