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.CSReindexFulltextRoot;
37 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
38 import org.collectionspace.services.client.CollectionSpaceClient;
39 import org.collectionspace.services.client.IQueryManager;
40 import org.collectionspace.services.client.PoxPayloadIn;
41 import org.collectionspace.services.client.PoxPayloadOut;
42 import org.collectionspace.services.client.Profiler;
43 import org.collectionspace.services.client.workflow.WorkflowClient;
44 import org.collectionspace.services.common.context.ServiceContext;
45 import org.collectionspace.services.common.query.QueryContext;
46 import org.collectionspace.services.common.repository.RepositoryClient;
47 import org.collectionspace.services.common.storage.JDBCTools;
48 import org.collectionspace.services.common.storage.PreparedStatementSimpleBuilder;
49 import org.collectionspace.services.common.document.BadRequestException;
50 import org.collectionspace.services.common.document.DocumentException;
51 import org.collectionspace.services.common.document.DocumentFilter;
52 import org.collectionspace.services.common.document.DocumentHandler;
53 import org.collectionspace.services.common.document.DocumentNotFoundException;
54 import org.collectionspace.services.common.document.DocumentHandler.Action;
55 import org.collectionspace.services.common.document.DocumentWrapper;
56 import org.collectionspace.services.common.document.DocumentWrapperImpl;
57 import org.collectionspace.services.common.document.TransactionException;
58 import org.collectionspace.services.common.CSWebApplicationException;
59 import org.collectionspace.services.common.ServiceMain;
60 import org.collectionspace.services.common.api.Tools;
61 import org.collectionspace.services.common.config.ConfigUtils;
62 import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl;
63 import org.collectionspace.services.common.config.TenantBindingUtils;
64 import org.collectionspace.services.common.storage.PreparedStatementBuilder;
65 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.AuthorityItemSpecifier;
66 import org.collectionspace.services.config.tenant.TenantBindingType;
67 import org.collectionspace.services.config.tenant.RepositoryDomainType;
70 // CSPACE-5036 - How to make CMISQL queries from Nuxeo
72 import org.apache.chemistry.opencmis.commons.enums.CmisVersion;
73 import org.apache.chemistry.opencmis.commons.server.CallContext;
74 import org.apache.chemistry.opencmis.server.impl.CallContextImpl;
75 import org.apache.chemistry.opencmis.server.shared.ThresholdOutputStreamFactory;
76 import org.nuxeo.common.utils.IdUtils;
77 import org.nuxeo.ecm.core.api.ClientException;
78 import org.nuxeo.ecm.core.api.DocumentModel;
79 import org.nuxeo.ecm.core.api.DocumentModelList;
80 import org.nuxeo.ecm.core.api.IterableQueryResult;
81 import org.nuxeo.ecm.core.api.VersioningOption;
82 import org.nuxeo.ecm.core.api.impl.DocumentModelListImpl;
83 import org.nuxeo.ecm.core.api.DocumentRef;
84 import org.nuxeo.ecm.core.api.IdRef;
85 import org.nuxeo.ecm.core.api.PathRef;
86 import org.nuxeo.runtime.transaction.TransactionRuntimeException;
87 import org.nuxeo.ecm.core.opencmis.bindings.NuxeoCmisServiceFactory;
88 import org.nuxeo.ecm.core.opencmis.impl.server.NuxeoCmisService;
89 import org.slf4j.Logger;
90 import org.slf4j.LoggerFactory;
93 * RepositoryClientImpl is used to perform CRUD operations on documents in Nuxeo
94 * repository using Remote Java APIs. It uses
96 * @see DocumentHandler as IOHandler with the client.
98 * $LastChangedRevision: $ $LastChangedDate: $
100 public class NuxeoRepositoryClientImpl implements RepositoryClient<PoxPayloadIn, PoxPayloadOut> {
105 private final Logger logger = LoggerFactory.getLogger(NuxeoRepositoryClientImpl.class);
106 // private final Logger profilerLogger = LoggerFactory.getLogger("remperf");
107 // private String foo = Profiler.createLogger();
108 public static final String NUXEO_CORE_TYPE_DOMAIN = "Domain";
109 public static final String NUXEO_CORE_TYPE_WORKSPACEROOT = "WorkspaceRoot";
110 // FIXME: Get this value from an existing constant, if available
111 public static final String BACKSLASH = "\\";
112 public static final String USER_SUPPLIED_WILDCARD = "*";
113 public static final String USER_SUPPLIED_WILDCARD_REGEX = BACKSLASH + USER_SUPPLIED_WILDCARD;
114 public static final String USER_SUPPLIED_ANCHOR_CHAR = "^";
115 public static final String USER_SUPPLIED_ANCHOR_CHAR_REGEX = BACKSLASH + USER_SUPPLIED_ANCHOR_CHAR;
116 public static final String ENDING_ANCHOR_CHAR = "$";
117 public static final String ENDING_ANCHOR_CHAR_REGEX = BACKSLASH + ENDING_ANCHOR_CHAR;
121 * Instantiates a new repository java client impl.
123 public NuxeoRepositoryClientImpl() {
127 public void assertWorkflowState(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, DocumentModel docModel) throws DocumentNotFoundException, ClientException {
128 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
129 if (queryParams != null) {
131 // Look for the workflow "delete" query param and see if we need to assert that the
132 // docModel is in a non-deleted workflow state.
134 String currentState = docModel.getCurrentLifeCycleState();
135 String includeDeletedStr = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_NONDELETED);
136 boolean includeDeleted = (includeDeletedStr == null) ? true : Boolean.parseBoolean(includeDeletedStr);
137 if (includeDeleted == false) {
139 // We don't wanted soft-deleted objects, so throw an exception if this one is soft-deleted.
141 if (currentState.contains(WorkflowClient.WORKFLOWSTATE_DELETED)) {
142 String msg = "The GET assertion that docModel not be in 'deleted' workflow state failed.";
144 throw new DocumentNotFoundException(msg);
151 * create document in the Nuxeo repository
153 * @param ctx service context under which this method is invoked
154 * @param handler should be used by the caller to provide and transform the
156 * @return id in repository of the newly created document
157 * @throws BadRequestException
158 * @throws TransactionException
159 * @throws DocumentException
162 public String create(ServiceContext ctx,
163 DocumentHandler handler) throws BadRequestException,
164 TransactionException, DocumentException {
166 String docType = NuxeoUtils.getTenantQualifiedDocType(ctx); //ctx.getDocumentType();
167 if (docType == null) {
168 throw new IllegalArgumentException(
169 "RepositoryJavaClient.create: docType is missing");
172 if (handler == null) {
173 throw new IllegalArgumentException(
174 "RepositoryJavaClient.create: handler is missing");
176 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
177 if (nuxeoWspaceId == null) {
178 throw new DocumentNotFoundException(
179 "Unable to find workspace for service " + ctx.getServiceName()
180 + " check if the workspace exists in the Nuxeo repository");
183 CoreSessionInterface repoSession = null;
185 handler.prepare(Action.CREATE);
186 repoSession = getRepositorySession(ctx);
187 DocumentRef nuxeoWspace = new IdRef(nuxeoWspaceId);
188 DocumentModel wspaceDoc = repoSession.getDocument(nuxeoWspace);
189 String wspacePath = wspaceDoc.getPathAsString();
190 //give our own ID so PathRef could be constructed later on
191 String id = IdUtils.generateId(UUID.randomUUID().toString());
192 // create document model
193 DocumentModel doc = repoSession.createDocumentModel(wspacePath, id, docType);
194 /* Check for a versioned document, and check In and Out before we proceed.
195 * This does not work as we do not have the uid schema on our docs.
196 if(((DocumentModelHandler) handler).supportsVersioning()) {
197 doc.setProperty("uid","major_version",1);
198 doc.setProperty("uid","minor_version",0);
201 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
202 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
203 handler.handle(Action.CREATE, wrapDoc);
204 // create document with documentmodel
205 doc = repoSession.createDocument(doc);
207 // TODO for sub-docs need to call into the handler to let it deal with subitems. Pass in the id,
208 // and assume the handler has the state it needs (doc fragments).
209 handler.complete(Action.CREATE, wrapDoc);
211 } catch (BadRequestException bre) {
212 rollbackTransaction(repoSession);
214 } catch (Throwable e) {
215 rollbackTransaction(repoSession);
216 if (logger.isDebugEnabled()) {
217 logger.debug("Call to low-level Nuxeo document create call failed: ", e);
219 throw new NuxeoDocumentException(e);
221 if (repoSession != null) {
222 releaseRepositorySession(ctx, repoSession);
228 public boolean reindex(DocumentHandler handler, String indexid) throws DocumentNotFoundException, DocumentException
230 return reindex(handler, null, indexid);
234 public boolean reindex(DocumentHandler handler, String csid, String indexid) throws DocumentNotFoundException, DocumentException
236 boolean result = true;
237 CoreSessionInterface repoSession = null;
238 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = handler.getServiceContext();
241 String queryString = handler.getDocumentsToIndexQuery(indexid, csid);
242 repoSession = getRepositorySession(ctx);
243 CSReindexFulltextRoot indexer = new CSReindexFulltextRoot(repoSession);
244 indexer.reindexFulltext(0, 0, queryString);
246 // Set repository session to handle the document
248 } catch (Throwable e) {
249 rollbackTransaction(repoSession);
250 if (logger.isDebugEnabled()) {
251 logger.debug("Caught exception trying to reindex Nuxeo repository ", e);
253 throw new NuxeoDocumentException(e);
255 if (repoSession != null) {
256 releaseRepositorySession(ctx, repoSession);
264 public boolean synchronize(ServiceContext ctx, Object specifier, DocumentHandler handler)
265 throws DocumentNotFoundException, TransactionException, DocumentException {
266 boolean result = false;
268 if (handler == null) {
269 throw new IllegalArgumentException("RepositoryJavaClient.get: handler is missing");
272 CoreSessionInterface repoSession = null;
274 handler.prepare(Action.SYNC);
275 repoSession = getRepositorySession(ctx);
276 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
277 DocumentWrapper<Object> wrapDoc = new DocumentWrapperImpl<Object>(specifier);
278 result = handler.handle(Action.SYNC, wrapDoc);
279 handler.complete(Action.SYNC, wrapDoc);
280 } catch (IllegalArgumentException iae) {
281 rollbackTransaction(repoSession);
283 } catch (DocumentException de) {
284 rollbackTransaction(repoSession);
286 } catch (Throwable e) {
287 rollbackTransaction(repoSession);
288 if (logger.isDebugEnabled()) {
289 logger.debug("Caught exception ", e);
291 throw new NuxeoDocumentException(e);
293 if (repoSession != null) {
294 releaseRepositorySession(ctx, repoSession);
302 public boolean synchronizeItem(ServiceContext ctx, AuthorityItemSpecifier itemSpecifier, DocumentHandler handler)
303 throws DocumentNotFoundException, TransactionException, DocumentException {
304 boolean result = false;
306 if (handler == null) {
307 throw new IllegalArgumentException(
308 "RepositoryJavaClient.get: handler is missing");
311 CoreSessionInterface repoSession = null;
313 handler.prepare(Action.SYNC);
314 repoSession = getRepositorySession(ctx);
315 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
316 DocumentWrapper<AuthorityItemSpecifier> wrapDoc = new DocumentWrapperImpl<AuthorityItemSpecifier>(itemSpecifier);
317 result = handler.handle(Action.SYNC, wrapDoc);
318 handler.complete(Action.SYNC, wrapDoc);
319 } catch (IllegalArgumentException iae) {
320 rollbackTransaction(repoSession);
322 } catch (DocumentException de) {
323 rollbackTransaction(repoSession);
325 } catch (Throwable e) {
326 rollbackTransaction(repoSession);
327 throw new NuxeoDocumentException(e);
329 if (repoSession != null) {
330 releaseRepositorySession(ctx, repoSession);
338 * get document from the Nuxeo repository
340 * @param ctx service context under which this method is invoked
341 * @param id of the document to retrieve
342 * @param handler should be used by the caller to provide and transform the
344 * @throws DocumentNotFoundException if the document cannot be found in the
346 * @throws TransactionException
347 * @throws DocumentException
350 public void get(ServiceContext ctx, String id, DocumentHandler handler)
351 throws DocumentNotFoundException, TransactionException, DocumentException {
353 if (handler == null) {
354 throw new IllegalArgumentException(
355 "RepositoryJavaClient.get: handler is missing");
358 CoreSessionInterface repoSession = null;
360 handler.prepare(Action.GET);
361 repoSession = getRepositorySession(ctx);
362 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
363 DocumentModel docModel = null;
365 docModel = repoSession.getDocument(docRef);
366 assertWorkflowState(ctx, docModel);
367 } catch (org.nuxeo.ecm.core.api.DocumentNotFoundException ce) {
368 String msg = logException(ce,
369 String.format("Could not find %s resource/record with CSID=%s", ctx.getDocumentType(), id));
370 throw new DocumentNotFoundException(msg, ce);
373 // Set repository session to handle the document
375 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
376 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(docModel);
377 handler.handle(Action.GET, wrapDoc);
378 handler.complete(Action.GET, wrapDoc);
379 } catch (IllegalArgumentException iae) {
381 } catch (DocumentException de) {
382 if (logger.isDebugEnabled()) {
383 logger.debug(de.getMessage(), de);
386 } catch (Throwable e) {
387 if (logger.isDebugEnabled()) {
388 logger.debug("Caught exception ", e);
390 throw new NuxeoDocumentException(e);
392 if (repoSession != null) {
393 releaseRepositorySession(ctx, repoSession);
399 * get a document from the Nuxeo repository, using the docFilter params.
401 * @param ctx service context under which this method is invoked
402 * @param handler should be used by the caller to provide and transform the
403 * document. Handler must have a docFilter set to return a single item.
404 * @throws DocumentNotFoundException if the document cannot be found in the
406 * @throws TransactionException
407 * @throws DocumentException
410 public void get(ServiceContext ctx, DocumentHandler handler)
411 throws DocumentNotFoundException, TransactionException, DocumentException {
412 QueryContext queryContext = new QueryContext(ctx, handler);
413 CoreSessionInterface repoSession = null;
416 handler.prepare(Action.GET);
417 repoSession = getRepositorySession(ctx);
419 DocumentModelList docList = null;
420 // force limit to 1, and ignore totalSize
421 String query = NuxeoUtils.buildNXQLQuery(queryContext);
422 docList = repoSession.query(query, null, 1, 0, false);
423 if (docList.size() != 1) {
424 throw new DocumentNotFoundException("No document found matching filter params: " + query);
426 DocumentModel doc = docList.get(0);
428 if (logger.isDebugEnabled()) {
429 logger.debug("Executed NXQL query: " + query);
432 //set reposession to handle the document
433 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
434 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
435 handler.handle(Action.GET, wrapDoc);
436 handler.complete(Action.GET, wrapDoc);
437 } catch (IllegalArgumentException iae) {
439 } catch (DocumentException de) {
441 } catch (Throwable e) {
442 if (logger.isDebugEnabled()) {
443 logger.debug("Caught exception ", e);
445 throw new NuxeoDocumentException(e);
447 if (repoSession != null) {
448 releaseRepositorySession(ctx, repoSession);
453 public DocumentWrapper<DocumentModel> getDoc(
454 CoreSessionInterface repoSession,
455 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
456 String csid) throws DocumentNotFoundException, DocumentException {
457 DocumentWrapper<DocumentModel> wrapDoc = null;
460 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
461 DocumentModel doc = null;
463 doc = repoSession.getDocument(docRef);
464 } catch (ClientException ce) {
465 String msg = logException(ce, "Could not find document with CSID=" + csid);
466 throw new DocumentNotFoundException(msg, ce);
468 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
469 } catch (IllegalArgumentException iae) {
471 } catch (DocumentException de) {
479 * Get wrapped documentModel from the Nuxeo repository. The search is
480 * restricted to the workspace of the current context.
482 * @param ctx service context under which this method is invoked
483 * @param csid of the document to retrieve
484 * @throws DocumentNotFoundException
485 * @throws TransactionException
486 * @throws DocumentException
487 * @return a wrapped documentModel
490 public DocumentWrapper<DocumentModel> getDoc(
491 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
492 String csid) throws DocumentNotFoundException, TransactionException, DocumentException {
493 CoreSessionInterface repoSession = null;
494 DocumentWrapper<DocumentModel> wrapDoc = null;
497 // Open a new repository session
498 repoSession = getRepositorySession(ctx);
499 wrapDoc = getDoc(repoSession, ctx, csid);
500 } catch (IllegalArgumentException iae) {
502 } catch (DocumentException de) {
504 } catch (Exception e) {
505 if (logger.isDebugEnabled()) {
506 logger.debug("Caught exception ", e);
508 throw new NuxeoDocumentException(e);
510 if (repoSession != null) {
511 releaseRepositorySession(ctx, repoSession);
515 if (logger.isWarnEnabled() == true) {
516 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
521 public DocumentWrapper<DocumentModel> findDoc(
522 CoreSessionInterface repoSession,
523 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
525 throws DocumentNotFoundException, DocumentException {
526 DocumentWrapper<DocumentModel> wrapDoc = null;
529 QueryContext queryContext = new QueryContext(ctx, whereClause);
530 DocumentModelList docList = null;
531 // force limit to 1, and ignore totalSize
532 String query = NuxeoUtils.buildNXQLQuery(queryContext);
533 docList = repoSession.query(query,
538 if (docList.size() != 1) {
539 if (logger.isDebugEnabled()) {
540 logger.debug("findDoc: Query found: " + docList.size() + " items.");
541 logger.debug(" Query: " + query);
543 throw new DocumentNotFoundException("No document found matching filter params: " + query);
545 DocumentModel doc = docList.get(0);
546 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
547 } catch (IllegalArgumentException iae) {
549 } catch (DocumentException de) {
551 } catch (Exception e) {
552 if (logger.isDebugEnabled()) {
553 logger.debug("Caught exception ", e);
555 throw new NuxeoDocumentException(e);
562 * find wrapped documentModel from the Nuxeo repository
564 * @param ctx service context under which this method is invoked
565 * @param whereClause where NXQL where clause to get the document
566 * @throws DocumentNotFoundException
567 * @throws TransactionException
568 * @throws DocumentException
569 * @return a wrapped documentModel retrieved by the repository query
572 public DocumentWrapper<DocumentModel> findDoc(
573 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
575 throws DocumentNotFoundException, TransactionException, DocumentException {
576 CoreSessionInterface repoSession = null;
577 DocumentWrapper<DocumentModel> wrapDoc = null;
580 repoSession = getRepositorySession(ctx);
581 wrapDoc = findDoc(repoSession, ctx, whereClause);
582 } catch (DocumentNotFoundException dnfe) {
584 } catch (DocumentException de) {
586 } catch (Exception e) {
587 if (repoSession == null) {
588 throw new NuxeoDocumentException("Unable to create a Nuxeo repository session.", e);
590 throw new NuxeoDocumentException("Unexpected Nuxeo exception.", e);
593 if (repoSession != null) {
594 releaseRepositorySession(ctx, repoSession);
598 if (logger.isWarnEnabled() == true) {
599 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
606 * find doc and return CSID from the Nuxeo repository
609 * @param ctx service context under which this method is invoked
610 * @param whereClause where NXQL where clause to get the document
611 * @throws DocumentNotFoundException
612 * @throws TransactionException
613 * @throws DocumentException
614 * @return the CollectionSpace ID (CSID) of the requested document
617 public String findDocCSID(CoreSessionInterface repoSession,
618 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String whereClause)
619 throws DocumentNotFoundException, TransactionException, DocumentException {
621 boolean releaseSession = false;
623 if (repoSession == null) {
624 repoSession = this.getRepositorySession(ctx);
625 releaseSession = true;
627 DocumentWrapper<DocumentModel> wrapDoc = findDoc(repoSession, ctx, whereClause);
628 DocumentModel docModel = wrapDoc.getWrappedObject();
629 csid = NuxeoUtils.getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
630 } catch (DocumentNotFoundException dnfe) {
632 } catch (IllegalArgumentException iae) {
634 } catch (DocumentException de) {
636 } catch (Exception e) {
637 if (logger.isDebugEnabled()) {
638 logger.debug("Caught exception ", e);
640 throw new NuxeoDocumentException(e);
642 if (releaseSession && (repoSession != null)) {
643 this.releaseRepositorySession(ctx, repoSession);
649 public DocumentWrapper<DocumentModelList> findDocs(
650 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
651 CoreSessionInterface repoSession,
652 List<String> docTypes,
654 String orderByClause,
657 boolean computeTotal)
658 throws DocumentNotFoundException, DocumentException {
659 DocumentWrapper<DocumentModelList> wrapDoc = null;
662 if (docTypes == null || docTypes.size() < 1) {
663 throw new DocumentNotFoundException(
664 "The findDocs() method must specify at least one DocumentType.");
666 DocumentModelList docList = null;
667 QueryContext queryContext = new QueryContext(ctx, whereClause, orderByClause);
668 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
669 if (logger.isDebugEnabled()) {
670 logger.debug("findDocs() NXQL: " + query);
672 docList = repoSession.query(query, null, pageSize, pageSize * pageNum, computeTotal);
673 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
674 } catch (IllegalArgumentException iae) {
676 } catch (Exception e) {
677 if (logger.isDebugEnabled()) {
678 logger.debug("Caught exception ", e);
680 throw new NuxeoDocumentException(e);
686 protected static String buildInListForDocTypes(List<String> docTypes) {
687 StringBuilder sb = new StringBuilder();
689 boolean first = true;
690 for (String docType : docTypes) {
701 return sb.toString();
704 public DocumentWrapper<DocumentModelList> findDocs(
705 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
706 DocumentHandler handler,
707 CoreSessionInterface repoSession,
708 List<String> docTypes)
709 throws DocumentNotFoundException, DocumentException {
710 DocumentWrapper<DocumentModelList> wrapDoc = null;
712 DocumentFilter filter = handler.getDocumentFilter();
713 String oldOrderBy = filter.getOrderByClause();
714 if (isClauseEmpty(oldOrderBy) == true) {
715 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
717 QueryContext queryContext = new QueryContext(ctx, handler);
720 if (docTypes == null || docTypes.size() < 1) {
721 throw new DocumentNotFoundException(
722 "The findDocs() method must specify at least one DocumentType.");
724 DocumentModelList docList = null;
725 if (handler.isCMISQuery() == true) {
726 String inList = buildInListForDocTypes(docTypes);
727 ctx.getQueryParams().add(IQueryManager.SEARCH_RELATED_MATCH_OBJ_DOCTYPES, inList);
728 if (isSubjectOrObjectQuery(ctx)) {
729 docList = getFilteredCMISForSubjectOrObject(repoSession, ctx, handler, queryContext);
731 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
734 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
735 if (logger.isDebugEnabled()) {
736 logger.debug("findDocs() NXQL: " + query);
738 docList = repoSession.query(query, null, filter.getPageSize(), filter.getOffset(), true);
740 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
741 } catch (IllegalArgumentException iae) {
743 } catch (Exception e) {
744 if (logger.isDebugEnabled()) {
745 logger.debug("Caught exception ", e);
747 throw new NuxeoDocumentException(e);
753 private DocumentModelList getFilteredCMISForSubjectOrObject(CoreSessionInterface repoSession,
754 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, DocumentHandler handler, QueryContext queryContext) throws DocumentNotFoundException, DocumentException {
755 DocumentModelList result = null;
757 if (isSubjectOrObjectQuery(ctx) == true) {
758 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
759 String asEitherCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_EITHER);
761 queryParams.remove(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT);
762 queryParams.remove(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT);
765 // First query for subjectCsid results.
767 queryParams.addFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT, asEitherCsid);
768 DocumentModelList subjectDocList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
769 queryParams.remove(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT);
772 // Next query for objectCsid results.
774 queryParams.addFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT, asEitherCsid);
775 DocumentModelList objectDocList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
776 queryParams.remove(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT);
779 // Finally, combine the two results
781 result = mergeDocumentModelLists(subjectDocList, objectDocList);
787 private DocumentModelList mergeDocumentModelLists(DocumentModelList subjectDocList,
788 DocumentModelList objectDocList) {
789 DocumentModelList result = null;
791 if (subjectDocList == null || subjectDocList.isEmpty()) {
792 return objectDocList;
795 if (objectDocList == null || objectDocList.isEmpty()) {
796 return subjectDocList;
799 result = new DocumentModelListImpl();
801 // Add the subject list
802 Iterator<DocumentModel> iterator = subjectDocList.iterator();
803 while (iterator.hasNext()) {
804 DocumentModel dm = iterator.next();
805 addToResults(result, dm);
808 // Add the object list
809 iterator = objectDocList.iterator();
810 while (iterator.hasNext()) {
811 DocumentModel dm = iterator.next();
812 addToResults(result, dm);
815 // Set the 'totalSize' value for book keeping sake
816 ((DocumentModelListImpl) result).setTotalSize(result.size());
822 // Only add if it is not already in the list
823 private void addToResults(DocumentModelList result, DocumentModel dm) {
824 Iterator<DocumentModel> iterator = result.iterator();
825 boolean found = false;
827 while (iterator.hasNext()) {
828 DocumentModel existingDm = iterator.next();
829 if (existingDm.getId().equals(dm.getId())) {
835 if (found == false) {
840 private boolean isSubjectOrObjectQuery(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
841 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
842 String asEitherCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_EITHER);
843 return asEitherCsid != null && !asEitherCsid.isEmpty();
847 * Find a list of documentModels from the Nuxeo repository
849 * @param docTypes a list of DocType names to match
850 * @param whereClause where the clause to qualify on
851 * @throws DocumentNotFoundException
852 * @throws TransactionException
853 * @throws DocumentException
854 * @return a list of documentModels
857 public DocumentWrapper<DocumentModelList> findDocs(
858 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
859 List<String> docTypes,
861 int pageSize, int pageNum, boolean computeTotal)
862 throws DocumentNotFoundException, TransactionException, DocumentException {
863 CoreSessionInterface repoSession = null;
864 DocumentWrapper<DocumentModelList> wrapDoc = null;
867 repoSession = getRepositorySession(ctx);
868 wrapDoc = findDocs(ctx, repoSession, docTypes, whereClause, null,
869 pageSize, pageNum, computeTotal);
870 } catch (IllegalArgumentException iae) {
872 } catch (Exception e) {
873 if (logger.isDebugEnabled()) {
874 logger.debug("Caught exception ", e);
876 throw new NuxeoDocumentException(e);
878 if (repoSession != null) {
879 releaseRepositorySession(ctx, repoSession);
883 if (logger.isWarnEnabled() == true) {
884 logger.warn("Returned DocumentModelList instance was created with a repository session that is now closed.");
891 * @see org.collectionspace.services.common.storage.StorageClient#get(org.collectionspace.services.common.context.ServiceContext, java.util.List, org.collectionspace.services.common.document.DocumentHandler)
894 public void get(ServiceContext ctx, List<String> csidList, DocumentHandler handler)
895 throws DocumentNotFoundException, TransactionException, DocumentException {
896 if (handler == null) {
897 throw new IllegalArgumentException(
898 "RepositoryJavaClient.getAll: handler is missing");
901 CoreSessionInterface repoSession = null;
903 handler.prepare(Action.GET_ALL);
904 repoSession = getRepositorySession(ctx);
905 DocumentModelList docModelList = new DocumentModelListImpl();
906 //FIXME: Should be using NuxeoUtils.createPathRef for security reasons
907 for (String csid : csidList) {
908 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
909 DocumentModel docModel = repoSession.getDocument(docRef);
910 docModelList.add(docModel);
913 //set reposession to handle the document
914 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
915 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docModelList);
916 handler.handle(Action.GET_ALL, wrapDoc);
917 handler.complete(Action.GET_ALL, wrapDoc);
918 } catch (DocumentException de) {
920 } catch (Exception e) {
921 if (logger.isDebugEnabled()) {
922 logger.debug("Caught exception ", e);
924 throw new NuxeoDocumentException(e);
926 if (repoSession != null) {
927 releaseRepositorySession(ctx, repoSession);
933 * getAll get all documents for an entity entity service from the Nuxeo
936 * @param ctx service context under which this method is invoked
937 * @param handler should be used by the caller to provide and transform the
939 * @throws DocumentNotFoundException
940 * @throws TransactionException
941 * @throws DocumentException
944 public void getAll(ServiceContext ctx, DocumentHandler handler)
945 throws DocumentNotFoundException, TransactionException, DocumentException {
946 if (handler == null) {
947 throw new IllegalArgumentException(
948 "RepositoryJavaClient.getAll: handler is missing");
950 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
951 if (nuxeoWspaceId == null) {
952 throw new DocumentNotFoundException(
953 "Unable to find workspace for service "
954 + ctx.getServiceName()
955 + " check if the workspace exists in the Nuxeo repository.");
958 CoreSessionInterface repoSession = null;
960 handler.prepare(Action.GET_ALL);
961 repoSession = getRepositorySession(ctx);
962 DocumentRef wsDocRef = new IdRef(nuxeoWspaceId);
963 DocumentModelList docList = repoSession.getChildren(wsDocRef);
964 //set reposession to handle the document
965 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
966 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
967 handler.handle(Action.GET_ALL, wrapDoc);
968 handler.complete(Action.GET_ALL, wrapDoc);
969 } catch (DocumentException de) {
971 } catch (Exception e) {
972 if (logger.isDebugEnabled()) {
973 logger.debug("Caught exception ", e);
975 throw new NuxeoDocumentException(e);
977 if (repoSession != null) {
978 releaseRepositorySession(ctx, repoSession);
983 private boolean isClauseEmpty(String theString) {
984 boolean result = true;
985 if (theString != null && !theString.isEmpty()) {
991 public DocumentWrapper<DocumentModel> getDocFromCsid(
992 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
993 CoreSessionInterface repoSession,
996 DocumentWrapper<DocumentModel> result = null;
998 result = new DocumentWrapperImpl<DocumentModel>(NuxeoUtils.getDocFromCsid(ctx, repoSession, csid));
1004 * A method to find a CollectionSpace document (of any type) given just a service context and
1005 * its CSID. A search across *all* service workspaces (within a given tenant context) is performed to find
1008 * This query searches Nuxeo's Hierarchy table where our CSIDs are stored in the "name" column.
1011 public DocumentWrapper<DocumentModel> getDocFromCsid(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1014 DocumentWrapper<DocumentModel> result = null;
1015 CoreSessionInterface repoSession = null;
1017 repoSession = getRepositorySession(ctx);
1018 result = getDocFromCsid(ctx, repoSession, csid);
1020 if (repoSession != null) {
1021 releaseRepositorySession(ctx, repoSession);
1025 if (logger.isWarnEnabled() == true) {
1026 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
1033 * Returns a URI value for a document in the Nuxeo repository
1035 * @param wrappedDoc a wrapped documentModel
1036 * @throws ClientException
1037 * @return a document URI
1040 public String getDocURI(DocumentWrapper<DocumentModel> wrappedDoc) throws ClientException {
1041 DocumentModel docModel = wrappedDoc.getWrappedObject();
1042 String uri = (String) docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
1043 CollectionSpaceClient.COLLECTIONSPACE_CORE_URI);
1048 * See CSPACE-5036 - How to make CMISQL queries from Nuxeo
1050 private IterableQueryResult makeCMISQLQuery(CoreSessionInterface repoSession, String query, QueryContext queryContext) throws DocumentException {
1051 IterableQueryResult result = null;
1052 /** Threshold over which temporary files are not kept in memory. */
1053 final int THRESHOLD = 1024 * 1024;
1056 logger.debug(String.format("Performing a CMIS query on Nuxeo repository named %s",
1057 repoSession.getRepositoryName()));
1059 ThresholdOutputStreamFactory streamFactory = ThresholdOutputStreamFactory.newInstance(
1060 null, THRESHOLD, -1, false);
1061 CallContextImpl callContext = new CallContextImpl(
1062 CallContext.BINDING_LOCAL,
1063 CmisVersion.CMIS_1_1,
1064 repoSession.getRepositoryName(),
1065 null, // ServletContext
1066 null, // HttpServletRequest
1067 null, // HttpServletResponse
1068 new NuxeoCmisServiceFactory(),
1070 callContext.put(CallContext.USERNAME, repoSession.getPrincipal().getName());
1072 NuxeoCmisService cmisService = new NuxeoCmisService(repoSession.getCoreSession());
1073 result = repoSession.queryAndFetch(query, "CMISQL", cmisService);
1074 } catch (ClientException e) {
1075 // TODO Auto-generated catch block
1076 logger.error("Encounter trouble making the following CMIS query: " + query, e);
1077 throw new NuxeoDocumentException(e);
1084 * getFiltered get all documents for an entity service from the Document
1085 * repository, given filter parameters specified by the handler.
1087 * @param ctx service context under which this method is invoked
1088 * @param handler should be used by the caller to provide and transform the
1090 * @throws DocumentNotFoundException if workspace not found
1091 * @throws TransactionException
1092 * @throws DocumentException
1095 public void getFiltered(ServiceContext ctx, DocumentHandler handler)
1096 throws DocumentNotFoundException, TransactionException, DocumentException {
1098 DocumentFilter filter = handler.getDocumentFilter();
1099 String oldOrderBy = filter.getOrderByClause();
1100 if (isClauseEmpty(oldOrderBy) == true) {
1101 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
1103 QueryContext queryContext = new QueryContext(ctx, handler);
1105 CoreSessionInterface repoSession = null;
1107 handler.prepare(Action.GET_ALL);
1108 repoSession = getRepositorySession(ctx); //Keeps a refcount here for the repository session so you need to release this when finished
1110 DocumentModelList docList = null;
1112 if (handler.isJDBCQuery() == true) {
1113 docList = getFilteredJDBC(repoSession, ctx, handler);
1115 } else if (handler.isCMISQuery() == true) { //FIXME: REM - Need to deal with paging info in CMIS query
1116 if (isSubjectOrObjectQuery(ctx)) {
1117 docList = getFilteredCMISForSubjectOrObject(repoSession, ctx, handler, queryContext);
1119 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
1123 String query = NuxeoUtils.buildNXQLQuery(queryContext);
1124 if (logger.isDebugEnabled()) {
1125 logger.debug("Executing NXQL query: " + query.toString());
1127 Profiler profiler = new Profiler(this, 2);
1128 profiler.log("Executing NXQL query: " + query.toString());
1130 // If we have a page size and/or offset, then reflect those values
1131 // when constructing the query, and also pass 'true' to get totalSize
1132 // in the returned DocumentModelList.
1133 if ((queryContext.getDocFilter().getOffset() > 0) || (queryContext.getDocFilter().getPageSize() > 0)) {
1134 docList = repoSession.query(query, null,
1135 queryContext.getDocFilter().getPageSize(), queryContext.getDocFilter().getOffset(), true);
1137 docList = repoSession.query(query);
1142 //set repoSession to handle the document
1143 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1144 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
1145 handler.handle(Action.GET_ALL, wrapDoc);
1146 handler.complete(Action.GET_ALL, wrapDoc);
1147 } catch (DocumentException de) {
1149 } catch (Exception e) {
1150 if (logger.isDebugEnabled()) {
1151 logger.debug("Caught exception ", e); // REM - 1/17/2014: Check for org.nuxeo.ecm.core.api.ClientException and re-attempt
1153 throw new NuxeoDocumentException(e);
1155 if (repoSession != null) {
1156 releaseRepositorySession(ctx, repoSession);
1162 * Perform a database query, via JDBC and SQL, to retrieve matching records
1163 * based on filter criteria.
1165 * Although this method currently has a general-purpose name, it is
1166 * currently dedicated to a specific task: that of improving performance
1167 * for partial term matching queries on authority items / terms, via
1168 * the use of a hand-tuned SQL query, rather than via the generated SQL
1169 * produced by Nuxeo from an NXQL query. (See CSPACE-6361 for a task
1170 * to generalize this method.)
1172 * @param repoSession a repository session.
1173 * @param ctx the service context.
1174 * @param handler a relevant document handler.
1175 * @return a list of document models matching the search criteria.
1178 private DocumentModelList getFilteredJDBC(CoreSessionInterface repoSession, ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1179 DocumentHandler handler) throws Exception {
1180 DocumentModelList result = new DocumentModelListImpl();
1182 // FIXME: Get all of the following values from appropriate external constants.
1184 // At present, the two constants below are duplicated in both RepositoryClientImpl
1185 // and in AuthorityItemDocumentModelHandler.
1186 final String TERM_GROUP_LIST_NAME = "TERM_GROUP_LIST_NAME";
1187 final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
1188 final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
1189 // Get this from a constant in AuthorityResource or equivalent
1190 final String PARENT_WILDCARD = "_ALL_";
1192 // Build two SQL statements, to be executed within a single transaction:
1193 // the first statement to control join order, and the second statement
1194 // representing the actual 'get filtered' query
1196 // Build the join control statement
1198 // Per http://www.postgresql.org/docs/9.2/static/runtime-config-query.html#GUC-JOIN-COLLAPSE-LIMIT
1199 // "Setting [this value] to 1 prevents any reordering of explicit JOINs.
1200 // Thus, the explicit join order specified in the query will be the
1201 // actual order in which the relations are joined."
1202 // See CSPACE-5945 for further discussion of why this setting is needed.
1204 // Adding this statement is commented out here for now. It significantly
1205 // improved query performance for authority item / term queries where
1206 // large numbers of rows were retrieved, but appears to have resulted
1207 // in consistently slower-than-desired query performance where zero or
1208 // very few records were retrieved. See notes on CSPACE-5945. - ADR 2013-04-09
1209 // String joinControlSql = "SET LOCAL join_collapse_limit TO 1;";
1211 // Build the query statement
1213 // Start with the default query
1214 String selectStatement =
1215 "SELECT DISTINCT commonschema.id"
1216 + " FROM " + handler.getServiceContext().getCommonPartLabel() + " commonschema";
1218 String joinClauses =
1220 + " ON misc.id = commonschema.id"
1221 + " INNER JOIN hierarchy hierarchy_termgroup"
1222 + " ON hierarchy_termgroup.parentid = misc.id"
1223 + " INNER JOIN " + handler.getJDBCQueryParams().get(TERM_GROUP_TABLE_NAME_PARAM) + " termgroup"
1224 + " ON termgroup.id = hierarchy_termgroup.id ";
1227 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
1228 // Value for replaceable parameter 1 in the query
1229 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
1230 // If the value of the partial term query parameter is blank ('pt='),
1231 // return all records, subject to restriction by any limit clause
1232 if (Tools.isBlank(partialTerm)) {
1235 // Otherwise, return records that match the supplied partial term
1237 " WHERE (termgroup.termdisplayname ILIKE ?)";
1240 // At present, results are ordered in code, below, rather than in SQL,
1241 // and the orderByClause below is thus intentionally blank.
1243 // To implement the orderByClause below in SQL; e.g. via
1244 // 'ORDER BY termgroup.termdisplayname', the relevant column
1245 // must be returned by the SELECT statement.
1246 String orderByClause = "";
1249 TenantBindingConfigReaderImpl tReader =
1250 ServiceMain.getInstance().getTenantBindingConfigReader();
1251 TenantBindingType tenantBinding = tReader.getTenantBinding(ctx.getTenantId());
1252 String maxListItemsLimit = TenantBindingUtils.getPropertyValue(tenantBinding,
1253 IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES);
1255 " LIMIT " + getMaxItemsLimitOnJdbcQueries(maxListItemsLimit); // implicit int-to-String conversion
1257 // After building the individual parts of the query, set the values
1258 // of replaceable parameters that will be inserted into that query
1259 // and optionally add restrictions
1261 List<String> params = new ArrayList<>();
1263 if (Tools.notBlank(whereClause)) {
1265 // Read tenant bindings configuration to determine whether
1266 // to automatically insert leading, as well as trailing, wildcards
1267 // into the term matching string.
1268 String usesStartingWildcard = TenantBindingUtils.getPropertyValue(tenantBinding,
1269 IQueryManager.TENANT_USES_STARTING_WILDCARD_FOR_PARTIAL_TERM);
1270 // Handle user-provided leading wildcard characters, in the
1271 // configuration where a leading wildcard is not automatically inserted.
1272 // (The user-provided wildcard must be in the first, or "starting"
1273 // character position in the partial term value.)
1274 if (Tools.notBlank(usesStartingWildcard)) {
1275 if (usesStartingWildcard.equalsIgnoreCase(Boolean.FALSE.toString())) {
1276 partialTerm = handleProvidedStartingWildcard(partialTerm);
1277 // Otherwise, in the configuration where a leading wildcard
1278 // is usually automatically inserted, handle the cases where
1279 // a user has entered an anchor character in the first position
1280 // in the starting term value. In those cases, strip that
1281 // anchor character and don't add a leading wildcard
1283 if (partialTerm.startsWith(USER_SUPPLIED_ANCHOR_CHAR)) {
1284 partialTerm = partialTerm.substring(1, partialTerm.length());
1285 // Otherwise, automatically add a leading wildcard
1287 partialTerm = JDBCTools.SQL_WILDCARD + partialTerm;
1291 // Add SQL wildcards in the midst of the partial term match search
1292 // expression, whever user-supplied wildcards appear, except in the
1293 // first or last character positions of the search expression.
1294 partialTerm = subtituteWildcardsInPartialTerm(partialTerm);
1296 // If a designated 'anchor character' is present as the last character
1297 // in the search expression, strip that character and don't add
1298 // a trailing wildcard
1299 int lastCharPos = partialTerm.length() - 1;
1300 if (partialTerm.endsWith(USER_SUPPLIED_ANCHOR_CHAR) && lastCharPos > 0) {
1301 partialTerm = partialTerm.substring(0, lastCharPos);
1303 // Otherwise, automatically add a trailing wildcard
1304 partialTerm = partialTerm + JDBCTools.SQL_WILDCARD;
1306 params.add(partialTerm);
1309 // Optionally add restrictions to the default query, based on variables
1310 // in the current request
1312 // Restrict the query to filter out deleted records, if requested
1313 String includeDeleted = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_NONDELETED);
1314 if (includeDeleted != null && includeDeleted.equalsIgnoreCase(Boolean.FALSE.toString())) {
1315 whereClause = whereClause
1316 + " AND (misc.lifecyclestate <> '" + WorkflowClient.WORKFLOWSTATE_DELETED + "')"
1317 + " AND (misc.lifecyclestate <> '" + WorkflowClient.WORKFLOWSTATE_LOCKED_DELETED + "')";
1320 // If a particular authority is specified, restrict the query further
1321 // to return only records within that authority
1322 String inAuthorityValue = (String) handler.getJDBCQueryParams().get(IN_AUTHORITY_PARAM);
1323 if (Tools.notBlank(inAuthorityValue)) {
1324 // Handle the '_ALL_' case for inAuthority
1325 if (inAuthorityValue.equals(PARENT_WILDCARD)) {
1326 // Add nothing to the query here if it should match within all authorities
1328 whereClause = whereClause
1329 + " AND (commonschema.inauthority = ?)";
1330 params.add(inAuthorityValue); // Value for replaceable parameter 2 in the query
1334 // Restrict the query further to return only records pertaining to
1335 // the current tenant, unless:
1336 // * Data for this service, in this tenant, is stored in its own,
1337 // separate repository, rather than being intermingled with other
1338 // tenants' data in the default repository; or
1339 // * Restriction by tenant ID in JDBC queries has been disabled,
1340 // via configuration for this tenant,
1341 if (restrictJDBCQueryByTenantID(tenantBinding, ctx)) {
1342 joinClauses = joinClauses
1343 + " INNER JOIN collectionspace_core core"
1344 + " ON core.id = hierarchy_termgroup.parentid";
1345 whereClause = whereClause
1346 + " AND (core.tenantid = ?)";
1347 params.add(ctx.getTenantId()); // Value for replaceable parameter 3 in the query
1350 // Piece together the SQL query from its parts
1351 String querySql = selectStatement + joinClauses + whereClause + orderByClause + limitClause;
1353 // Note: PostgreSQL 9.2 introduced a change that may improve performance
1354 // of certain queries using JDBC PreparedStatements. See comments on
1355 // CSPACE-5943 for details.
1357 // See a comment above for the reason that the joinControl SQL statement,
1358 // along with its corresponding prepared statement builder, is commented out for now.
1359 // PreparedStatementBuilder joinControlBuilder = new PreparedStatementBuilder(joinControlSql);
1360 PreparedStatementSimpleBuilder queryBuilder = new PreparedStatementSimpleBuilder(querySql, params);
1361 List<PreparedStatementBuilder> builders = new ArrayList<>();
1362 // builders.add(joinControlBuilder);
1363 builders.add(queryBuilder);
1364 String dataSourceName = JDBCTools.NUXEO_DATASOURCE_NAME;
1365 String repositoryName = ctx.getRepositoryName();
1366 final Boolean EXECUTE_WITHIN_TRANSACTION = true;
1367 Set<String> docIds = new HashSet<>();
1369 String cspaceInstanceId = ServiceMain.getInstance().getCspaceInstanceId();
1370 List<CachedRowSet> resultsList = JDBCTools.executePreparedQueries(builders,
1371 dataSourceName, repositoryName, cspaceInstanceId, EXECUTE_WITHIN_TRANSACTION);
1373 // At least one set of results is expected, from the second prepared
1374 // statement to be executed.
1375 // If fewer results are returned, return an empty list of document models
1376 if (resultsList == null || resultsList.size() < 1) {
1377 return result; // return an empty list of document models
1379 // The join control query (if enabled - it is currently commented
1380 // out as per comments above) will not return results, so query results
1381 // will be the first set of results (rowSet) returned in the list
1382 CachedRowSet queryResults = resultsList.get(0);
1384 // If the result from executing the query is null or contains zero rows,
1385 // return an empty list of document models
1386 if (queryResults == null) {
1387 return result; // return an empty list of document models
1389 queryResults.last();
1390 if (queryResults.getRow() == 0) {
1391 return result; // return an empty list of document models
1394 // Otherwise, get the document IDs from the results of the query
1396 queryResults.beforeFirst();
1397 while (queryResults.next()) {
1398 id = queryResults.getString(1);
1399 if (Tools.notBlank(id)) {
1403 } catch (SQLException sqle) {
1404 logger.warn("Could not obtain document IDs via SQL query '" + querySql + "': " + sqle.getMessage());
1405 return result; // return an empty list of document models
1408 // Get a list of document models, using the list of IDs obtained from the query
1410 // FIXME: Check whether we have a 'get document models from list of CSIDs'
1411 // utility method like this, and if not, add this to the appropriate
1413 DocumentModel docModel;
1414 for (String docId : docIds) {
1415 docModel = NuxeoUtils.getDocumentModel(repoSession, docId);
1416 if (docModel == null) {
1417 logger.warn("Could not obtain document model for document with ID " + docId);
1419 result.add(docModel);
1423 // Order the results
1424 final String COMMON_PART_SCHEMA = handler.getServiceContext().getCommonPartLabel();
1425 final String DISPLAY_NAME_XPATH =
1426 "//" + handler.getJDBCQueryParams().get(TERM_GROUP_LIST_NAME) + "/[0]/termDisplayName";
1427 Collections.sort(result, new Comparator<DocumentModel>() {
1429 public int compare(DocumentModel doc1, DocumentModel doc2) {
1430 String termDisplayName1 = null;
1431 String termDisplayName2 = null;
1433 termDisplayName1 = (String) NuxeoUtils.getXPathValue(doc1, COMMON_PART_SCHEMA, DISPLAY_NAME_XPATH);
1434 termDisplayName2 = (String) NuxeoUtils.getXPathValue(doc2, COMMON_PART_SCHEMA, DISPLAY_NAME_XPATH);
1435 } catch (NuxeoDocumentException e) {
1436 throw new RuntimeException(e); // We need to throw a RuntimeException because the compare() method of the Comparator interface does not support throwing an Exception
1438 return termDisplayName1.compareToIgnoreCase(termDisplayName2);
1446 private DocumentModelList getFilteredCMIS(CoreSessionInterface repoSession,
1447 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, DocumentHandler handler, QueryContext queryContext)
1448 throws DocumentNotFoundException, DocumentException {
1450 DocumentModelList result = new DocumentModelListImpl();
1452 String query = handler.getCMISQuery(queryContext);
1454 DocumentFilter docFilter = handler.getDocumentFilter();
1455 int pageSize = docFilter.getPageSize();
1456 int offset = docFilter.getOffset();
1457 if (logger.isDebugEnabled()) {
1458 logger.debug("Executing CMIS query: " + query.toString()
1459 + "with pageSize: " + pageSize + " at offset: " + offset);
1462 // If we have limit and/or offset, then pass true to get totalSize
1463 // in returned DocumentModelList.
1464 Profiler profiler = new Profiler(this, 2);
1465 profiler.log("Executing CMIS query: " + query.toString());
1468 IterableQueryResult queryResult = makeCMISQLQuery(repoSession, query, queryContext);
1470 int totalSize = (int) queryResult.size();
1471 ((DocumentModelListImpl) result).setTotalSize(totalSize);
1472 // Skip the rows before our offset
1474 queryResult.skipTo(offset);
1477 for (Map<String, Serializable> row : queryResult) {
1478 if (logger.isTraceEnabled()) {
1479 logger.trace(" Hierarchy Table ID is:" + row.get(IQueryManager.CMIS_TARGET_NUXEO_ID)
1480 + " nuxeo:pathSegment is: " + row.get(IQueryManager.CMIS_TARGET_NAME));
1482 String nuxeoId = (String) row.get(IQueryManager.CMIS_TARGET_NUXEO_ID);
1483 DocumentModel docModel = NuxeoUtils.getDocumentModel(repoSession, nuxeoId);
1484 result.add(docModel);
1486 if (nRows >= pageSize && pageSize != 0) { // A page size of zero means that they want all of them
1487 logger.debug("Got page full of items - quitting");
1492 queryResult.close();
1497 } catch (Exception e) {
1498 if (logger.isDebugEnabled()) {
1499 logger.debug("Caught exception ", e);
1501 throw new NuxeoDocumentException(e);
1505 // Since we're not supporting paging yet for CMIS queries, we need to perform
1506 // a workaround for the paging information we return in our list of results
1509 if (result != null) {
1510 docFilter.setStartPage(0);
1511 if (totalSize > docFilter.getPageSize()) {
1512 docFilter.setPageSize(totalSize);
1513 ((DocumentModelListImpl)result).setTotalSize(totalSize);
1521 private String logException(Exception e, String msg) {
1522 String result = null;
1524 String exceptionMessage = e.getMessage();
1525 exceptionMessage = exceptionMessage != null ? exceptionMessage : "<No details provided>";
1526 result = msg = msg + ". Caught exception:" + exceptionMessage;
1528 if (logger.isTraceEnabled() == true) {
1529 logger.error(msg, e);
1538 * update given document in the Nuxeo repository
1540 * @param ctx service context under which this method is invoked
1541 * @param csid of the document
1542 * @param handler should be used by the caller to provide and transform the
1544 * @throws BadRequestException
1545 * @throws DocumentNotFoundException
1546 * @throws TransactionException if the transaction times out or otherwise
1547 * cannot be successfully completed
1548 * @throws DocumentException
1551 public void update(ServiceContext ctx, String csid, DocumentHandler handler)
1552 throws BadRequestException, DocumentNotFoundException, TransactionException,
1554 if (handler == null) {
1555 throw new IllegalArgumentException(
1556 "RepositoryJavaClient.update: document handler is missing.");
1559 CoreSessionInterface repoSession = null;
1561 handler.prepare(Action.UPDATE);
1562 repoSession = getRepositorySession(ctx);
1563 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
1564 DocumentModel doc = null;
1566 doc = repoSession.getDocument(docRef);
1567 } catch (org.nuxeo.ecm.core.api.DocumentNotFoundException ce) {
1568 String msg = logException(ce,
1569 String.format("Could not find %s resource/record to update with CSID=%s", ctx.getDocumentType(), csid));
1570 throw new DocumentNotFoundException(msg, ce);
1572 // Check for a versioned document, and check In and Out before we proceed.
1573 if (((DocumentModelHandler) handler).supportsVersioning()) {
1574 /* Once we advance to 5.5 or later, we can add this.
1575 * See also https://jira.nuxeo.com/browse/NXP-8506
1576 if(!doc.isVersionable()) {
1577 throw new NuxeoDocumentException("Configuration for: "
1578 +handler.getServiceContextPath()+" supports versioning, but Nuxeo config does not!");
1581 /* Force a version number - Not working. Apparently we need to configure the uid schema??
1582 if(doc.getProperty("uid","major_version") == null) {
1583 doc.setProperty("uid","major_version",1);
1585 if(doc.getProperty("uid","minor_version") == null) {
1586 doc.setProperty("uid","minor_version",0);
1589 doc.checkIn(VersioningOption.MINOR, null);
1594 // Set reposession to handle the document
1596 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1597 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
1598 handler.handle(Action.UPDATE, wrapDoc);
1599 repoSession.saveDocument(doc);
1601 handler.complete(Action.UPDATE, wrapDoc);
1602 } catch (BadRequestException bre) {
1603 rollbackTransaction(repoSession);
1605 } catch (DocumentException de) {
1606 rollbackTransaction(repoSession);
1608 } catch (CSWebApplicationException wae) {
1609 rollbackTransaction(repoSession);
1611 } catch (Throwable e) {
1612 rollbackTransaction(repoSession);
1613 throw new NuxeoDocumentException(e);
1615 if (repoSession != null) {
1616 releaseRepositorySession(ctx, repoSession);
1622 * Save a documentModel to the Nuxeo repository.
1624 * @param ctx service context under which this method is invoked
1625 * @param repoSession
1626 * @param docModel the document to save
1627 * @param fSaveSession if TRUE, will call CoreSessionInterface.save() to save
1628 * accumulated changes.
1629 * @throws ClientException
1630 * @throws DocumentException
1633 public void saveDocWithoutHandlerProcessing(
1634 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1635 CoreSessionInterface repoSession,
1636 DocumentModel docModel,
1637 boolean fSaveSession)
1638 throws ClientException, DocumentException {
1641 repoSession.saveDocument(docModel);
1645 } catch (ClientException ce) {
1647 } catch (Exception e) {
1648 if (logger.isDebugEnabled()) {
1649 logger.debug("Caught exception ", e);
1651 throw new NuxeoDocumentException(e);
1656 * Save a list of documentModels to the Nuxeo repository.
1658 * @param ctx service context under which this method is invoked
1659 * @param repoSession a repository session
1660 * @param docModelList a list of document models
1661 * @param fSaveSession if TRUE, will call CoreSessionInterface.save() to save
1662 * accumulated changes.
1663 * @throws ClientException
1664 * @throws DocumentException
1666 public void saveDocListWithoutHandlerProcessing(
1667 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1668 CoreSessionInterface repoSession,
1669 DocumentModelList docList,
1670 boolean fSaveSession)
1671 throws ClientException, DocumentException {
1673 DocumentModel[] docModelArray = new DocumentModel[docList.size()];
1674 repoSession.saveDocuments(docList.toArray(docModelArray));
1678 } catch (ClientException ce) {
1680 } catch (Exception e) {
1681 logger.error("Caught exception ", e);
1682 throw new NuxeoDocumentException(e);
1687 public void deleteWithWhereClause(@SuppressWarnings("rawtypes") ServiceContext ctx, String whereClause,
1688 @SuppressWarnings("rawtypes") DocumentHandler handler) throws
1689 DocumentNotFoundException, DocumentException {
1691 throw new IllegalArgumentException(
1692 "delete(ctx, specifier): ctx is missing");
1694 if (logger.isDebugEnabled()) {
1695 logger.debug("Deleting document with whereClause=" + whereClause);
1698 DocumentWrapper<DocumentModel> foundDocWrapper = this.findDoc(ctx, whereClause);
1699 if (foundDocWrapper != null) {
1700 DocumentModel docModel = foundDocWrapper.getWrappedObject();
1701 String csid = docModel.getName();
1702 this.delete(ctx, csid, handler);
1707 * delete a document from the Nuxeo repository
1709 * @param ctx service context under which this method is invoked
1710 * @param id of the document
1711 * @throws DocumentException
1714 public boolean delete(ServiceContext ctx, List<String> idList, DocumentHandler handler) throws DocumentNotFoundException,
1715 DocumentException, TransactionException {
1716 boolean result = true;
1719 throw new IllegalArgumentException(
1720 "delete(ctx, ix, handler): ctx is missing");
1722 if (handler == null) {
1723 throw new IllegalArgumentException(
1724 "delete(ctx, ix, handler): handler is missing");
1727 CoreSessionInterface repoSession = null;
1729 handler.prepare(Action.DELETE);
1730 repoSession = getRepositorySession(ctx);
1732 for (String id : idList) {
1733 if (logger.isDebugEnabled()) {
1734 logger.debug("Deleting document with CSID=" + id);
1736 DocumentWrapper<DocumentModel> wrapDoc = null;
1738 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
1739 wrapDoc = new DocumentWrapperImpl<DocumentModel>(repoSession.getDocument(docRef));
1740 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1741 if (handler.handle(Action.DELETE, wrapDoc) == true) {
1742 repoSession.removeDocument(docRef);
1743 if (logger.isDebugEnabled()) {
1744 String msg = String.format("DELETE - User '%s' hard-deleted document CSID=%s of type %s.",
1745 ctx.getUserId(), id, ctx.getDocumentType());
1749 String msg = String.format("Could not delete %s resource with csid=%s.",
1750 handler.getServiceContext().getServiceName(), id);
1751 throw new DocumentException(msg);
1753 } catch (org.nuxeo.ecm.core.api.DocumentNotFoundException ce) {
1754 String msg = logException(ce,
1755 String.format("Could not find %s resource/record to delete with CSID=%s", ctx.getDocumentType(), id));
1756 throw new DocumentNotFoundException(msg, ce);
1759 handler.complete(Action.DELETE, wrapDoc);
1761 } catch (DocumentException de) {
1762 rollbackTransaction(repoSession);
1764 } catch (Throwable e) {
1765 rollbackTransaction(repoSession);
1766 throw new NuxeoDocumentException(e);
1768 if (repoSession != null) {
1769 releaseRepositorySession(ctx, repoSession);
1777 * delete a document from the Nuxeo repository
1779 * @param ctx service context under which this method is invoked
1780 * @param id of the document
1781 * @throws DocumentException
1784 public boolean delete(ServiceContext ctx, String id, DocumentHandler handler) throws DocumentNotFoundException,
1785 DocumentException, TransactionException {
1788 List<String> idList = new ArrayList<String>();
1790 result = delete(ctx, idList, handler);
1796 * @see org.collectionspace.services.common.storage.StorageClient#delete(org.collectionspace.services.common.context.ServiceContext, java.lang.String, org.collectionspace.services.common.document.DocumentHandler)
1800 public void delete(@SuppressWarnings("rawtypes") ServiceContext ctx, String id)
1801 throws DocumentNotFoundException, DocumentException {
1802 throw new UnsupportedOperationException();
1803 // Use the other delete instead
1807 public Hashtable<String, String> retrieveWorkspaceIds(RepositoryDomainType repoDomain) throws Exception {
1808 return NuxeoConnectorEmbedded.getInstance().retrieveWorkspaceIds(repoDomain);
1812 public String createDomain(RepositoryDomainType repositoryDomain) throws Exception {
1813 CoreSessionInterface repoSession = null;
1814 String domainId = null;
1817 // Open a connection to the domain's repo/db
1819 String repoName = repositoryDomain.getRepositoryName();
1820 repoSession = getRepositorySession(repoName); // domainName=storageName=repoName=databaseName
1822 // First create the top-level domain directory
1824 String domainName = repositoryDomain.getStorageName();
1825 DocumentRef parentDocRef = new PathRef("/");
1826 DocumentModel parentDoc = repoSession.getDocument(parentDocRef);
1827 DocumentModel domainDoc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1828 domainName, NUXEO_CORE_TYPE_DOMAIN);
1829 domainDoc.setPropertyValue("dc:title", domainName);
1830 domainDoc.setPropertyValue("dc:description", "A CollectionSpace domain "
1832 domainDoc = repoSession.createDocument(domainDoc);
1833 domainId = domainDoc.getId();
1836 // Next, create a "Workspaces" root directory to contain the workspace folders for the individual service documents
1838 DocumentModel workspacesRoot = repoSession.createDocumentModel(domainDoc.getPathAsString(),
1839 NuxeoUtils.Workspaces, NUXEO_CORE_TYPE_WORKSPACEROOT);
1840 workspacesRoot.setPropertyValue("dc:title", NuxeoUtils.Workspaces);
1841 workspacesRoot.setPropertyValue("dc:description", "A CollectionSpace workspaces directory for "
1842 + domainDoc.getPathAsString());
1843 workspacesRoot = repoSession.createDocument(workspacesRoot);
1844 String workspacesRootId = workspacesRoot.getId();
1847 if (logger.isDebugEnabled()) {
1848 logger.debug("Created tenant domain name=" + domainName
1849 + " id=" + domainId + " "
1850 + NuxeoUtils.Workspaces + " id=" + workspacesRootId);
1851 logger.debug("Path to Domain: " + domainDoc.getPathAsString());
1852 logger.debug("Path to Workspaces root: " + workspacesRoot.getPathAsString());
1854 } catch (Throwable e) {
1855 rollbackTransaction(repoSession);
1856 if (logger.isDebugEnabled()) {
1857 logger.debug("Could not create tenant domain name=" + repositoryDomain.getStorageName() + " caught exception ", e);
1861 if (repoSession != null) {
1862 releaseRepositorySession(null, repoSession);
1870 public String getDomainId(RepositoryDomainType repositoryDomain) throws Exception {
1871 String domainId = null;
1872 CoreSessionInterface repoSession = null;
1874 String repoName = repositoryDomain.getRepositoryName();
1875 String domainStorageName = repositoryDomain.getStorageName();
1876 if (domainStorageName != null && !domainStorageName.isEmpty()) {
1878 repoSession = getRepositorySession(repoName);
1879 DocumentRef docRef = new PathRef("/" + domainStorageName);
1880 DocumentModel domain = repoSession.getDocument(docRef);
1881 domainId = domain.getId();
1882 } catch (Exception e) {
1883 if (logger.isTraceEnabled()) {
1884 logger.trace("Caught exception ", e); // The document doesn't exist, this let's us know we need to create it
1887 if (repoSession != null) {
1888 releaseRepositorySession(null, repoSession);
1897 * Returns the workspaces root directory for a given domain.
1899 private DocumentModel getWorkspacesRoot(CoreSessionInterface repoSession,
1900 String domainName) throws Exception {
1901 DocumentModel result = null;
1903 String domainPath = "/" + domainName;
1904 DocumentRef parentDocRef = new PathRef(domainPath);
1905 DocumentModelList domainChildrenList = repoSession.getChildren(
1907 Iterator<DocumentModel> witer = domainChildrenList.iterator();
1908 while (witer.hasNext()) {
1909 DocumentModel childNode = witer.next();
1910 if (NuxeoUtils.Workspaces.equalsIgnoreCase(childNode.getName())) {
1912 logger.trace("Found workspaces directory at: " + result.getPathAsString());
1917 if (result == null) {
1918 throw new ClientException("Could not find workspace root directory in: "
1926 * @see org.collectionspace.services.common.repository.RepositoryClient#createWorkspace(java.lang.String, java.lang.String)
1929 public String createWorkspace(RepositoryDomainType repositoryDomain, String workspaceName) throws Exception {
1930 CoreSessionInterface repoSession = null;
1931 String workspaceId = null;
1933 String repoName = repositoryDomain.getRepositoryName();
1934 repoSession = getRepositorySession(repoName);
1936 String domainStorageName = repositoryDomain.getStorageName();
1937 DocumentModel parentDoc = getWorkspacesRoot(repoSession, domainStorageName);
1938 if (logger.isTraceEnabled()) {
1939 for (String facet : parentDoc.getFacets()) {
1940 logger.trace("Facet: " + facet);
1944 DocumentModel doc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1945 workspaceName, NuxeoUtils.WORKSPACE_DOCUMENT_TYPE);
1946 doc.setPropertyValue("dc:title", workspaceName);
1947 doc.setPropertyValue("dc:description", "A CollectionSpace workspace for "
1949 doc = repoSession.createDocument(doc);
1950 workspaceId = doc.getId();
1952 if (logger.isDebugEnabled()) {
1953 logger.debug("Created workspace name=" + workspaceName
1954 + " id=" + workspaceId);
1956 } catch (Throwable e) {
1957 rollbackTransaction(repoSession);
1958 if (logger.isDebugEnabled()) {
1959 logger.debug("createWorkspace caught exception ", e);
1963 if (repoSession != null) {
1964 releaseRepositorySession(null, repoSession);
1971 * @see org.collectionspace.services.common.repository.RepositoryClient#getWorkspaceId(java.lang.String, java.lang.String)
1975 public String getWorkspaceId(String tenantDomain, String workspaceName) throws Exception {
1976 String workspaceId = null;
1978 CoreSessionInterface repoSession = null;
1980 repoSession = getRepositorySession((ServiceContext<PoxPayloadIn, PoxPayloadOut>) null);
1981 DocumentRef docRef = new PathRef(
1983 + "/" + NuxeoUtils.Workspaces
1984 + "/" + workspaceName);
1985 DocumentModel workspace = repoSession.getDocument(docRef);
1986 workspaceId = workspace.getId();
1987 } catch (DocumentException de) {
1989 } catch (Exception e) {
1990 if (logger.isDebugEnabled()) {
1991 logger.debug("Caught exception ", e);
1993 throw new NuxeoDocumentException(e);
1995 if (repoSession != null) {
1996 releaseRepositorySession(null, repoSession);
2004 public CoreSessionInterface getRepositorySession(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) throws Exception {
2005 return getRepositorySession(ctx, ctx.getRepositoryName(), ctx.getTimeoutSecs());
2008 public CoreSessionInterface getRepositorySession(String repoName) throws Exception {
2009 return getRepositorySession(null, repoName, ServiceContext.DEFAULT_TX_TIMEOUT);
2013 * Gets the repository session. - Package access only. If the 'ctx' param is
2014 * null then the repo name must be non-mull and vice-versa
2016 * @return the repository session
2017 * @throws Exception the exception
2019 public CoreSessionInterface getRepositorySession(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
2021 int timeoutSeconds) throws Exception {
2022 CoreSessionInterface repoSession = null;
2024 Profiler profiler = new Profiler("getRepositorySession():", 2);
2027 // To get a connection to the Nuxeo repo, we need either a valid ServiceContext instance or a repository name
2030 repoSession = (CoreSessionInterface) ctx.getCurrentRepositorySession(); // First see if the context already has a repo session
2031 if (repoSession == null) {
2032 repoName = ctx.getRepositoryName(); // Notice we are overriding the passed in 'repoName' since we have a valid service context passed in to us
2034 } else if (Tools.isBlank(repoName)) {
2035 String errMsg = String.format("Either a valid session context or repository name are required to get a new connection.");
2036 logger.error(errMsg);
2037 throw new Exception(errMsg);
2040 if (repoSession == null) {
2042 // 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
2043 // just the repository name.
2045 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
2046 repoSession = client.openRepository(repoName, timeoutSeconds);
2048 if (logger.isTraceEnabled() == true) {
2049 logger.trace("Reusing the current context's repository session.");
2053 // Debugging only code
2055 if (logger.isTraceEnabled()) {
2057 if (logger.isTraceEnabled()) {
2058 logger.trace("Testing call to getRepository() repository root: " + repoSession.getRootDocument());
2060 } catch (Throwable e) {
2061 logger.trace("Test call to Nuxeo's getRepository() repository root failed", e);
2068 ctx.setCurrentRepositorySession(repoSession); // For reusing, save the repository session in the current service context. The context will reference count it.
2075 * Release repository session. - Package access only.
2077 * @param repoSession the repo session
2080 public void releaseRepositorySession(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, Object repositorySession) throws TransactionException {
2082 CoreSessionInterface repoSession = (CoreSessionInterface)repositorySession;
2083 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
2086 ctx.clearCurrentRepositorySession(); //clear the current context of the now closed repo session
2087 if (ctx.getCurrentRepositorySession() == null) {
2088 client.releaseRepository(repoSession); //release the repo session if the service context's ref count is zeo.
2091 client.releaseRepository(repoSession); //repo session was acquired without a service context
2093 } catch (TransactionRuntimeException tre) {
2094 String causeMsg = null;
2095 Throwable cause = tre.getCause();
2096 if (cause != null) {
2097 causeMsg = cause.getMessage();
2100 TransactionException te; // a CollectionSpace specific tx exception
2101 if (causeMsg != null) {
2102 te = new TransactionException(causeMsg, tre);
2104 te = new TransactionException(tre);
2107 logger.error(te.getMessage(), tre); // Log the standard transaction exception message, plus an exception-specific stack trace
2109 } catch (Exception e) {
2110 logger.error("Could not close the repository session.", e);
2111 // no need to throw this service specific exception
2116 public void doWorkflowTransition(ServiceContext ctx, String id,
2117 DocumentHandler handler, TransitionDef transitionDef)
2118 throws BadRequestException, DocumentNotFoundException,
2120 // 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
2123 private String handleProvidedStartingWildcard(String partialTerm) {
2124 if (Tools.notBlank(partialTerm)) {
2125 if (partialTerm.substring(0, 1).equals(USER_SUPPLIED_WILDCARD)) {
2126 StringBuffer buffer = new StringBuffer(partialTerm);
2127 buffer.setCharAt(0, JDBCTools.SQL_WILDCARD.charAt(0));
2128 partialTerm = buffer.toString();
2135 * Replaces user-supplied wildcards with SQL wildcards, in a partial term
2136 * matching search expression.
2138 * The scope of this replacement excludes the beginning character
2139 * in that search expression, as that character is treated specially.
2141 * @param partialTerm
2142 * @return the partial term, with any user-supplied wildcards replaced
2145 private String subtituteWildcardsInPartialTerm(String partialTerm) {
2146 if (Tools.isBlank(partialTerm)) {
2149 if (! partialTerm.contains(USER_SUPPLIED_WILDCARD)) {
2152 int len = partialTerm.length();
2153 // Partial term search expressions of 2 or fewer characters
2154 // currently aren't amenable to the use of wildcards
2156 logger.warn("Partial term match search expression of just 1-2 characters in length contains a user-supplied wildcard: " + partialTerm);
2157 logger.warn("Will handle that character as a literal value, rather than as a wildcard ...");
2160 return partialTerm.substring(0, 1) // first char
2161 + partialTerm.substring(1, len).replaceAll(USER_SUPPLIED_WILDCARD_REGEX, JDBCTools.SQL_WILDCARD);
2165 private int getMaxItemsLimitOnJdbcQueries(String maxListItemsLimit) {
2166 final int DEFAULT_ITEMS_LIMIT = 40;
2167 if (maxListItemsLimit == null) {
2168 return DEFAULT_ITEMS_LIMIT;
2172 itemsLimit = Integer.parseInt(maxListItemsLimit);
2173 if (itemsLimit < 1) {
2174 logger.warn("Value of configuration setting "
2175 + IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES
2176 + " must be a positive integer; invalid current value is " + maxListItemsLimit);
2177 logger.warn("Reverting to default value of " + DEFAULT_ITEMS_LIMIT);
2178 itemsLimit = DEFAULT_ITEMS_LIMIT;
2180 } catch (NumberFormatException nfe) {
2181 logger.warn("Value of configuration setting "
2182 + IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES
2183 + " must be a positive integer; invalid current value is " + maxListItemsLimit);
2184 logger.warn("Reverting to default value of " + DEFAULT_ITEMS_LIMIT);
2185 itemsLimit = DEFAULT_ITEMS_LIMIT;
2191 * Identifies whether a restriction on tenant ID - to return only records
2192 * pertaining to the current tenant - is required in a JDBC query.
2194 * @param tenantBinding a tenant binding configuration.
2195 * @param ctx a service context.
2196 * @return true if a restriction on tenant ID is required in the query;
2197 * false if a restriction is not required.
2199 private boolean restrictJDBCQueryByTenantID(TenantBindingType tenantBinding, ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
2200 boolean restrict = true;
2201 // If data for the current service, in the current tenant, is isolated
2202 // within its own separate, per-tenant repository, as contrasted with
2203 // being intermingled with other tenants' data in the default repository,
2204 // no restriction on Tenant ID is required in the query.
2205 String repositoryDomainName = ConfigUtils.getRepositoryName(tenantBinding, ctx.getRepositoryDomainName());
2206 if (!(repositoryDomainName.equals(ConfigUtils.DEFAULT_NUXEO_REPOSITORY_NAME))) {
2209 // If a configuration setting for this tenant identifies that JDBC
2210 // queries should not be restricted by tenant ID (perhaps because
2211 // there is always expected to be only one tenant's data present in
2212 // the system), no restriction on Tenant ID is required in the query.
2213 String queriesRestrictedByTenantId = TenantBindingUtils.getPropertyValue(tenantBinding,
2214 IQueryManager.JDBC_QUERIES_ARE_TENANT_ID_RESTRICTED);
2215 if (Tools.notBlank(queriesRestrictedByTenantId) &&
2216 queriesRestrictedByTenantId.equalsIgnoreCase(Boolean.FALSE.toString())) {
2222 private void rollbackTransaction(CoreSessionInterface repoSession) {
2223 if (repoSession != null) {
2224 repoSession.setTransactionRollbackOnly();
2229 * Should never get called.
2232 public boolean delete(ServiceContext ctx, Object entityFound, DocumentHandler handler)
2233 throws DocumentNotFoundException, DocumentException {
2234 throw new UnsupportedOperationException();