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 RepositoryClientImpl implements RepositoryClient<PoxPayloadIn, PoxPayloadOut> {
105 private final Logger logger = LoggerFactory.getLogger(RepositoryClientImpl.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 RepositoryClientImpl() {
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) {
213 } catch (Exception e) {
214 if (logger.isDebugEnabled()) {
215 logger.debug("Call to low-level Nuxeo document create call failed: ", e);
217 throw new NuxeoDocumentException(e);
219 if (repoSession != null) {
220 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 (Exception e) {
249 if (logger.isDebugEnabled()) {
250 logger.debug("Caught exception ", e);
252 throw new NuxeoDocumentException(e);
254 if (repoSession != null) {
255 releaseRepositorySession(ctx, repoSession);
263 public boolean synchronize(ServiceContext ctx, Object specifier, DocumentHandler handler)
264 throws DocumentNotFoundException, TransactionException, DocumentException {
265 boolean result = false;
267 if (handler == null) {
268 throw new IllegalArgumentException(
269 "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) {
282 } catch (DocumentException de) {
284 } catch (Exception e) {
285 if (logger.isDebugEnabled()) {
286 logger.debug("Caught exception ", e);
288 throw new NuxeoDocumentException(e);
290 if (repoSession != null) {
291 releaseRepositorySession(ctx, repoSession);
299 public boolean synchronizeItem(ServiceContext ctx, AuthorityItemSpecifier itemSpecifier, DocumentHandler handler)
300 throws DocumentNotFoundException, TransactionException, DocumentException {
301 boolean result = false;
303 if (handler == null) {
304 throw new IllegalArgumentException(
305 "RepositoryJavaClient.get: handler is missing");
308 CoreSessionInterface repoSession = null;
310 handler.prepare(Action.SYNC);
311 repoSession = getRepositorySession(ctx);
312 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
313 DocumentWrapper<AuthorityItemSpecifier> wrapDoc = new DocumentWrapperImpl<AuthorityItemSpecifier>(itemSpecifier);
314 result = handler.handle(Action.SYNC, wrapDoc);
315 handler.complete(Action.SYNC, wrapDoc);
316 } catch (IllegalArgumentException iae) {
318 } catch (DocumentException de) {
320 } catch (Exception e) {
321 if (logger.isDebugEnabled()) {
322 logger.debug("Caught exception ", e);
324 throw new NuxeoDocumentException(e);
326 if (repoSession != null) {
327 releaseRepositorySession(ctx, repoSession);
335 * get document from the Nuxeo repository
337 * @param ctx service context under which this method is invoked
338 * @param id of the document to retrieve
339 * @param handler should be used by the caller to provide and transform the
341 * @throws DocumentNotFoundException if the document cannot be found in the
343 * @throws TransactionException
344 * @throws DocumentException
347 public void get(ServiceContext ctx, String id, DocumentHandler handler)
348 throws DocumentNotFoundException, TransactionException, DocumentException {
350 if (handler == null) {
351 throw new IllegalArgumentException(
352 "RepositoryJavaClient.get: handler is missing");
355 CoreSessionInterface repoSession = null;
357 handler.prepare(Action.GET);
358 repoSession = getRepositorySession(ctx);
359 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
360 DocumentModel docModel = null;
362 docModel = repoSession.getDocument(docRef);
363 assertWorkflowState(ctx, docModel);
364 } catch (org.nuxeo.ecm.core.api.DocumentNotFoundException ce) {
365 String msg = logException(ce,
366 String.format("Could not find %s resource/record with CSID=%s", ctx.getDocumentType(), id));
367 throw new DocumentNotFoundException(msg, ce);
370 // Set repository session to handle the document
372 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
373 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(docModel);
374 handler.handle(Action.GET, wrapDoc);
375 handler.complete(Action.GET, wrapDoc);
376 } catch (IllegalArgumentException iae) {
378 } catch (DocumentException de) {
379 if (logger.isDebugEnabled()) {
380 logger.debug(de.getMessage(), de);
383 } catch (Exception e) {
384 if (logger.isDebugEnabled()) {
385 logger.debug("Caught exception ", e);
387 throw new NuxeoDocumentException(e);
389 if (repoSession != null) {
390 releaseRepositorySession(ctx, repoSession);
396 * get a document from the Nuxeo repository, using the docFilter params.
398 * @param ctx service context under which this method is invoked
399 * @param handler should be used by the caller to provide and transform the
400 * document. Handler must have a docFilter set to return a single item.
401 * @throws DocumentNotFoundException if the document cannot be found in the
403 * @throws TransactionException
404 * @throws DocumentException
407 public void get(ServiceContext ctx, DocumentHandler handler)
408 throws DocumentNotFoundException, TransactionException, DocumentException {
409 QueryContext queryContext = new QueryContext(ctx, handler);
410 CoreSessionInterface repoSession = null;
413 handler.prepare(Action.GET);
414 repoSession = getRepositorySession(ctx);
416 DocumentModelList docList = null;
417 // force limit to 1, and ignore totalSize
418 String query = NuxeoUtils.buildNXQLQuery(queryContext);
419 docList = repoSession.query(query, null, 1, 0, false);
420 if (docList.size() != 1) {
421 throw new DocumentNotFoundException("No document found matching filter params: " + query);
423 DocumentModel doc = docList.get(0);
425 if (logger.isDebugEnabled()) {
426 logger.debug("Executed NXQL query: " + query);
429 //set reposession to handle the document
430 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
431 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
432 handler.handle(Action.GET, wrapDoc);
433 handler.complete(Action.GET, wrapDoc);
434 } catch (IllegalArgumentException iae) {
436 } catch (DocumentException de) {
438 } catch (Exception e) {
439 if (logger.isDebugEnabled()) {
440 logger.debug("Caught exception ", e);
442 throw new NuxeoDocumentException(e);
444 if (repoSession != null) {
445 releaseRepositorySession(ctx, repoSession);
450 public DocumentWrapper<DocumentModel> getDoc(
451 CoreSessionInterface repoSession,
452 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
453 String csid) throws DocumentNotFoundException, DocumentException {
454 DocumentWrapper<DocumentModel> wrapDoc = null;
457 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
458 DocumentModel doc = null;
460 doc = repoSession.getDocument(docRef);
461 } catch (ClientException ce) {
462 String msg = logException(ce, "Could not find document with CSID=" + csid);
463 throw new DocumentNotFoundException(msg, ce);
465 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
466 } catch (IllegalArgumentException iae) {
468 } catch (DocumentException de) {
476 * Get wrapped documentModel from the Nuxeo repository. The search is
477 * restricted to the workspace of the current context.
479 * @param ctx service context under which this method is invoked
480 * @param csid of the document to retrieve
481 * @throws DocumentNotFoundException
482 * @throws TransactionException
483 * @throws DocumentException
484 * @return a wrapped documentModel
487 public DocumentWrapper<DocumentModel> getDoc(
488 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
489 String csid) throws DocumentNotFoundException, TransactionException, DocumentException {
490 CoreSessionInterface repoSession = null;
491 DocumentWrapper<DocumentModel> wrapDoc = null;
494 // Open a new repository session
495 repoSession = getRepositorySession(ctx);
496 wrapDoc = getDoc(repoSession, ctx, csid);
497 } catch (IllegalArgumentException iae) {
499 } catch (DocumentException de) {
501 } catch (Exception e) {
502 if (logger.isDebugEnabled()) {
503 logger.debug("Caught exception ", e);
505 throw new NuxeoDocumentException(e);
507 if (repoSession != null) {
508 releaseRepositorySession(ctx, repoSession);
512 if (logger.isWarnEnabled() == true) {
513 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
518 public DocumentWrapper<DocumentModel> findDoc(
519 CoreSessionInterface repoSession,
520 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
522 throws DocumentNotFoundException, DocumentException {
523 DocumentWrapper<DocumentModel> wrapDoc = null;
526 QueryContext queryContext = new QueryContext(ctx, whereClause);
527 DocumentModelList docList = null;
528 // force limit to 1, and ignore totalSize
529 String query = NuxeoUtils.buildNXQLQuery(queryContext);
530 docList = repoSession.query(query,
535 if (docList.size() != 1) {
536 if (logger.isDebugEnabled()) {
537 logger.debug("findDoc: Query found: " + docList.size() + " items.");
538 logger.debug(" Query: " + query);
540 throw new DocumentNotFoundException("No document found matching filter params: " + query);
542 DocumentModel doc = docList.get(0);
543 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
544 } catch (IllegalArgumentException iae) {
546 } catch (DocumentException de) {
548 } catch (Exception e) {
549 if (logger.isDebugEnabled()) {
550 logger.debug("Caught exception ", e);
552 throw new NuxeoDocumentException(e);
559 * find wrapped documentModel from the Nuxeo repository
561 * @param ctx service context under which this method is invoked
562 * @param whereClause where NXQL where clause to get the document
563 * @throws DocumentNotFoundException
564 * @throws TransactionException
565 * @throws DocumentException
566 * @return a wrapped documentModel retrieved by the repository query
569 public DocumentWrapper<DocumentModel> findDoc(
570 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
572 throws DocumentNotFoundException, TransactionException, DocumentException {
573 CoreSessionInterface repoSession = null;
574 DocumentWrapper<DocumentModel> wrapDoc = null;
577 repoSession = getRepositorySession(ctx);
578 wrapDoc = findDoc(repoSession, ctx, whereClause);
579 } catch (DocumentNotFoundException dnfe) {
581 } catch (DocumentException de) {
583 } catch (Exception e) {
584 if (repoSession == null) {
585 throw new NuxeoDocumentException("Unable to create a Nuxeo repository session.", e);
587 throw new NuxeoDocumentException("Unexpected Nuxeo exception.", e);
590 if (repoSession != null) {
591 releaseRepositorySession(ctx, repoSession);
595 if (logger.isWarnEnabled() == true) {
596 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
603 * find doc and return CSID from the Nuxeo repository
606 * @param ctx service context under which this method is invoked
607 * @param whereClause where NXQL where clause to get the document
608 * @throws DocumentNotFoundException
609 * @throws TransactionException
610 * @throws DocumentException
611 * @return the CollectionSpace ID (CSID) of the requested document
614 public String findDocCSID(CoreSessionInterface repoSession,
615 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String whereClause)
616 throws DocumentNotFoundException, TransactionException, DocumentException {
618 boolean releaseSession = false;
620 if (repoSession == null) {
621 repoSession = this.getRepositorySession(ctx);
622 releaseSession = true;
624 DocumentWrapper<DocumentModel> wrapDoc = findDoc(repoSession, ctx, whereClause);
625 DocumentModel docModel = wrapDoc.getWrappedObject();
626 csid = NuxeoUtils.getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
627 } catch (DocumentNotFoundException dnfe) {
629 } catch (IllegalArgumentException iae) {
631 } catch (DocumentException de) {
633 } catch (Exception e) {
634 if (logger.isDebugEnabled()) {
635 logger.debug("Caught exception ", e);
637 throw new NuxeoDocumentException(e);
639 if (releaseSession && (repoSession != null)) {
640 this.releaseRepositorySession(ctx, repoSession);
646 public DocumentWrapper<DocumentModelList> findDocs(
647 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
648 CoreSessionInterface repoSession,
649 List<String> docTypes,
651 String orderByClause,
654 boolean computeTotal)
655 throws DocumentNotFoundException, DocumentException {
656 DocumentWrapper<DocumentModelList> wrapDoc = null;
659 if (docTypes == null || docTypes.size() < 1) {
660 throw new DocumentNotFoundException(
661 "The findDocs() method must specify at least one DocumentType.");
663 DocumentModelList docList = null;
664 QueryContext queryContext = new QueryContext(ctx, whereClause, orderByClause);
665 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
666 if (logger.isDebugEnabled()) {
667 logger.debug("findDocs() NXQL: " + query);
669 docList = repoSession.query(query, null, pageSize, pageSize * pageNum, computeTotal);
670 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
671 } catch (IllegalArgumentException iae) {
673 } catch (Exception e) {
674 if (logger.isDebugEnabled()) {
675 logger.debug("Caught exception ", e);
677 throw new NuxeoDocumentException(e);
683 protected static String buildInListForDocTypes(List<String> docTypes) {
684 StringBuilder sb = new StringBuilder();
686 boolean first = true;
687 for (String docType : docTypes) {
698 return sb.toString();
701 public DocumentWrapper<DocumentModelList> findDocs(
702 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
703 DocumentHandler handler,
704 CoreSessionInterface repoSession,
705 List<String> docTypes)
706 throws DocumentNotFoundException, DocumentException {
707 DocumentWrapper<DocumentModelList> wrapDoc = null;
709 DocumentFilter filter = handler.getDocumentFilter();
710 String oldOrderBy = filter.getOrderByClause();
711 if (isClauseEmpty(oldOrderBy) == true) {
712 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
714 QueryContext queryContext = new QueryContext(ctx, handler);
717 if (docTypes == null || docTypes.size() < 1) {
718 throw new DocumentNotFoundException(
719 "The findDocs() method must specify at least one DocumentType.");
721 DocumentModelList docList = null;
722 if (handler.isCMISQuery() == true) {
723 String inList = buildInListForDocTypes(docTypes);
724 ctx.getQueryParams().add(IQueryManager.SEARCH_RELATED_MATCH_OBJ_DOCTYPES, inList);
725 if (isSubjectOrObjectQuery(ctx)) {
726 docList = getFilteredCMISForSubjectOrObject(repoSession, ctx, handler, queryContext);
728 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
731 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
732 if (logger.isDebugEnabled()) {
733 logger.debug("findDocs() NXQL: " + query);
735 docList = repoSession.query(query, null, filter.getPageSize(), filter.getOffset(), true);
737 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
738 } catch (IllegalArgumentException iae) {
740 } catch (Exception e) {
741 if (logger.isDebugEnabled()) {
742 logger.debug("Caught exception ", e);
744 throw new NuxeoDocumentException(e);
750 private DocumentModelList getFilteredCMISForSubjectOrObject(CoreSessionInterface repoSession,
751 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, DocumentHandler handler, QueryContext queryContext) throws DocumentNotFoundException, DocumentException {
752 DocumentModelList result = null;
754 if (isSubjectOrObjectQuery(ctx) == true) {
755 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
756 String asEitherCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_EITHER);
758 queryParams.remove(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT);
759 queryParams.remove(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT);
762 // First query for subjectCsid results.
764 queryParams.addFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT, asEitherCsid);
765 DocumentModelList subjectDocList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
766 queryParams.remove(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT);
769 // Next query for objectCsid results.
771 queryParams.addFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT, asEitherCsid);
772 DocumentModelList objectDocList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
773 queryParams.remove(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT);
776 // Finally, combine the two results
778 result = mergeDocumentModelLists(subjectDocList, objectDocList);
784 private DocumentModelList mergeDocumentModelLists(DocumentModelList subjectDocList,
785 DocumentModelList objectDocList) {
786 DocumentModelList result = null;
788 if (subjectDocList == null || subjectDocList.isEmpty()) {
789 return objectDocList;
792 if (objectDocList == null || objectDocList.isEmpty()) {
793 return subjectDocList;
796 result = new DocumentModelListImpl();
798 // Add the subject list
799 Iterator<DocumentModel> iterator = subjectDocList.iterator();
800 while (iterator.hasNext()) {
801 DocumentModel dm = iterator.next();
802 addToResults(result, dm);
805 // Add the object list
806 iterator = objectDocList.iterator();
807 while (iterator.hasNext()) {
808 DocumentModel dm = iterator.next();
809 addToResults(result, dm);
812 // Set the 'totalSize' value for book keeping sake
813 ((DocumentModelListImpl) result).setTotalSize(result.size());
819 // Only add if it is not already in the list
820 private void addToResults(DocumentModelList result, DocumentModel dm) {
821 Iterator<DocumentModel> iterator = result.iterator();
822 boolean found = false;
824 while (iterator.hasNext()) {
825 DocumentModel existingDm = iterator.next();
826 if (existingDm.getId().equals(dm.getId())) {
832 if (found == false) {
837 private boolean isSubjectOrObjectQuery(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
838 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
839 String asEitherCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_EITHER);
840 return asEitherCsid != null && !asEitherCsid.isEmpty();
844 * Find a list of documentModels from the Nuxeo repository
846 * @param docTypes a list of DocType names to match
847 * @param whereClause where the clause to qualify on
848 * @throws DocumentNotFoundException
849 * @throws TransactionException
850 * @throws DocumentException
851 * @return a list of documentModels
854 public DocumentWrapper<DocumentModelList> findDocs(
855 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
856 List<String> docTypes,
858 int pageSize, int pageNum, boolean computeTotal)
859 throws DocumentNotFoundException, TransactionException, DocumentException {
860 CoreSessionInterface repoSession = null;
861 DocumentWrapper<DocumentModelList> wrapDoc = null;
864 repoSession = getRepositorySession(ctx);
865 wrapDoc = findDocs(ctx, repoSession, docTypes, whereClause, null,
866 pageSize, pageNum, computeTotal);
867 } catch (IllegalArgumentException iae) {
869 } catch (Exception e) {
870 if (logger.isDebugEnabled()) {
871 logger.debug("Caught exception ", e);
873 throw new NuxeoDocumentException(e);
875 if (repoSession != null) {
876 releaseRepositorySession(ctx, repoSession);
880 if (logger.isWarnEnabled() == true) {
881 logger.warn("Returned DocumentModelList instance was created with a repository session that is now closed.");
888 * @see org.collectionspace.services.common.storage.StorageClient#get(org.collectionspace.services.common.context.ServiceContext, java.util.List, org.collectionspace.services.common.document.DocumentHandler)
891 public void get(ServiceContext ctx, List<String> csidList, DocumentHandler handler)
892 throws DocumentNotFoundException, TransactionException, DocumentException {
893 if (handler == null) {
894 throw new IllegalArgumentException(
895 "RepositoryJavaClient.getAll: handler is missing");
898 CoreSessionInterface repoSession = null;
900 handler.prepare(Action.GET_ALL);
901 repoSession = getRepositorySession(ctx);
902 DocumentModelList docModelList = new DocumentModelListImpl();
903 //FIXME: Should be using NuxeoUtils.createPathRef for security reasons
904 for (String csid : csidList) {
905 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
906 DocumentModel docModel = repoSession.getDocument(docRef);
907 docModelList.add(docModel);
910 //set reposession to handle the document
911 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
912 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docModelList);
913 handler.handle(Action.GET_ALL, wrapDoc);
914 handler.complete(Action.GET_ALL, wrapDoc);
915 } catch (DocumentException de) {
917 } catch (Exception e) {
918 if (logger.isDebugEnabled()) {
919 logger.debug("Caught exception ", e);
921 throw new NuxeoDocumentException(e);
923 if (repoSession != null) {
924 releaseRepositorySession(ctx, repoSession);
930 * getAll get all documents for an entity entity service from the Nuxeo
933 * @param ctx service context under which this method is invoked
934 * @param handler should be used by the caller to provide and transform the
936 * @throws DocumentNotFoundException
937 * @throws TransactionException
938 * @throws DocumentException
941 public void getAll(ServiceContext ctx, DocumentHandler handler)
942 throws DocumentNotFoundException, TransactionException, DocumentException {
943 if (handler == null) {
944 throw new IllegalArgumentException(
945 "RepositoryJavaClient.getAll: handler is missing");
947 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
948 if (nuxeoWspaceId == null) {
949 throw new DocumentNotFoundException(
950 "Unable to find workspace for service "
951 + ctx.getServiceName()
952 + " check if the workspace exists in the Nuxeo repository.");
955 CoreSessionInterface repoSession = null;
957 handler.prepare(Action.GET_ALL);
958 repoSession = getRepositorySession(ctx);
959 DocumentRef wsDocRef = new IdRef(nuxeoWspaceId);
960 DocumentModelList docList = repoSession.getChildren(wsDocRef);
961 //set reposession to handle the document
962 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
963 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
964 handler.handle(Action.GET_ALL, wrapDoc);
965 handler.complete(Action.GET_ALL, wrapDoc);
966 } catch (DocumentException de) {
968 } catch (Exception e) {
969 if (logger.isDebugEnabled()) {
970 logger.debug("Caught exception ", e);
972 throw new NuxeoDocumentException(e);
974 if (repoSession != null) {
975 releaseRepositorySession(ctx, repoSession);
980 private boolean isClauseEmpty(String theString) {
981 boolean result = true;
982 if (theString != null && !theString.isEmpty()) {
988 public DocumentWrapper<DocumentModel> getDocFromCsid(
989 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
990 CoreSessionInterface repoSession,
993 DocumentWrapper<DocumentModel> result = null;
995 result = new DocumentWrapperImpl<DocumentModel>(NuxeoUtils.getDocFromCsid(ctx, repoSession, csid));
1001 * A method to find a CollectionSpace document (of any type) given just a service context and
1002 * its CSID. A search across *all* service workspaces (within a given tenant context) is performed to find
1005 * This query searches Nuxeo's Hierarchy table where our CSIDs are stored in the "name" column.
1008 public DocumentWrapper<DocumentModel> getDocFromCsid(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1011 DocumentWrapper<DocumentModel> result = null;
1012 CoreSessionInterface repoSession = null;
1014 repoSession = getRepositorySession(ctx);
1015 result = getDocFromCsid(ctx, repoSession, csid);
1017 if (repoSession != null) {
1018 releaseRepositorySession(ctx, repoSession);
1022 if (logger.isWarnEnabled() == true) {
1023 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
1030 * Returns a URI value for a document in the Nuxeo repository
1032 * @param wrappedDoc a wrapped documentModel
1033 * @throws ClientException
1034 * @return a document URI
1037 public String getDocURI(DocumentWrapper<DocumentModel> wrappedDoc) throws ClientException {
1038 DocumentModel docModel = wrappedDoc.getWrappedObject();
1039 String uri = (String) docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
1040 CollectionSpaceClient.COLLECTIONSPACE_CORE_URI);
1045 * See CSPACE-5036 - How to make CMISQL queries from Nuxeo
1047 private IterableQueryResult makeCMISQLQuery(CoreSessionInterface repoSession, String query, QueryContext queryContext) throws DocumentException {
1048 IterableQueryResult result = null;
1049 /** Threshold over which temporary files are not kept in memory. */
1050 final int THRESHOLD = 1024 * 1024;
1053 logger.debug(String.format("Performing a CMIS query on Nuxeo repository named %s",
1054 repoSession.getRepositoryName()));
1056 ThresholdOutputStreamFactory streamFactory = ThresholdOutputStreamFactory.newInstance(
1057 null, THRESHOLD, -1, false);
1058 CallContextImpl callContext = new CallContextImpl(
1059 CallContext.BINDING_LOCAL,
1060 CmisVersion.CMIS_1_1,
1061 repoSession.getRepositoryName(),
1062 null, // ServletContext
1063 null, // HttpServletRequest
1064 null, // HttpServletResponse
1065 new NuxeoCmisServiceFactory(),
1067 callContext.put(CallContext.USERNAME, repoSession.getPrincipal().getName());
1069 NuxeoCmisService cmisService = new NuxeoCmisService(repoSession.getCoreSession());
1070 result = repoSession.queryAndFetch(query, "CMISQL", cmisService);
1071 } catch (ClientException e) {
1072 // TODO Auto-generated catch block
1073 logger.error("Encounter trouble making the following CMIS query: " + query, e);
1074 throw new NuxeoDocumentException(e);
1081 * getFiltered get all documents for an entity service from the Document
1082 * repository, given filter parameters specified by the handler.
1084 * @param ctx service context under which this method is invoked
1085 * @param handler should be used by the caller to provide and transform the
1087 * @throws DocumentNotFoundException if workspace not found
1088 * @throws TransactionException
1089 * @throws DocumentException
1092 public void getFiltered(ServiceContext ctx, DocumentHandler handler)
1093 throws DocumentNotFoundException, TransactionException, DocumentException {
1095 DocumentFilter filter = handler.getDocumentFilter();
1096 String oldOrderBy = filter.getOrderByClause();
1097 if (isClauseEmpty(oldOrderBy) == true) {
1098 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
1100 QueryContext queryContext = new QueryContext(ctx, handler);
1102 CoreSessionInterface repoSession = null;
1104 handler.prepare(Action.GET_ALL);
1105 repoSession = getRepositorySession(ctx); //Keeps a refcount here for the repository session so you need to release this when finished
1107 DocumentModelList docList = null;
1109 if (handler.isJDBCQuery() == true) {
1110 docList = getFilteredJDBC(repoSession, ctx, handler);
1112 } else if (handler.isCMISQuery() == true) { //FIXME: REM - Need to deal with paging info in CMIS query
1113 if (isSubjectOrObjectQuery(ctx)) {
1114 docList = getFilteredCMISForSubjectOrObject(repoSession, ctx, handler, queryContext);
1116 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
1120 String query = NuxeoUtils.buildNXQLQuery(queryContext);
1121 if (logger.isDebugEnabled()) {
1122 logger.debug("Executing NXQL query: " + query.toString());
1124 Profiler profiler = new Profiler(this, 2);
1125 profiler.log("Executing NXQL query: " + query.toString());
1127 // If we have a page size and/or offset, then reflect those values
1128 // when constructing the query, and also pass 'true' to get totalSize
1129 // in the returned DocumentModelList.
1130 if ((queryContext.getDocFilter().getOffset() > 0) || (queryContext.getDocFilter().getPageSize() > 0)) {
1131 docList = repoSession.query(query, null,
1132 queryContext.getDocFilter().getPageSize(), queryContext.getDocFilter().getOffset(), true);
1134 docList = repoSession.query(query);
1139 //set repoSession to handle the document
1140 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1141 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
1142 handler.handle(Action.GET_ALL, wrapDoc);
1143 handler.complete(Action.GET_ALL, wrapDoc);
1144 } catch (DocumentException de) {
1146 } catch (Exception e) {
1147 if (logger.isDebugEnabled()) {
1148 logger.debug("Caught exception ", e); // REM - 1/17/2014: Check for org.nuxeo.ecm.core.api.ClientException and re-attempt
1150 throw new NuxeoDocumentException(e);
1152 if (repoSession != null) {
1153 releaseRepositorySession(ctx, repoSession);
1159 * Perform a database query, via JDBC and SQL, to retrieve matching records
1160 * based on filter criteria.
1162 * Although this method currently has a general-purpose name, it is
1163 * currently dedicated to a specific task: that of improving performance
1164 * for partial term matching queries on authority items / terms, via
1165 * the use of a hand-tuned SQL query, rather than via the generated SQL
1166 * produced by Nuxeo from an NXQL query. (See CSPACE-6361 for a task
1167 * to generalize this method.)
1169 * @param repoSession a repository session.
1170 * @param ctx the service context.
1171 * @param handler a relevant document handler.
1172 * @return a list of document models matching the search criteria.
1175 private DocumentModelList getFilteredJDBC(CoreSessionInterface repoSession, ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1176 DocumentHandler handler) throws Exception {
1177 DocumentModelList result = new DocumentModelListImpl();
1179 // FIXME: Get all of the following values from appropriate external constants.
1181 // At present, the two constants below are duplicated in both RepositoryClientImpl
1182 // and in AuthorityItemDocumentModelHandler.
1183 final String TERM_GROUP_LIST_NAME = "TERM_GROUP_LIST_NAME";
1184 final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
1185 final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
1186 // Get this from a constant in AuthorityResource or equivalent
1187 final String PARENT_WILDCARD = "_ALL_";
1189 // Build two SQL statements, to be executed within a single transaction:
1190 // the first statement to control join order, and the second statement
1191 // representing the actual 'get filtered' query
1193 // Build the join control statement
1195 // Per http://www.postgresql.org/docs/9.2/static/runtime-config-query.html#GUC-JOIN-COLLAPSE-LIMIT
1196 // "Setting [this value] to 1 prevents any reordering of explicit JOINs.
1197 // Thus, the explicit join order specified in the query will be the
1198 // actual order in which the relations are joined."
1199 // See CSPACE-5945 for further discussion of why this setting is needed.
1201 // Adding this statement is commented out here for now. It significantly
1202 // improved query performance for authority item / term queries where
1203 // large numbers of rows were retrieved, but appears to have resulted
1204 // in consistently slower-than-desired query performance where zero or
1205 // very few records were retrieved. See notes on CSPACE-5945. - ADR 2013-04-09
1206 // String joinControlSql = "SET LOCAL join_collapse_limit TO 1;";
1208 // Build the query statement
1210 // Start with the default query
1211 String selectStatement =
1212 "SELECT DISTINCT commonschema.id"
1213 + " FROM " + handler.getServiceContext().getCommonPartLabel() + " commonschema";
1215 String joinClauses =
1217 + " ON misc.id = commonschema.id"
1218 + " INNER JOIN hierarchy hierarchy_termgroup"
1219 + " ON hierarchy_termgroup.parentid = misc.id"
1220 + " INNER JOIN " + handler.getJDBCQueryParams().get(TERM_GROUP_TABLE_NAME_PARAM) + " termgroup"
1221 + " ON termgroup.id = hierarchy_termgroup.id ";
1224 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
1225 // Value for replaceable parameter 1 in the query
1226 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
1227 // If the value of the partial term query parameter is blank ('pt='),
1228 // return all records, subject to restriction by any limit clause
1229 if (Tools.isBlank(partialTerm)) {
1232 // Otherwise, return records that match the supplied partial term
1234 " WHERE (termgroup.termdisplayname ILIKE ?)";
1237 // At present, results are ordered in code, below, rather than in SQL,
1238 // and the orderByClause below is thus intentionally blank.
1240 // To implement the orderByClause below in SQL; e.g. via
1241 // 'ORDER BY termgroup.termdisplayname', the relevant column
1242 // must be returned by the SELECT statement.
1243 String orderByClause = "";
1246 TenantBindingConfigReaderImpl tReader =
1247 ServiceMain.getInstance().getTenantBindingConfigReader();
1248 TenantBindingType tenantBinding = tReader.getTenantBinding(ctx.getTenantId());
1249 String maxListItemsLimit = TenantBindingUtils.getPropertyValue(tenantBinding,
1250 IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES);
1252 " LIMIT " + getMaxItemsLimitOnJdbcQueries(maxListItemsLimit); // implicit int-to-String conversion
1254 // After building the individual parts of the query, set the values
1255 // of replaceable parameters that will be inserted into that query
1256 // and optionally add restrictions
1258 List<String> params = new ArrayList<>();
1260 if (Tools.notBlank(whereClause)) {
1262 // Read tenant bindings configuration to determine whether
1263 // to automatically insert leading, as well as trailing, wildcards
1264 // into the term matching string.
1265 String usesStartingWildcard = TenantBindingUtils.getPropertyValue(tenantBinding,
1266 IQueryManager.TENANT_USES_STARTING_WILDCARD_FOR_PARTIAL_TERM);
1267 // Handle user-provided leading wildcard characters, in the
1268 // configuration where a leading wildcard is not automatically inserted.
1269 // (The user-provided wildcard must be in the first, or "starting"
1270 // character position in the partial term value.)
1271 if (Tools.notBlank(usesStartingWildcard)) {
1272 if (usesStartingWildcard.equalsIgnoreCase(Boolean.FALSE.toString())) {
1273 partialTerm = handleProvidedStartingWildcard(partialTerm);
1274 // Otherwise, in the configuration where a leading wildcard
1275 // is usually automatically inserted, handle the cases where
1276 // a user has entered an anchor character in the first position
1277 // in the starting term value. In those cases, strip that
1278 // anchor character and don't add a leading wildcard
1280 if (partialTerm.startsWith(USER_SUPPLIED_ANCHOR_CHAR)) {
1281 partialTerm = partialTerm.substring(1, partialTerm.length());
1282 // Otherwise, automatically add a leading wildcard
1284 partialTerm = JDBCTools.SQL_WILDCARD + partialTerm;
1288 // Add SQL wildcards in the midst of the partial term match search
1289 // expression, whever user-supplied wildcards appear, except in the
1290 // first or last character positions of the search expression.
1291 partialTerm = subtituteWildcardsInPartialTerm(partialTerm);
1293 // If a designated 'anchor character' is present as the last character
1294 // in the search expression, strip that character and don't add
1295 // a trailing wildcard
1296 int lastCharPos = partialTerm.length() - 1;
1297 if (partialTerm.endsWith(USER_SUPPLIED_ANCHOR_CHAR) && lastCharPos > 0) {
1298 partialTerm = partialTerm.substring(0, lastCharPos);
1300 // Otherwise, automatically add a trailing wildcard
1301 partialTerm = partialTerm + JDBCTools.SQL_WILDCARD;
1303 params.add(partialTerm);
1306 // Optionally add restrictions to the default query, based on variables
1307 // in the current request
1309 // Restrict the query to filter out deleted records, if requested
1310 String includeDeleted = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_NONDELETED);
1311 if (includeDeleted != null && includeDeleted.equalsIgnoreCase(Boolean.FALSE.toString())) {
1312 whereClause = whereClause
1313 + " AND (misc.lifecyclestate <> '" + WorkflowClient.WORKFLOWSTATE_DELETED + "')"
1314 + " AND (misc.lifecyclestate <> '" + WorkflowClient.WORKFLOWSTATE_LOCKED_DELETED + "')";
1317 // If a particular authority is specified, restrict the query further
1318 // to return only records within that authority
1319 String inAuthorityValue = (String) handler.getJDBCQueryParams().get(IN_AUTHORITY_PARAM);
1320 if (Tools.notBlank(inAuthorityValue)) {
1321 // Handle the '_ALL_' case for inAuthority
1322 if (inAuthorityValue.equals(PARENT_WILDCARD)) {
1323 // Add nothing to the query here if it should match within all authorities
1325 whereClause = whereClause
1326 + " AND (commonschema.inauthority = ?)";
1327 params.add(inAuthorityValue); // Value for replaceable parameter 2 in the query
1331 // Restrict the query further to return only records pertaining to
1332 // the current tenant, unless:
1333 // * Data for this service, in this tenant, is stored in its own,
1334 // separate repository, rather than being intermingled with other
1335 // tenants' data in the default repository; or
1336 // * Restriction by tenant ID in JDBC queries has been disabled,
1337 // via configuration for this tenant,
1338 if (restrictJDBCQueryByTenantID(tenantBinding, ctx)) {
1339 joinClauses = joinClauses
1340 + " INNER JOIN collectionspace_core core"
1341 + " ON core.id = hierarchy_termgroup.parentid";
1342 whereClause = whereClause
1343 + " AND (core.tenantid = ?)";
1344 params.add(ctx.getTenantId()); // Value for replaceable parameter 3 in the query
1347 // Piece together the SQL query from its parts
1348 String querySql = selectStatement + joinClauses + whereClause + orderByClause + limitClause;
1350 // Note: PostgreSQL 9.2 introduced a change that may improve performance
1351 // of certain queries using JDBC PreparedStatements. See comments on
1352 // CSPACE-5943 for details.
1354 // See a comment above for the reason that the joinControl SQL statement,
1355 // along with its corresponding prepared statement builder, is commented out for now.
1356 // PreparedStatementBuilder joinControlBuilder = new PreparedStatementBuilder(joinControlSql);
1357 PreparedStatementSimpleBuilder queryBuilder = new PreparedStatementSimpleBuilder(querySql, params);
1358 List<PreparedStatementBuilder> builders = new ArrayList<>();
1359 // builders.add(joinControlBuilder);
1360 builders.add(queryBuilder);
1361 String dataSourceName = JDBCTools.NUXEO_DATASOURCE_NAME;
1362 String repositoryName = ctx.getRepositoryName();
1363 final Boolean EXECUTE_WITHIN_TRANSACTION = true;
1364 Set<String> docIds = new HashSet<>();
1366 String cspaceInstanceId = ServiceMain.getInstance().getCspaceInstanceId();
1367 List<CachedRowSet> resultsList = JDBCTools.executePreparedQueries(builders,
1368 dataSourceName, repositoryName, cspaceInstanceId, EXECUTE_WITHIN_TRANSACTION);
1370 // At least one set of results is expected, from the second prepared
1371 // statement to be executed.
1372 // If fewer results are returned, return an empty list of document models
1373 if (resultsList == null || resultsList.size() < 1) {
1374 return result; // return an empty list of document models
1376 // The join control query (if enabled - it is currently commented
1377 // out as per comments above) will not return results, so query results
1378 // will be the first set of results (rowSet) returned in the list
1379 CachedRowSet queryResults = resultsList.get(0);
1381 // If the result from executing the query is null or contains zero rows,
1382 // return an empty list of document models
1383 if (queryResults == null) {
1384 return result; // return an empty list of document models
1386 queryResults.last();
1387 if (queryResults.getRow() == 0) {
1388 return result; // return an empty list of document models
1391 // Otherwise, get the document IDs from the results of the query
1393 queryResults.beforeFirst();
1394 while (queryResults.next()) {
1395 id = queryResults.getString(1);
1396 if (Tools.notBlank(id)) {
1400 } catch (SQLException sqle) {
1401 logger.warn("Could not obtain document IDs via SQL query '" + querySql + "': " + sqle.getMessage());
1402 return result; // return an empty list of document models
1405 // Get a list of document models, using the list of IDs obtained from the query
1407 // FIXME: Check whether we have a 'get document models from list of CSIDs'
1408 // utility method like this, and if not, add this to the appropriate
1410 DocumentModel docModel;
1411 for (String docId : docIds) {
1412 docModel = NuxeoUtils.getDocumentModel(repoSession, docId);
1413 if (docModel == null) {
1414 logger.warn("Could not obtain document model for document with ID " + docId);
1416 result.add(docModel);
1420 // Order the results
1421 final String COMMON_PART_SCHEMA = handler.getServiceContext().getCommonPartLabel();
1422 final String DISPLAY_NAME_XPATH =
1423 "//" + handler.getJDBCQueryParams().get(TERM_GROUP_LIST_NAME) + "/[0]/termDisplayName";
1424 Collections.sort(result, new Comparator<DocumentModel>() {
1426 public int compare(DocumentModel doc1, DocumentModel doc2) {
1427 String termDisplayName1 = null;
1428 String termDisplayName2 = null;
1430 termDisplayName1 = (String) NuxeoUtils.getXPathValue(doc1, COMMON_PART_SCHEMA, DISPLAY_NAME_XPATH);
1431 termDisplayName2 = (String) NuxeoUtils.getXPathValue(doc2, COMMON_PART_SCHEMA, DISPLAY_NAME_XPATH);
1432 } catch (NuxeoDocumentException e) {
1433 throw new RuntimeException(e); // We need to throw a RuntimeException because the compare() method of the Comparator interface does not support throwing an Exception
1435 return termDisplayName1.compareToIgnoreCase(termDisplayName2);
1443 private DocumentModelList getFilteredCMIS(CoreSessionInterface repoSession,
1444 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, DocumentHandler handler, QueryContext queryContext)
1445 throws DocumentNotFoundException, DocumentException {
1447 DocumentModelList result = new DocumentModelListImpl();
1449 String query = handler.getCMISQuery(queryContext);
1451 DocumentFilter docFilter = handler.getDocumentFilter();
1452 int pageSize = docFilter.getPageSize();
1453 int offset = docFilter.getOffset();
1454 if (logger.isDebugEnabled()) {
1455 logger.debug("Executing CMIS query: " + query.toString()
1456 + "with pageSize: " + pageSize + " at offset: " + offset);
1459 // If we have limit and/or offset, then pass true to get totalSize
1460 // in returned DocumentModelList.
1461 Profiler profiler = new Profiler(this, 2);
1462 profiler.log("Executing CMIS query: " + query.toString());
1465 IterableQueryResult queryResult = makeCMISQLQuery(repoSession, query, queryContext);
1467 int totalSize = (int) queryResult.size();
1468 ((DocumentModelListImpl) result).setTotalSize(totalSize);
1469 // Skip the rows before our offset
1471 queryResult.skipTo(offset);
1474 for (Map<String, Serializable> row : queryResult) {
1475 if (logger.isTraceEnabled()) {
1476 logger.trace(" Hierarchy Table ID is:" + row.get(IQueryManager.CMIS_TARGET_NUXEO_ID)
1477 + " nuxeo:pathSegment is: " + row.get(IQueryManager.CMIS_TARGET_NAME));
1479 String nuxeoId = (String) row.get(IQueryManager.CMIS_TARGET_NUXEO_ID);
1480 DocumentModel docModel = NuxeoUtils.getDocumentModel(repoSession, nuxeoId);
1481 result.add(docModel);
1483 if (nRows >= pageSize && pageSize != 0) { // A page size of zero means that they want all of them
1484 logger.debug("Got page full of items - quitting");
1489 queryResult.close();
1494 } catch (Exception e) {
1495 if (logger.isDebugEnabled()) {
1496 logger.debug("Caught exception ", e);
1498 throw new NuxeoDocumentException(e);
1502 // Since we're not supporting paging yet for CMIS queries, we need to perform
1503 // a workaround for the paging information we return in our list of results
1506 if (result != null) {
1507 docFilter.setStartPage(0);
1508 if (totalSize > docFilter.getPageSize()) {
1509 docFilter.setPageSize(totalSize);
1510 ((DocumentModelListImpl)result).setTotalSize(totalSize);
1518 private String logException(Exception e, String msg) {
1519 String result = null;
1521 String exceptionMessage = e.getMessage();
1522 exceptionMessage = exceptionMessage != null ? exceptionMessage : "<No details provided>";
1523 result = msg = msg + ". Caught exception:" + exceptionMessage;
1525 if (logger.isTraceEnabled() == true) {
1526 logger.error(msg, e);
1535 * update given document in the Nuxeo repository
1537 * @param ctx service context under which this method is invoked
1538 * @param csid of the document
1539 * @param handler should be used by the caller to provide and transform the
1541 * @throws BadRequestException
1542 * @throws DocumentNotFoundException
1543 * @throws TransactionException if the transaction times out or otherwise
1544 * cannot be successfully completed
1545 * @throws DocumentException
1548 public void update(ServiceContext ctx, String csid, DocumentHandler handler)
1549 throws BadRequestException, DocumentNotFoundException, TransactionException,
1551 if (handler == null) {
1552 throw new IllegalArgumentException(
1553 "RepositoryJavaClient.update: document handler is missing.");
1556 CoreSessionInterface repoSession = null;
1558 handler.prepare(Action.UPDATE);
1559 repoSession = getRepositorySession(ctx);
1560 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
1561 DocumentModel doc = null;
1563 doc = repoSession.getDocument(docRef);
1564 } catch (org.nuxeo.ecm.core.api.DocumentNotFoundException ce) {
1565 String msg = logException(ce,
1566 String.format("Could not find %s resource/record to update with CSID=%s", ctx.getDocumentType(), csid));
1567 throw new DocumentNotFoundException(msg, ce);
1569 // Check for a versioned document, and check In and Out before we proceed.
1570 if (((DocumentModelHandler) handler).supportsVersioning()) {
1571 /* Once we advance to 5.5 or later, we can add this.
1572 * See also https://jira.nuxeo.com/browse/NXP-8506
1573 if(!doc.isVersionable()) {
1574 throw new NuxeoDocumentException("Configuration for: "
1575 +handler.getServiceContextPath()+" supports versioning, but Nuxeo config does not!");
1578 /* Force a version number - Not working. Apparently we need to configure the uid schema??
1579 if(doc.getProperty("uid","major_version") == null) {
1580 doc.setProperty("uid","major_version",1);
1582 if(doc.getProperty("uid","minor_version") == null) {
1583 doc.setProperty("uid","minor_version",0);
1586 doc.checkIn(VersioningOption.MINOR, null);
1591 // Set reposession to handle the document
1593 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1594 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
1595 handler.handle(Action.UPDATE, wrapDoc);
1596 repoSession.saveDocument(doc);
1598 handler.complete(Action.UPDATE, wrapDoc);
1599 } catch (BadRequestException bre) {
1601 } catch (DocumentException de) {
1603 } catch (CSWebApplicationException wae) {
1605 } catch (Exception e) {
1606 throw new NuxeoDocumentException(e);
1608 if (repoSession != null) {
1609 releaseRepositorySession(ctx, repoSession);
1615 * Save a documentModel to the Nuxeo repository.
1617 * @param ctx service context under which this method is invoked
1618 * @param repoSession
1619 * @param docModel the document to save
1620 * @param fSaveSession if TRUE, will call CoreSessionInterface.save() to save
1621 * accumulated changes.
1622 * @throws ClientException
1623 * @throws DocumentException
1625 public void saveDocWithoutHandlerProcessing(
1626 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1627 CoreSessionInterface repoSession,
1628 DocumentModel docModel,
1629 boolean fSaveSession)
1630 throws ClientException, DocumentException {
1633 repoSession.saveDocument(docModel);
1637 } catch (ClientException ce) {
1639 } catch (Exception e) {
1640 if (logger.isDebugEnabled()) {
1641 logger.debug("Caught exception ", e);
1643 throw new NuxeoDocumentException(e);
1648 * Save a list of documentModels to the Nuxeo repository.
1650 * @param ctx service context under which this method is invoked
1651 * @param repoSession a repository session
1652 * @param docModelList a list of document models
1653 * @param fSaveSession if TRUE, will call CoreSessionInterface.save() to save
1654 * accumulated changes.
1655 * @throws ClientException
1656 * @throws DocumentException
1658 public void saveDocListWithoutHandlerProcessing(
1659 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1660 CoreSessionInterface repoSession,
1661 DocumentModelList docList,
1662 boolean fSaveSession)
1663 throws ClientException, DocumentException {
1665 DocumentModel[] docModelArray = new DocumentModel[docList.size()];
1666 repoSession.saveDocuments(docList.toArray(docModelArray));
1670 } catch (ClientException ce) {
1672 } catch (Exception e) {
1673 logger.error("Caught exception ", e);
1674 throw new NuxeoDocumentException(e);
1679 public void deleteWithWhereClause(@SuppressWarnings("rawtypes") ServiceContext ctx, String whereClause,
1680 @SuppressWarnings("rawtypes") DocumentHandler handler) throws
1681 DocumentNotFoundException, DocumentException {
1683 throw new IllegalArgumentException(
1684 "delete(ctx, specifier): ctx is missing");
1686 if (logger.isDebugEnabled()) {
1687 logger.debug("Deleting document with whereClause=" + whereClause);
1690 DocumentWrapper<DocumentModel> foundDocWrapper = this.findDoc(ctx, whereClause);
1691 if (foundDocWrapper != null) {
1692 DocumentModel docModel = foundDocWrapper.getWrappedObject();
1693 String csid = docModel.getName();
1694 this.delete(ctx, csid, handler);
1699 * delete a document from the Nuxeo repository
1701 * @param ctx service context under which this method is invoked
1702 * @param id of the document
1703 * @throws DocumentException
1706 public boolean delete(ServiceContext ctx, String id, DocumentHandler handler) throws DocumentNotFoundException,
1707 DocumentException, TransactionException {
1708 boolean result = true;
1711 throw new IllegalArgumentException(
1712 "delete(ctx, ix, handler): ctx is missing");
1714 if (handler == null) {
1715 throw new IllegalArgumentException(
1716 "delete(ctx, ix, handler): handler is missing");
1718 if (logger.isDebugEnabled()) {
1719 logger.debug("Deleting document with CSID=" + id);
1721 CoreSessionInterface repoSession = null;
1723 handler.prepare(Action.DELETE);
1724 repoSession = getRepositorySession(ctx);
1725 DocumentWrapper<DocumentModel> wrapDoc = null;
1727 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
1728 wrapDoc = new DocumentWrapperImpl<DocumentModel>(repoSession.getDocument(docRef));
1729 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1730 if (handler.handle(Action.DELETE, wrapDoc)) {
1731 repoSession.removeDocument(docRef);
1732 if (logger.isDebugEnabled()) {
1733 String msg = String.format("DELETE - User '%s' hard-deleted document CSID=%s of type %s.",
1734 ctx.getUserId(), id, ctx.getDocumentType());
1738 result = false; // delete failed for some reason
1740 } catch (org.nuxeo.ecm.core.api.DocumentNotFoundException ce) {
1741 String msg = logException(ce,
1742 String.format("Could not find %s resource/record to delete with CSID=%s", ctx.getDocumentType(), id));
1743 throw new DocumentNotFoundException(msg, ce);
1746 handler.complete(Action.DELETE, wrapDoc);
1747 } catch (DocumentException de) {
1749 } catch (Exception e) {
1750 if (logger.isDebugEnabled()) {
1751 logger.debug("Caught exception ", e);
1753 throw new NuxeoDocumentException(e);
1755 if (repoSession != null) {
1756 releaseRepositorySession(ctx, repoSession);
1764 * @see org.collectionspace.services.common.storage.StorageClient#delete(org.collectionspace.services.common.context.ServiceContext, java.lang.String, org.collectionspace.services.common.document.DocumentHandler)
1768 public void delete(@SuppressWarnings("rawtypes") ServiceContext ctx, String id)
1769 throws DocumentNotFoundException, DocumentException {
1770 throw new UnsupportedOperationException();
1771 // Use the other delete instead
1775 public Hashtable<String, String> retrieveWorkspaceIds(RepositoryDomainType repoDomain) throws Exception {
1776 return NuxeoConnectorEmbedded.getInstance().retrieveWorkspaceIds(repoDomain);
1780 public String createDomain(RepositoryDomainType repositoryDomain) throws Exception {
1781 CoreSessionInterface repoSession = null;
1782 String domainId = null;
1785 // Open a connection to the domain's repo/db
1787 String repoName = repositoryDomain.getRepositoryName();
1788 repoSession = getRepositorySession(repoName); // domainName=storageName=repoName=databaseName
1790 // First create the top-level domain directory
1792 String domainName = repositoryDomain.getStorageName();
1793 DocumentRef parentDocRef = new PathRef("/");
1794 DocumentModel parentDoc = repoSession.getDocument(parentDocRef);
1795 DocumentModel domainDoc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1796 domainName, NUXEO_CORE_TYPE_DOMAIN);
1797 domainDoc.setPropertyValue("dc:title", domainName);
1798 domainDoc.setPropertyValue("dc:description", "A CollectionSpace domain "
1800 domainDoc = repoSession.createDocument(domainDoc);
1801 domainId = domainDoc.getId();
1804 // Next, create a "Workspaces" root directory to contain the workspace folders for the individual service documents
1806 DocumentModel workspacesRoot = repoSession.createDocumentModel(domainDoc.getPathAsString(),
1807 NuxeoUtils.Workspaces, NUXEO_CORE_TYPE_WORKSPACEROOT);
1808 workspacesRoot.setPropertyValue("dc:title", NuxeoUtils.Workspaces);
1809 workspacesRoot.setPropertyValue("dc:description", "A CollectionSpace workspaces directory for "
1810 + domainDoc.getPathAsString());
1811 workspacesRoot = repoSession.createDocument(workspacesRoot);
1812 String workspacesRootId = workspacesRoot.getId();
1815 if (logger.isDebugEnabled()) {
1816 logger.debug("Created tenant domain name=" + domainName
1817 + " id=" + domainId + " "
1818 + NuxeoUtils.Workspaces + " id=" + workspacesRootId);
1819 logger.debug("Path to Domain: " + domainDoc.getPathAsString());
1820 logger.debug("Path to Workspaces root: " + workspacesRoot.getPathAsString());
1822 } catch (Exception e) {
1823 if (logger.isDebugEnabled()) {
1824 logger.debug("Could not create tenant domain name=" + repositoryDomain.getStorageName() + " caught exception ", e);
1828 if (repoSession != null) {
1829 releaseRepositorySession(null, repoSession);
1837 public String getDomainId(RepositoryDomainType repositoryDomain) throws Exception {
1838 String domainId = null;
1839 CoreSessionInterface repoSession = null;
1841 String repoName = repositoryDomain.getRepositoryName();
1842 String domainStorageName = repositoryDomain.getStorageName();
1843 if (domainStorageName != null && !domainStorageName.isEmpty()) {
1845 repoSession = getRepositorySession(repoName);
1846 DocumentRef docRef = new PathRef("/" + domainStorageName);
1847 DocumentModel domain = repoSession.getDocument(docRef);
1848 domainId = domain.getId();
1849 } catch (Exception e) {
1850 if (logger.isTraceEnabled()) {
1851 logger.trace("Caught exception ", e); // The document doesn't exist, this let's us know we need to create it
1853 //there is no way to identify if document does not exist due to
1854 //lack of typed exception for getDocument method
1857 if (repoSession != null) {
1858 releaseRepositorySession(null, repoSession);
1867 * Returns the workspaces root directory for a given domain.
1869 private DocumentModel getWorkspacesRoot(CoreSessionInterface repoSession,
1870 String domainName) throws Exception {
1871 DocumentModel result = null;
1873 String domainPath = "/" + domainName;
1874 DocumentRef parentDocRef = new PathRef(domainPath);
1875 DocumentModelList domainChildrenList = repoSession.getChildren(
1877 Iterator<DocumentModel> witer = domainChildrenList.iterator();
1878 while (witer.hasNext()) {
1879 DocumentModel childNode = witer.next();
1880 if (NuxeoUtils.Workspaces.equalsIgnoreCase(childNode.getName())) {
1882 logger.trace("Found workspaces directory at: " + result.getPathAsString());
1887 if (result == null) {
1888 throw new ClientException("Could not find workspace root directory in: "
1896 * @see org.collectionspace.services.common.repository.RepositoryClient#createWorkspace(java.lang.String, java.lang.String)
1899 public String createWorkspace(RepositoryDomainType repositoryDomain, String workspaceName) throws Exception {
1900 CoreSessionInterface repoSession = null;
1901 String workspaceId = null;
1903 String repoName = repositoryDomain.getRepositoryName();
1904 repoSession = getRepositorySession(repoName);
1906 String domainStorageName = repositoryDomain.getStorageName();
1907 DocumentModel parentDoc = getWorkspacesRoot(repoSession, domainStorageName);
1908 if (logger.isTraceEnabled()) {
1909 for (String facet : parentDoc.getFacets()) {
1910 logger.trace("Facet: " + facet);
1914 DocumentModel doc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1915 workspaceName, NuxeoUtils.WORKSPACE_DOCUMENT_TYPE);
1916 doc.setPropertyValue("dc:title", workspaceName);
1917 doc.setPropertyValue("dc:description", "A CollectionSpace workspace for "
1919 doc = repoSession.createDocument(doc);
1920 workspaceId = doc.getId();
1922 if (logger.isDebugEnabled()) {
1923 logger.debug("Created workspace name=" + workspaceName
1924 + " id=" + workspaceId);
1926 } catch (Exception e) {
1927 if (logger.isDebugEnabled()) {
1928 logger.debug("createWorkspace caught exception ", e);
1932 if (repoSession != null) {
1933 releaseRepositorySession(null, repoSession);
1940 * @see org.collectionspace.services.common.repository.RepositoryClient#getWorkspaceId(java.lang.String, java.lang.String)
1944 public String getWorkspaceId(String tenantDomain, String workspaceName) throws Exception {
1945 String workspaceId = null;
1947 CoreSessionInterface repoSession = null;
1949 repoSession = getRepositorySession((ServiceContext<PoxPayloadIn, PoxPayloadOut>) null);
1950 DocumentRef docRef = new PathRef(
1952 + "/" + NuxeoUtils.Workspaces
1953 + "/" + workspaceName);
1954 DocumentModel workspace = repoSession.getDocument(docRef);
1955 workspaceId = workspace.getId();
1956 } catch (DocumentException de) {
1958 } catch (Exception e) {
1959 if (logger.isDebugEnabled()) {
1960 logger.debug("Caught exception ", e);
1962 throw new NuxeoDocumentException(e);
1964 if (repoSession != null) {
1965 releaseRepositorySession(null, repoSession);
1972 public CoreSessionInterface getRepositorySession(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) throws Exception {
1973 return getRepositorySession(ctx, ctx.getRepositoryName(), ctx.getTimeoutSecs());
1976 public CoreSessionInterface getRepositorySession(String repoName) throws Exception {
1977 return getRepositorySession(null, repoName, ServiceContext.DEFAULT_TX_TIMEOUT);
1981 * Gets the repository session. - Package access only. If the 'ctx' param is
1982 * null then the repo name must be non-mull and vice-versa
1984 * @return the repository session
1985 * @throws Exception the exception
1987 public CoreSessionInterface getRepositorySession(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1989 int timeoutSeconds) throws Exception {
1990 CoreSessionInterface repoSession = null;
1992 Profiler profiler = new Profiler("getRepositorySession():", 2);
1995 // To get a connection to the Nuxeo repo, we need either a valid ServiceContext instance or a repository name
1998 repoSession = (CoreSessionInterface) ctx.getCurrentRepositorySession(); // First see if the context already has a repo session
1999 if (repoSession == null) {
2000 repoName = ctx.getRepositoryName(); // Notice we are overriding the passed in 'repoName' since we have a valid service context passed in to us
2002 } else if (repoName == null || repoName.trim().isEmpty()) {
2003 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.");
2004 logger.error(errMsg);
2005 throw new Exception(errMsg);
2007 if (repoSession == null) {
2009 // 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
2010 // just the repository name.
2012 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
2013 repoSession = client.openRepository(repoName, timeoutSeconds);
2015 if (logger.isTraceEnabled() == true) {
2016 logger.trace("Reusing the current context's repository session.");
2021 if (logger.isTraceEnabled()) {
2022 logger.trace("Testing call to getRepository() repository root: " + repoSession.getRootDocument());
2024 } catch (Throwable e) {
2025 logger.trace("Test call to Nuxeo's getRepository() repository root failed", e);
2031 ctx.setCurrentRepositorySession(repoSession); // For reusing, save the repository session in the current service context
2038 * Release repository session. - Package access only.
2040 * @param repoSession the repo session
2042 public void releaseRepositorySession(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, CoreSessionInterface repoSession) throws TransactionException {
2044 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
2047 ctx.clearCurrentRepositorySession(); //clear the current context of the now closed repo session
2048 if (ctx.getCurrentRepositorySession() == null) {
2049 client.releaseRepository(repoSession); //release the repo session if the service context's ref count is zeo.
2052 client.releaseRepository(repoSession); //repo session was acquired without a service context
2054 } catch (TransactionRuntimeException tre) {
2055 String causeMsg = null;
2056 Throwable cause = tre.getCause();
2057 if (cause != null) {
2058 causeMsg = cause.getMessage();
2061 TransactionException te; // a CollectionSpace specific tx exception
2062 if (causeMsg != null) {
2063 te = new TransactionException(causeMsg, tre);
2065 te = new TransactionException(tre);
2068 logger.error(te.getMessage(), tre); // Log the standard transaction exception message, plus an exception-specific stack trace
2070 } catch (Exception e) {
2071 logger.error("Could not close the repository session.", e);
2072 // no need to throw this service specific exception
2077 public void doWorkflowTransition(ServiceContext ctx, String id,
2078 DocumentHandler handler, TransitionDef transitionDef)
2079 throws BadRequestException, DocumentNotFoundException,
2081 // 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
2084 private String handleProvidedStartingWildcard(String partialTerm) {
2085 if (Tools.notBlank(partialTerm)) {
2086 if (partialTerm.substring(0, 1).equals(USER_SUPPLIED_WILDCARD)) {
2087 StringBuffer buffer = new StringBuffer(partialTerm);
2088 buffer.setCharAt(0, JDBCTools.SQL_WILDCARD.charAt(0));
2089 partialTerm = buffer.toString();
2096 * Replaces user-supplied wildcards with SQL wildcards, in a partial term
2097 * matching search expression.
2099 * The scope of this replacement excludes the beginning character
2100 * in that search expression, as that character is treated specially.
2102 * @param partialTerm
2103 * @return the partial term, with any user-supplied wildcards replaced
2106 private String subtituteWildcardsInPartialTerm(String partialTerm) {
2107 if (Tools.isBlank(partialTerm)) {
2110 if (! partialTerm.contains(USER_SUPPLIED_WILDCARD)) {
2113 int len = partialTerm.length();
2114 // Partial term search expressions of 2 or fewer characters
2115 // currently aren't amenable to the use of wildcards
2117 logger.warn("Partial term match search expression of just 1-2 characters in length contains a user-supplied wildcard: " + partialTerm);
2118 logger.warn("Will handle that character as a literal value, rather than as a wildcard ...");
2121 return partialTerm.substring(0, 1) // first char
2122 + partialTerm.substring(1, len).replaceAll(USER_SUPPLIED_WILDCARD_REGEX, JDBCTools.SQL_WILDCARD);
2126 private int getMaxItemsLimitOnJdbcQueries(String maxListItemsLimit) {
2127 final int DEFAULT_ITEMS_LIMIT = 40;
2128 if (maxListItemsLimit == null) {
2129 return DEFAULT_ITEMS_LIMIT;
2133 itemsLimit = Integer.parseInt(maxListItemsLimit);
2134 if (itemsLimit < 1) {
2135 logger.warn("Value of configuration setting "
2136 + IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES
2137 + " must be a positive integer; invalid current value is " + maxListItemsLimit);
2138 logger.warn("Reverting to default value of " + DEFAULT_ITEMS_LIMIT);
2139 itemsLimit = DEFAULT_ITEMS_LIMIT;
2141 } catch (NumberFormatException nfe) {
2142 logger.warn("Value of configuration setting "
2143 + IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES
2144 + " must be a positive integer; invalid current value is " + maxListItemsLimit);
2145 logger.warn("Reverting to default value of " + DEFAULT_ITEMS_LIMIT);
2146 itemsLimit = DEFAULT_ITEMS_LIMIT;
2152 * Identifies whether a restriction on tenant ID - to return only records
2153 * pertaining to the current tenant - is required in a JDBC query.
2155 * @param tenantBinding a tenant binding configuration.
2156 * @param ctx a service context.
2157 * @return true if a restriction on tenant ID is required in the query;
2158 * false if a restriction is not required.
2160 private boolean restrictJDBCQueryByTenantID(TenantBindingType tenantBinding, ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
2161 boolean restrict = true;
2162 // If data for the current service, in the current tenant, is isolated
2163 // within its own separate, per-tenant repository, as contrasted with
2164 // being intermingled with other tenants' data in the default repository,
2165 // no restriction on Tenant ID is required in the query.
2166 String repositoryDomainName = ConfigUtils.getRepositoryName(tenantBinding, ctx.getRepositoryDomainName());
2167 if (!(repositoryDomainName.equals(ConfigUtils.DEFAULT_NUXEO_REPOSITORY_NAME))) {
2170 // If a configuration setting for this tenant identifies that JDBC
2171 // queries should not be restricted by tenant ID (perhaps because
2172 // there is always expected to be only one tenant's data present in
2173 // the system), no restriction on Tenant ID is required in the query.
2174 String queriesRestrictedByTenantId = TenantBindingUtils.getPropertyValue(tenantBinding,
2175 IQueryManager.JDBC_QUERIES_ARE_TENANT_ID_RESTRICTED);
2176 if (Tools.notBlank(queriesRestrictedByTenantId) &&
2177 queriesRestrictedByTenantId.equalsIgnoreCase(Boolean.FALSE.toString())) {