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.SQLException;
21 import java.util.ArrayList;
22 import java.util.Collections;
23 import java.util.Comparator;
24 import java.util.HashSet;
25 import java.util.Hashtable;
26 import java.util.Iterator;
27 import java.util.List;
30 import java.util.UUID;
32 import javax.sql.rowset.CachedRowSet;
33 import javax.ws.rs.core.MultivaluedMap;
35 import org.collectionspace.services.lifecycle.TransitionDef;
36 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
37 import org.collectionspace.services.client.CollectionSpaceClient;
38 import org.collectionspace.services.client.IQueryManager;
39 import org.collectionspace.services.client.PoxPayloadIn;
40 import org.collectionspace.services.client.PoxPayloadOut;
41 import org.collectionspace.services.client.Profiler;
42 import org.collectionspace.services.client.workflow.WorkflowClient;
43 import org.collectionspace.services.common.context.ServiceContext;
44 import org.collectionspace.services.common.query.QueryContext;
45 import org.collectionspace.services.common.repository.RepositoryClient;
46 import org.collectionspace.services.common.storage.JDBCTools;
47 import org.collectionspace.services.common.storage.PreparedStatementSimpleBuilder;
48 import org.collectionspace.services.common.document.BadRequestException;
49 import org.collectionspace.services.common.document.DocumentException;
50 import org.collectionspace.services.common.document.DocumentFilter;
51 import org.collectionspace.services.common.document.DocumentHandler;
52 import org.collectionspace.services.common.document.DocumentNotFoundException;
53 import org.collectionspace.services.common.document.DocumentHandler.Action;
54 import org.collectionspace.services.common.document.DocumentWrapper;
55 import org.collectionspace.services.common.document.DocumentWrapperImpl;
56 import org.collectionspace.services.common.document.TransactionException;
57 import org.collectionspace.services.common.CSWebApplicationException;
58 import org.collectionspace.services.common.ServiceMain;
59 import org.collectionspace.services.common.api.Tools;
60 import org.collectionspace.services.common.config.ConfigUtils;
61 import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl;
62 import org.collectionspace.services.common.config.TenantBindingUtils;
63 import org.collectionspace.services.common.storage.PreparedStatementBuilder;
64 import org.collectionspace.services.config.tenant.TenantBindingType;
65 import org.collectionspace.services.config.tenant.RepositoryDomainType;
68 // CSPACE-5036 - How to make CMISQL queries from Nuxeo
70 import org.apache.chemistry.opencmis.commons.enums.CmisVersion;
71 import org.apache.chemistry.opencmis.commons.server.CallContext;
72 import org.apache.chemistry.opencmis.server.impl.CallContextImpl;
73 import org.apache.chemistry.opencmis.server.shared.ThresholdOutputStreamFactory;
74 import org.nuxeo.common.utils.IdUtils;
75 import org.nuxeo.ecm.core.api.ClientException;
76 import org.nuxeo.ecm.core.api.DocumentModel;
77 import org.nuxeo.ecm.core.api.DocumentModelList;
78 import org.nuxeo.ecm.core.api.IterableQueryResult;
79 import org.nuxeo.ecm.core.api.VersioningOption;
80 import org.nuxeo.ecm.core.api.impl.DocumentModelListImpl;
81 import org.nuxeo.ecm.core.api.DocumentRef;
82 import org.nuxeo.ecm.core.api.IdRef;
83 import org.nuxeo.ecm.core.api.PathRef;
84 import org.nuxeo.runtime.transaction.TransactionRuntimeException;
85 import org.nuxeo.ecm.core.opencmis.bindings.NuxeoCmisServiceFactory;
86 import org.nuxeo.ecm.core.opencmis.impl.server.NuxeoCmisService;
87 import org.slf4j.Logger;
88 import org.slf4j.LoggerFactory;
91 * RepositoryJavaClient is used to perform CRUD operations on documents in Nuxeo
92 * repository using Remote Java APIs. It uses
94 * @see DocumentHandler as IOHandler with the client.
96 * $LastChangedRevision: $ $LastChangedDate: $
98 public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn, PoxPayloadOut> {
103 private final Logger logger = LoggerFactory.getLogger(RepositoryJavaClientImpl.class);
104 // private final Logger profilerLogger = LoggerFactory.getLogger("remperf");
105 // private String foo = Profiler.createLogger();
106 public static final String NUXEO_CORE_TYPE_DOMAIN = "Domain";
107 public static final String NUXEO_CORE_TYPE_WORKSPACEROOT = "WorkspaceRoot";
108 // FIXME: Get this value from an existing constant, if available
109 public static final String BACKSLASH = "\\";
110 public static final String USER_SUPPLIED_WILDCARD = "*";
111 public static final String USER_SUPPLIED_WILDCARD_REGEX = BACKSLASH + USER_SUPPLIED_WILDCARD;
112 public static final String USER_SUPPLIED_ANCHOR_CHAR = "^";
113 public static final String USER_SUPPLIED_ANCHOR_CHAR_REGEX = BACKSLASH + USER_SUPPLIED_ANCHOR_CHAR;
114 public static final String ENDING_ANCHOR_CHAR = "$";
115 public static final String ENDING_ANCHOR_CHAR_REGEX = BACKSLASH + ENDING_ANCHOR_CHAR;
119 * Instantiates a new repository java client impl.
121 public RepositoryJavaClientImpl() {
125 public void assertWorkflowState(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
126 DocumentModel docModel) throws DocumentNotFoundException, ClientException {
127 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
128 if (queryParams != null) {
130 // Look for the workflow "delete" query param and see if we need to assert that the
131 // docModel is in a non-deleted workflow state.
133 String currentState = docModel.getCurrentLifeCycleState();
134 String includeDeletedStr = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_NONDELETED);
135 boolean includeDeleted = includeDeletedStr == null ? true : Boolean.parseBoolean(includeDeletedStr);
136 if (includeDeleted == false) {
138 // We don't wanted soft-deleted object, so throw an exception if this one is soft-deleted.
140 if (currentState.equalsIgnoreCase(WorkflowClient.WORKFLOWSTATE_DELETED)) {
141 String msg = "The GET assertion that docModel not be in 'deleted' workflow state failed.";
143 throw new DocumentNotFoundException(msg);
150 * create document in the Nuxeo repository
152 * @param ctx service context under which this method is invoked
153 * @param handler should be used by the caller to provide and transform the
155 * @return id in repository of the newly created document
156 * @throws BadRequestException
157 * @throws TransactionException
158 * @throws DocumentException
161 public String create(ServiceContext ctx,
162 DocumentHandler handler) throws BadRequestException,
163 TransactionException, DocumentException {
165 String docType = NuxeoUtils.getTenantQualifiedDocType(ctx); //ctx.getDocumentType();
166 if (docType == null) {
167 throw new IllegalArgumentException(
168 "RepositoryJavaClient.create: docType is missing");
171 if (handler == null) {
172 throw new IllegalArgumentException(
173 "RepositoryJavaClient.create: handler is missing");
175 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
176 if (nuxeoWspaceId == null) {
177 throw new DocumentNotFoundException(
178 "Unable to find workspace for service " + ctx.getServiceName()
179 + " check if the workspace exists in the Nuxeo repository");
182 CoreSessionInterface repoSession = null;
184 handler.prepare(Action.CREATE);
185 repoSession = getRepositorySession(ctx);
186 DocumentRef nuxeoWspace = new IdRef(nuxeoWspaceId);
187 DocumentModel wspaceDoc = repoSession.getDocument(nuxeoWspace);
188 String wspacePath = wspaceDoc.getPathAsString();
189 //give our own ID so PathRef could be constructed later on
190 String id = IdUtils.generateId(UUID.randomUUID().toString());
191 // create document model
192 DocumentModel doc = repoSession.createDocumentModel(wspacePath, id, docType);
193 /* Check for a versioned document, and check In and Out before we proceed.
194 * This does not work as we do not have the uid schema on our docs.
195 if(((DocumentModelHandler) handler).supportsVersioning()) {
196 doc.setProperty("uid","major_version",1);
197 doc.setProperty("uid","minor_version",0);
200 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
201 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
202 handler.handle(Action.CREATE, wrapDoc);
203 // create document with documentmodel
204 doc = repoSession.createDocument(doc);
206 // TODO for sub-docs need to call into the handler to let it deal with subitems. Pass in the id,
207 // and assume the handler has the state it needs (doc fragments).
208 handler.complete(Action.CREATE, wrapDoc);
210 } catch (BadRequestException bre) {
212 } catch (Exception e) {
213 logger.error("Caught exception ", e);
214 throw new NuxeoDocumentException(e);
216 if (repoSession != null) {
217 releaseRepositorySession(ctx, repoSession);
224 * get document from the Nuxeo repository
226 * @param ctx service context under which this method is invoked
227 * @param id of the document to retrieve
228 * @param handler should be used by the caller to provide and transform the
230 * @throws DocumentNotFoundException if the document cannot be found in the
232 * @throws TransactionException
233 * @throws DocumentException
236 public void get(ServiceContext ctx, String id, DocumentHandler handler)
237 throws DocumentNotFoundException, TransactionException, DocumentException {
239 if (handler == null) {
240 throw new IllegalArgumentException(
241 "RepositoryJavaClient.get: handler is missing");
244 CoreSessionInterface repoSession = null;
246 handler.prepare(Action.GET);
247 repoSession = getRepositorySession(ctx);
248 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
249 DocumentModel docModel = null;
251 docModel = repoSession.getDocument(docRef);
252 assertWorkflowState(ctx, docModel);
253 } catch (ClientException ce) {
254 String msg = logException(ce, "Could not find document with CSID=" + id);
255 throw new DocumentNotFoundException(msg, ce);
258 // Set repository session to handle the document
260 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
261 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(docModel);
262 handler.handle(Action.GET, wrapDoc);
263 handler.complete(Action.GET, wrapDoc);
264 } catch (IllegalArgumentException iae) {
266 } catch (DocumentException de) {
268 } catch (Exception e) {
269 if (logger.isDebugEnabled()) {
270 logger.debug("Caught exception ", e);
272 throw new NuxeoDocumentException(e);
274 if (repoSession != null) {
275 releaseRepositorySession(ctx, repoSession);
281 * get a document from the Nuxeo repository, using the docFilter params.
283 * @param ctx service context under which this method is invoked
284 * @param handler should be used by the caller to provide and transform the
285 * document. Handler must have a docFilter set to return a single item.
286 * @throws DocumentNotFoundException if the document cannot be found in the
288 * @throws TransactionException
289 * @throws DocumentException
292 public void get(ServiceContext ctx, DocumentHandler handler)
293 throws DocumentNotFoundException, TransactionException, DocumentException {
294 QueryContext queryContext = new QueryContext(ctx, handler);
295 CoreSessionInterface repoSession = null;
298 handler.prepare(Action.GET);
299 repoSession = getRepositorySession(ctx);
301 DocumentModelList docList = null;
302 // force limit to 1, and ignore totalSize
303 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
304 docList = repoSession.query(query, null, 1, 0, false);
305 if (docList.size() != 1) {
306 throw new DocumentNotFoundException("No document found matching filter params: " + query);
308 DocumentModel doc = docList.get(0);
310 if (logger.isDebugEnabled()) {
311 logger.debug("Executed NXQL query: " + query);
314 //set reposession to handle the document
315 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
316 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
317 handler.handle(Action.GET, wrapDoc);
318 handler.complete(Action.GET, wrapDoc);
319 } catch (IllegalArgumentException iae) {
321 } catch (DocumentException de) {
323 } catch (Exception e) {
324 if (logger.isDebugEnabled()) {
325 logger.debug("Caught exception ", e);
327 throw new NuxeoDocumentException(e);
329 if (repoSession != null) {
330 releaseRepositorySession(ctx, repoSession);
335 public DocumentWrapper<DocumentModel> getDoc(
336 CoreSessionInterface repoSession,
337 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
338 String csid) throws DocumentNotFoundException, DocumentException {
339 DocumentWrapper<DocumentModel> wrapDoc = null;
342 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
343 DocumentModel doc = null;
345 doc = repoSession.getDocument(docRef);
346 } catch (ClientException ce) {
347 String msg = logException(ce, "Could not find document with CSID=" + csid);
348 throw new DocumentNotFoundException(msg, ce);
350 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
351 } catch (IllegalArgumentException iae) {
353 } catch (DocumentException de) {
361 * Get wrapped documentModel from the Nuxeo repository. The search is
362 * restricted to the workspace of the current context.
364 * @param ctx service context under which this method is invoked
365 * @param csid of the document to retrieve
366 * @throws DocumentNotFoundException
367 * @throws TransactionException
368 * @throws DocumentException
369 * @return a wrapped documentModel
372 public DocumentWrapper<DocumentModel> getDoc(
373 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
374 String csid) throws DocumentNotFoundException, TransactionException, DocumentException {
375 CoreSessionInterface repoSession = null;
376 DocumentWrapper<DocumentModel> wrapDoc = null;
379 // Open a new repository session
380 repoSession = getRepositorySession(ctx);
381 wrapDoc = getDoc(repoSession, ctx, csid);
382 } catch (IllegalArgumentException iae) {
384 } catch (DocumentException de) {
386 } catch (Exception e) {
387 if (logger.isDebugEnabled()) {
388 logger.debug("Caught exception ", e);
390 throw new NuxeoDocumentException(e);
392 if (repoSession != null) {
393 releaseRepositorySession(ctx, repoSession);
397 if (logger.isWarnEnabled() == true) {
398 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
403 public DocumentWrapper<DocumentModel> findDoc(
404 CoreSessionInterface repoSession,
405 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
407 throws DocumentNotFoundException, DocumentException {
408 DocumentWrapper<DocumentModel> wrapDoc = null;
411 QueryContext queryContext = new QueryContext(ctx, whereClause);
412 DocumentModelList docList = null;
413 // force limit to 1, and ignore totalSize
414 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
415 docList = repoSession.query(query,
420 if (docList.size() != 1) {
421 if (logger.isDebugEnabled()) {
422 logger.debug("findDoc: Query found: " + docList.size() + " items.");
423 logger.debug(" Query: " + query);
425 throw new DocumentNotFoundException("No document found matching filter params: " + query);
427 DocumentModel doc = docList.get(0);
428 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
429 } catch (IllegalArgumentException iae) {
431 } catch (DocumentException de) {
433 } catch (Exception e) {
434 if (logger.isDebugEnabled()) {
435 logger.debug("Caught exception ", e);
437 throw new NuxeoDocumentException(e);
444 * find wrapped documentModel from the Nuxeo repository
446 * @param ctx service context under which this method is invoked
447 * @param whereClause where NXQL where clause to get the document
448 * @throws DocumentNotFoundException
449 * @throws TransactionException
450 * @throws DocumentException
451 * @return a wrapped documentModel retrieved by the repository query
454 public DocumentWrapper<DocumentModel> findDoc(
455 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
457 throws DocumentNotFoundException, TransactionException, DocumentException {
458 CoreSessionInterface repoSession = null;
459 DocumentWrapper<DocumentModel> wrapDoc = null;
462 repoSession = getRepositorySession(ctx);
463 wrapDoc = findDoc(repoSession, ctx, whereClause);
464 } catch (Exception e) {
465 throw new NuxeoDocumentException("Unable to create a Nuxeo repository session.", e);
467 if (repoSession != null) {
468 releaseRepositorySession(ctx, repoSession);
472 if (logger.isWarnEnabled() == true) {
473 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
480 * find doc and return CSID from the Nuxeo repository
483 * @param ctx service context under which this method is invoked
484 * @param whereClause where NXQL where clause to get the document
485 * @throws DocumentNotFoundException
486 * @throws TransactionException
487 * @throws DocumentException
488 * @return the CollectionSpace ID (CSID) of the requested document
491 public String findDocCSID(CoreSessionInterface repoSession,
492 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String whereClause)
493 throws DocumentNotFoundException, TransactionException, DocumentException {
495 boolean releaseSession = false;
497 if (repoSession == null) {
498 repoSession = this.getRepositorySession(ctx);
499 releaseSession = true;
501 DocumentWrapper<DocumentModel> wrapDoc = findDoc(repoSession, ctx, whereClause);
502 DocumentModel docModel = wrapDoc.getWrappedObject();
503 csid = NuxeoUtils.getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
504 } catch (DocumentNotFoundException dnfe) {
506 } catch (IllegalArgumentException iae) {
508 } catch (DocumentException de) {
510 } catch (Exception e) {
511 if (logger.isDebugEnabled()) {
512 logger.debug("Caught exception ", e);
514 throw new NuxeoDocumentException(e);
516 if (releaseSession && (repoSession != null)) {
517 this.releaseRepositorySession(ctx, repoSession);
523 public DocumentWrapper<DocumentModelList> findDocs(
524 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
525 CoreSessionInterface repoSession,
526 List<String> docTypes,
528 String orderByClause,
531 boolean computeTotal)
532 throws DocumentNotFoundException, DocumentException {
533 DocumentWrapper<DocumentModelList> wrapDoc = null;
536 if (docTypes == null || docTypes.size() < 1) {
537 throw new DocumentNotFoundException(
538 "The findDocs() method must specify at least one DocumentType.");
540 DocumentModelList docList = null;
541 QueryContext queryContext = new QueryContext(ctx, whereClause, orderByClause);
542 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
543 if (logger.isDebugEnabled()) {
544 logger.debug("findDocs() NXQL: " + query);
546 docList = repoSession.query(query, null, pageSize, pageSize * pageNum, computeTotal);
547 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
548 } catch (IllegalArgumentException iae) {
550 } catch (Exception e) {
551 if (logger.isDebugEnabled()) {
552 logger.debug("Caught exception ", e);
554 throw new NuxeoDocumentException(e);
560 protected static String buildInListForDocTypes(List<String> docTypes) {
561 StringBuilder sb = new StringBuilder();
563 boolean first = true;
564 for (String docType : docTypes) {
575 return sb.toString();
578 public DocumentWrapper<DocumentModelList> findDocs(
579 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
580 DocumentHandler handler,
581 CoreSessionInterface repoSession,
582 List<String> docTypes)
583 throws DocumentNotFoundException, DocumentException {
584 DocumentWrapper<DocumentModelList> wrapDoc = null;
586 DocumentFilter filter = handler.getDocumentFilter();
587 String oldOrderBy = filter.getOrderByClause();
588 if (isClauseEmpty(oldOrderBy) == true) {
589 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
591 QueryContext queryContext = new QueryContext(ctx, handler);
594 if (docTypes == null || docTypes.size() < 1) {
595 throw new DocumentNotFoundException(
596 "The findDocs() method must specify at least one DocumentType.");
598 DocumentModelList docList = null;
599 if (handler.isCMISQuery() == true) {
600 String inList = buildInListForDocTypes(docTypes);
601 ctx.getQueryParams().add(IQueryManager.SEARCH_RELATED_MATCH_OBJ_DOCTYPES, inList);
602 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
604 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
605 if (logger.isDebugEnabled()) {
606 logger.debug("findDocs() NXQL: " + query);
608 docList = repoSession.query(query, null, filter.getPageSize(), filter.getOffset(), true);
610 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
611 } catch (IllegalArgumentException iae) {
613 } catch (Exception e) {
614 if (logger.isDebugEnabled()) {
615 logger.debug("Caught exception ", e);
617 throw new NuxeoDocumentException(e);
624 * Find a list of documentModels from the Nuxeo repository
626 * @param docTypes a list of DocType names to match
627 * @param whereClause where the clause to qualify on
628 * @throws DocumentNotFoundException
629 * @throws TransactionException
630 * @throws DocumentException
631 * @return a list of documentModels
634 public DocumentWrapper<DocumentModelList> findDocs(
635 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
636 List<String> docTypes,
638 int pageSize, int pageNum, boolean computeTotal)
639 throws DocumentNotFoundException, TransactionException, DocumentException {
640 CoreSessionInterface repoSession = null;
641 DocumentWrapper<DocumentModelList> wrapDoc = null;
644 repoSession = getRepositorySession(ctx);
645 wrapDoc = findDocs(ctx, repoSession, docTypes, whereClause, null,
646 pageSize, pageNum, computeTotal);
647 } catch (IllegalArgumentException iae) {
649 } catch (Exception e) {
650 if (logger.isDebugEnabled()) {
651 logger.debug("Caught exception ", e);
653 throw new NuxeoDocumentException(e);
655 if (repoSession != null) {
656 releaseRepositorySession(ctx, repoSession);
660 if (logger.isWarnEnabled() == true) {
661 logger.warn("Returned DocumentModelList instance was created with a repository session that is now closed.");
668 * @see org.collectionspace.services.common.storage.StorageClient#get(org.collectionspace.services.common.context.ServiceContext, java.util.List, org.collectionspace.services.common.document.DocumentHandler)
671 public void get(ServiceContext ctx, List<String> csidList, DocumentHandler handler)
672 throws DocumentNotFoundException, TransactionException, DocumentException {
673 if (handler == null) {
674 throw new IllegalArgumentException(
675 "RepositoryJavaClient.getAll: handler is missing");
678 CoreSessionInterface repoSession = null;
680 handler.prepare(Action.GET_ALL);
681 repoSession = getRepositorySession(ctx);
682 DocumentModelList docModelList = new DocumentModelListImpl();
683 //FIXME: Should be using NuxeoUtils.createPathRef for security reasons
684 for (String csid : csidList) {
685 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
686 DocumentModel docModel = repoSession.getDocument(docRef);
687 docModelList.add(docModel);
690 //set reposession to handle the document
691 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
692 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docModelList);
693 handler.handle(Action.GET_ALL, wrapDoc);
694 handler.complete(Action.GET_ALL, wrapDoc);
695 } catch (DocumentException de) {
697 } catch (Exception e) {
698 if (logger.isDebugEnabled()) {
699 logger.debug("Caught exception ", e);
701 throw new NuxeoDocumentException(e);
703 if (repoSession != null) {
704 releaseRepositorySession(ctx, repoSession);
710 * getAll get all documents for an entity entity service from the Nuxeo
713 * @param ctx service context under which this method is invoked
714 * @param handler should be used by the caller to provide and transform the
716 * @throws DocumentNotFoundException
717 * @throws TransactionException
718 * @throws DocumentException
721 public void getAll(ServiceContext ctx, DocumentHandler handler)
722 throws DocumentNotFoundException, TransactionException, DocumentException {
723 if (handler == null) {
724 throw new IllegalArgumentException(
725 "RepositoryJavaClient.getAll: handler is missing");
727 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
728 if (nuxeoWspaceId == null) {
729 throw new DocumentNotFoundException(
730 "Unable to find workspace for service "
731 + ctx.getServiceName()
732 + " check if the workspace exists in the Nuxeo repository.");
735 CoreSessionInterface repoSession = null;
737 handler.prepare(Action.GET_ALL);
738 repoSession = getRepositorySession(ctx);
739 DocumentRef wsDocRef = new IdRef(nuxeoWspaceId);
740 DocumentModelList docList = repoSession.getChildren(wsDocRef);
741 //set reposession to handle the document
742 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
743 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
744 handler.handle(Action.GET_ALL, wrapDoc);
745 handler.complete(Action.GET_ALL, wrapDoc);
746 } catch (DocumentException de) {
748 } catch (Exception e) {
749 if (logger.isDebugEnabled()) {
750 logger.debug("Caught exception ", e);
752 throw new NuxeoDocumentException(e);
754 if (repoSession != null) {
755 releaseRepositorySession(ctx, repoSession);
760 private boolean isClauseEmpty(String theString) {
761 boolean result = true;
762 if (theString != null && !theString.isEmpty()) {
768 public DocumentWrapper<DocumentModel> getDocFromCsid(
769 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
770 CoreSessionInterface repoSession,
773 DocumentWrapper<DocumentModel> result = null;
775 result = new DocumentWrapperImpl<DocumentModel>(NuxeoUtils.getDocFromCsid(ctx, repoSession, csid));
781 * A method to find a CollectionSpace document (of any type) given just a service context and
782 * its CSID. A search across *all* service workspaces (within a given tenant context) is performed to find
785 * This query searches Nuxeo's Hierarchy table where our CSIDs are stored in the "name" column.
788 public DocumentWrapper<DocumentModel> getDocFromCsid(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
791 DocumentWrapper<DocumentModel> result = null;
792 CoreSessionInterface repoSession = null;
794 repoSession = getRepositorySession(ctx);
795 result = getDocFromCsid(ctx, repoSession, csid);
797 if (repoSession != null) {
798 releaseRepositorySession(ctx, repoSession);
802 if (logger.isWarnEnabled() == true) {
803 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
810 * Returns a URI value for a document in the Nuxeo repository
812 * @param wrappedDoc a wrapped documentModel
813 * @throws ClientException
814 * @return a document URI
817 public String getDocURI(DocumentWrapper<DocumentModel> wrappedDoc) throws ClientException {
818 DocumentModel docModel = wrappedDoc.getWrappedObject();
819 String uri = (String) docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
820 CollectionSpaceClient.COLLECTIONSPACE_CORE_URI);
825 * See CSPACE-5036 - How to make CMISQL queries from Nuxeo
827 private IterableQueryResult makeCMISQLQuery(CoreSessionInterface repoSession, String query, QueryContext queryContext) throws DocumentException {
828 IterableQueryResult result = null;
829 /** Threshold over which temporary files are not kept in memory. */
830 final int THRESHOLD = 1024 * 1024;
833 logger.debug(String.format("Performing a CMIS query on Nuxeo repository named %s",
834 repoSession.getRepositoryName()));
836 ThresholdOutputStreamFactory streamFactory = ThresholdOutputStreamFactory.newInstance(
837 null, THRESHOLD, -1, false);
838 CallContextImpl callContext = new CallContextImpl(
839 CallContext.BINDING_LOCAL,
840 CmisVersion.CMIS_1_1,
841 repoSession.getRepositoryName(),
842 null, // ServletContext
843 null, // HttpServletRequest
844 null, // HttpServletResponse
845 new NuxeoCmisServiceFactory(),
847 callContext.put(CallContext.USERNAME, repoSession.getPrincipal().getName());
849 NuxeoCmisService cmisService = new NuxeoCmisService(repoSession.getCoreSession());
850 result = repoSession.queryAndFetch(query, "CMISQL", cmisService);
851 } catch (ClientException e) {
852 // TODO Auto-generated catch block
853 logger.error("Encounter trouble making the following CMIS query: " + query, e);
854 throw new NuxeoDocumentException(e);
861 * getFiltered get all documents for an entity service from the Document
862 * repository, given filter parameters specified by the handler.
864 * @param ctx service context under which this method is invoked
865 * @param handler should be used by the caller to provide and transform the
867 * @throws DocumentNotFoundException if workspace not found
868 * @throws TransactionException
869 * @throws DocumentException
872 public void getFiltered(ServiceContext ctx, DocumentHandler handler)
873 throws DocumentNotFoundException, TransactionException, DocumentException {
875 DocumentFilter filter = handler.getDocumentFilter();
876 String oldOrderBy = filter.getOrderByClause();
877 if (isClauseEmpty(oldOrderBy) == true) {
878 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
880 QueryContext queryContext = new QueryContext(ctx, handler);
882 CoreSessionInterface repoSession = null;
884 handler.prepare(Action.GET_ALL);
885 repoSession = getRepositorySession(ctx); //Keeps a refcount here for the repository session so you need to release this when finished
887 DocumentModelList docList = null;
889 if (handler.isJDBCQuery() == true) {
890 docList = getFilteredJDBC(repoSession, ctx, handler);
892 } else if (handler.isCMISQuery() == true) {
893 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext); //FIXME: REM - Need to deal with paging info in CMIS query
896 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
897 if (logger.isDebugEnabled()) {
898 logger.debug("Executing NXQL query: " + query.toString());
900 Profiler profiler = new Profiler(this, 2);
901 profiler.log("Executing NXQL query: " + query.toString());
903 // If we have a page size and/or offset, then reflect those values
904 // when constructing the query, and also pass 'true' to get totalSize
905 // in the returned DocumentModelList.
906 if ((queryContext.getDocFilter().getOffset() > 0) || (queryContext.getDocFilter().getPageSize() > 0)) {
907 docList = repoSession.query(query, null,
908 queryContext.getDocFilter().getPageSize(), queryContext.getDocFilter().getOffset(), true);
910 docList = repoSession.query(query);
915 //set repoSession to handle the document
916 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
917 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
918 handler.handle(Action.GET_ALL, wrapDoc);
919 handler.complete(Action.GET_ALL, wrapDoc);
920 } catch (DocumentException de) {
922 } catch (Exception e) {
923 if (logger.isDebugEnabled()) {
924 logger.debug("Caught exception ", e); // REM - 1/17/2014: Check for org.nuxeo.ecm.core.api.ClientException and re-attempt
926 throw new NuxeoDocumentException(e);
928 if (repoSession != null) {
929 releaseRepositorySession(ctx, repoSession);
935 * Perform a database query, via JDBC and SQL, to retrieve matching records
936 * based on filter criteria.
938 * Although this method currently has a general-purpose name, it is
939 * currently dedicated to a specific task: that of improving performance
940 * for partial term matching queries on authority items / terms, via
941 * the use of a hand-tuned SQL query, rather than via the generated SQL
942 * produced by Nuxeo from an NXQL query. (See CSPACE-6361 for a task
943 * to generalize this method.)
945 * @param repoSession a repository session.
946 * @param ctx the service context.
947 * @param handler a relevant document handler.
948 * @return a list of document models matching the search criteria.
951 private DocumentModelList getFilteredJDBC(CoreSessionInterface repoSession, ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
952 DocumentHandler handler) throws Exception {
953 DocumentModelList result = new DocumentModelListImpl();
955 // FIXME: Get all of the following values from appropriate external constants.
957 // At present, the two constants below are duplicated in both RepositoryJavaClientImpl
958 // and in AuthorityItemDocumentModelHandler.
959 final String TERM_GROUP_LIST_NAME = "TERM_GROUP_LIST_NAME";
960 final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
961 final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
962 // Get this from a constant in AuthorityResource or equivalent
963 final String PARENT_WILDCARD = "_ALL_";
965 // Build two SQL statements, to be executed within a single transaction:
966 // the first statement to control join order, and the second statement
967 // representing the actual 'get filtered' query
969 // Build the join control statement
971 // Per http://www.postgresql.org/docs/9.2/static/runtime-config-query.html#GUC-JOIN-COLLAPSE-LIMIT
972 // "Setting [this value] to 1 prevents any reordering of explicit JOINs.
973 // Thus, the explicit join order specified in the query will be the
974 // actual order in which the relations are joined."
975 // See CSPACE-5945 for further discussion of why this setting is needed.
977 // Adding this statement is commented out here for now. It significantly
978 // improved query performance for authority item / term queries where
979 // large numbers of rows were retrieved, but appears to have resulted
980 // in consistently slower-than-desired query performance where zero or
981 // very few records were retrieved. See notes on CSPACE-5945. - ADR 2013-04-09
982 // String joinControlSql = "SET LOCAL join_collapse_limit TO 1;";
984 // Build the query statement
986 // Start with the default query
987 String selectStatement =
988 "SELECT DISTINCT commonschema.id"
989 + " FROM " + handler.getServiceContext().getCommonPartLabel() + " commonschema";
993 + " ON misc.id = commonschema.id"
994 + " INNER JOIN hierarchy hierarchy_termgroup"
995 + " ON hierarchy_termgroup.parentid = misc.id"
996 + " INNER JOIN " + handler.getJDBCQueryParams().get(TERM_GROUP_TABLE_NAME_PARAM) + " termgroup"
997 + " ON termgroup.id = hierarchy_termgroup.id ";
1000 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
1001 // Value for replaceable parameter 1 in the query
1002 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
1003 // If the value of the partial term query parameter is blank ('pt='),
1004 // return all records, subject to restriction by any limit clause
1005 if (Tools.isBlank(partialTerm)) {
1008 // Otherwise, return records that match the supplied partial term
1010 " WHERE (termgroup.termdisplayname ILIKE ?)";
1013 // At present, results are ordered in code, below, rather than in SQL,
1014 // and the orderByClause below is thus intentionally blank.
1016 // To implement the orderByClause below in SQL; e.g. via
1017 // 'ORDER BY termgroup.termdisplayname', the relevant column
1018 // must be returned by the SELECT statement.
1019 String orderByClause = "";
1022 TenantBindingConfigReaderImpl tReader =
1023 ServiceMain.getInstance().getTenantBindingConfigReader();
1024 TenantBindingType tenantBinding = tReader.getTenantBinding(ctx.getTenantId());
1025 String maxListItemsLimit = TenantBindingUtils.getPropertyValue(tenantBinding,
1026 IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES);
1028 " LIMIT " + getMaxItemsLimitOnJdbcQueries(maxListItemsLimit); // implicit int-to-String conversion
1030 // After building the individual parts of the query, set the values
1031 // of replaceable parameters that will be inserted into that query
1032 // and optionally add restrictions
1034 List<String> params = new ArrayList<>();
1036 if (Tools.notBlank(whereClause)) {
1038 // Read tenant bindings configuration to determine whether
1039 // to automatically insert leading, as well as trailing, wildcards
1040 // into the term matching string.
1041 String usesStartingWildcard = TenantBindingUtils.getPropertyValue(tenantBinding,
1042 IQueryManager.TENANT_USES_STARTING_WILDCARD_FOR_PARTIAL_TERM);
1043 // Handle user-provided leading wildcard characters, in the
1044 // configuration where a leading wildcard is not automatically inserted.
1045 // (The user-provided wildcard must be in the first, or "starting"
1046 // character position in the partial term value.)
1047 if (Tools.notBlank(usesStartingWildcard)) {
1048 if (usesStartingWildcard.equalsIgnoreCase(Boolean.FALSE.toString())) {
1049 partialTerm = handleProvidedStartingWildcard(partialTerm);
1050 // Otherwise, in the configuration where a leading wildcard
1051 // is usually automatically inserted, handle the cases where
1052 // a user has entered an anchor character in the first position
1053 // in the starting term value. In those cases, strip that
1054 // anchor character and don't add a leading wildcard
1056 if (partialTerm.startsWith(USER_SUPPLIED_ANCHOR_CHAR)) {
1057 partialTerm = partialTerm.substring(1, partialTerm.length());
1058 // Otherwise, automatically add a leading wildcard
1060 partialTerm = JDBCTools.SQL_WILDCARD + partialTerm;
1064 // Add SQL wildcards in the midst of the partial term match search
1065 // expression, whever user-supplied wildcards appear, except in the
1066 // first or last character positions of the search expression.
1067 partialTerm = subtituteWildcardsInPartialTerm(partialTerm);
1069 // If a designated 'anchor character' is present as the last character
1070 // in the search expression, strip that character and don't add
1071 // a trailing wildcard
1072 int lastCharPos = partialTerm.length() - 1;
1073 if (partialTerm.endsWith(USER_SUPPLIED_ANCHOR_CHAR) && lastCharPos > 0) {
1074 partialTerm = partialTerm.substring(0, lastCharPos);
1076 // Otherwise, automatically add a trailing wildcard
1077 partialTerm = partialTerm + JDBCTools.SQL_WILDCARD;
1079 params.add(partialTerm);
1082 // Optionally add restrictions to the default query, based on variables
1083 // in the current request
1085 // Restrict the query to filter out deleted records, if requested
1086 String includeDeleted = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_NONDELETED);
1087 if (includeDeleted != null && includeDeleted.equalsIgnoreCase(Boolean.FALSE.toString())) {
1088 whereClause = whereClause
1089 + " AND (misc.lifecyclestate <> '" + WorkflowClient.WORKFLOWSTATE_DELETED + "')";
1092 // If a particular authority is specified, restrict the query further
1093 // to return only records within that authority
1094 String inAuthorityValue = (String) handler.getJDBCQueryParams().get(IN_AUTHORITY_PARAM);
1095 if (Tools.notBlank(inAuthorityValue)) {
1096 // Handle the '_ALL_' case for inAuthority
1097 if (inAuthorityValue.equals(PARENT_WILDCARD)) {
1098 // Add nothing to the query here if it should match within all authorities
1100 whereClause = whereClause
1101 + " AND (commonschema.inauthority = ?)";
1102 params.add(inAuthorityValue); // Value for replaceable parameter 2 in the query
1106 // Restrict the query further to return only records pertaining to
1107 // the current tenant, unless:
1108 // * Data for this service, in this tenant, is stored in its own,
1109 // separate repository, rather than being intermingled with other
1110 // tenants' data in the default repository; or
1111 // * Restriction by tenant ID in JDBC queries has been disabled,
1112 // via configuration for this tenant,
1113 if (restrictJDBCQueryByTenantID(tenantBinding, ctx)) {
1114 joinClauses = joinClauses
1115 + " INNER JOIN collectionspace_core core"
1116 + " ON core.id = hierarchy_termgroup.parentid";
1117 whereClause = whereClause
1118 + " AND (core.tenantid = ?)";
1119 params.add(ctx.getTenantId()); // Value for replaceable parameter 3 in the query
1122 // Piece together the SQL query from its parts
1123 String querySql = selectStatement + joinClauses + whereClause + orderByClause + limitClause;
1125 // Note: PostgreSQL 9.2 introduced a change that may improve performance
1126 // of certain queries using JDBC PreparedStatements. See comments on
1127 // CSPACE-5943 for details.
1129 // See a comment above for the reason that the joinControl SQL statement,
1130 // along with its corresponding prepared statement builder, is commented out for now.
1131 // PreparedStatementBuilder joinControlBuilder = new PreparedStatementBuilder(joinControlSql);
1132 PreparedStatementSimpleBuilder queryBuilder = new PreparedStatementSimpleBuilder(querySql, params);
1133 List<PreparedStatementBuilder> builders = new ArrayList<>();
1134 // builders.add(joinControlBuilder);
1135 builders.add(queryBuilder);
1136 String dataSourceName = JDBCTools.NUXEO_DATASOURCE_NAME;
1137 String repositoryName = ctx.getRepositoryName();
1138 final Boolean EXECUTE_WITHIN_TRANSACTION = true;
1139 Set<String> docIds = new HashSet<>();
1141 String cspaceInstanceId = ServiceMain.getInstance().getCspaceInstanceId();
1142 List<CachedRowSet> resultsList = JDBCTools.executePreparedQueries(builders,
1143 dataSourceName, repositoryName, cspaceInstanceId, EXECUTE_WITHIN_TRANSACTION);
1145 // At least one set of results is expected, from the second prepared
1146 // statement to be executed.
1147 // If fewer results are returned, return an empty list of document models
1148 if (resultsList == null || resultsList.size() < 1) {
1149 return result; // return an empty list of document models
1151 // The join control query (if enabled - it is currently commented
1152 // out as per comments above) will not return results, so query results
1153 // will be the first set of results (rowSet) returned in the list
1154 CachedRowSet queryResults = resultsList.get(0);
1156 // If the result from executing the query is null or contains zero rows,
1157 // return an empty list of document models
1158 if (queryResults == null) {
1159 return result; // return an empty list of document models
1161 queryResults.last();
1162 if (queryResults.getRow() == 0) {
1163 return result; // return an empty list of document models
1166 // Otherwise, get the document IDs from the results of the query
1168 queryResults.beforeFirst();
1169 while (queryResults.next()) {
1170 id = queryResults.getString(1);
1171 if (Tools.notBlank(id)) {
1175 } catch (SQLException sqle) {
1176 logger.warn("Could not obtain document IDs via SQL query '" + querySql + "': " + sqle.getMessage());
1177 return result; // return an empty list of document models
1180 // Get a list of document models, using the list of IDs obtained from the query
1182 // FIXME: Check whether we have a 'get document models from list of CSIDs'
1183 // utility method like this, and if not, add this to the appropriate
1185 DocumentModel docModel;
1186 for (String docId : docIds) {
1187 docModel = NuxeoUtils.getDocumentModel(repoSession, docId);
1188 if (docModel == null) {
1189 logger.warn("Could not obtain document model for document with ID " + docId);
1191 result.add(docModel);
1195 // Order the results
1196 final String COMMON_PART_SCHEMA = handler.getServiceContext().getCommonPartLabel();
1197 final String DISPLAY_NAME_XPATH =
1198 "//" + handler.getJDBCQueryParams().get(TERM_GROUP_LIST_NAME) + "/[0]/termDisplayName";
1199 Collections.sort(result, new Comparator<DocumentModel>() {
1201 public int compare(DocumentModel doc1, DocumentModel doc2) {
1202 String termDisplayName1 = null;
1203 String termDisplayName2 = null;
1205 termDisplayName1 = (String) NuxeoUtils.getXPathValue(doc1, COMMON_PART_SCHEMA, DISPLAY_NAME_XPATH);
1206 termDisplayName2 = (String) NuxeoUtils.getXPathValue(doc2, COMMON_PART_SCHEMA, DISPLAY_NAME_XPATH);
1207 } catch (NuxeoDocumentException e) {
1208 throw new RuntimeException(e); // We need to throw a RuntimeException because the compare() method of the Comparator interface does not support throwing an Exception
1210 return termDisplayName1.compareToIgnoreCase(termDisplayName2);
1218 private DocumentModelList getFilteredCMIS(CoreSessionInterface repoSession,
1219 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, DocumentHandler handler, QueryContext queryContext)
1220 throws DocumentNotFoundException, DocumentException {
1222 DocumentModelList result = new DocumentModelListImpl();
1224 String query = handler.getCMISQuery(queryContext);
1226 DocumentFilter docFilter = handler.getDocumentFilter();
1227 int pageSize = docFilter.getPageSize();
1228 int offset = docFilter.getOffset();
1229 if (logger.isDebugEnabled()) {
1230 logger.debug("Executing CMIS query: " + query.toString()
1231 + "with pageSize: " + pageSize + " at offset: " + offset);
1234 // If we have limit and/or offset, then pass true to get totalSize
1235 // in returned DocumentModelList.
1236 Profiler profiler = new Profiler(this, 2);
1237 profiler.log("Executing CMIS query: " + query.toString());
1240 IterableQueryResult queryResult = makeCMISQLQuery(repoSession, query, queryContext);
1242 int totalSize = (int) queryResult.size();
1243 ((DocumentModelListImpl) result).setTotalSize(totalSize);
1244 // Skip the rows before our offset
1246 queryResult.skipTo(offset);
1249 for (Map<String, Serializable> row : queryResult) {
1250 if (logger.isTraceEnabled()) {
1251 logger.trace(" Hierarchy Table ID is:" + row.get(IQueryManager.CMIS_TARGET_NUXEO_ID)
1252 + " nuxeo:pathSegment is: " + row.get(IQueryManager.CMIS_TARGET_NAME));
1254 String nuxeoId = (String) row.get(IQueryManager.CMIS_TARGET_NUXEO_ID);
1255 DocumentModel docModel = NuxeoUtils.getDocumentModel(repoSession, nuxeoId);
1256 result.add(docModel);
1258 if (nRows >= pageSize && pageSize != 0) { // A page size of zero means that they want all of them
1259 logger.debug("Got page full of items - quitting");
1264 queryResult.close();
1269 } catch (Exception e) {
1270 if (logger.isDebugEnabled()) {
1271 logger.debug("Caught exception ", e);
1273 throw new NuxeoDocumentException(e);
1277 // Since we're not supporting paging yet for CMIS queries, we need to perform
1278 // a workaround for the paging information we return in our list of results
1281 if (result != null) {
1282 docFilter.setStartPage(0);
1283 if (totalSize > docFilter.getPageSize()) {
1284 docFilter.setPageSize(totalSize);
1285 ((DocumentModelListImpl)result).setTotalSize(totalSize);
1293 private String logException(Exception e, String msg) {
1294 String result = null;
1296 String exceptionMessage = e.getMessage();
1297 exceptionMessage = exceptionMessage != null ? exceptionMessage : "<No details provided>";
1298 result = msg = msg + ". Caught exception:" + exceptionMessage;
1300 if (logger.isTraceEnabled() == true) {
1301 logger.error(msg, e);
1310 * update given document in the Nuxeo repository
1312 * @param ctx service context under which this method is invoked
1313 * @param csid of the document
1314 * @param handler should be used by the caller to provide and transform the
1316 * @throws BadRequestException
1317 * @throws DocumentNotFoundException
1318 * @throws TransactionException if the transaction times out or otherwise
1319 * cannot be successfully completed
1320 * @throws DocumentException
1323 public void update(ServiceContext ctx, String csid, DocumentHandler handler)
1324 throws BadRequestException, DocumentNotFoundException, TransactionException,
1326 if (handler == null) {
1327 throw new IllegalArgumentException(
1328 "RepositoryJavaClient.update: document handler is missing.");
1331 CoreSessionInterface repoSession = null;
1333 handler.prepare(Action.UPDATE);
1334 repoSession = getRepositorySession(ctx);
1335 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
1336 DocumentModel doc = null;
1338 doc = repoSession.getDocument(docRef);
1339 } catch (ClientException ce) {
1340 String msg = logException(ce, "Could not find document to update with CSID=" + csid);
1341 throw new DocumentNotFoundException(msg, ce);
1343 // Check for a versioned document, and check In and Out before we proceed.
1344 if (((DocumentModelHandler) handler).supportsVersioning()) {
1345 /* Once we advance to 5.5 or later, we can add this.
1346 * See also https://jira.nuxeo.com/browse/NXP-8506
1347 if(!doc.isVersionable()) {
1348 throw new NuxeoDocumentException("Configuration for: "
1349 +handler.getServiceContextPath()+" supports versioning, but Nuxeo config does not!");
1352 /* Force a version number - Not working. Apparently we need to configure the uid schema??
1353 if(doc.getProperty("uid","major_version") == null) {
1354 doc.setProperty("uid","major_version",1);
1356 if(doc.getProperty("uid","minor_version") == null) {
1357 doc.setProperty("uid","minor_version",0);
1360 doc.checkIn(VersioningOption.MINOR, null);
1365 // Set reposession to handle the document
1367 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1368 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
1369 handler.handle(Action.UPDATE, wrapDoc);
1370 repoSession.saveDocument(doc);
1372 handler.complete(Action.UPDATE, wrapDoc);
1373 } catch (BadRequestException bre) {
1375 } catch (DocumentException de) {
1377 } catch (CSWebApplicationException wae) {
1379 } catch (Exception e) {
1380 if (logger.isDebugEnabled()) {
1381 logger.debug("Caught exception ", e);
1383 throw new NuxeoDocumentException(e);
1385 if (repoSession != null) {
1386 releaseRepositorySession(ctx, repoSession);
1392 * Save a documentModel to the Nuxeo repository.
1394 * @param ctx service context under which this method is invoked
1395 * @param repoSession
1396 * @param docModel the document to save
1397 * @param fSaveSession if TRUE, will call CoreSessionInterface.save() to save
1398 * accumulated changes.
1399 * @throws ClientException
1400 * @throws DocumentException
1402 public void saveDocWithoutHandlerProcessing(
1403 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1404 CoreSessionInterface repoSession,
1405 DocumentModel docModel,
1406 boolean fSaveSession)
1407 throws ClientException, DocumentException {
1410 repoSession.saveDocument(docModel);
1414 } catch (ClientException ce) {
1416 } catch (Exception e) {
1417 if (logger.isDebugEnabled()) {
1418 logger.debug("Caught exception ", e);
1420 throw new NuxeoDocumentException(e);
1425 * Save a list of documentModels to the Nuxeo repository.
1427 * @param ctx service context under which this method is invoked
1428 * @param repoSession a repository session
1429 * @param docModelList a list of document models
1430 * @param fSaveSession if TRUE, will call CoreSessionInterface.save() to save
1431 * accumulated changes.
1432 * @throws ClientException
1433 * @throws DocumentException
1435 public void saveDocListWithoutHandlerProcessing(
1436 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1437 CoreSessionInterface repoSession,
1438 DocumentModelList docList,
1439 boolean fSaveSession)
1440 throws ClientException, DocumentException {
1442 DocumentModel[] docModelArray = new DocumentModel[docList.size()];
1443 repoSession.saveDocuments(docList.toArray(docModelArray));
1447 } catch (ClientException ce) {
1449 } catch (Exception e) {
1450 logger.error("Caught exception ", e);
1451 throw new NuxeoDocumentException(e);
1456 * delete a document from the Nuxeo repository
1458 * @param ctx service context under which this method is invoked
1459 * @param id of the document
1460 * @throws DocumentException
1463 public void delete(ServiceContext ctx, String id, DocumentHandler handler) throws DocumentNotFoundException,
1464 DocumentException, TransactionException {
1466 throw new IllegalArgumentException(
1467 "delete(ctx, ix, handler): ctx is missing");
1469 if (handler == null) {
1470 throw new IllegalArgumentException(
1471 "delete(ctx, ix, handler): handler is missing");
1473 if (logger.isDebugEnabled()) {
1474 logger.debug("Deleting document with CSID=" + id);
1476 CoreSessionInterface repoSession = null;
1478 handler.prepare(Action.DELETE);
1479 repoSession = getRepositorySession(ctx);
1480 DocumentWrapper<DocumentModel> wrapDoc = null;
1482 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
1483 wrapDoc = new DocumentWrapperImpl<DocumentModel>(repoSession.getDocument(docRef));
1484 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1485 handler.handle(Action.DELETE, wrapDoc);
1486 repoSession.removeDocument(docRef);
1487 } catch (ClientException ce) {
1488 String msg = logException(ce, "Could not find document to delete with CSID=" + id);
1489 throw new DocumentNotFoundException(msg, ce);
1492 handler.complete(Action.DELETE, wrapDoc);
1493 } catch (DocumentException de) {
1495 } catch (Exception e) {
1496 if (logger.isDebugEnabled()) {
1497 logger.debug("Caught exception ", e);
1499 throw new NuxeoDocumentException(e);
1501 if (repoSession != null) {
1502 releaseRepositorySession(ctx, repoSession);
1508 * @see org.collectionspace.services.common.storage.StorageClient#delete(org.collectionspace.services.common.context.ServiceContext, java.lang.String, org.collectionspace.services.common.document.DocumentHandler)
1512 public void delete(@SuppressWarnings("rawtypes") ServiceContext ctx, String id)
1513 throws DocumentNotFoundException, DocumentException {
1514 throw new UnsupportedOperationException();
1515 // Use the other delete instead
1519 public Hashtable<String, String> retrieveWorkspaceIds(RepositoryDomainType repoDomain) throws Exception {
1520 return NuxeoConnectorEmbedded.getInstance().retrieveWorkspaceIds(repoDomain);
1524 public String createDomain(RepositoryDomainType repositoryDomain) throws Exception {
1525 CoreSessionInterface repoSession = null;
1526 String domainId = null;
1529 // Open a connection to the domain's repo/db
1531 String repoName = repositoryDomain.getRepositoryName();
1532 repoSession = getRepositorySession(repoName); // domainName=storageName=repoName=databaseName
1534 // First create the top-level domain directory
1536 String domainName = repositoryDomain.getStorageName();
1537 DocumentRef parentDocRef = new PathRef("/");
1538 DocumentModel parentDoc = repoSession.getDocument(parentDocRef);
1539 DocumentModel domainDoc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1540 domainName, NUXEO_CORE_TYPE_DOMAIN);
1541 domainDoc.setPropertyValue("dc:title", domainName);
1542 domainDoc.setPropertyValue("dc:description", "A CollectionSpace domain "
1544 domainDoc = repoSession.createDocument(domainDoc);
1545 domainId = domainDoc.getId();
1548 // Next, create a "Workspaces" root directory to contain the workspace folders for the individual service documents
1550 DocumentModel workspacesRoot = repoSession.createDocumentModel(domainDoc.getPathAsString(),
1551 NuxeoUtils.Workspaces, NUXEO_CORE_TYPE_WORKSPACEROOT);
1552 workspacesRoot.setPropertyValue("dc:title", NuxeoUtils.Workspaces);
1553 workspacesRoot.setPropertyValue("dc:description", "A CollectionSpace workspaces directory for "
1554 + domainDoc.getPathAsString());
1555 workspacesRoot = repoSession.createDocument(workspacesRoot);
1556 String workspacesRootId = workspacesRoot.getId();
1559 if (logger.isDebugEnabled()) {
1560 logger.debug("Created tenant domain name=" + domainName
1561 + " id=" + domainId + " "
1562 + NuxeoUtils.Workspaces + " id=" + workspacesRootId);
1563 logger.debug("Path to Domain: " + domainDoc.getPathAsString());
1564 logger.debug("Path to Workspaces root: " + workspacesRoot.getPathAsString());
1566 } catch (Exception e) {
1567 if (logger.isDebugEnabled()) {
1568 logger.debug("Could not create tenant domain name=" + repositoryDomain.getStorageName() + " caught exception ", e);
1572 if (repoSession != null) {
1573 releaseRepositorySession(null, repoSession);
1581 public String getDomainId(RepositoryDomainType repositoryDomain) throws Exception {
1582 String domainId = null;
1583 CoreSessionInterface repoSession = null;
1585 String repoName = repositoryDomain.getRepositoryName();
1586 String domainStorageName = repositoryDomain.getStorageName();
1587 if (domainStorageName != null && !domainStorageName.isEmpty()) {
1589 repoSession = getRepositorySession(repoName);
1590 DocumentRef docRef = new PathRef("/" + domainStorageName);
1591 DocumentModel domain = repoSession.getDocument(docRef);
1592 domainId = domain.getId();
1593 } catch (Exception e) {
1594 if (logger.isTraceEnabled()) {
1595 logger.trace("Caught exception ", e); // The document doesn't exist, this let's us know we need to create it
1597 //there is no way to identify if document does not exist due to
1598 //lack of typed exception for getDocument method
1601 if (repoSession != null) {
1602 releaseRepositorySession(null, repoSession);
1611 * Returns the workspaces root directory for a given domain.
1613 private DocumentModel getWorkspacesRoot(CoreSessionInterface repoSession,
1614 String domainName) throws Exception {
1615 DocumentModel result = null;
1617 String domainPath = "/" + domainName;
1618 DocumentRef parentDocRef = new PathRef(domainPath);
1619 DocumentModelList domainChildrenList = repoSession.getChildren(
1621 Iterator<DocumentModel> witer = domainChildrenList.iterator();
1622 while (witer.hasNext()) {
1623 DocumentModel childNode = witer.next();
1624 if (NuxeoUtils.Workspaces.equalsIgnoreCase(childNode.getName())) {
1626 logger.trace("Found workspaces directory at: " + result.getPathAsString());
1631 if (result == null) {
1632 throw new ClientException("Could not find workspace root directory in: "
1640 * @see org.collectionspace.services.common.repository.RepositoryClient#createWorkspace(java.lang.String, java.lang.String)
1643 public String createWorkspace(RepositoryDomainType repositoryDomain, String workspaceName) throws Exception {
1644 CoreSessionInterface repoSession = null;
1645 String workspaceId = null;
1647 String repoName = repositoryDomain.getRepositoryName();
1648 repoSession = getRepositorySession(repoName);
1650 String domainStorageName = repositoryDomain.getStorageName();
1651 DocumentModel parentDoc = getWorkspacesRoot(repoSession, domainStorageName);
1652 if (logger.isTraceEnabled()) {
1653 for (String facet : parentDoc.getFacets()) {
1654 logger.trace("Facet: " + facet);
1658 DocumentModel doc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1659 workspaceName, NuxeoUtils.WORKSPACE_DOCUMENT_TYPE);
1660 doc.setPropertyValue("dc:title", workspaceName);
1661 doc.setPropertyValue("dc:description", "A CollectionSpace workspace for "
1663 doc = repoSession.createDocument(doc);
1664 workspaceId = doc.getId();
1666 if (logger.isDebugEnabled()) {
1667 logger.debug("Created workspace name=" + workspaceName
1668 + " id=" + workspaceId);
1670 } catch (Exception e) {
1671 if (logger.isDebugEnabled()) {
1672 logger.debug("createWorkspace caught exception ", e);
1676 if (repoSession != null) {
1677 releaseRepositorySession(null, repoSession);
1684 * @see org.collectionspace.services.common.repository.RepositoryClient#getWorkspaceId(java.lang.String, java.lang.String)
1688 public String getWorkspaceId(String tenantDomain, String workspaceName) throws Exception {
1689 String workspaceId = null;
1691 CoreSessionInterface repoSession = null;
1693 repoSession = getRepositorySession((ServiceContext<PoxPayloadIn, PoxPayloadOut>) null);
1694 DocumentRef docRef = new PathRef(
1696 + "/" + NuxeoUtils.Workspaces
1697 + "/" + workspaceName);
1698 DocumentModel workspace = repoSession.getDocument(docRef);
1699 workspaceId = workspace.getId();
1700 } catch (DocumentException de) {
1702 } catch (Exception e) {
1703 if (logger.isDebugEnabled()) {
1704 logger.debug("Caught exception ", e);
1706 throw new NuxeoDocumentException(e);
1708 if (repoSession != null) {
1709 releaseRepositorySession(null, repoSession);
1716 public CoreSessionInterface getRepositorySession(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) throws Exception {
1717 return getRepositorySession(ctx, ctx.getRepositoryName(), ctx.getTimeoutSecs());
1720 public CoreSessionInterface getRepositorySession(String repoName) throws Exception {
1721 return getRepositorySession(null, repoName, ServiceContext.DEFAULT_TX_TIMEOUT);
1725 * Gets the repository session. - Package access only. If the 'ctx' param is
1726 * null then the repo name must be non-mull and vice-versa
1728 * @return the repository session
1729 * @throws Exception the exception
1731 public CoreSessionInterface getRepositorySession(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1733 int timeoutSeconds) throws Exception {
1734 CoreSessionInterface repoSession = null;
1736 Profiler profiler = new Profiler("getRepositorySession():", 2);
1739 // To get a connection to the Nuxeo repo, we need either a valid ServiceContext instance or a repository name
1742 repoName = ctx.getRepositoryName(); // Notice we are overriding the passed in 'repoName' since we have a valid service context passed in to us
1743 repoSession = (CoreSessionInterface) ctx.getCurrentRepositorySession(); // Look to see if one exists in the context before creating one
1744 } else if (repoName == null || repoName.trim().isEmpty()) {
1745 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.");
1746 logger.error(errMsg);
1747 throw new Exception(errMsg);
1750 // 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
1751 // just the repo name
1753 if (repoSession == null) {
1754 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1755 repoSession = client.openRepository(repoName, timeoutSeconds);
1757 if (logger.isDebugEnabled() == true) {
1758 logger.warn("Reusing the current context's repository session.");
1763 if (logger.isTraceEnabled()) {
1764 logger.trace("Testing call to getRepository() repository root: " + repoSession.getRootDocument());
1766 } catch (Throwable e) {
1767 logger.trace("Test call to Nuxeo's getRepository() repository root failed", e);
1773 ctx.setCurrentRepositorySession(repoSession); // For reusing, save the repository session in the current service context
1780 * Release repository session. - Package access only.
1782 * @param repoSession the repo session
1784 public void releaseRepositorySession(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, CoreSessionInterface repoSession) throws TransactionException {
1786 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1789 ctx.clearCurrentRepositorySession(); //clear the current context of the now closed repo session
1790 if (ctx.getCurrentRepositorySession() == null) {
1791 client.releaseRepository(repoSession); //release the repo session if the service context's ref count is zeo.
1794 client.releaseRepository(repoSession); //repo session was acquired without a service context
1796 } catch (TransactionRuntimeException tre) {
1797 String causeMsg = null;
1798 Throwable cause = tre.getCause();
1799 if (cause != null) {
1800 causeMsg = cause.getMessage();
1803 TransactionException te; // a CollectionSpace specific tx exception
1804 if (causeMsg != null) {
1805 te = new TransactionException(causeMsg, tre);
1807 te = new TransactionException(tre);
1810 logger.error(te.getMessage(), tre); // Log the standard transaction exception message, plus an exception-specific stack trace
1812 } catch (Exception e) {
1813 logger.error("Could not close the repository session.", e);
1814 // no need to throw this service specific exception
1819 public void doWorkflowTransition(ServiceContext ctx, String id,
1820 DocumentHandler handler, TransitionDef transitionDef)
1821 throws BadRequestException, DocumentNotFoundException,
1823 // 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
1826 private String handleProvidedStartingWildcard(String partialTerm) {
1827 if (Tools.notBlank(partialTerm)) {
1828 if (partialTerm.substring(0, 1).equals(USER_SUPPLIED_WILDCARD)) {
1829 StringBuffer buffer = new StringBuffer(partialTerm);
1830 buffer.setCharAt(0, JDBCTools.SQL_WILDCARD.charAt(0));
1831 partialTerm = buffer.toString();
1838 * Replaces user-supplied wildcards with SQL wildcards, in a partial term
1839 * matching search expression.
1841 * The scope of this replacement excludes the beginning character
1842 * in that search expression, as that character is treated specially.
1844 * @param partialTerm
1845 * @return the partial term, with any user-supplied wildcards replaced
1848 private String subtituteWildcardsInPartialTerm(String partialTerm) {
1849 if (Tools.isBlank(partialTerm)) {
1852 if (! partialTerm.contains(USER_SUPPLIED_WILDCARD)) {
1855 int len = partialTerm.length();
1856 // Partial term search expressions of 2 or fewer characters
1857 // currently aren't amenable to the use of wildcards
1859 logger.warn("Partial term match search expression of just 1-2 characters in length contains a user-supplied wildcard: " + partialTerm);
1860 logger.warn("Will handle that character as a literal value, rather than as a wildcard ...");
1863 return partialTerm.substring(0, 1) // first char
1864 + partialTerm.substring(1, len).replaceAll(USER_SUPPLIED_WILDCARD_REGEX, JDBCTools.SQL_WILDCARD);
1868 private int getMaxItemsLimitOnJdbcQueries(String maxListItemsLimit) {
1869 final int DEFAULT_ITEMS_LIMIT = 40;
1870 if (maxListItemsLimit == null) {
1871 return DEFAULT_ITEMS_LIMIT;
1875 itemsLimit = Integer.parseInt(maxListItemsLimit);
1876 if (itemsLimit < 1) {
1877 logger.warn("Value of configuration setting "
1878 + IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES
1879 + " must be a positive integer; invalid current value is " + maxListItemsLimit);
1880 logger.warn("Reverting to default value of " + DEFAULT_ITEMS_LIMIT);
1881 itemsLimit = DEFAULT_ITEMS_LIMIT;
1883 } catch (NumberFormatException nfe) {
1884 logger.warn("Value of configuration setting "
1885 + IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES
1886 + " must be a positive integer; invalid current value is " + maxListItemsLimit);
1887 logger.warn("Reverting to default value of " + DEFAULT_ITEMS_LIMIT);
1888 itemsLimit = DEFAULT_ITEMS_LIMIT;
1894 * Identifies whether a restriction on tenant ID - to return only records
1895 * pertaining to the current tenant - is required in a JDBC query.
1897 * @param tenantBinding a tenant binding configuration.
1898 * @param ctx a service context.
1899 * @return true if a restriction on tenant ID is required in the query;
1900 * false if a restriction is not required.
1902 private boolean restrictJDBCQueryByTenantID(TenantBindingType tenantBinding, ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
1903 boolean restrict = true;
1904 // If data for the current service, in the current tenant, is isolated
1905 // within its own separate, per-tenant repository, as contrasted with
1906 // being intermingled with other tenants' data in the default repository,
1907 // no restriction on Tenant ID is required in the query.
1908 String repositoryDomainName = ConfigUtils.getRepositoryName(tenantBinding, ctx.getRepositoryDomainName());
1909 if (!(repositoryDomainName.equals(ConfigUtils.DEFAULT_NUXEO_REPOSITORY_NAME))) {
1912 // If a configuration setting for this tenant identifies that JDBC
1913 // queries should not be restricted by tenant ID (perhaps because
1914 // there is always expected to be only one tenant's data present in
1915 // the system), no restriction on Tenant ID is required in the query.
1916 String queriesRestrictedByTenantId = TenantBindingUtils.getPropertyValue(tenantBinding,
1917 IQueryManager.JDBC_QUERIES_ARE_TENANT_ID_RESTRICTED);
1918 if (Tools.notBlank(queriesRestrictedByTenantId) &&
1919 queriesRestrictedByTenantId.equalsIgnoreCase(Boolean.FALSE.toString())) {