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) {
380 } catch (Exception e) {
381 if (logger.isDebugEnabled()) {
382 logger.debug("Caught exception ", e);
384 throw new NuxeoDocumentException(e);
386 if (repoSession != null) {
387 releaseRepositorySession(ctx, repoSession);
393 * get a document from the Nuxeo repository, using the docFilter params.
395 * @param ctx service context under which this method is invoked
396 * @param handler should be used by the caller to provide and transform the
397 * document. Handler must have a docFilter set to return a single item.
398 * @throws DocumentNotFoundException if the document cannot be found in the
400 * @throws TransactionException
401 * @throws DocumentException
404 public void get(ServiceContext ctx, DocumentHandler handler)
405 throws DocumentNotFoundException, TransactionException, DocumentException {
406 QueryContext queryContext = new QueryContext(ctx, handler);
407 CoreSessionInterface repoSession = null;
410 handler.prepare(Action.GET);
411 repoSession = getRepositorySession(ctx);
413 DocumentModelList docList = null;
414 // force limit to 1, and ignore totalSize
415 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
416 docList = repoSession.query(query, null, 1, 0, false);
417 if (docList.size() != 1) {
418 throw new DocumentNotFoundException("No document found matching filter params: " + query);
420 DocumentModel doc = docList.get(0);
422 if (logger.isDebugEnabled()) {
423 logger.debug("Executed NXQL query: " + query);
426 //set reposession to handle the document
427 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
428 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
429 handler.handle(Action.GET, wrapDoc);
430 handler.complete(Action.GET, wrapDoc);
431 } catch (IllegalArgumentException iae) {
433 } catch (DocumentException de) {
435 } catch (Exception e) {
436 if (logger.isDebugEnabled()) {
437 logger.debug("Caught exception ", e);
439 throw new NuxeoDocumentException(e);
441 if (repoSession != null) {
442 releaseRepositorySession(ctx, repoSession);
447 public DocumentWrapper<DocumentModel> getDoc(
448 CoreSessionInterface repoSession,
449 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
450 String csid) throws DocumentNotFoundException, DocumentException {
451 DocumentWrapper<DocumentModel> wrapDoc = null;
454 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
455 DocumentModel doc = null;
457 doc = repoSession.getDocument(docRef);
458 } catch (ClientException ce) {
459 String msg = logException(ce, "Could not find document with CSID=" + csid);
460 throw new DocumentNotFoundException(msg, ce);
462 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
463 } catch (IllegalArgumentException iae) {
465 } catch (DocumentException de) {
473 * Get wrapped documentModel from the Nuxeo repository. The search is
474 * restricted to the workspace of the current context.
476 * @param ctx service context under which this method is invoked
477 * @param csid of the document to retrieve
478 * @throws DocumentNotFoundException
479 * @throws TransactionException
480 * @throws DocumentException
481 * @return a wrapped documentModel
484 public DocumentWrapper<DocumentModel> getDoc(
485 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
486 String csid) throws DocumentNotFoundException, TransactionException, DocumentException {
487 CoreSessionInterface repoSession = null;
488 DocumentWrapper<DocumentModel> wrapDoc = null;
491 // Open a new repository session
492 repoSession = getRepositorySession(ctx);
493 wrapDoc = getDoc(repoSession, ctx, csid);
494 } catch (IllegalArgumentException iae) {
496 } catch (DocumentException de) {
498 } catch (Exception e) {
499 if (logger.isDebugEnabled()) {
500 logger.debug("Caught exception ", e);
502 throw new NuxeoDocumentException(e);
504 if (repoSession != null) {
505 releaseRepositorySession(ctx, repoSession);
509 if (logger.isWarnEnabled() == true) {
510 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
515 public DocumentWrapper<DocumentModel> findDoc(
516 CoreSessionInterface repoSession,
517 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
519 throws DocumentNotFoundException, DocumentException {
520 DocumentWrapper<DocumentModel> wrapDoc = null;
523 QueryContext queryContext = new QueryContext(ctx, whereClause);
524 DocumentModelList docList = null;
525 // force limit to 1, and ignore totalSize
526 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
527 docList = repoSession.query(query,
532 if (docList.size() != 1) {
533 if (logger.isDebugEnabled()) {
534 logger.debug("findDoc: Query found: " + docList.size() + " items.");
535 logger.debug(" Query: " + query);
537 throw new DocumentNotFoundException("No document found matching filter params: " + query);
539 DocumentModel doc = docList.get(0);
540 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
541 } catch (IllegalArgumentException iae) {
543 } catch (DocumentException de) {
545 } catch (Exception e) {
546 if (logger.isDebugEnabled()) {
547 logger.debug("Caught exception ", e);
549 throw new NuxeoDocumentException(e);
556 * find wrapped documentModel from the Nuxeo repository
558 * @param ctx service context under which this method is invoked
559 * @param whereClause where NXQL where clause to get the document
560 * @throws DocumentNotFoundException
561 * @throws TransactionException
562 * @throws DocumentException
563 * @return a wrapped documentModel retrieved by the repository query
566 public DocumentWrapper<DocumentModel> findDoc(
567 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
569 throws DocumentNotFoundException, TransactionException, DocumentException {
570 CoreSessionInterface repoSession = null;
571 DocumentWrapper<DocumentModel> wrapDoc = null;
574 repoSession = getRepositorySession(ctx);
575 wrapDoc = findDoc(repoSession, ctx, whereClause);
576 } catch (DocumentNotFoundException dnfe) {
578 } catch (DocumentException de) {
580 } catch (Exception e) {
581 if (repoSession == null) {
582 throw new NuxeoDocumentException("Unable to create a Nuxeo repository session.", e);
584 throw new NuxeoDocumentException("Unexpected Nuxeo exception.", e);
587 if (repoSession != null) {
588 releaseRepositorySession(ctx, repoSession);
592 if (logger.isWarnEnabled() == true) {
593 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
600 * find doc and return CSID from the Nuxeo repository
603 * @param ctx service context under which this method is invoked
604 * @param whereClause where NXQL where clause to get the document
605 * @throws DocumentNotFoundException
606 * @throws TransactionException
607 * @throws DocumentException
608 * @return the CollectionSpace ID (CSID) of the requested document
611 public String findDocCSID(CoreSessionInterface repoSession,
612 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String whereClause)
613 throws DocumentNotFoundException, TransactionException, DocumentException {
615 boolean releaseSession = false;
617 if (repoSession == null) {
618 repoSession = this.getRepositorySession(ctx);
619 releaseSession = true;
621 DocumentWrapper<DocumentModel> wrapDoc = findDoc(repoSession, ctx, whereClause);
622 DocumentModel docModel = wrapDoc.getWrappedObject();
623 csid = NuxeoUtils.getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
624 } catch (DocumentNotFoundException dnfe) {
626 } catch (IllegalArgumentException iae) {
628 } catch (DocumentException de) {
630 } catch (Exception e) {
631 if (logger.isDebugEnabled()) {
632 logger.debug("Caught exception ", e);
634 throw new NuxeoDocumentException(e);
636 if (releaseSession && (repoSession != null)) {
637 this.releaseRepositorySession(ctx, repoSession);
643 public DocumentWrapper<DocumentModelList> findDocs(
644 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
645 CoreSessionInterface repoSession,
646 List<String> docTypes,
648 String orderByClause,
651 boolean computeTotal)
652 throws DocumentNotFoundException, DocumentException {
653 DocumentWrapper<DocumentModelList> wrapDoc = null;
656 if (docTypes == null || docTypes.size() < 1) {
657 throw new DocumentNotFoundException(
658 "The findDocs() method must specify at least one DocumentType.");
660 DocumentModelList docList = null;
661 QueryContext queryContext = new QueryContext(ctx, whereClause, orderByClause);
662 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
663 if (logger.isDebugEnabled()) {
664 logger.debug("findDocs() NXQL: " + query);
666 docList = repoSession.query(query, null, pageSize, pageSize * pageNum, computeTotal);
667 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
668 } catch (IllegalArgumentException iae) {
670 } catch (Exception e) {
671 if (logger.isDebugEnabled()) {
672 logger.debug("Caught exception ", e);
674 throw new NuxeoDocumentException(e);
680 protected static String buildInListForDocTypes(List<String> docTypes) {
681 StringBuilder sb = new StringBuilder();
683 boolean first = true;
684 for (String docType : docTypes) {
695 return sb.toString();
698 public DocumentWrapper<DocumentModelList> findDocs(
699 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
700 DocumentHandler handler,
701 CoreSessionInterface repoSession,
702 List<String> docTypes)
703 throws DocumentNotFoundException, DocumentException {
704 DocumentWrapper<DocumentModelList> wrapDoc = null;
706 DocumentFilter filter = handler.getDocumentFilter();
707 String oldOrderBy = filter.getOrderByClause();
708 if (isClauseEmpty(oldOrderBy) == true) {
709 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
711 QueryContext queryContext = new QueryContext(ctx, handler);
714 if (docTypes == null || docTypes.size() < 1) {
715 throw new DocumentNotFoundException(
716 "The findDocs() method must specify at least one DocumentType.");
718 DocumentModelList docList = null;
719 if (handler.isCMISQuery() == true) {
720 String inList = buildInListForDocTypes(docTypes);
721 ctx.getQueryParams().add(IQueryManager.SEARCH_RELATED_MATCH_OBJ_DOCTYPES, inList);
722 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
724 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
725 if (logger.isDebugEnabled()) {
726 logger.debug("findDocs() NXQL: " + query);
728 docList = repoSession.query(query, null, filter.getPageSize(), filter.getOffset(), true);
730 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
731 } catch (IllegalArgumentException iae) {
733 } catch (Exception e) {
734 if (logger.isDebugEnabled()) {
735 logger.debug("Caught exception ", e);
737 throw new NuxeoDocumentException(e);
744 * Find a list of documentModels from the Nuxeo repository
746 * @param docTypes a list of DocType names to match
747 * @param whereClause where the clause to qualify on
748 * @throws DocumentNotFoundException
749 * @throws TransactionException
750 * @throws DocumentException
751 * @return a list of documentModels
754 public DocumentWrapper<DocumentModelList> findDocs(
755 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
756 List<String> docTypes,
758 int pageSize, int pageNum, boolean computeTotal)
759 throws DocumentNotFoundException, TransactionException, DocumentException {
760 CoreSessionInterface repoSession = null;
761 DocumentWrapper<DocumentModelList> wrapDoc = null;
764 repoSession = getRepositorySession(ctx);
765 wrapDoc = findDocs(ctx, repoSession, docTypes, whereClause, null,
766 pageSize, pageNum, computeTotal);
767 } catch (IllegalArgumentException iae) {
769 } catch (Exception e) {
770 if (logger.isDebugEnabled()) {
771 logger.debug("Caught exception ", e);
773 throw new NuxeoDocumentException(e);
775 if (repoSession != null) {
776 releaseRepositorySession(ctx, repoSession);
780 if (logger.isWarnEnabled() == true) {
781 logger.warn("Returned DocumentModelList instance was created with a repository session that is now closed.");
788 * @see org.collectionspace.services.common.storage.StorageClient#get(org.collectionspace.services.common.context.ServiceContext, java.util.List, org.collectionspace.services.common.document.DocumentHandler)
791 public void get(ServiceContext ctx, List<String> csidList, DocumentHandler handler)
792 throws DocumentNotFoundException, TransactionException, DocumentException {
793 if (handler == null) {
794 throw new IllegalArgumentException(
795 "RepositoryJavaClient.getAll: handler is missing");
798 CoreSessionInterface repoSession = null;
800 handler.prepare(Action.GET_ALL);
801 repoSession = getRepositorySession(ctx);
802 DocumentModelList docModelList = new DocumentModelListImpl();
803 //FIXME: Should be using NuxeoUtils.createPathRef for security reasons
804 for (String csid : csidList) {
805 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
806 DocumentModel docModel = repoSession.getDocument(docRef);
807 docModelList.add(docModel);
810 //set reposession to handle the document
811 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
812 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docModelList);
813 handler.handle(Action.GET_ALL, wrapDoc);
814 handler.complete(Action.GET_ALL, wrapDoc);
815 } catch (DocumentException de) {
817 } catch (Exception e) {
818 if (logger.isDebugEnabled()) {
819 logger.debug("Caught exception ", e);
821 throw new NuxeoDocumentException(e);
823 if (repoSession != null) {
824 releaseRepositorySession(ctx, repoSession);
830 * getAll get all documents for an entity entity service from the Nuxeo
833 * @param ctx service context under which this method is invoked
834 * @param handler should be used by the caller to provide and transform the
836 * @throws DocumentNotFoundException
837 * @throws TransactionException
838 * @throws DocumentException
841 public void getAll(ServiceContext ctx, DocumentHandler handler)
842 throws DocumentNotFoundException, TransactionException, DocumentException {
843 if (handler == null) {
844 throw new IllegalArgumentException(
845 "RepositoryJavaClient.getAll: handler is missing");
847 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
848 if (nuxeoWspaceId == null) {
849 throw new DocumentNotFoundException(
850 "Unable to find workspace for service "
851 + ctx.getServiceName()
852 + " check if the workspace exists in the Nuxeo repository.");
855 CoreSessionInterface repoSession = null;
857 handler.prepare(Action.GET_ALL);
858 repoSession = getRepositorySession(ctx);
859 DocumentRef wsDocRef = new IdRef(nuxeoWspaceId);
860 DocumentModelList docList = repoSession.getChildren(wsDocRef);
861 //set reposession to handle the document
862 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
863 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
864 handler.handle(Action.GET_ALL, wrapDoc);
865 handler.complete(Action.GET_ALL, wrapDoc);
866 } catch (DocumentException de) {
868 } catch (Exception e) {
869 if (logger.isDebugEnabled()) {
870 logger.debug("Caught exception ", e);
872 throw new NuxeoDocumentException(e);
874 if (repoSession != null) {
875 releaseRepositorySession(ctx, repoSession);
880 private boolean isClauseEmpty(String theString) {
881 boolean result = true;
882 if (theString != null && !theString.isEmpty()) {
888 public DocumentWrapper<DocumentModel> getDocFromCsid(
889 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
890 CoreSessionInterface repoSession,
893 DocumentWrapper<DocumentModel> result = null;
895 result = new DocumentWrapperImpl<DocumentModel>(NuxeoUtils.getDocFromCsid(ctx, repoSession, csid));
901 * A method to find a CollectionSpace document (of any type) given just a service context and
902 * its CSID. A search across *all* service workspaces (within a given tenant context) is performed to find
905 * This query searches Nuxeo's Hierarchy table where our CSIDs are stored in the "name" column.
908 public DocumentWrapper<DocumentModel> getDocFromCsid(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
911 DocumentWrapper<DocumentModel> result = null;
912 CoreSessionInterface repoSession = null;
914 repoSession = getRepositorySession(ctx);
915 result = getDocFromCsid(ctx, repoSession, csid);
917 if (repoSession != null) {
918 releaseRepositorySession(ctx, repoSession);
922 if (logger.isWarnEnabled() == true) {
923 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
930 * Returns a URI value for a document in the Nuxeo repository
932 * @param wrappedDoc a wrapped documentModel
933 * @throws ClientException
934 * @return a document URI
937 public String getDocURI(DocumentWrapper<DocumentModel> wrappedDoc) throws ClientException {
938 DocumentModel docModel = wrappedDoc.getWrappedObject();
939 String uri = (String) docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
940 CollectionSpaceClient.COLLECTIONSPACE_CORE_URI);
945 * See CSPACE-5036 - How to make CMISQL queries from Nuxeo
947 private IterableQueryResult makeCMISQLQuery(CoreSessionInterface repoSession, String query, QueryContext queryContext) throws DocumentException {
948 IterableQueryResult result = null;
949 /** Threshold over which temporary files are not kept in memory. */
950 final int THRESHOLD = 1024 * 1024;
953 logger.debug(String.format("Performing a CMIS query on Nuxeo repository named %s",
954 repoSession.getRepositoryName()));
956 ThresholdOutputStreamFactory streamFactory = ThresholdOutputStreamFactory.newInstance(
957 null, THRESHOLD, -1, false);
958 CallContextImpl callContext = new CallContextImpl(
959 CallContext.BINDING_LOCAL,
960 CmisVersion.CMIS_1_1,
961 repoSession.getRepositoryName(),
962 null, // ServletContext
963 null, // HttpServletRequest
964 null, // HttpServletResponse
965 new NuxeoCmisServiceFactory(),
967 callContext.put(CallContext.USERNAME, repoSession.getPrincipal().getName());
969 NuxeoCmisService cmisService = new NuxeoCmisService(repoSession.getCoreSession());
970 result = repoSession.queryAndFetch(query, "CMISQL", cmisService);
971 } catch (ClientException e) {
972 // TODO Auto-generated catch block
973 logger.error("Encounter trouble making the following CMIS query: " + query, e);
974 throw new NuxeoDocumentException(e);
981 * getFiltered get all documents for an entity service from the Document
982 * repository, given filter parameters specified by the handler.
984 * @param ctx service context under which this method is invoked
985 * @param handler should be used by the caller to provide and transform the
987 * @throws DocumentNotFoundException if workspace not found
988 * @throws TransactionException
989 * @throws DocumentException
992 public void getFiltered(ServiceContext ctx, DocumentHandler handler)
993 throws DocumentNotFoundException, TransactionException, DocumentException {
995 DocumentFilter filter = handler.getDocumentFilter();
996 String oldOrderBy = filter.getOrderByClause();
997 if (isClauseEmpty(oldOrderBy) == true) {
998 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
1000 QueryContext queryContext = new QueryContext(ctx, handler);
1002 CoreSessionInterface repoSession = null;
1004 handler.prepare(Action.GET_ALL);
1005 repoSession = getRepositorySession(ctx); //Keeps a refcount here for the repository session so you need to release this when finished
1007 DocumentModelList docList = null;
1009 if (handler.isJDBCQuery() == true) {
1010 docList = getFilteredJDBC(repoSession, ctx, handler);
1012 } else if (handler.isCMISQuery() == true) {
1013 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext); //FIXME: REM - Need to deal with paging info in CMIS query
1016 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
1017 if (logger.isDebugEnabled()) {
1018 logger.debug("Executing NXQL query: " + query.toString());
1020 Profiler profiler = new Profiler(this, 2);
1021 profiler.log("Executing NXQL query: " + query.toString());
1023 // If we have a page size and/or offset, then reflect those values
1024 // when constructing the query, and also pass 'true' to get totalSize
1025 // in the returned DocumentModelList.
1026 if ((queryContext.getDocFilter().getOffset() > 0) || (queryContext.getDocFilter().getPageSize() > 0)) {
1027 docList = repoSession.query(query, null,
1028 queryContext.getDocFilter().getPageSize(), queryContext.getDocFilter().getOffset(), true);
1030 docList = repoSession.query(query);
1035 //set repoSession to handle the document
1036 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1037 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
1038 handler.handle(Action.GET_ALL, wrapDoc);
1039 handler.complete(Action.GET_ALL, wrapDoc);
1040 } catch (DocumentException de) {
1042 } catch (Exception e) {
1043 if (logger.isDebugEnabled()) {
1044 logger.debug("Caught exception ", e); // REM - 1/17/2014: Check for org.nuxeo.ecm.core.api.ClientException and re-attempt
1046 throw new NuxeoDocumentException(e);
1048 if (repoSession != null) {
1049 releaseRepositorySession(ctx, repoSession);
1055 * Perform a database query, via JDBC and SQL, to retrieve matching records
1056 * based on filter criteria.
1058 * Although this method currently has a general-purpose name, it is
1059 * currently dedicated to a specific task: that of improving performance
1060 * for partial term matching queries on authority items / terms, via
1061 * the use of a hand-tuned SQL query, rather than via the generated SQL
1062 * produced by Nuxeo from an NXQL query. (See CSPACE-6361 for a task
1063 * to generalize this method.)
1065 * @param repoSession a repository session.
1066 * @param ctx the service context.
1067 * @param handler a relevant document handler.
1068 * @return a list of document models matching the search criteria.
1071 private DocumentModelList getFilteredJDBC(CoreSessionInterface repoSession, ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1072 DocumentHandler handler) throws Exception {
1073 DocumentModelList result = new DocumentModelListImpl();
1075 // FIXME: Get all of the following values from appropriate external constants.
1077 // At present, the two constants below are duplicated in both RepositoryClientImpl
1078 // and in AuthorityItemDocumentModelHandler.
1079 final String TERM_GROUP_LIST_NAME = "TERM_GROUP_LIST_NAME";
1080 final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
1081 final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
1082 // Get this from a constant in AuthorityResource or equivalent
1083 final String PARENT_WILDCARD = "_ALL_";
1085 // Build two SQL statements, to be executed within a single transaction:
1086 // the first statement to control join order, and the second statement
1087 // representing the actual 'get filtered' query
1089 // Build the join control statement
1091 // Per http://www.postgresql.org/docs/9.2/static/runtime-config-query.html#GUC-JOIN-COLLAPSE-LIMIT
1092 // "Setting [this value] to 1 prevents any reordering of explicit JOINs.
1093 // Thus, the explicit join order specified in the query will be the
1094 // actual order in which the relations are joined."
1095 // See CSPACE-5945 for further discussion of why this setting is needed.
1097 // Adding this statement is commented out here for now. It significantly
1098 // improved query performance for authority item / term queries where
1099 // large numbers of rows were retrieved, but appears to have resulted
1100 // in consistently slower-than-desired query performance where zero or
1101 // very few records were retrieved. See notes on CSPACE-5945. - ADR 2013-04-09
1102 // String joinControlSql = "SET LOCAL join_collapse_limit TO 1;";
1104 // Build the query statement
1106 // Start with the default query
1107 String selectStatement =
1108 "SELECT DISTINCT commonschema.id"
1109 + " FROM " + handler.getServiceContext().getCommonPartLabel() + " commonschema";
1111 String joinClauses =
1113 + " ON misc.id = commonschema.id"
1114 + " INNER JOIN hierarchy hierarchy_termgroup"
1115 + " ON hierarchy_termgroup.parentid = misc.id"
1116 + " INNER JOIN " + handler.getJDBCQueryParams().get(TERM_GROUP_TABLE_NAME_PARAM) + " termgroup"
1117 + " ON termgroup.id = hierarchy_termgroup.id ";
1120 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
1121 // Value for replaceable parameter 1 in the query
1122 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
1123 // If the value of the partial term query parameter is blank ('pt='),
1124 // return all records, subject to restriction by any limit clause
1125 if (Tools.isBlank(partialTerm)) {
1128 // Otherwise, return records that match the supplied partial term
1130 " WHERE (termgroup.termdisplayname ILIKE ?)";
1133 // At present, results are ordered in code, below, rather than in SQL,
1134 // and the orderByClause below is thus intentionally blank.
1136 // To implement the orderByClause below in SQL; e.g. via
1137 // 'ORDER BY termgroup.termdisplayname', the relevant column
1138 // must be returned by the SELECT statement.
1139 String orderByClause = "";
1142 TenantBindingConfigReaderImpl tReader =
1143 ServiceMain.getInstance().getTenantBindingConfigReader();
1144 TenantBindingType tenantBinding = tReader.getTenantBinding(ctx.getTenantId());
1145 String maxListItemsLimit = TenantBindingUtils.getPropertyValue(tenantBinding,
1146 IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES);
1148 " LIMIT " + getMaxItemsLimitOnJdbcQueries(maxListItemsLimit); // implicit int-to-String conversion
1150 // After building the individual parts of the query, set the values
1151 // of replaceable parameters that will be inserted into that query
1152 // and optionally add restrictions
1154 List<String> params = new ArrayList<>();
1156 if (Tools.notBlank(whereClause)) {
1158 // Read tenant bindings configuration to determine whether
1159 // to automatically insert leading, as well as trailing, wildcards
1160 // into the term matching string.
1161 String usesStartingWildcard = TenantBindingUtils.getPropertyValue(tenantBinding,
1162 IQueryManager.TENANT_USES_STARTING_WILDCARD_FOR_PARTIAL_TERM);
1163 // Handle user-provided leading wildcard characters, in the
1164 // configuration where a leading wildcard is not automatically inserted.
1165 // (The user-provided wildcard must be in the first, or "starting"
1166 // character position in the partial term value.)
1167 if (Tools.notBlank(usesStartingWildcard)) {
1168 if (usesStartingWildcard.equalsIgnoreCase(Boolean.FALSE.toString())) {
1169 partialTerm = handleProvidedStartingWildcard(partialTerm);
1170 // Otherwise, in the configuration where a leading wildcard
1171 // is usually automatically inserted, handle the cases where
1172 // a user has entered an anchor character in the first position
1173 // in the starting term value. In those cases, strip that
1174 // anchor character and don't add a leading wildcard
1176 if (partialTerm.startsWith(USER_SUPPLIED_ANCHOR_CHAR)) {
1177 partialTerm = partialTerm.substring(1, partialTerm.length());
1178 // Otherwise, automatically add a leading wildcard
1180 partialTerm = JDBCTools.SQL_WILDCARD + partialTerm;
1184 // Add SQL wildcards in the midst of the partial term match search
1185 // expression, whever user-supplied wildcards appear, except in the
1186 // first or last character positions of the search expression.
1187 partialTerm = subtituteWildcardsInPartialTerm(partialTerm);
1189 // If a designated 'anchor character' is present as the last character
1190 // in the search expression, strip that character and don't add
1191 // a trailing wildcard
1192 int lastCharPos = partialTerm.length() - 1;
1193 if (partialTerm.endsWith(USER_SUPPLIED_ANCHOR_CHAR) && lastCharPos > 0) {
1194 partialTerm = partialTerm.substring(0, lastCharPos);
1196 // Otherwise, automatically add a trailing wildcard
1197 partialTerm = partialTerm + JDBCTools.SQL_WILDCARD;
1199 params.add(partialTerm);
1202 // Optionally add restrictions to the default query, based on variables
1203 // in the current request
1205 // Restrict the query to filter out deleted records, if requested
1206 String includeDeleted = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_NONDELETED);
1207 if (includeDeleted != null && includeDeleted.equalsIgnoreCase(Boolean.FALSE.toString())) {
1208 whereClause = whereClause
1209 + " AND (misc.lifecyclestate <> '" + WorkflowClient.WORKFLOWSTATE_DELETED + "')"
1210 + " AND (misc.lifecyclestate <> '" + WorkflowClient.WORKFLOWSTATE_LOCKED_DELETED + "')";
1213 // If a particular authority is specified, restrict the query further
1214 // to return only records within that authority
1215 String inAuthorityValue = (String) handler.getJDBCQueryParams().get(IN_AUTHORITY_PARAM);
1216 if (Tools.notBlank(inAuthorityValue)) {
1217 // Handle the '_ALL_' case for inAuthority
1218 if (inAuthorityValue.equals(PARENT_WILDCARD)) {
1219 // Add nothing to the query here if it should match within all authorities
1221 whereClause = whereClause
1222 + " AND (commonschema.inauthority = ?)";
1223 params.add(inAuthorityValue); // Value for replaceable parameter 2 in the query
1227 // Restrict the query further to return only records pertaining to
1228 // the current tenant, unless:
1229 // * Data for this service, in this tenant, is stored in its own,
1230 // separate repository, rather than being intermingled with other
1231 // tenants' data in the default repository; or
1232 // * Restriction by tenant ID in JDBC queries has been disabled,
1233 // via configuration for this tenant,
1234 if (restrictJDBCQueryByTenantID(tenantBinding, ctx)) {
1235 joinClauses = joinClauses
1236 + " INNER JOIN collectionspace_core core"
1237 + " ON core.id = hierarchy_termgroup.parentid";
1238 whereClause = whereClause
1239 + " AND (core.tenantid = ?)";
1240 params.add(ctx.getTenantId()); // Value for replaceable parameter 3 in the query
1243 // Piece together the SQL query from its parts
1244 String querySql = selectStatement + joinClauses + whereClause + orderByClause + limitClause;
1246 // Note: PostgreSQL 9.2 introduced a change that may improve performance
1247 // of certain queries using JDBC PreparedStatements. See comments on
1248 // CSPACE-5943 for details.
1250 // See a comment above for the reason that the joinControl SQL statement,
1251 // along with its corresponding prepared statement builder, is commented out for now.
1252 // PreparedStatementBuilder joinControlBuilder = new PreparedStatementBuilder(joinControlSql);
1253 PreparedStatementSimpleBuilder queryBuilder = new PreparedStatementSimpleBuilder(querySql, params);
1254 List<PreparedStatementBuilder> builders = new ArrayList<>();
1255 // builders.add(joinControlBuilder);
1256 builders.add(queryBuilder);
1257 String dataSourceName = JDBCTools.NUXEO_DATASOURCE_NAME;
1258 String repositoryName = ctx.getRepositoryName();
1259 final Boolean EXECUTE_WITHIN_TRANSACTION = true;
1260 Set<String> docIds = new HashSet<>();
1262 String cspaceInstanceId = ServiceMain.getInstance().getCspaceInstanceId();
1263 List<CachedRowSet> resultsList = JDBCTools.executePreparedQueries(builders,
1264 dataSourceName, repositoryName, cspaceInstanceId, EXECUTE_WITHIN_TRANSACTION);
1266 // At least one set of results is expected, from the second prepared
1267 // statement to be executed.
1268 // If fewer results are returned, return an empty list of document models
1269 if (resultsList == null || resultsList.size() < 1) {
1270 return result; // return an empty list of document models
1272 // The join control query (if enabled - it is currently commented
1273 // out as per comments above) will not return results, so query results
1274 // will be the first set of results (rowSet) returned in the list
1275 CachedRowSet queryResults = resultsList.get(0);
1277 // If the result from executing the query is null or contains zero rows,
1278 // return an empty list of document models
1279 if (queryResults == null) {
1280 return result; // return an empty list of document models
1282 queryResults.last();
1283 if (queryResults.getRow() == 0) {
1284 return result; // return an empty list of document models
1287 // Otherwise, get the document IDs from the results of the query
1289 queryResults.beforeFirst();
1290 while (queryResults.next()) {
1291 id = queryResults.getString(1);
1292 if (Tools.notBlank(id)) {
1296 } catch (SQLException sqle) {
1297 logger.warn("Could not obtain document IDs via SQL query '" + querySql + "': " + sqle.getMessage());
1298 return result; // return an empty list of document models
1301 // Get a list of document models, using the list of IDs obtained from the query
1303 // FIXME: Check whether we have a 'get document models from list of CSIDs'
1304 // utility method like this, and if not, add this to the appropriate
1306 DocumentModel docModel;
1307 for (String docId : docIds) {
1308 docModel = NuxeoUtils.getDocumentModel(repoSession, docId);
1309 if (docModel == null) {
1310 logger.warn("Could not obtain document model for document with ID " + docId);
1312 result.add(docModel);
1316 // Order the results
1317 final String COMMON_PART_SCHEMA = handler.getServiceContext().getCommonPartLabel();
1318 final String DISPLAY_NAME_XPATH =
1319 "//" + handler.getJDBCQueryParams().get(TERM_GROUP_LIST_NAME) + "/[0]/termDisplayName";
1320 Collections.sort(result, new Comparator<DocumentModel>() {
1322 public int compare(DocumentModel doc1, DocumentModel doc2) {
1323 String termDisplayName1 = null;
1324 String termDisplayName2 = null;
1326 termDisplayName1 = (String) NuxeoUtils.getXPathValue(doc1, COMMON_PART_SCHEMA, DISPLAY_NAME_XPATH);
1327 termDisplayName2 = (String) NuxeoUtils.getXPathValue(doc2, COMMON_PART_SCHEMA, DISPLAY_NAME_XPATH);
1328 } catch (NuxeoDocumentException e) {
1329 throw new RuntimeException(e); // We need to throw a RuntimeException because the compare() method of the Comparator interface does not support throwing an Exception
1331 return termDisplayName1.compareToIgnoreCase(termDisplayName2);
1339 private DocumentModelList getFilteredCMIS(CoreSessionInterface repoSession,
1340 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, DocumentHandler handler, QueryContext queryContext)
1341 throws DocumentNotFoundException, DocumentException {
1343 DocumentModelList result = new DocumentModelListImpl();
1345 String query = handler.getCMISQuery(queryContext);
1347 DocumentFilter docFilter = handler.getDocumentFilter();
1348 int pageSize = docFilter.getPageSize();
1349 int offset = docFilter.getOffset();
1350 if (logger.isDebugEnabled()) {
1351 logger.debug("Executing CMIS query: " + query.toString()
1352 + "with pageSize: " + pageSize + " at offset: " + offset);
1355 // If we have limit and/or offset, then pass true to get totalSize
1356 // in returned DocumentModelList.
1357 Profiler profiler = new Profiler(this, 2);
1358 profiler.log("Executing CMIS query: " + query.toString());
1361 IterableQueryResult queryResult = makeCMISQLQuery(repoSession, query, queryContext);
1363 int totalSize = (int) queryResult.size();
1364 ((DocumentModelListImpl) result).setTotalSize(totalSize);
1365 // Skip the rows before our offset
1367 queryResult.skipTo(offset);
1370 for (Map<String, Serializable> row : queryResult) {
1371 if (logger.isTraceEnabled()) {
1372 logger.trace(" Hierarchy Table ID is:" + row.get(IQueryManager.CMIS_TARGET_NUXEO_ID)
1373 + " nuxeo:pathSegment is: " + row.get(IQueryManager.CMIS_TARGET_NAME));
1375 String nuxeoId = (String) row.get(IQueryManager.CMIS_TARGET_NUXEO_ID);
1376 DocumentModel docModel = NuxeoUtils.getDocumentModel(repoSession, nuxeoId);
1377 result.add(docModel);
1379 if (nRows >= pageSize && pageSize != 0) { // A page size of zero means that they want all of them
1380 logger.debug("Got page full of items - quitting");
1385 queryResult.close();
1390 } catch (Exception e) {
1391 if (logger.isDebugEnabled()) {
1392 logger.debug("Caught exception ", e);
1394 throw new NuxeoDocumentException(e);
1398 // Since we're not supporting paging yet for CMIS queries, we need to perform
1399 // a workaround for the paging information we return in our list of results
1402 if (result != null) {
1403 docFilter.setStartPage(0);
1404 if (totalSize > docFilter.getPageSize()) {
1405 docFilter.setPageSize(totalSize);
1406 ((DocumentModelListImpl)result).setTotalSize(totalSize);
1414 private String logException(Exception e, String msg) {
1415 String result = null;
1417 String exceptionMessage = e.getMessage();
1418 exceptionMessage = exceptionMessage != null ? exceptionMessage : "<No details provided>";
1419 result = msg = msg + ". Caught exception:" + exceptionMessage;
1421 if (logger.isTraceEnabled() == true) {
1422 logger.error(msg, e);
1431 * update given document in the Nuxeo repository
1433 * @param ctx service context under which this method is invoked
1434 * @param csid of the document
1435 * @param handler should be used by the caller to provide and transform the
1437 * @throws BadRequestException
1438 * @throws DocumentNotFoundException
1439 * @throws TransactionException if the transaction times out or otherwise
1440 * cannot be successfully completed
1441 * @throws DocumentException
1444 public void update(ServiceContext ctx, String csid, DocumentHandler handler)
1445 throws BadRequestException, DocumentNotFoundException, TransactionException,
1447 if (handler == null) {
1448 throw new IllegalArgumentException(
1449 "RepositoryJavaClient.update: document handler is missing.");
1452 CoreSessionInterface repoSession = null;
1454 handler.prepare(Action.UPDATE);
1455 repoSession = getRepositorySession(ctx);
1456 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
1457 DocumentModel doc = null;
1459 doc = repoSession.getDocument(docRef);
1460 } catch (org.nuxeo.ecm.core.api.DocumentNotFoundException ce) {
1461 String msg = logException(ce,
1462 String.format("Could not find %s resource/record to update with CSID=%s", ctx.getDocumentType(), csid));
1463 throw new DocumentNotFoundException(msg, ce);
1465 // Check for a versioned document, and check In and Out before we proceed.
1466 if (((DocumentModelHandler) handler).supportsVersioning()) {
1467 /* Once we advance to 5.5 or later, we can add this.
1468 * See also https://jira.nuxeo.com/browse/NXP-8506
1469 if(!doc.isVersionable()) {
1470 throw new NuxeoDocumentException("Configuration for: "
1471 +handler.getServiceContextPath()+" supports versioning, but Nuxeo config does not!");
1474 /* Force a version number - Not working. Apparently we need to configure the uid schema??
1475 if(doc.getProperty("uid","major_version") == null) {
1476 doc.setProperty("uid","major_version",1);
1478 if(doc.getProperty("uid","minor_version") == null) {
1479 doc.setProperty("uid","minor_version",0);
1482 doc.checkIn(VersioningOption.MINOR, null);
1487 // Set reposession to handle the document
1489 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1490 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
1491 handler.handle(Action.UPDATE, wrapDoc);
1492 repoSession.saveDocument(doc);
1494 handler.complete(Action.UPDATE, wrapDoc);
1495 } catch (BadRequestException bre) {
1497 } catch (DocumentException de) {
1499 } catch (CSWebApplicationException wae) {
1501 } catch (Exception e) {
1502 throw new NuxeoDocumentException(e);
1504 if (repoSession != null) {
1505 releaseRepositorySession(ctx, repoSession);
1511 * Save a documentModel to the Nuxeo repository.
1513 * @param ctx service context under which this method is invoked
1514 * @param repoSession
1515 * @param docModel the document to save
1516 * @param fSaveSession if TRUE, will call CoreSessionInterface.save() to save
1517 * accumulated changes.
1518 * @throws ClientException
1519 * @throws DocumentException
1521 public void saveDocWithoutHandlerProcessing(
1522 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1523 CoreSessionInterface repoSession,
1524 DocumentModel docModel,
1525 boolean fSaveSession)
1526 throws ClientException, DocumentException {
1529 repoSession.saveDocument(docModel);
1533 } catch (ClientException ce) {
1535 } catch (Exception e) {
1536 if (logger.isDebugEnabled()) {
1537 logger.debug("Caught exception ", e);
1539 throw new NuxeoDocumentException(e);
1544 * Save a list of documentModels to the Nuxeo repository.
1546 * @param ctx service context under which this method is invoked
1547 * @param repoSession a repository session
1548 * @param docModelList a list of document models
1549 * @param fSaveSession if TRUE, will call CoreSessionInterface.save() to save
1550 * accumulated changes.
1551 * @throws ClientException
1552 * @throws DocumentException
1554 public void saveDocListWithoutHandlerProcessing(
1555 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1556 CoreSessionInterface repoSession,
1557 DocumentModelList docList,
1558 boolean fSaveSession)
1559 throws ClientException, DocumentException {
1561 DocumentModel[] docModelArray = new DocumentModel[docList.size()];
1562 repoSession.saveDocuments(docList.toArray(docModelArray));
1566 } catch (ClientException ce) {
1568 } catch (Exception e) {
1569 logger.error("Caught exception ", e);
1570 throw new NuxeoDocumentException(e);
1575 public void deleteWithWhereClause(@SuppressWarnings("rawtypes") ServiceContext ctx, String whereClause,
1576 @SuppressWarnings("rawtypes") DocumentHandler handler) throws
1577 DocumentNotFoundException, DocumentException {
1579 throw new IllegalArgumentException(
1580 "delete(ctx, specifier): ctx is missing");
1582 if (logger.isDebugEnabled()) {
1583 logger.debug("Deleting document with whereClause=" + whereClause);
1586 DocumentWrapper<DocumentModel> foundDocWrapper = this.findDoc(ctx, whereClause);
1587 if (foundDocWrapper != null) {
1588 DocumentModel docModel = foundDocWrapper.getWrappedObject();
1589 String csid = docModel.getName();
1590 this.delete(ctx, csid, handler);
1595 * delete a document from the Nuxeo repository
1597 * @param ctx service context under which this method is invoked
1598 * @param id of the document
1599 * @throws DocumentException
1602 public boolean delete(ServiceContext ctx, String id, DocumentHandler handler) throws DocumentNotFoundException,
1603 DocumentException, TransactionException {
1604 boolean result = true;
1607 throw new IllegalArgumentException(
1608 "delete(ctx, ix, handler): ctx is missing");
1610 if (handler == null) {
1611 throw new IllegalArgumentException(
1612 "delete(ctx, ix, handler): handler is missing");
1614 if (logger.isDebugEnabled()) {
1615 logger.debug("Deleting document with CSID=" + id);
1617 CoreSessionInterface repoSession = null;
1619 handler.prepare(Action.DELETE);
1620 repoSession = getRepositorySession(ctx);
1621 DocumentWrapper<DocumentModel> wrapDoc = null;
1623 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
1624 wrapDoc = new DocumentWrapperImpl<DocumentModel>(repoSession.getDocument(docRef));
1625 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1626 if (handler.handle(Action.DELETE, wrapDoc)) {
1627 repoSession.removeDocument(docRef);
1628 if (logger.isDebugEnabled()) {
1629 String msg = String.format("DELETE - User '%s' hard-deleted document CSID=%s of type %s.",
1630 ctx.getUserId(), id, ctx.getDocumentType());
1634 result = false; // delete failed for some reason
1636 } catch (org.nuxeo.ecm.core.api.DocumentNotFoundException ce) {
1637 String msg = logException(ce,
1638 String.format("Could not find %s resource/record to delete with CSID=%s", ctx.getDocumentType(), id));
1639 throw new DocumentNotFoundException(msg, ce);
1642 handler.complete(Action.DELETE, wrapDoc);
1643 } catch (DocumentException de) {
1645 } catch (Exception e) {
1646 if (logger.isDebugEnabled()) {
1647 logger.debug("Caught exception ", e);
1649 throw new NuxeoDocumentException(e);
1651 if (repoSession != null) {
1652 releaseRepositorySession(ctx, repoSession);
1660 * @see org.collectionspace.services.common.storage.StorageClient#delete(org.collectionspace.services.common.context.ServiceContext, java.lang.String, org.collectionspace.services.common.document.DocumentHandler)
1664 public void delete(@SuppressWarnings("rawtypes") ServiceContext ctx, String id)
1665 throws DocumentNotFoundException, DocumentException {
1666 throw new UnsupportedOperationException();
1667 // Use the other delete instead
1671 public Hashtable<String, String> retrieveWorkspaceIds(RepositoryDomainType repoDomain) throws Exception {
1672 return NuxeoConnectorEmbedded.getInstance().retrieveWorkspaceIds(repoDomain);
1676 public String createDomain(RepositoryDomainType repositoryDomain) throws Exception {
1677 CoreSessionInterface repoSession = null;
1678 String domainId = null;
1681 // Open a connection to the domain's repo/db
1683 String repoName = repositoryDomain.getRepositoryName();
1684 repoSession = getRepositorySession(repoName); // domainName=storageName=repoName=databaseName
1686 // First create the top-level domain directory
1688 String domainName = repositoryDomain.getStorageName();
1689 DocumentRef parentDocRef = new PathRef("/");
1690 DocumentModel parentDoc = repoSession.getDocument(parentDocRef);
1691 DocumentModel domainDoc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1692 domainName, NUXEO_CORE_TYPE_DOMAIN);
1693 domainDoc.setPropertyValue("dc:title", domainName);
1694 domainDoc.setPropertyValue("dc:description", "A CollectionSpace domain "
1696 domainDoc = repoSession.createDocument(domainDoc);
1697 domainId = domainDoc.getId();
1700 // Next, create a "Workspaces" root directory to contain the workspace folders for the individual service documents
1702 DocumentModel workspacesRoot = repoSession.createDocumentModel(domainDoc.getPathAsString(),
1703 NuxeoUtils.Workspaces, NUXEO_CORE_TYPE_WORKSPACEROOT);
1704 workspacesRoot.setPropertyValue("dc:title", NuxeoUtils.Workspaces);
1705 workspacesRoot.setPropertyValue("dc:description", "A CollectionSpace workspaces directory for "
1706 + domainDoc.getPathAsString());
1707 workspacesRoot = repoSession.createDocument(workspacesRoot);
1708 String workspacesRootId = workspacesRoot.getId();
1711 if (logger.isDebugEnabled()) {
1712 logger.debug("Created tenant domain name=" + domainName
1713 + " id=" + domainId + " "
1714 + NuxeoUtils.Workspaces + " id=" + workspacesRootId);
1715 logger.debug("Path to Domain: " + domainDoc.getPathAsString());
1716 logger.debug("Path to Workspaces root: " + workspacesRoot.getPathAsString());
1718 } catch (Exception e) {
1719 if (logger.isDebugEnabled()) {
1720 logger.debug("Could not create tenant domain name=" + repositoryDomain.getStorageName() + " caught exception ", e);
1724 if (repoSession != null) {
1725 releaseRepositorySession(null, repoSession);
1733 public String getDomainId(RepositoryDomainType repositoryDomain) throws Exception {
1734 String domainId = null;
1735 CoreSessionInterface repoSession = null;
1737 String repoName = repositoryDomain.getRepositoryName();
1738 String domainStorageName = repositoryDomain.getStorageName();
1739 if (domainStorageName != null && !domainStorageName.isEmpty()) {
1741 repoSession = getRepositorySession(repoName);
1742 DocumentRef docRef = new PathRef("/" + domainStorageName);
1743 DocumentModel domain = repoSession.getDocument(docRef);
1744 domainId = domain.getId();
1745 } catch (Exception e) {
1746 if (logger.isTraceEnabled()) {
1747 logger.trace("Caught exception ", e); // The document doesn't exist, this let's us know we need to create it
1749 //there is no way to identify if document does not exist due to
1750 //lack of typed exception for getDocument method
1753 if (repoSession != null) {
1754 releaseRepositorySession(null, repoSession);
1763 * Returns the workspaces root directory for a given domain.
1765 private DocumentModel getWorkspacesRoot(CoreSessionInterface repoSession,
1766 String domainName) throws Exception {
1767 DocumentModel result = null;
1769 String domainPath = "/" + domainName;
1770 DocumentRef parentDocRef = new PathRef(domainPath);
1771 DocumentModelList domainChildrenList = repoSession.getChildren(
1773 Iterator<DocumentModel> witer = domainChildrenList.iterator();
1774 while (witer.hasNext()) {
1775 DocumentModel childNode = witer.next();
1776 if (NuxeoUtils.Workspaces.equalsIgnoreCase(childNode.getName())) {
1778 logger.trace("Found workspaces directory at: " + result.getPathAsString());
1783 if (result == null) {
1784 throw new ClientException("Could not find workspace root directory in: "
1792 * @see org.collectionspace.services.common.repository.RepositoryClient#createWorkspace(java.lang.String, java.lang.String)
1795 public String createWorkspace(RepositoryDomainType repositoryDomain, String workspaceName) throws Exception {
1796 CoreSessionInterface repoSession = null;
1797 String workspaceId = null;
1799 String repoName = repositoryDomain.getRepositoryName();
1800 repoSession = getRepositorySession(repoName);
1802 String domainStorageName = repositoryDomain.getStorageName();
1803 DocumentModel parentDoc = getWorkspacesRoot(repoSession, domainStorageName);
1804 if (logger.isTraceEnabled()) {
1805 for (String facet : parentDoc.getFacets()) {
1806 logger.trace("Facet: " + facet);
1810 DocumentModel doc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1811 workspaceName, NuxeoUtils.WORKSPACE_DOCUMENT_TYPE);
1812 doc.setPropertyValue("dc:title", workspaceName);
1813 doc.setPropertyValue("dc:description", "A CollectionSpace workspace for "
1815 doc = repoSession.createDocument(doc);
1816 workspaceId = doc.getId();
1818 if (logger.isDebugEnabled()) {
1819 logger.debug("Created workspace name=" + workspaceName
1820 + " id=" + workspaceId);
1822 } catch (Exception e) {
1823 if (logger.isDebugEnabled()) {
1824 logger.debug("createWorkspace caught exception ", e);
1828 if (repoSession != null) {
1829 releaseRepositorySession(null, repoSession);
1836 * @see org.collectionspace.services.common.repository.RepositoryClient#getWorkspaceId(java.lang.String, java.lang.String)
1840 public String getWorkspaceId(String tenantDomain, String workspaceName) throws Exception {
1841 String workspaceId = null;
1843 CoreSessionInterface repoSession = null;
1845 repoSession = getRepositorySession((ServiceContext<PoxPayloadIn, PoxPayloadOut>) null);
1846 DocumentRef docRef = new PathRef(
1848 + "/" + NuxeoUtils.Workspaces
1849 + "/" + workspaceName);
1850 DocumentModel workspace = repoSession.getDocument(docRef);
1851 workspaceId = workspace.getId();
1852 } catch (DocumentException de) {
1854 } catch (Exception e) {
1855 if (logger.isDebugEnabled()) {
1856 logger.debug("Caught exception ", e);
1858 throw new NuxeoDocumentException(e);
1860 if (repoSession != null) {
1861 releaseRepositorySession(null, repoSession);
1868 public CoreSessionInterface getRepositorySession(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) throws Exception {
1869 return getRepositorySession(ctx, ctx.getRepositoryName(), ctx.getTimeoutSecs());
1872 public CoreSessionInterface getRepositorySession(String repoName) throws Exception {
1873 return getRepositorySession(null, repoName, ServiceContext.DEFAULT_TX_TIMEOUT);
1877 * Gets the repository session. - Package access only. If the 'ctx' param is
1878 * null then the repo name must be non-mull and vice-versa
1880 * @return the repository session
1881 * @throws Exception the exception
1883 public CoreSessionInterface getRepositorySession(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1885 int timeoutSeconds) throws Exception {
1886 CoreSessionInterface repoSession = null;
1888 Profiler profiler = new Profiler("getRepositorySession():", 2);
1891 // To get a connection to the Nuxeo repo, we need either a valid ServiceContext instance or a repository name
1894 repoSession = (CoreSessionInterface) ctx.getCurrentRepositorySession(); // First see if the context already has a repo session
1895 if (repoSession == null) {
1896 repoName = ctx.getRepositoryName(); // Notice we are overriding the passed in 'repoName' since we have a valid service context passed in to us
1898 } else if (repoName == null || repoName.trim().isEmpty()) {
1899 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.");
1900 logger.error(errMsg);
1901 throw new Exception(errMsg);
1903 if (repoSession == null) {
1905 // 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
1906 // just the repository name.
1908 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1909 repoSession = client.openRepository(repoName, timeoutSeconds);
1911 if (logger.isTraceEnabled() == true) {
1912 logger.trace("Reusing the current context's repository session.");
1917 if (logger.isTraceEnabled()) {
1918 logger.trace("Testing call to getRepository() repository root: " + repoSession.getRootDocument());
1920 } catch (Throwable e) {
1921 logger.trace("Test call to Nuxeo's getRepository() repository root failed", e);
1927 ctx.setCurrentRepositorySession(repoSession); // For reusing, save the repository session in the current service context
1934 * Release repository session. - Package access only.
1936 * @param repoSession the repo session
1938 public void releaseRepositorySession(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, CoreSessionInterface repoSession) throws TransactionException {
1940 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1943 ctx.clearCurrentRepositorySession(); //clear the current context of the now closed repo session
1944 if (ctx.getCurrentRepositorySession() == null) {
1945 client.releaseRepository(repoSession); //release the repo session if the service context's ref count is zeo.
1948 client.releaseRepository(repoSession); //repo session was acquired without a service context
1950 } catch (TransactionRuntimeException tre) {
1951 String causeMsg = null;
1952 Throwable cause = tre.getCause();
1953 if (cause != null) {
1954 causeMsg = cause.getMessage();
1957 TransactionException te; // a CollectionSpace specific tx exception
1958 if (causeMsg != null) {
1959 te = new TransactionException(causeMsg, tre);
1961 te = new TransactionException(tre);
1964 logger.error(te.getMessage(), tre); // Log the standard transaction exception message, plus an exception-specific stack trace
1966 } catch (Exception e) {
1967 logger.error("Could not close the repository session.", e);
1968 // no need to throw this service specific exception
1973 public void doWorkflowTransition(ServiceContext ctx, String id,
1974 DocumentHandler handler, TransitionDef transitionDef)
1975 throws BadRequestException, DocumentNotFoundException,
1977 // 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
1980 private String handleProvidedStartingWildcard(String partialTerm) {
1981 if (Tools.notBlank(partialTerm)) {
1982 if (partialTerm.substring(0, 1).equals(USER_SUPPLIED_WILDCARD)) {
1983 StringBuffer buffer = new StringBuffer(partialTerm);
1984 buffer.setCharAt(0, JDBCTools.SQL_WILDCARD.charAt(0));
1985 partialTerm = buffer.toString();
1992 * Replaces user-supplied wildcards with SQL wildcards, in a partial term
1993 * matching search expression.
1995 * The scope of this replacement excludes the beginning character
1996 * in that search expression, as that character is treated specially.
1998 * @param partialTerm
1999 * @return the partial term, with any user-supplied wildcards replaced
2002 private String subtituteWildcardsInPartialTerm(String partialTerm) {
2003 if (Tools.isBlank(partialTerm)) {
2006 if (! partialTerm.contains(USER_SUPPLIED_WILDCARD)) {
2009 int len = partialTerm.length();
2010 // Partial term search expressions of 2 or fewer characters
2011 // currently aren't amenable to the use of wildcards
2013 logger.warn("Partial term match search expression of just 1-2 characters in length contains a user-supplied wildcard: " + partialTerm);
2014 logger.warn("Will handle that character as a literal value, rather than as a wildcard ...");
2017 return partialTerm.substring(0, 1) // first char
2018 + partialTerm.substring(1, len).replaceAll(USER_SUPPLIED_WILDCARD_REGEX, JDBCTools.SQL_WILDCARD);
2022 private int getMaxItemsLimitOnJdbcQueries(String maxListItemsLimit) {
2023 final int DEFAULT_ITEMS_LIMIT = 40;
2024 if (maxListItemsLimit == null) {
2025 return DEFAULT_ITEMS_LIMIT;
2029 itemsLimit = Integer.parseInt(maxListItemsLimit);
2030 if (itemsLimit < 1) {
2031 logger.warn("Value of configuration setting "
2032 + IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES
2033 + " must be a positive integer; invalid current value is " + maxListItemsLimit);
2034 logger.warn("Reverting to default value of " + DEFAULT_ITEMS_LIMIT);
2035 itemsLimit = DEFAULT_ITEMS_LIMIT;
2037 } catch (NumberFormatException nfe) {
2038 logger.warn("Value of configuration setting "
2039 + IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES
2040 + " must be a positive integer; invalid current value is " + maxListItemsLimit);
2041 logger.warn("Reverting to default value of " + DEFAULT_ITEMS_LIMIT);
2042 itemsLimit = DEFAULT_ITEMS_LIMIT;
2048 * Identifies whether a restriction on tenant ID - to return only records
2049 * pertaining to the current tenant - is required in a JDBC query.
2051 * @param tenantBinding a tenant binding configuration.
2052 * @param ctx a service context.
2053 * @return true if a restriction on tenant ID is required in the query;
2054 * false if a restriction is not required.
2056 private boolean restrictJDBCQueryByTenantID(TenantBindingType tenantBinding, ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
2057 boolean restrict = true;
2058 // If data for the current service, in the current tenant, is isolated
2059 // within its own separate, per-tenant repository, as contrasted with
2060 // being intermingled with other tenants' data in the default repository,
2061 // no restriction on Tenant ID is required in the query.
2062 String repositoryDomainName = ConfigUtils.getRepositoryName(tenantBinding, ctx.getRepositoryDomainName());
2063 if (!(repositoryDomainName.equals(ConfigUtils.DEFAULT_NUXEO_REPOSITORY_NAME))) {
2066 // If a configuration setting for this tenant identifies that JDBC
2067 // queries should not be restricted by tenant ID (perhaps because
2068 // there is always expected to be only one tenant's data present in
2069 // the system), no restriction on Tenant ID is required in the query.
2070 String queriesRestrictedByTenantId = TenantBindingUtils.getPropertyValue(tenantBinding,
2071 IQueryManager.JDBC_QUERIES_ARE_TENANT_ID_RESTRICTED);
2072 if (Tools.notBlank(queriesRestrictedByTenantId) &&
2073 queriesRestrictedByTenantId.equalsIgnoreCase(Boolean.FALSE.toString())) {