2 * This document is a part of the source code and related artifacts for
3 * CollectionSpace, an open source collections management system for museums and
4 * related institutions:
6 * http://www.collectionspace.org http://wiki.collectionspace.org
8 * Copyright 2009 University of California at Berkeley
10 * Licensed under the Educational Community License (ECL), Version 2.0. You may
11 * not use this file except in compliance with this License.
13 * You may obtain a copy of the ECL 2.0 License at
15 * https://source.collectionspace.org/collection-space/LICENSE.txt
17 package org.collectionspace.services.nuxeo.client.java;
19 import java.io.Serializable;
20 import java.sql.SQLException;
21 import java.util.ArrayList;
22 import java.util.Collections;
23 import java.util.Comparator;
24 import java.util.HashSet;
25 import java.util.Hashtable;
26 import java.util.Iterator;
27 import java.util.List;
30 import java.util.UUID;
32 import javax.sql.rowset.CachedRowSet;
33 import javax.ws.rs.core.MultivaluedMap;
35 import org.collectionspace.services.lifecycle.TransitionDef;
36 import org.collectionspace.services.nuxeo.util.CSReindexFulltextRoot;
37 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
38 import org.collectionspace.services.client.CollectionSpaceClient;
39 import org.collectionspace.services.client.IQueryManager;
40 import org.collectionspace.services.client.PoxPayloadIn;
41 import org.collectionspace.services.client.PoxPayloadOut;
42 import org.collectionspace.services.client.Profiler;
43 import org.collectionspace.services.client.workflow.WorkflowClient;
44 import org.collectionspace.services.common.context.ServiceContext;
45 import org.collectionspace.services.common.query.QueryContext;
46 import org.collectionspace.services.common.repository.RepositoryClient;
47 import org.collectionspace.services.common.storage.JDBCTools;
48 import org.collectionspace.services.common.storage.PreparedStatementSimpleBuilder;
49 import org.collectionspace.services.common.document.BadRequestException;
50 import org.collectionspace.services.common.document.DocumentException;
51 import org.collectionspace.services.common.document.DocumentFilter;
52 import org.collectionspace.services.common.document.DocumentHandler;
53 import org.collectionspace.services.common.document.DocumentNotFoundException;
54 import org.collectionspace.services.common.document.DocumentHandler.Action;
55 import org.collectionspace.services.common.document.DocumentWrapper;
56 import org.collectionspace.services.common.document.DocumentWrapperImpl;
57 import org.collectionspace.services.common.document.TransactionException;
58 import org.collectionspace.services.common.CSWebApplicationException;
59 import org.collectionspace.services.common.ServiceMain;
60 import org.collectionspace.services.common.api.Tools;
61 import org.collectionspace.services.common.config.ConfigUtils;
62 import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl;
63 import org.collectionspace.services.common.config.TenantBindingUtils;
64 import org.collectionspace.services.common.storage.PreparedStatementBuilder;
65 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.AuthorityItemSpecifier;
66 import org.collectionspace.services.config.tenant.TenantBindingType;
67 import org.collectionspace.services.config.tenant.RepositoryDomainType;
70 // CSPACE-5036 - How to make CMISQL queries from Nuxeo
72 import org.apache.chemistry.opencmis.commons.enums.CmisVersion;
73 import org.apache.chemistry.opencmis.commons.server.CallContext;
74 import org.apache.chemistry.opencmis.server.impl.CallContextImpl;
75 import org.apache.chemistry.opencmis.server.shared.ThresholdOutputStreamFactory;
76 import org.nuxeo.common.utils.IdUtils;
77 import org.nuxeo.ecm.core.api.ClientException;
78 import org.nuxeo.ecm.core.api.DocumentModel;
79 import org.nuxeo.ecm.core.api.DocumentModelList;
80 import org.nuxeo.ecm.core.api.IterableQueryResult;
81 import org.nuxeo.ecm.core.api.VersioningOption;
82 import org.nuxeo.ecm.core.api.impl.DocumentModelListImpl;
83 import org.nuxeo.ecm.core.api.DocumentRef;
84 import org.nuxeo.ecm.core.api.IdRef;
85 import org.nuxeo.ecm.core.api.PathRef;
86 import org.nuxeo.runtime.transaction.TransactionRuntimeException;
87 import org.nuxeo.ecm.core.opencmis.bindings.NuxeoCmisServiceFactory;
88 import org.nuxeo.ecm.core.opencmis.impl.server.NuxeoCmisService;
89 import org.slf4j.Logger;
90 import org.slf4j.LoggerFactory;
93 * RepositoryClientImpl is used to perform CRUD operations on documents in Nuxeo
94 * repository using Remote Java APIs. It uses
96 * @see DocumentHandler as IOHandler with the client.
98 * $LastChangedRevision: $ $LastChangedDate: $
100 public class NuxeoRepositoryClientImpl implements RepositoryClient<PoxPayloadIn, PoxPayloadOut> {
105 private final Logger logger = LoggerFactory.getLogger(NuxeoRepositoryClientImpl.class);
106 // private final Logger profilerLogger = LoggerFactory.getLogger("remperf");
107 // private String foo = Profiler.createLogger();
108 public static final String NUXEO_CORE_TYPE_DOMAIN = "Domain";
109 public static final String NUXEO_CORE_TYPE_WORKSPACEROOT = "WorkspaceRoot";
110 // FIXME: Get this value from an existing constant, if available
111 public static final String BACKSLASH = "\\";
112 public static final String USER_SUPPLIED_WILDCARD = "*";
113 public static final String USER_SUPPLIED_WILDCARD_REGEX = BACKSLASH + USER_SUPPLIED_WILDCARD;
114 public static final String USER_SUPPLIED_ANCHOR_CHAR = "^";
115 public static final String USER_SUPPLIED_ANCHOR_CHAR_REGEX = BACKSLASH + USER_SUPPLIED_ANCHOR_CHAR;
116 public static final String ENDING_ANCHOR_CHAR = "$";
117 public static final String ENDING_ANCHOR_CHAR_REGEX = BACKSLASH + ENDING_ANCHOR_CHAR;
121 * Instantiates a new repository java client impl.
123 public NuxeoRepositoryClientImpl() {
127 public void assertWorkflowState(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, DocumentModel docModel) throws DocumentNotFoundException, ClientException {
128 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
129 if (queryParams != null) {
131 // Look for the workflow "delete" query param and see if we need to assert that the
132 // docModel is in a non-deleted workflow state.
134 String currentState = docModel.getCurrentLifeCycleState();
135 String includeDeletedStr = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_DELETED_QP);
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(), "-", true, 24);
192 // create document model
193 DocumentModel doc = repoSession.createDocumentModel(wspacePath, id, docType);
194 /* Check for a versioned document, and check In and Out before we proceed.
195 * This does not work as we do not have the uid schema on our docs.
196 if(((DocumentModelHandler) handler).supportsVersioning()) {
197 doc.setProperty("uid","major_version",1);
198 doc.setProperty("uid","minor_version",0);
201 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
202 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
203 handler.handle(Action.CREATE, wrapDoc);
204 // create document with documentmodel
205 doc = repoSession.createDocument(doc);
207 // TODO for sub-docs need to call into the handler to let it deal with subitems. Pass in the id,
208 // and assume the handler has the state it needs (doc fragments).
209 handler.complete(Action.CREATE, wrapDoc);
211 } catch (BadRequestException bre) {
212 rollbackTransaction(repoSession);
214 } catch (Throwable e) {
215 rollbackTransaction(repoSession);
216 if (logger.isDebugEnabled()) {
217 logger.debug("Call to low-level Nuxeo document create call failed: ", e);
219 throw new NuxeoDocumentException(e);
221 if (repoSession != null) {
222 releaseRepositorySession(ctx, repoSession);
228 public boolean reindex(DocumentHandler handler, String indexid) throws DocumentNotFoundException, DocumentException
230 return reindex(handler, null, indexid);
234 public boolean reindex(DocumentHandler handler, String csid, String indexid) throws DocumentNotFoundException, DocumentException
236 boolean result = true;
237 CoreSessionInterface repoSession = null;
238 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = handler.getServiceContext();
241 String queryString = handler.getDocumentsToIndexQuery(indexid, csid);
242 repoSession = getRepositorySession(ctx);
243 CSReindexFulltextRoot indexer = new CSReindexFulltextRoot(repoSession);
244 indexer.reindexFulltext(0, 0, queryString);
246 // Set repository session to handle the document
248 } catch (Throwable e) {
249 rollbackTransaction(repoSession);
250 if (logger.isDebugEnabled()) {
251 logger.debug("Caught exception trying to reindex Nuxeo repository ", e);
253 throw new NuxeoDocumentException(e);
255 if (repoSession != null) {
256 releaseRepositorySession(ctx, repoSession);
264 public boolean synchronize(ServiceContext ctx, Object specifier, DocumentHandler handler)
265 throws DocumentNotFoundException, TransactionException, DocumentException {
266 boolean result = false;
268 if (handler == null) {
269 throw new IllegalArgumentException("RepositoryJavaClient.get: handler is missing");
272 CoreSessionInterface repoSession = null;
274 handler.prepare(Action.SYNC);
275 repoSession = getRepositorySession(ctx);
276 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
277 DocumentWrapper<Object> wrapDoc = new DocumentWrapperImpl<Object>(specifier);
278 result = handler.handle(Action.SYNC, wrapDoc);
279 handler.complete(Action.SYNC, wrapDoc);
280 } catch (IllegalArgumentException iae) {
281 rollbackTransaction(repoSession);
283 } catch (DocumentException de) {
284 rollbackTransaction(repoSession);
286 } catch (Throwable e) {
287 rollbackTransaction(repoSession);
288 if (logger.isDebugEnabled()) {
289 logger.debug("Caught exception ", e);
291 throw new NuxeoDocumentException(e);
293 if (repoSession != null) {
294 releaseRepositorySession(ctx, repoSession);
302 public boolean synchronizeItem(ServiceContext ctx, AuthorityItemSpecifier itemSpecifier, DocumentHandler handler)
303 throws DocumentNotFoundException, TransactionException, DocumentException {
304 boolean result = false;
306 if (handler == null) {
307 throw new IllegalArgumentException(
308 "RepositoryJavaClient.get: handler is missing");
311 CoreSessionInterface repoSession = null;
313 handler.prepare(Action.SYNC);
314 repoSession = getRepositorySession(ctx);
315 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
316 DocumentWrapper<AuthorityItemSpecifier> wrapDoc = new DocumentWrapperImpl<AuthorityItemSpecifier>(itemSpecifier);
317 result = handler.handle(Action.SYNC, wrapDoc);
318 handler.complete(Action.SYNC, wrapDoc);
319 } catch (IllegalArgumentException iae) {
320 rollbackTransaction(repoSession);
322 } catch (DocumentException de) {
323 rollbackTransaction(repoSession);
325 } catch (Throwable e) {
326 rollbackTransaction(repoSession);
327 throw new NuxeoDocumentException(e);
329 if (repoSession != null) {
330 releaseRepositorySession(ctx, repoSession);
338 * get document from the Nuxeo repository
340 * @param ctx service context under which this method is invoked
341 * @param id of the document to retrieve
342 * @param handler should be used by the caller to provide and transform the
344 * @throws DocumentNotFoundException if the document cannot be found in the
346 * @throws TransactionException
347 * @throws DocumentException
350 public void get(ServiceContext ctx, String id, DocumentHandler handler)
351 throws DocumentNotFoundException, TransactionException, DocumentException {
353 if (handler == null) {
354 throw new IllegalArgumentException(
355 "RepositoryJavaClient.get: handler is missing");
358 CoreSessionInterface repoSession = null;
360 handler.prepare(Action.GET);
361 repoSession = getRepositorySession(ctx);
362 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
363 DocumentModel docModel = null;
365 docModel = repoSession.getDocument(docRef);
366 assertWorkflowState(ctx, docModel);
367 } catch (org.nuxeo.ecm.core.api.DocumentNotFoundException ce) {
368 String msg = logException(ce,
369 String.format("Could not find %s resource/record with CSID=%s", ctx.getDocumentType(), id));
370 throw new DocumentNotFoundException(msg, ce);
373 // Set repository session to handle the document
375 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
376 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(docModel);
377 handler.handle(Action.GET, wrapDoc);
378 handler.complete(Action.GET, wrapDoc);
379 } catch (IllegalArgumentException iae) {
381 } catch (DocumentException de) {
382 if (logger.isDebugEnabled()) {
383 logger.debug(de.getMessage(), de);
386 } catch (Throwable e) {
387 if (logger.isDebugEnabled()) {
388 logger.debug("Caught exception ", e);
390 throw new NuxeoDocumentException(e);
392 if (repoSession != null) {
393 releaseRepositorySession(ctx, repoSession);
399 * get a document from the Nuxeo repository, using the docFilter params.
401 * @param ctx service context under which this method is invoked
402 * @param handler should be used by the caller to provide and transform the
403 * document. Handler must have a docFilter set to return a single item.
404 * @throws DocumentNotFoundException if the document cannot be found in the
406 * @throws TransactionException
407 * @throws DocumentException
410 public void get(ServiceContext ctx, DocumentHandler handler)
411 throws DocumentNotFoundException, TransactionException, DocumentException {
412 QueryContext queryContext = new QueryContext(ctx, handler);
413 CoreSessionInterface repoSession = null;
416 handler.prepare(Action.GET);
417 repoSession = getRepositorySession(ctx);
419 DocumentModelList docList = null;
420 // force limit to 1, and ignore totalSize
421 String query = NuxeoUtils.buildNXQLQuery(queryContext);
422 docList = repoSession.query(query, null, 1, 0, false);
423 if (docList.size() != 1) {
424 throw new DocumentNotFoundException("No document found matching filter params: " + query);
426 DocumentModel doc = docList.get(0);
428 if (logger.isDebugEnabled()) {
429 logger.debug("Executed NXQL query: " + query);
432 //set reposession to handle the document
433 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
434 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
435 handler.handle(Action.GET, wrapDoc);
436 handler.complete(Action.GET, wrapDoc);
437 } catch (IllegalArgumentException iae) {
439 } catch (DocumentException de) {
441 } catch (Throwable e) {
442 if (logger.isDebugEnabled()) {
443 logger.debug("Caught exception ", e);
445 throw new NuxeoDocumentException(e);
447 if (repoSession != null) {
448 releaseRepositorySession(ctx, repoSession);
453 public DocumentWrapper<DocumentModel> getDoc(
454 CoreSessionInterface repoSession,
455 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
456 String csid) throws DocumentNotFoundException, DocumentException {
457 DocumentWrapper<DocumentModel> wrapDoc = null;
460 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
461 DocumentModel doc = null;
463 doc = repoSession.getDocument(docRef);
464 } catch (ClientException ce) {
465 String msg = logException(ce, "Could not find document with CSID=" + csid);
466 throw new DocumentNotFoundException(msg, ce);
468 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
469 } catch (IllegalArgumentException iae) {
471 } catch (DocumentException de) {
479 * Get wrapped documentModel from the Nuxeo repository. The search is
480 * restricted to the workspace of the current context.
482 * @param ctx service context under which this method is invoked
483 * @param csid of the document to retrieve
484 * @throws DocumentNotFoundException
485 * @throws TransactionException
486 * @throws DocumentException
487 * @return a wrapped documentModel
490 public DocumentWrapper<DocumentModel> getDoc(
491 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
492 String csid) throws DocumentNotFoundException, TransactionException, DocumentException {
493 CoreSessionInterface repoSession = null;
494 DocumentWrapper<DocumentModel> wrapDoc = null;
497 // Open a new repository session
498 repoSession = getRepositorySession(ctx);
499 wrapDoc = getDoc(repoSession, ctx, csid);
500 } catch (IllegalArgumentException iae) {
502 } catch (DocumentException de) {
504 } catch (Exception e) {
505 if (logger.isDebugEnabled()) {
506 logger.debug("Caught exception ", e);
508 throw new NuxeoDocumentException(e);
510 if (repoSession != null) {
511 releaseRepositorySession(ctx, repoSession);
515 if (logger.isWarnEnabled() == true) {
516 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
521 public DocumentWrapper<DocumentModel> findDoc(
522 CoreSessionInterface repoSession,
523 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
525 throws DocumentNotFoundException, DocumentException {
526 DocumentWrapper<DocumentModel> wrapDoc = null;
529 QueryContext queryContext = new QueryContext(ctx, whereClause);
530 DocumentModelList docList = null;
531 // force limit to 1, and ignore totalSize
532 String query = NuxeoUtils.buildNXQLQuery(queryContext);
533 docList = repoSession.query(query,
538 if (docList.size() != 1) {
539 if (logger.isDebugEnabled()) {
540 logger.debug("findDoc: Query found: " + docList.size() + " items.");
541 logger.debug(" Query: " + query);
543 throw new DocumentNotFoundException("No document found matching filter params: " + query);
545 DocumentModel doc = docList.get(0);
546 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
547 } catch (IllegalArgumentException iae) {
549 } catch (DocumentException de) {
551 } catch (Exception e) {
552 if (logger.isDebugEnabled()) {
553 logger.debug("Caught exception ", e);
555 throw new NuxeoDocumentException(e);
562 * find wrapped documentModel from the Nuxeo repository
564 * @param ctx service context under which this method is invoked
565 * @param whereClause where NXQL where clause to get the document
566 * @throws DocumentNotFoundException
567 * @throws TransactionException
568 * @throws DocumentException
569 * @return a wrapped documentModel retrieved by the repository query
572 public DocumentWrapper<DocumentModel> findDoc(
573 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
575 throws DocumentNotFoundException, TransactionException, DocumentException {
576 CoreSessionInterface repoSession = null;
577 DocumentWrapper<DocumentModel> wrapDoc = null;
580 repoSession = getRepositorySession(ctx);
581 wrapDoc = findDoc(repoSession, ctx, whereClause);
582 } catch (DocumentNotFoundException dnfe) {
584 } catch (DocumentException de) {
586 } catch (Exception e) {
587 if (repoSession == null) {
588 throw new NuxeoDocumentException("Unable to create a Nuxeo repository session.", e);
590 throw new NuxeoDocumentException("Unexpected Nuxeo exception.", e);
593 if (repoSession != null) {
594 releaseRepositorySession(ctx, repoSession);
598 if (logger.isWarnEnabled() == true) {
599 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
606 * find doc and return CSID from the Nuxeo repository
609 * @param ctx service context under which this method is invoked
610 * @param whereClause where NXQL where clause to get the document
611 * @throws DocumentNotFoundException
612 * @throws TransactionException
613 * @throws DocumentException
614 * @return the CollectionSpace ID (CSID) of the requested document
617 public String findDocCSID(CoreSessionInterface repoSession,
618 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String whereClause)
619 throws DocumentNotFoundException, TransactionException, DocumentException {
621 boolean releaseSession = false;
623 if (repoSession == null) {
624 repoSession = this.getRepositorySession(ctx);
625 releaseSession = true;
627 DocumentWrapper<DocumentModel> wrapDoc = findDoc(repoSession, ctx, whereClause);
628 DocumentModel docModel = wrapDoc.getWrappedObject();
629 csid = NuxeoUtils.getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
630 } catch (DocumentNotFoundException dnfe) {
632 } catch (IllegalArgumentException iae) {
634 } catch (DocumentException de) {
636 } catch (Exception e) {
637 if (logger.isDebugEnabled()) {
638 logger.debug("Caught exception ", e);
640 throw new NuxeoDocumentException(e);
642 if (releaseSession && (repoSession != null)) {
643 this.releaseRepositorySession(ctx, repoSession);
649 public DocumentWrapper<DocumentModelList> findDocs(
650 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
651 CoreSessionInterface repoSession,
652 List<String> docTypes,
654 String orderByClause,
657 boolean useDefaultOrderByClause,
658 boolean computeTotal)
659 throws DocumentNotFoundException, DocumentException {
660 DocumentWrapper<DocumentModelList> wrapDoc = null;
663 if (docTypes == null || docTypes.size() < 1) {
664 throw new DocumentNotFoundException(
665 "The findDocs() method must specify at least one DocumentType.");
667 DocumentModelList docList = null;
668 QueryContext queryContext = new QueryContext(ctx, whereClause, orderByClause);
669 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext, useDefaultOrderByClause);
670 if (logger.isDebugEnabled()) {
671 logger.debug("findDocs() NXQL: " + query);
673 docList = repoSession.query(query, null, pageSize, pageSize * pageNum, computeTotal);
674 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
675 } catch (IllegalArgumentException iae) {
677 } catch (Exception e) {
678 if (logger.isDebugEnabled()) {
679 logger.debug("Caught exception ", e);
681 throw new NuxeoDocumentException(e);
687 protected static String buildInListForDocTypes(List<String> docTypes) {
688 StringBuilder sb = new StringBuilder();
690 boolean first = true;
691 for (String docType : docTypes) {
702 return sb.toString();
705 public DocumentWrapper<DocumentModelList> findDocs(
706 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
707 DocumentHandler handler,
708 CoreSessionInterface repoSession,
709 List<String> docTypes) throws DocumentNotFoundException, DocumentException {
710 DocumentWrapper<DocumentModelList> wrapDoc = null;
712 DocumentFilter filter = handler.getDocumentFilter();
713 String oldOrderBy = filter.getOrderByClause();
714 if (isClauseEmpty(oldOrderBy) == true) {
715 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
717 QueryContext queryContext = new QueryContext(ctx, handler);
720 if (docTypes == null || docTypes.size() < 1) {
721 throw new DocumentNotFoundException(
722 "The findDocs() method must specify at least one DocumentType.");
724 DocumentModelList docList = null;
725 if (handler.isCMISQuery() == true) {
726 String inList = buildInListForDocTypes(docTypes);
727 ctx.getQueryParams().add(IQueryManager.SEARCH_RELATED_MATCH_OBJ_DOCTYPES, inList);
728 if (isSubjectOrObjectQuery(ctx)) {
729 docList = getFilteredCMISForSubjectOrObject(repoSession, ctx, handler, queryContext);
731 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
734 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
735 if (logger.isDebugEnabled()) {
736 logger.debug("findDocs() NXQL: " + query);
738 docList = repoSession.query(query, null, filter.getPageSize(), filter.getOffset(), true);
740 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
741 } catch (IllegalArgumentException iae) {
743 } catch (Exception e) {
744 if (logger.isDebugEnabled()) {
745 logger.debug("Caught exception ", e);
747 throw new NuxeoDocumentException(e);
753 private DocumentModelList getFilteredCMISForSubjectOrObject(CoreSessionInterface repoSession,
754 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, DocumentHandler handler, QueryContext queryContext) throws DocumentNotFoundException, DocumentException {
755 DocumentModelList result = null;
757 if (isSubjectOrObjectQuery(ctx) == true) {
758 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
759 String asEitherCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_EITHER);
761 queryParams.remove(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT);
762 queryParams.remove(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT);
765 // First query for subjectCsid results.
767 queryParams.addFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT, asEitherCsid);
768 DocumentModelList subjectDocList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
769 queryParams.remove(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT);
772 // Next query for objectCsid results.
774 queryParams.addFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT, asEitherCsid);
775 DocumentModelList objectDocList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
776 queryParams.remove(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT);
779 // Finally, combine the two results
781 result = mergeDocumentModelLists(subjectDocList, objectDocList);
787 private DocumentModelList mergeDocumentModelLists(DocumentModelList subjectDocList,
788 DocumentModelList objectDocList) {
789 DocumentModelList result = null;
791 if (subjectDocList == null || subjectDocList.isEmpty()) {
792 return objectDocList;
795 if (objectDocList == null || objectDocList.isEmpty()) {
796 return subjectDocList;
799 result = new DocumentModelListImpl();
801 // Add the subject list
802 Iterator<DocumentModel> iterator = subjectDocList.iterator();
803 while (iterator.hasNext()) {
804 DocumentModel dm = iterator.next();
805 addToResults(result, dm);
808 // Add the object list
809 iterator = objectDocList.iterator();
810 while (iterator.hasNext()) {
811 DocumentModel dm = iterator.next();
812 addToResults(result, dm);
815 // Set the 'totalSize' value for book keeping sake
816 ((DocumentModelListImpl) result).setTotalSize(result.size());
822 // Only add if it is not already in the list
823 private void addToResults(DocumentModelList result, DocumentModel dm) {
824 Iterator<DocumentModel> iterator = result.iterator();
825 boolean found = false;
827 while (iterator.hasNext()) {
828 DocumentModel existingDm = iterator.next();
829 if (existingDm.getId().equals(dm.getId())) {
835 if (found == false) {
840 private boolean isSubjectOrObjectQuery(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
841 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
842 String asEitherCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_EITHER);
843 return asEitherCsid != null && !asEitherCsid.isEmpty();
847 * Find a list of documentModels from the Nuxeo repository
849 * @param docTypes a list of DocType names to match
850 * @param whereClause where the clause to qualify on
851 * @throws DocumentNotFoundException
852 * @throws TransactionException
853 * @throws DocumentException
854 * @return a list of documentModels
857 public DocumentWrapper<DocumentModelList> findDocs(
858 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
859 List<String> docTypes,
863 boolean useDefaultOrderByClause,
864 boolean computeTotal) throws DocumentNotFoundException, TransactionException, DocumentException {
865 CoreSessionInterface repoSession = null;
866 DocumentWrapper<DocumentModelList> wrapDoc = null;
869 repoSession = getRepositorySession(ctx);
870 wrapDoc = findDocs(ctx,
877 useDefaultOrderByClause,
879 } catch (IllegalArgumentException iae) {
881 } catch (Exception e) {
882 if (logger.isDebugEnabled()) {
883 logger.debug("Caught exception ", e);
885 throw new NuxeoDocumentException(e);
887 if (repoSession != null) {
888 releaseRepositorySession(ctx, repoSession);
892 if (logger.isWarnEnabled() == true) {
893 logger.warn("Returned DocumentModelList instance was created with a repository session that is now closed.");
900 * @see org.collectionspace.services.common.storage.StorageClient#get(org.collectionspace.services.common.context.ServiceContext, java.util.List, org.collectionspace.services.common.document.DocumentHandler)
903 public void get(ServiceContext ctx, List<String> csidList, DocumentHandler handler)
904 throws DocumentNotFoundException, TransactionException, DocumentException {
905 if (handler == null) {
906 throw new IllegalArgumentException(
907 "RepositoryJavaClient.getAll: handler is missing");
910 CoreSessionInterface repoSession = null;
912 handler.prepare(Action.GET_ALL);
913 repoSession = getRepositorySession(ctx);
914 DocumentModelList docModelList = new DocumentModelListImpl();
915 //FIXME: Should be using NuxeoUtils.createPathRef for security reasons
916 for (String csid : csidList) {
917 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
918 DocumentModel docModel = repoSession.getDocument(docRef);
919 docModelList.add(docModel);
922 //set reposession to handle the document
923 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
924 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docModelList);
925 handler.handle(Action.GET_ALL, wrapDoc);
926 handler.complete(Action.GET_ALL, wrapDoc);
927 } catch (DocumentException de) {
929 } catch (Exception e) {
930 if (logger.isDebugEnabled()) {
931 logger.debug("Caught exception ", e);
933 throw new NuxeoDocumentException(e);
935 if (repoSession != null) {
936 releaseRepositorySession(ctx, repoSession);
942 * getAll get all documents for an entity entity service from the Nuxeo
945 * @param ctx service context under which this method is invoked
946 * @param handler should be used by the caller to provide and transform the
948 * @throws DocumentNotFoundException
949 * @throws TransactionException
950 * @throws DocumentException
953 public void getAll(ServiceContext ctx, DocumentHandler handler)
954 throws DocumentNotFoundException, TransactionException, DocumentException {
955 if (handler == null) {
956 throw new IllegalArgumentException(
957 "RepositoryJavaClient.getAll: handler is missing");
959 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
960 if (nuxeoWspaceId == null) {
961 throw new DocumentNotFoundException(
962 "Unable to find workspace for service "
963 + ctx.getServiceName()
964 + " check if the workspace exists in the Nuxeo repository.");
967 CoreSessionInterface repoSession = null;
969 handler.prepare(Action.GET_ALL);
970 repoSession = getRepositorySession(ctx);
971 DocumentRef wsDocRef = new IdRef(nuxeoWspaceId);
972 DocumentModelList docList = repoSession.getChildren(wsDocRef);
973 //set reposession to handle the document
974 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
975 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
976 handler.handle(Action.GET_ALL, wrapDoc);
977 handler.complete(Action.GET_ALL, wrapDoc);
978 } catch (DocumentException de) {
980 } catch (Exception e) {
981 if (logger.isDebugEnabled()) {
982 logger.debug("Caught exception ", e);
984 throw new NuxeoDocumentException(e);
986 if (repoSession != null) {
987 releaseRepositorySession(ctx, repoSession);
992 private boolean isClauseEmpty(String theString) {
993 boolean result = true;
994 if (theString != null && !theString.isEmpty()) {
1000 public DocumentWrapper<DocumentModel> getDocFromCsid(
1001 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1002 CoreSessionInterface repoSession,
1005 DocumentWrapper<DocumentModel> result = null;
1007 result = new DocumentWrapperImpl<DocumentModel>(NuxeoUtils.getDocFromCsid(ctx, repoSession, csid));
1013 * A method to find a CollectionSpace document (of any type) given just a service context and
1014 * its CSID. A search across *all* service workspaces (within a given tenant context) is performed to find
1017 * This query searches Nuxeo's Hierarchy table where our CSIDs are stored in the "name" column.
1020 public DocumentWrapper<DocumentModel> getDocFromCsid(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1023 DocumentWrapper<DocumentModel> result = null;
1024 CoreSessionInterface repoSession = null;
1026 repoSession = getRepositorySession(ctx);
1027 result = getDocFromCsid(ctx, repoSession, csid);
1029 if (repoSession != null) {
1030 releaseRepositorySession(ctx, repoSession);
1034 if (logger.isWarnEnabled() == true) {
1035 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
1042 * Returns a URI value for a document in the Nuxeo repository
1044 * @param wrappedDoc a wrapped documentModel
1045 * @throws ClientException
1046 * @return a document URI
1049 public String getDocURI(DocumentWrapper<DocumentModel> wrappedDoc) throws ClientException {
1050 DocumentModel docModel = wrappedDoc.getWrappedObject();
1051 String uri = (String) docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
1052 CollectionSpaceClient.COLLECTIONSPACE_CORE_URI);
1057 * See CSPACE-5036 - How to make CMISQL queries from Nuxeo
1059 private IterableQueryResult makeCMISQLQuery(CoreSessionInterface repoSession, String query, QueryContext queryContext) throws DocumentException {
1060 IterableQueryResult result = null;
1061 /** Threshold over which temporary files are not kept in memory. */
1062 final int THRESHOLD = 1024 * 1024;
1065 logger.debug(String.format("Performing a CMIS query on Nuxeo repository named %s",
1066 repoSession.getRepositoryName()));
1068 ThresholdOutputStreamFactory streamFactory = ThresholdOutputStreamFactory.newInstance(
1069 null, THRESHOLD, -1, false);
1070 CallContextImpl callContext = new CallContextImpl(
1071 CallContext.BINDING_LOCAL,
1072 CmisVersion.CMIS_1_1,
1073 repoSession.getRepositoryName(),
1074 null, // ServletContext
1075 null, // HttpServletRequest
1076 null, // HttpServletResponse
1077 new NuxeoCmisServiceFactory(),
1079 callContext.put(CallContext.USERNAME, repoSession.getPrincipal().getName());
1081 NuxeoCmisService cmisService = new NuxeoCmisService(repoSession.getCoreSession());
1082 result = repoSession.queryAndFetch(query, "CMISQL", cmisService);
1083 } catch (ClientException e) {
1084 // TODO Auto-generated catch block
1085 logger.error("Encounter trouble making the following CMIS query: " + query, e);
1086 throw new NuxeoDocumentException(e);
1093 * getFiltered get all documents for an entity service from the Document
1094 * repository, given filter parameters specified by the handler.
1096 * @param ctx service context under which this method is invoked
1097 * @param handler should be used by the caller to provide and transform the
1099 * @throws DocumentNotFoundException if workspace not found
1100 * @throws TransactionException
1101 * @throws DocumentException
1104 public void getFiltered(ServiceContext ctx, DocumentHandler handler)
1105 throws DocumentNotFoundException, TransactionException, DocumentException {
1107 DocumentFilter filter = handler.getDocumentFilter();
1108 String oldOrderBy = filter.getOrderByClause();
1109 if (isClauseEmpty(oldOrderBy) == true) {
1110 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
1112 QueryContext queryContext = new QueryContext(ctx, handler);
1114 CoreSessionInterface repoSession = null;
1116 handler.prepare(Action.GET_ALL);
1117 repoSession = getRepositorySession(ctx); //Keeps a refcount here for the repository session so you need to release this when finished
1119 DocumentModelList docList = null;
1121 if (handler.isJDBCQuery() == true) {
1122 docList = getFilteredJDBC(repoSession, ctx, handler);
1124 } else if (handler.isCMISQuery() == true) { //FIXME: REM - Need to deal with paging info in CMIS query
1125 if (isSubjectOrObjectQuery(ctx)) {
1126 docList = getFilteredCMISForSubjectOrObject(repoSession, ctx, handler, queryContext);
1128 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
1132 String query = NuxeoUtils.buildNXQLQuery(queryContext);
1133 if (logger.isDebugEnabled()) {
1134 logger.debug("Executing NXQL query: " + query.toString());
1136 Profiler profiler = new Profiler(this, 2);
1137 profiler.log("Executing NXQL query: " + query.toString());
1139 // If we have a page size and/or offset, then reflect those values
1140 // when constructing the query, and also pass 'true' to get totalSize
1141 // in the returned DocumentModelList.
1142 if ((queryContext.getDocFilter().getOffset() > 0) || (queryContext.getDocFilter().getPageSize() > 0)) {
1143 docList = repoSession.query(query, null,
1144 queryContext.getDocFilter().getPageSize(), queryContext.getDocFilter().getOffset(), true);
1146 docList = repoSession.query(query);
1151 //set repoSession to handle the document
1152 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1153 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
1154 handler.handle(Action.GET_ALL, wrapDoc);
1155 handler.complete(Action.GET_ALL, wrapDoc);
1156 } catch (DocumentException de) {
1158 } catch (Exception e) {
1159 if (logger.isDebugEnabled()) {
1160 logger.debug("Caught exception ", e); // REM - 1/17/2014: Check for org.nuxeo.ecm.core.api.ClientException and re-attempt
1162 throw new NuxeoDocumentException(e);
1164 if (repoSession != null) {
1165 releaseRepositorySession(ctx, repoSession);
1171 * Perform a database query, via JDBC and SQL, to retrieve matching records
1172 * based on filter criteria.
1174 * Although this method currently has a general-purpose name, it is
1175 * currently dedicated to a specific task: that of improving performance
1176 * for partial term matching queries on authority items / terms, via
1177 * the use of a hand-tuned SQL query, rather than via the generated SQL
1178 * produced by Nuxeo from an NXQL query. (See CSPACE-6361 for a task
1179 * to generalize this method.)
1181 * @param repoSession a repository session.
1182 * @param ctx the service context.
1183 * @param handler a relevant document handler.
1184 * @return a list of document models matching the search criteria.
1187 private DocumentModelList getFilteredJDBC(CoreSessionInterface repoSession, ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1188 DocumentHandler handler) throws Exception {
1189 DocumentModelList result = new DocumentModelListImpl();
1191 // FIXME: Get all of the following values from appropriate external constants.
1193 // At present, the two constants below are duplicated in both RepositoryClientImpl
1194 // and in AuthorityItemDocumentModelHandler.
1195 final String TERM_GROUP_LIST_NAME = "TERM_GROUP_LIST_NAME";
1196 final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
1197 final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
1198 // Get this from a constant in AuthorityResource or equivalent
1199 final String PARENT_WILDCARD = "_ALL_";
1201 // Build two SQL statements, to be executed within a single transaction:
1202 // the first statement to control join order, and the second statement
1203 // representing the actual 'get filtered' query
1205 // Build the join control statement
1207 // Per http://www.postgresql.org/docs/9.2/static/runtime-config-query.html#GUC-JOIN-COLLAPSE-LIMIT
1208 // "Setting [this value] to 1 prevents any reordering of explicit JOINs.
1209 // Thus, the explicit join order specified in the query will be the
1210 // actual order in which the relations are joined."
1211 // See CSPACE-5945 for further discussion of why this setting is needed.
1213 // Adding this statement is commented out here for now. It significantly
1214 // improved query performance for authority item / term queries where
1215 // large numbers of rows were retrieved, but appears to have resulted
1216 // in consistently slower-than-desired query performance where zero or
1217 // very few records were retrieved. See notes on CSPACE-5945. - ADR 2013-04-09
1218 // String joinControlSql = "SET LOCAL join_collapse_limit TO 1;";
1220 // Build the query statement
1222 // Start with the default query
1223 String selectStatement =
1224 "SELECT DISTINCT commonschema.id"
1225 + " FROM " + handler.getServiceContext().getCommonPartLabel() + " commonschema";
1227 String joinClauses =
1229 + " ON misc.id = commonschema.id"
1230 + " INNER JOIN hierarchy hierarchy_termgroup"
1231 + " ON hierarchy_termgroup.parentid = misc.id"
1232 + " INNER JOIN " + handler.getJDBCQueryParams().get(TERM_GROUP_TABLE_NAME_PARAM) + " termgroup"
1233 + " ON termgroup.id = hierarchy_termgroup.id ";
1236 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
1237 // Value for replaceable parameter 1 in the query
1238 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
1239 // If the value of the partial term query parameter is blank ('pt='),
1240 // return all records, subject to restriction by any limit clause
1241 if (Tools.isBlank(partialTerm)) {
1244 // Otherwise, return records that match the supplied partial term
1246 " WHERE (termgroup.termdisplayname ILIKE ?)";
1249 // At present, results are ordered in code, below, rather than in SQL,
1250 // and the orderByClause below is thus intentionally blank.
1252 // To implement the orderByClause below in SQL; e.g. via
1253 // 'ORDER BY termgroup.termdisplayname', the relevant column
1254 // must be returned by the SELECT statement.
1255 String orderByClause = "";
1258 TenantBindingConfigReaderImpl tReader =
1259 ServiceMain.getInstance().getTenantBindingConfigReader();
1260 TenantBindingType tenantBinding = tReader.getTenantBinding(ctx.getTenantId());
1261 String maxListItemsLimit = TenantBindingUtils.getPropertyValue(tenantBinding,
1262 IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES);
1264 " LIMIT " + getMaxItemsLimitOnJdbcQueries(maxListItemsLimit); // implicit int-to-String conversion
1266 // After building the individual parts of the query, set the values
1267 // of replaceable parameters that will be inserted into that query
1268 // and optionally add restrictions
1270 List<String> params = new ArrayList<>();
1272 if (Tools.notBlank(whereClause)) {
1274 // Read tenant bindings configuration to determine whether
1275 // to automatically insert leading, as well as trailing, wildcards
1276 // into the term matching string.
1277 String usesStartingWildcard = TenantBindingUtils.getPropertyValue(tenantBinding,
1278 IQueryManager.TENANT_USES_STARTING_WILDCARD_FOR_PARTIAL_TERM);
1279 // Handle user-provided leading wildcard characters, in the
1280 // configuration where a leading wildcard is not automatically inserted.
1281 // (The user-provided wildcard must be in the first, or "starting"
1282 // character position in the partial term value.)
1283 if (Tools.notBlank(usesStartingWildcard)) {
1284 if (usesStartingWildcard.equalsIgnoreCase(Boolean.FALSE.toString())) {
1285 partialTerm = handleProvidedStartingWildcard(partialTerm);
1286 // Otherwise, in the configuration where a leading wildcard
1287 // is usually automatically inserted, handle the cases where
1288 // a user has entered an anchor character in the first position
1289 // in the starting term value. In those cases, strip that
1290 // anchor character and don't add a leading wildcard
1292 if (partialTerm.startsWith(USER_SUPPLIED_ANCHOR_CHAR)) {
1293 partialTerm = partialTerm.substring(1, partialTerm.length());
1294 // Otherwise, automatically add a leading wildcard
1296 partialTerm = JDBCTools.SQL_WILDCARD + partialTerm;
1300 // Add SQL wildcards in the midst of the partial term match search
1301 // expression, whever user-supplied wildcards appear, except in the
1302 // first or last character positions of the search expression.
1303 partialTerm = subtituteWildcardsInPartialTerm(partialTerm);
1305 // If a designated 'anchor character' is present as the last character
1306 // in the search expression, strip that character and don't add
1307 // a trailing wildcard
1308 int lastCharPos = partialTerm.length() - 1;
1309 if (partialTerm.endsWith(USER_SUPPLIED_ANCHOR_CHAR) && lastCharPos > 0) {
1310 partialTerm = partialTerm.substring(0, lastCharPos);
1312 // Otherwise, automatically add a trailing wildcard
1313 partialTerm = partialTerm + JDBCTools.SQL_WILDCARD;
1315 params.add(partialTerm);
1318 // Optionally add restrictions to the default query, based on variables
1319 // in the current request
1321 // Restrict the query to filter out deleted records, if requested
1322 String includeDeleted = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_DELETED_QP);
1323 if (includeDeleted != null && includeDeleted.equalsIgnoreCase(Boolean.FALSE.toString())) {
1324 whereClause = whereClause
1325 + " AND (misc.lifecyclestate <> '" + WorkflowClient.WORKFLOWSTATE_DELETED + "')"
1326 + " AND (misc.lifecyclestate <> '" + WorkflowClient.WORKFLOWSTATE_LOCKED_DELETED + "')";
1329 // If a particular authority is specified, restrict the query further
1330 // to return only records within that authority
1331 String inAuthorityValue = (String) handler.getJDBCQueryParams().get(IN_AUTHORITY_PARAM);
1332 if (Tools.notBlank(inAuthorityValue)) {
1333 // Handle the '_ALL_' case for inAuthority
1334 if (inAuthorityValue.equals(PARENT_WILDCARD)) {
1335 // Add nothing to the query here if it should match within all authorities
1337 whereClause = whereClause
1338 + " AND (commonschema.inauthority = ?)";
1339 params.add(inAuthorityValue); // Value for replaceable parameter 2 in the query
1343 // Restrict the query further to return only records pertaining to
1344 // the current tenant, unless:
1345 // * Data for this service, in this tenant, is stored in its own,
1346 // separate repository, rather than being intermingled with other
1347 // tenants' data in the default repository; or
1348 // * Restriction by tenant ID in JDBC queries has been disabled,
1349 // via configuration for this tenant,
1350 if (restrictJDBCQueryByTenantID(tenantBinding, ctx)) {
1351 joinClauses = joinClauses
1352 + " INNER JOIN collectionspace_core core"
1353 + " ON core.id = hierarchy_termgroup.parentid";
1354 whereClause = whereClause
1355 + " AND (core.tenantid = ?)";
1356 params.add(ctx.getTenantId()); // Value for replaceable parameter 3 in the query
1359 // Piece together the SQL query from its parts
1360 String querySql = selectStatement + joinClauses + whereClause + orderByClause + limitClause;
1362 // Note: PostgreSQL 9.2 introduced a change that may improve performance
1363 // of certain queries using JDBC PreparedStatements. See comments on
1364 // CSPACE-5943 for details.
1366 // See a comment above for the reason that the joinControl SQL statement,
1367 // along with its corresponding prepared statement builder, is commented out for now.
1368 // PreparedStatementBuilder joinControlBuilder = new PreparedStatementBuilder(joinControlSql);
1369 PreparedStatementSimpleBuilder queryBuilder = new PreparedStatementSimpleBuilder(querySql, params);
1370 List<PreparedStatementBuilder> builders = new ArrayList<>();
1371 // builders.add(joinControlBuilder);
1372 builders.add(queryBuilder);
1373 String dataSourceName = JDBCTools.NUXEO_DATASOURCE_NAME;
1374 String repositoryName = ctx.getRepositoryName();
1375 final Boolean EXECUTE_WITHIN_TRANSACTION = true;
1376 Set<String> docIds = new HashSet<>();
1378 String cspaceInstanceId = ServiceMain.getInstance().getCspaceInstanceId();
1379 List<CachedRowSet> resultsList = JDBCTools.executePreparedQueries(builders,
1380 dataSourceName, repositoryName, cspaceInstanceId, EXECUTE_WITHIN_TRANSACTION);
1382 // At least one set of results is expected, from the second prepared
1383 // statement to be executed.
1384 // If fewer results are returned, return an empty list of document models
1385 if (resultsList == null || resultsList.size() < 1) {
1386 return result; // return an empty list of document models
1388 // The join control query (if enabled - it is currently commented
1389 // out as per comments above) will not return results, so query results
1390 // will be the first set of results (rowSet) returned in the list
1391 CachedRowSet queryResults = resultsList.get(0);
1393 // If the result from executing the query is null or contains zero rows,
1394 // return an empty list of document models
1395 if (queryResults == null) {
1396 return result; // return an empty list of document models
1398 queryResults.last();
1399 if (queryResults.getRow() == 0) {
1400 return result; // return an empty list of document models
1403 // Otherwise, get the document IDs from the results of the query
1405 queryResults.beforeFirst();
1406 while (queryResults.next()) {
1407 id = queryResults.getString(1);
1408 if (Tools.notBlank(id)) {
1412 } catch (SQLException sqle) {
1413 logger.warn("Could not obtain document IDs via SQL query '" + querySql + "': " + sqle.getMessage());
1414 return result; // return an empty list of document models
1417 // Get a list of document models, using the list of IDs obtained from the query
1419 // FIXME: Check whether we have a 'get document models from list of CSIDs'
1420 // utility method like this, and if not, add this to the appropriate
1422 DocumentModel docModel;
1423 for (String docId : docIds) {
1424 docModel = NuxeoUtils.getDocumentModel(repoSession, docId);
1425 if (docModel == null) {
1426 logger.warn("Could not obtain document model for document with ID " + docId);
1428 result.add(docModel);
1432 // Order the results
1433 final String COMMON_PART_SCHEMA = handler.getServiceContext().getCommonPartLabel();
1434 final String DISPLAY_NAME_XPATH =
1435 "//" + handler.getJDBCQueryParams().get(TERM_GROUP_LIST_NAME) + "/[0]/termDisplayName";
1436 Collections.sort(result, new Comparator<DocumentModel>() {
1438 public int compare(DocumentModel doc1, DocumentModel doc2) {
1439 String termDisplayName1 = null;
1440 String termDisplayName2 = null;
1442 termDisplayName1 = (String) NuxeoUtils.getXPathValue(doc1, COMMON_PART_SCHEMA, DISPLAY_NAME_XPATH);
1443 termDisplayName2 = (String) NuxeoUtils.getXPathValue(doc2, COMMON_PART_SCHEMA, DISPLAY_NAME_XPATH);
1444 } catch (NuxeoDocumentException e) {
1445 throw new RuntimeException(e); // We need to throw a RuntimeException because the compare() method of the Comparator interface does not support throwing an Exception
1447 return termDisplayName1.compareToIgnoreCase(termDisplayName2);
1455 private DocumentModelList getFilteredCMIS(CoreSessionInterface repoSession,
1456 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, DocumentHandler handler, QueryContext queryContext)
1457 throws DocumentNotFoundException, DocumentException {
1459 DocumentModelList result = new DocumentModelListImpl();
1461 String query = handler.getCMISQuery(queryContext);
1463 DocumentFilter docFilter = handler.getDocumentFilter();
1464 int pageSize = docFilter.getPageSize();
1465 int offset = docFilter.getOffset();
1466 if (logger.isDebugEnabled()) {
1467 logger.debug("Executing CMIS query: " + query.toString()
1468 + "with pageSize: " + pageSize + " at offset: " + offset);
1471 // If we have limit and/or offset, then pass true to get totalSize
1472 // in returned DocumentModelList.
1473 Profiler profiler = new Profiler(this, 2);
1474 profiler.log("Executing CMIS query: " + query.toString());
1477 IterableQueryResult queryResult = makeCMISQLQuery(repoSession, query, queryContext);
1479 int totalSize = (int) queryResult.size();
1480 ((DocumentModelListImpl) result).setTotalSize(totalSize);
1481 // Skip the rows before our offset
1483 queryResult.skipTo(offset);
1486 for (Map<String, Serializable> row : queryResult) {
1487 if (logger.isTraceEnabled()) {
1488 logger.trace(" Hierarchy Table ID is:" + row.get(IQueryManager.CMIS_TARGET_NUXEO_ID)
1489 + " nuxeo:pathSegment is: " + row.get(IQueryManager.CMIS_TARGET_NAME));
1491 String nuxeoId = (String) row.get(IQueryManager.CMIS_TARGET_NUXEO_ID);
1492 DocumentModel docModel = NuxeoUtils.getDocumentModel(repoSession, nuxeoId);
1493 result.add(docModel);
1495 if (nRows >= pageSize && pageSize != 0) { // A page size of zero means that they want all of them
1496 logger.debug("Got page full of items - quitting");
1501 queryResult.close();
1506 } catch (Exception e) {
1507 if (logger.isDebugEnabled()) {
1508 logger.debug("Caught exception ", e);
1510 throw new NuxeoDocumentException(e);
1514 // Since we're not supporting paging yet for CMIS queries, we need to perform
1515 // a workaround for the paging information we return in our list of results
1518 if (result != null) {
1519 docFilter.setStartPage(0);
1520 if (totalSize > docFilter.getPageSize()) {
1521 docFilter.setPageSize(totalSize);
1522 ((DocumentModelListImpl)result).setTotalSize(totalSize);
1530 private String logException(Exception e, String msg) {
1531 String result = null;
1533 String exceptionMessage = e.getMessage();
1534 exceptionMessage = exceptionMessage != null ? exceptionMessage : "<No details provided>";
1535 result = msg = msg + ". Caught exception:" + exceptionMessage;
1537 if (logger.isTraceEnabled() == true) {
1538 logger.error(msg, e);
1547 * update given document in the Nuxeo repository
1549 * @param ctx service context under which this method is invoked
1550 * @param csid of the document
1551 * @param handler should be used by the caller to provide and transform the
1553 * @throws BadRequestException
1554 * @throws DocumentNotFoundException
1555 * @throws TransactionException if the transaction times out or otherwise
1556 * cannot be successfully completed
1557 * @throws DocumentException
1560 public void update(ServiceContext ctx, String csid, DocumentHandler handler)
1561 throws BadRequestException, DocumentNotFoundException, TransactionException,
1563 if (handler == null) {
1564 throw new IllegalArgumentException(
1565 "RepositoryJavaClient.update: document handler is missing.");
1568 CoreSessionInterface repoSession = null;
1570 handler.prepare(Action.UPDATE);
1571 repoSession = getRepositorySession(ctx);
1572 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
1573 DocumentModel doc = null;
1575 doc = repoSession.getDocument(docRef);
1576 } catch (org.nuxeo.ecm.core.api.DocumentNotFoundException ce) {
1577 String msg = logException(ce,
1578 String.format("Could not find %s resource/record to update with CSID=%s", ctx.getDocumentType(), csid));
1579 throw new DocumentNotFoundException(msg, ce);
1581 // Check for a versioned document, and check In and Out before we proceed.
1582 if (((DocumentModelHandler) handler).supportsVersioning()) {
1583 /* Once we advance to 5.5 or later, we can add this.
1584 * See also https://jira.nuxeo.com/browse/NXP-8506
1585 if(!doc.isVersionable()) {
1586 throw new NuxeoDocumentException("Configuration for: "
1587 +handler.getServiceContextPath()+" supports versioning, but Nuxeo config does not!");
1590 /* Force a version number - Not working. Apparently we need to configure the uid schema??
1591 if(doc.getProperty("uid","major_version") == null) {
1592 doc.setProperty("uid","major_version",1);
1594 if(doc.getProperty("uid","minor_version") == null) {
1595 doc.setProperty("uid","minor_version",0);
1598 doc.checkIn(VersioningOption.MINOR, null);
1603 // Set reposession to handle the document
1605 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1606 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
1607 handler.handle(Action.UPDATE, wrapDoc);
1608 repoSession.saveDocument(doc);
1610 handler.complete(Action.UPDATE, wrapDoc);
1611 } catch (BadRequestException bre) {
1612 rollbackTransaction(repoSession);
1614 } catch (DocumentException de) {
1615 rollbackTransaction(repoSession);
1617 } catch (CSWebApplicationException wae) {
1618 rollbackTransaction(repoSession);
1620 } catch (Throwable e) {
1621 rollbackTransaction(repoSession);
1622 throw new NuxeoDocumentException(e);
1624 if (repoSession != null) {
1625 releaseRepositorySession(ctx, repoSession);
1631 * Save a documentModel to the Nuxeo repository.
1633 * @param ctx service context under which this method is invoked
1634 * @param repoSession
1635 * @param docModel the document to save
1636 * @param fSaveSession if TRUE, will call CoreSessionInterface.save() to save
1637 * accumulated changes.
1638 * @throws ClientException
1639 * @throws DocumentException
1642 public void saveDocWithoutHandlerProcessing(
1643 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1644 CoreSessionInterface repoSession,
1645 DocumentModel docModel,
1646 boolean fSaveSession)
1647 throws ClientException, DocumentException {
1650 repoSession.saveDocument(docModel);
1654 } catch (ClientException ce) {
1656 } catch (Exception e) {
1657 if (logger.isDebugEnabled()) {
1658 logger.debug("Caught exception ", e);
1660 throw new NuxeoDocumentException(e);
1665 * Save a list of documentModels to the Nuxeo repository.
1667 * @param ctx service context under which this method is invoked
1668 * @param repoSession a repository session
1669 * @param docModelList a list of document models
1670 * @param fSaveSession if TRUE, will call CoreSessionInterface.save() to save
1671 * accumulated changes.
1672 * @throws ClientException
1673 * @throws DocumentException
1675 public void saveDocListWithoutHandlerProcessing(
1676 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1677 CoreSessionInterface repoSession,
1678 DocumentModelList docList,
1679 boolean fSaveSession)
1680 throws ClientException, DocumentException {
1682 DocumentModel[] docModelArray = new DocumentModel[docList.size()];
1683 repoSession.saveDocuments(docList.toArray(docModelArray));
1687 } catch (ClientException ce) {
1689 } catch (Exception e) {
1690 logger.error("Caught exception ", e);
1691 throw new NuxeoDocumentException(e);
1696 public void deleteWithWhereClause(@SuppressWarnings("rawtypes") ServiceContext ctx, String whereClause,
1697 @SuppressWarnings("rawtypes") DocumentHandler handler) throws
1698 DocumentNotFoundException, DocumentException {
1700 throw new IllegalArgumentException(
1701 "delete(ctx, specifier): ctx is missing");
1703 if (logger.isDebugEnabled()) {
1704 logger.debug("Deleting document with whereClause=" + whereClause);
1707 DocumentWrapper<DocumentModel> foundDocWrapper = this.findDoc(ctx, whereClause);
1708 if (foundDocWrapper != null) {
1709 DocumentModel docModel = foundDocWrapper.getWrappedObject();
1710 String csid = docModel.getName();
1711 this.delete(ctx, csid, handler);
1716 * delete a document from the Nuxeo repository
1718 * @param ctx service context under which this method is invoked
1719 * @param id of the document
1720 * @throws DocumentException
1723 public boolean delete(ServiceContext ctx, List<String> idList, DocumentHandler handler) throws DocumentNotFoundException,
1724 DocumentException, TransactionException {
1725 boolean result = true;
1728 throw new IllegalArgumentException(
1729 "delete(ctx, ix, handler): ctx is missing");
1731 if (handler == null) {
1732 throw new IllegalArgumentException(
1733 "delete(ctx, ix, handler): handler is missing");
1736 CoreSessionInterface repoSession = null;
1738 handler.prepare(Action.DELETE);
1739 repoSession = getRepositorySession(ctx);
1741 for (String id : idList) {
1742 if (logger.isDebugEnabled()) {
1743 logger.debug("Deleting document with CSID=" + id);
1745 DocumentWrapper<DocumentModel> wrapDoc = null;
1747 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
1748 wrapDoc = new DocumentWrapperImpl<DocumentModel>(repoSession.getDocument(docRef));
1749 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1750 if (handler.handle(Action.DELETE, wrapDoc) == true) {
1751 repoSession.removeDocument(docRef);
1752 if (logger.isDebugEnabled()) {
1753 String msg = String.format("DELETE - User '%s' hard-deleted document CSID=%s of type %s.",
1754 ctx.getUserId(), id, ctx.getDocumentType());
1758 String msg = String.format("Could not delete %s resource with csid=%s.",
1759 handler.getServiceContext().getServiceName(), id);
1760 throw new DocumentException(msg);
1762 } catch (org.nuxeo.ecm.core.api.DocumentNotFoundException ce) {
1763 String msg = logException(ce,
1764 String.format("Could not find %s resource/record to delete with CSID=%s", ctx.getDocumentType(), id));
1765 throw new DocumentNotFoundException(msg, ce);
1768 handler.complete(Action.DELETE, wrapDoc);
1770 } catch (DocumentException de) {
1771 rollbackTransaction(repoSession);
1773 } catch (Throwable e) {
1774 rollbackTransaction(repoSession);
1775 throw new NuxeoDocumentException(e);
1777 if (repoSession != null) {
1778 releaseRepositorySession(ctx, repoSession);
1786 * delete a document from the Nuxeo repository
1788 * @param ctx service context under which this method is invoked
1789 * @param id of the document
1790 * @throws DocumentException
1793 public boolean delete(ServiceContext ctx, String id, DocumentHandler handler) throws DocumentNotFoundException,
1794 DocumentException, TransactionException {
1797 List<String> idList = new ArrayList<String>();
1799 result = delete(ctx, idList, handler);
1805 * @see org.collectionspace.services.common.storage.StorageClient#delete(org.collectionspace.services.common.context.ServiceContext, java.lang.String, org.collectionspace.services.common.document.DocumentHandler)
1809 public void delete(@SuppressWarnings("rawtypes") ServiceContext ctx, String id)
1810 throws DocumentNotFoundException, DocumentException {
1811 throw new UnsupportedOperationException();
1812 // Use the other delete instead
1816 public Hashtable<String, String> retrieveWorkspaceIds(RepositoryDomainType repoDomain) throws Exception {
1817 return NuxeoConnectorEmbedded.getInstance().retrieveWorkspaceIds(repoDomain);
1821 public String createDomain(RepositoryDomainType repositoryDomain) throws Exception {
1822 CoreSessionInterface repoSession = null;
1823 String domainId = null;
1826 // Open a connection to the domain's repo/db
1828 String repoName = repositoryDomain.getRepositoryName();
1829 repoSession = getRepositorySession(repoName); // domainName=storageName=repoName=databaseName
1831 // First create the top-level domain directory
1833 String domainName = repositoryDomain.getStorageName();
1834 DocumentRef parentDocRef = new PathRef("/");
1835 DocumentModel parentDoc = repoSession.getDocument(parentDocRef);
1836 DocumentModel domainDoc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1837 domainName, NUXEO_CORE_TYPE_DOMAIN);
1838 domainDoc.setPropertyValue("dc:title", domainName);
1839 domainDoc.setPropertyValue("dc:description", "A CollectionSpace domain "
1841 domainDoc = repoSession.createDocument(domainDoc);
1842 domainId = domainDoc.getId();
1845 // Next, create a "Workspaces" root directory to contain the workspace folders for the individual service documents
1847 DocumentModel workspacesRoot = repoSession.createDocumentModel(domainDoc.getPathAsString(),
1848 NuxeoUtils.Workspaces, NUXEO_CORE_TYPE_WORKSPACEROOT);
1849 workspacesRoot.setPropertyValue("dc:title", NuxeoUtils.Workspaces);
1850 workspacesRoot.setPropertyValue("dc:description", "A CollectionSpace workspaces directory for "
1851 + domainDoc.getPathAsString());
1852 workspacesRoot = repoSession.createDocument(workspacesRoot);
1853 String workspacesRootId = workspacesRoot.getId();
1856 if (logger.isDebugEnabled()) {
1857 logger.debug("Created tenant domain name=" + domainName
1858 + " id=" + domainId + " "
1859 + NuxeoUtils.Workspaces + " id=" + workspacesRootId);
1860 logger.debug("Path to Domain: " + domainDoc.getPathAsString());
1861 logger.debug("Path to Workspaces root: " + workspacesRoot.getPathAsString());
1863 } catch (Throwable e) {
1864 rollbackTransaction(repoSession);
1865 if (logger.isDebugEnabled()) {
1866 logger.debug("Could not create tenant domain name=" + repositoryDomain.getStorageName() + " caught exception ", e);
1870 if (repoSession != null) {
1871 releaseRepositorySession(null, repoSession);
1879 public String getDomainId(RepositoryDomainType repositoryDomain) throws Exception {
1880 String domainId = null;
1881 CoreSessionInterface repoSession = null;
1883 String repoName = repositoryDomain.getRepositoryName();
1884 String domainStorageName = repositoryDomain.getStorageName();
1885 if (domainStorageName != null && !domainStorageName.isEmpty()) {
1887 repoSession = getRepositorySession(repoName);
1888 DocumentRef docRef = new PathRef("/" + domainStorageName);
1889 DocumentModel domain = repoSession.getDocument(docRef);
1890 domainId = domain.getId();
1891 } catch (Exception e) {
1892 if (logger.isTraceEnabled()) {
1893 logger.trace("Caught exception ", e); // The document doesn't exist, this let's us know we need to create it
1896 if (repoSession != null) {
1897 releaseRepositorySession(null, repoSession);
1906 * Returns the workspaces root directory for a given domain.
1908 private DocumentModel getWorkspacesRoot(CoreSessionInterface repoSession,
1909 String domainName) throws Exception {
1910 DocumentModel result = null;
1912 String domainPath = "/" + domainName;
1913 DocumentRef parentDocRef = new PathRef(domainPath);
1914 DocumentModelList domainChildrenList = repoSession.getChildren(
1916 Iterator<DocumentModel> witer = domainChildrenList.iterator();
1917 while (witer.hasNext()) {
1918 DocumentModel childNode = witer.next();
1919 if (NuxeoUtils.Workspaces.equalsIgnoreCase(childNode.getName())) {
1921 logger.trace("Found workspaces directory at: " + result.getPathAsString());
1926 if (result == null) {
1927 throw new ClientException("Could not find workspace root directory in: "
1935 * @see org.collectionspace.services.common.repository.RepositoryClient#createWorkspace(java.lang.String, java.lang.String)
1938 public String createWorkspace(RepositoryDomainType repositoryDomain, String workspaceName) throws Exception {
1939 CoreSessionInterface repoSession = null;
1940 String workspaceId = null;
1942 String repoName = repositoryDomain.getRepositoryName();
1943 repoSession = getRepositorySession(repoName);
1945 String domainStorageName = repositoryDomain.getStorageName();
1946 DocumentModel parentDoc = getWorkspacesRoot(repoSession, domainStorageName);
1947 if (logger.isTraceEnabled()) {
1948 for (String facet : parentDoc.getFacets()) {
1949 logger.trace("Facet: " + facet);
1953 DocumentModel doc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1954 workspaceName, NuxeoUtils.WORKSPACE_DOCUMENT_TYPE);
1955 doc.setPropertyValue("dc:title", workspaceName);
1956 doc.setPropertyValue("dc:description", "A CollectionSpace workspace for "
1958 doc = repoSession.createDocument(doc);
1959 workspaceId = doc.getId();
1961 if (logger.isDebugEnabled()) {
1962 logger.debug("Created workspace name=" + workspaceName
1963 + " id=" + workspaceId);
1965 } catch (Throwable e) {
1966 rollbackTransaction(repoSession);
1967 if (logger.isDebugEnabled()) {
1968 logger.debug("createWorkspace caught exception ", e);
1972 if (repoSession != null) {
1973 releaseRepositorySession(null, repoSession);
1980 * @see org.collectionspace.services.common.repository.RepositoryClient#getWorkspaceId(java.lang.String, java.lang.String)
1984 public String getWorkspaceId(String tenantDomain, String workspaceName) throws Exception {
1985 String workspaceId = null;
1987 CoreSessionInterface repoSession = null;
1989 repoSession = getRepositorySession((ServiceContext<PoxPayloadIn, PoxPayloadOut>) null);
1990 DocumentRef docRef = new PathRef(
1992 + "/" + NuxeoUtils.Workspaces
1993 + "/" + workspaceName);
1994 DocumentModel workspace = repoSession.getDocument(docRef);
1995 workspaceId = workspace.getId();
1996 } catch (DocumentException de) {
1998 } catch (Exception e) {
1999 if (logger.isDebugEnabled()) {
2000 logger.debug("Caught exception ", e);
2002 throw new NuxeoDocumentException(e);
2004 if (repoSession != null) {
2005 releaseRepositorySession(null, repoSession);
2013 public CoreSessionInterface getRepositorySession(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) throws Exception {
2014 return getRepositorySession(ctx, ctx.getRepositoryName(), ctx.getTimeoutSecs());
2017 public CoreSessionInterface getRepositorySession(String repoName) throws Exception {
2018 return getRepositorySession(null, repoName, ServiceContext.DEFAULT_TX_TIMEOUT);
2022 * Gets the repository session. - Package access only. If the 'ctx' param is
2023 * null then the repo name must be non-mull and vice-versa
2025 * @return the repository session
2026 * @throws Exception the exception
2028 public CoreSessionInterface getRepositorySession(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
2030 int timeoutSeconds) throws Exception {
2031 CoreSessionInterface repoSession = null;
2033 Profiler profiler = new Profiler("getRepositorySession():", 2);
2036 // To get a connection to the Nuxeo repo, we need either a valid ServiceContext instance or a repository name
2039 repoSession = (CoreSessionInterface) ctx.getCurrentRepositorySession(); // First see if the context already has a repo session
2040 if (repoSession == null) {
2041 repoName = ctx.getRepositoryName(); // Notice we are overriding the passed in 'repoName' since we have a valid service context passed in to us
2043 } else if (Tools.isBlank(repoName)) {
2044 String errMsg = String.format("Either a valid session context or repository name are required to get a new connection.");
2045 logger.error(errMsg);
2046 throw new Exception(errMsg);
2049 if (repoSession == null) {
2051 // 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
2052 // just the repository name.
2054 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
2055 repoSession = client.openRepository(repoName, timeoutSeconds);
2057 if (logger.isTraceEnabled() == true) {
2058 logger.trace("Reusing the current context's repository session.");
2062 // Debugging only code
2064 if (logger.isTraceEnabled()) {
2066 if (logger.isTraceEnabled()) {
2067 logger.trace("Testing call to getRepository() repository root: " + repoSession.getRootDocument());
2069 } catch (Throwable e) {
2070 logger.trace("Test call to Nuxeo's getRepository() repository root failed", e);
2077 ctx.setCurrentRepositorySession(repoSession); // For reusing, save the repository session in the current service context. The context will reference count it.
2084 * Release repository session. - Package access only.
2086 * @param repoSession the repo session
2089 public void releaseRepositorySession(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, Object repositorySession) throws TransactionException {
2091 CoreSessionInterface repoSession = (CoreSessionInterface)repositorySession;
2092 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
2095 ctx.clearCurrentRepositorySession(); //clear the current context of the now closed repo session
2096 if (ctx.getCurrentRepositorySession() == null) {
2097 client.releaseRepository(repoSession); //release the repo session if the service context's ref count is zeo.
2100 client.releaseRepository(repoSession); //repo session was acquired without a service context
2102 } catch (TransactionRuntimeException tre) {
2103 String causeMsg = null;
2104 Throwable cause = tre.getCause();
2105 if (cause != null) {
2106 causeMsg = cause.getMessage();
2109 TransactionException te; // a CollectionSpace specific tx exception
2110 if (causeMsg != null) {
2111 te = new TransactionException(causeMsg, tre);
2113 te = new TransactionException(tre);
2116 logger.error(te.getMessage(), tre); // Log the standard transaction exception message, plus an exception-specific stack trace
2118 } catch (Exception e) {
2119 logger.error("Could not close the repository session.", e);
2120 // no need to throw this service specific exception
2125 public void doWorkflowTransition(ServiceContext ctx, String id,
2126 DocumentHandler handler, TransitionDef transitionDef)
2127 throws BadRequestException, DocumentNotFoundException,
2129 // 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
2132 private String handleProvidedStartingWildcard(String partialTerm) {
2133 if (Tools.notBlank(partialTerm)) {
2134 if (partialTerm.substring(0, 1).equals(USER_SUPPLIED_WILDCARD)) {
2135 StringBuffer buffer = new StringBuffer(partialTerm);
2136 buffer.setCharAt(0, JDBCTools.SQL_WILDCARD.charAt(0));
2137 partialTerm = buffer.toString();
2144 * Replaces user-supplied wildcards with SQL wildcards, in a partial term
2145 * matching search expression.
2147 * The scope of this replacement excludes the beginning character
2148 * in that search expression, as that character is treated specially.
2150 * @param partialTerm
2151 * @return the partial term, with any user-supplied wildcards replaced
2154 private String subtituteWildcardsInPartialTerm(String partialTerm) {
2155 if (Tools.isBlank(partialTerm)) {
2158 if (! partialTerm.contains(USER_SUPPLIED_WILDCARD)) {
2161 int len = partialTerm.length();
2162 // Partial term search expressions of 2 or fewer characters
2163 // currently aren't amenable to the use of wildcards
2165 logger.warn("Partial term match search expression of just 1-2 characters in length contains a user-supplied wildcard: " + partialTerm);
2166 logger.warn("Will handle that character as a literal value, rather than as a wildcard ...");
2169 return partialTerm.substring(0, 1) // first char
2170 + partialTerm.substring(1, len).replaceAll(USER_SUPPLIED_WILDCARD_REGEX, JDBCTools.SQL_WILDCARD);
2174 private int getMaxItemsLimitOnJdbcQueries(String maxListItemsLimit) {
2175 final int DEFAULT_ITEMS_LIMIT = 40;
2176 if (maxListItemsLimit == null) {
2177 return DEFAULT_ITEMS_LIMIT;
2181 itemsLimit = Integer.parseInt(maxListItemsLimit);
2182 if (itemsLimit < 1) {
2183 logger.warn("Value of configuration setting "
2184 + IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES
2185 + " must be a positive integer; invalid current value is " + maxListItemsLimit);
2186 logger.warn("Reverting to default value of " + DEFAULT_ITEMS_LIMIT);
2187 itemsLimit = DEFAULT_ITEMS_LIMIT;
2189 } catch (NumberFormatException nfe) {
2190 logger.warn("Value of configuration setting "
2191 + IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES
2192 + " must be a positive integer; invalid current value is " + maxListItemsLimit);
2193 logger.warn("Reverting to default value of " + DEFAULT_ITEMS_LIMIT);
2194 itemsLimit = DEFAULT_ITEMS_LIMIT;
2200 * Identifies whether a restriction on tenant ID - to return only records
2201 * pertaining to the current tenant - is required in a JDBC query.
2203 * @param tenantBinding a tenant binding configuration.
2204 * @param ctx a service context.
2205 * @return true if a restriction on tenant ID is required in the query;
2206 * false if a restriction is not required.
2208 private boolean restrictJDBCQueryByTenantID(TenantBindingType tenantBinding, ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
2209 boolean restrict = true;
2210 // If data for the current service, in the current tenant, is isolated
2211 // within its own separate, per-tenant repository, as contrasted with
2212 // being intermingled with other tenants' data in the default repository,
2213 // no restriction on Tenant ID is required in the query.
2214 String repositoryDomainName = ConfigUtils.getRepositoryName(tenantBinding, ctx.getRepositoryDomainName());
2215 if (!(repositoryDomainName.equals(ConfigUtils.DEFAULT_NUXEO_REPOSITORY_NAME))) {
2218 // If a configuration setting for this tenant identifies that JDBC
2219 // queries should not be restricted by tenant ID (perhaps because
2220 // there is always expected to be only one tenant's data present in
2221 // the system), no restriction on Tenant ID is required in the query.
2222 String queriesRestrictedByTenantId = TenantBindingUtils.getPropertyValue(tenantBinding,
2223 IQueryManager.JDBC_QUERIES_ARE_TENANT_ID_RESTRICTED);
2224 if (Tools.notBlank(queriesRestrictedByTenantId) &&
2225 queriesRestrictedByTenantId.equalsIgnoreCase(Boolean.FALSE.toString())) {
2231 private void rollbackTransaction(CoreSessionInterface repoSession) {
2232 if (repoSession != null) {
2233 repoSession.setTransactionRollbackOnly();
2238 * Should never get called.
2241 public boolean delete(ServiceContext ctx, Object entityFound, DocumentHandler handler)
2242 throws DocumentNotFoundException, DocumentException {
2243 throw new UnsupportedOperationException();