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.index.IndexClient;
44 import org.collectionspace.services.client.workflow.WorkflowClient;
45 import org.collectionspace.services.common.context.ServiceContext;
46 import org.collectionspace.services.common.query.QueryContext;
47 import org.collectionspace.services.common.repository.RepositoryClient;
48 import org.collectionspace.services.common.storage.JDBCTools;
49 import org.collectionspace.services.common.storage.PreparedStatementSimpleBuilder;
50 import org.collectionspace.services.common.document.BadRequestException;
51 import org.collectionspace.services.common.document.DocumentException;
52 import org.collectionspace.services.common.document.DocumentFilter;
53 import org.collectionspace.services.common.document.DocumentHandler;
54 import org.collectionspace.services.common.document.DocumentNotFoundException;
55 import org.collectionspace.services.common.document.DocumentHandler.Action;
56 import org.collectionspace.services.common.document.DocumentWrapper;
57 import org.collectionspace.services.common.document.DocumentWrapperImpl;
58 import org.collectionspace.services.common.document.TransactionException;
59 import org.collectionspace.services.common.CSWebApplicationException;
60 import org.collectionspace.services.common.ServiceMain;
61 import org.collectionspace.services.common.api.Tools;
62 import org.collectionspace.services.common.config.ConfigUtils;
63 import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl;
64 import org.collectionspace.services.common.config.TenantBindingUtils;
65 import org.collectionspace.services.common.storage.PreparedStatementBuilder;
66 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.AuthorityItemSpecifier;
67 import org.collectionspace.services.config.tenant.TenantBindingType;
68 import org.collectionspace.services.config.tenant.RepositoryDomainType;
71 // CSPACE-5036 - How to make CMISQL queries from Nuxeo
73 import org.apache.chemistry.opencmis.commons.enums.CmisVersion;
74 import org.apache.chemistry.opencmis.commons.server.CallContext;
75 import org.apache.chemistry.opencmis.server.impl.CallContextImpl;
76 import org.apache.chemistry.opencmis.server.shared.ThresholdOutputStreamFactory;
77 import org.nuxeo.common.utils.IdUtils;
78 import org.nuxeo.ecm.core.api.ClientException;
79 import org.nuxeo.ecm.core.api.DocumentModel;
80 import org.nuxeo.ecm.core.api.DocumentModelList;
81 import org.nuxeo.ecm.core.api.IterableQueryResult;
82 import org.nuxeo.ecm.core.api.VersioningOption;
83 import org.nuxeo.ecm.core.api.impl.DocumentModelListImpl;
84 import org.nuxeo.ecm.core.api.DocumentRef;
85 import org.nuxeo.ecm.core.api.IdRef;
86 import org.nuxeo.ecm.core.api.PathRef;
87 import org.nuxeo.runtime.api.Framework;
88 import org.nuxeo.runtime.transaction.TransactionRuntimeException;
89 import org.nuxeo.ecm.core.opencmis.bindings.NuxeoCmisServiceFactory;
90 import org.nuxeo.ecm.core.opencmis.impl.server.NuxeoCmisService;
91 import org.nuxeo.elasticsearch.api.ElasticSearchAdmin;
92 import org.nuxeo.elasticsearch.api.ElasticSearchIndexing;
93 import org.nuxeo.elasticsearch.api.ElasticSearchService;
94 import org.slf4j.Logger;
95 import org.slf4j.LoggerFactory;
98 * RepositoryClientImpl is used to perform CRUD operations on documents in Nuxeo
99 * repository using Remote Java APIs. It uses
101 * @see DocumentHandler as IOHandler with the client.
103 * $LastChangedRevision: $ $LastChangedDate: $
105 public class NuxeoRepositoryClientImpl implements RepositoryClient<PoxPayloadIn, PoxPayloadOut> {
110 private final Logger logger = LoggerFactory.getLogger(NuxeoRepositoryClientImpl.class);
111 // private final Logger profilerLogger = LoggerFactory.getLogger("remperf");
112 // private String foo = Profiler.createLogger();
113 public static final String NUXEO_CORE_TYPE_DOMAIN = "Domain";
114 public static final String NUXEO_CORE_TYPE_WORKSPACEROOT = "WorkspaceRoot";
115 // FIXME: Get this value from an existing constant, if available
116 public static final String BACKSLASH = "\\";
117 public static final String USER_SUPPLIED_WILDCARD = "*";
118 public static final String USER_SUPPLIED_WILDCARD_REGEX = BACKSLASH + USER_SUPPLIED_WILDCARD;
119 public static final String USER_SUPPLIED_ANCHOR_CHAR = "^";
120 public static final String USER_SUPPLIED_ANCHOR_CHAR_REGEX = BACKSLASH + USER_SUPPLIED_ANCHOR_CHAR;
121 public static final String ENDING_ANCHOR_CHAR = "$";
122 public static final String ENDING_ANCHOR_CHAR_REGEX = BACKSLASH + ENDING_ANCHOR_CHAR;
126 * Instantiates a new repository java client impl.
128 public NuxeoRepositoryClientImpl() {
132 public void assertWorkflowState(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, DocumentModel docModel) throws DocumentNotFoundException, ClientException {
133 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
134 if (queryParams != null) {
136 // Look for the workflow "delete" query param and see if we need to assert that the
137 // docModel is in a non-deleted workflow state.
139 String currentState = docModel.getCurrentLifeCycleState();
140 String includeDeletedStr = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_DELETED_QP);
141 boolean includeDeleted = (includeDeletedStr == null) ? true : Boolean.parseBoolean(includeDeletedStr);
142 if (includeDeleted == false) {
144 // We don't wanted soft-deleted objects, so throw an exception if this one is soft-deleted.
146 if (currentState.contains(WorkflowClient.WORKFLOWSTATE_DELETED)) {
147 String msg = "The GET assertion that docModel not be in 'deleted' workflow state failed.";
149 throw new DocumentNotFoundException(msg);
156 * create document in the Nuxeo repository
158 * @param ctx service context under which this method is invoked
159 * @param handler should be used by the caller to provide and transform the
161 * @return id in repository of the newly created document
162 * @throws BadRequestException
163 * @throws TransactionException
164 * @throws DocumentException
167 public String create(ServiceContext ctx,
168 DocumentHandler handler) throws BadRequestException,
169 TransactionException, DocumentException {
171 String docType = NuxeoUtils.getTenantQualifiedDocType(ctx); //ctx.getDocumentType();
172 if (docType == null) {
173 throw new IllegalArgumentException(
174 "RepositoryJavaClient.create: docType is missing");
177 if (handler == null) {
178 throw new IllegalArgumentException(
179 "RepositoryJavaClient.create: handler is missing");
181 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
182 if (nuxeoWspaceId == null) {
183 throw new DocumentNotFoundException(
184 "Unable to find workspace for service " + ctx.getServiceName()
185 + " check if the workspace exists in the Nuxeo repository");
188 CoreSessionInterface repoSession = null;
190 handler.prepare(Action.CREATE);
191 repoSession = getRepositorySession(ctx);
192 DocumentRef nuxeoWspace = new IdRef(nuxeoWspaceId);
193 DocumentModel wspaceDoc = repoSession.getDocument(nuxeoWspace);
194 String wspacePath = wspaceDoc.getPathAsString();
195 //give our own ID so PathRef could be constructed later on
196 String id = IdUtils.generateId(UUID.randomUUID().toString(), "-", true, 24);
197 // create document model
198 DocumentModel doc = repoSession.createDocumentModel(wspacePath, id, docType);
199 /* Check for a versioned document, and check In and Out before we proceed.
200 * This does not work as we do not have the uid schema on our docs.
201 if(((DocumentModelHandler) handler).supportsVersioning()) {
202 doc.setProperty("uid","major_version",1);
203 doc.setProperty("uid","minor_version",0);
206 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
207 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
208 handler.handle(Action.CREATE, wrapDoc);
209 // create document with documentmodel
210 doc = repoSession.createDocument(doc);
212 // TODO for sub-docs need to call into the handler to let it deal with subitems. Pass in the id,
213 // and assume the handler has the state it needs (doc fragments).
214 handler.complete(Action.CREATE, wrapDoc);
216 } catch (BadRequestException bre) {
217 rollbackTransaction(repoSession);
219 } catch (Throwable e) {
220 rollbackTransaction(repoSession);
221 if (logger.isDebugEnabled()) {
222 logger.debug("Call to low-level Nuxeo document create call failed: ", e);
224 throw new NuxeoDocumentException(e);
226 if (repoSession != null) {
227 releaseRepositorySession(ctx, repoSession);
233 public boolean reindex(DocumentHandler handler, String indexid) throws DocumentNotFoundException, DocumentException
235 return reindex(handler, null, indexid);
239 public boolean reindex(DocumentHandler handler, String csid, String indexid) throws DocumentNotFoundException, DocumentException
241 boolean result = true;
244 case IndexClient.FULLTEXT_ID:
245 result = reindexFulltext(handler, csid, indexid);
247 case IndexClient.ELASTICSEARCH_ID:
248 result = reindexElasticsearch(handler, csid, indexid);
251 throw new NuxeoDocumentException(String.format("Unknown index '%s'. Reindex request failed.",
259 * Reindex Nuxeo's fulltext index.
265 * @throws NuxeoDocumentException
266 * @throws TransactionException
268 private boolean reindexFulltext(DocumentHandler handler, String csid, String indexid) throws NuxeoDocumentException, TransactionException {
269 boolean result = true;
270 CoreSessionInterface repoSession = null;
271 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = handler.getServiceContext();
274 String queryString = handler.getDocumentsToIndexQuery(indexid, csid);
275 repoSession = getRepositorySession(ctx);
276 CSReindexFulltextRoot indexer = new CSReindexFulltextRoot(repoSession);
277 indexer.reindexFulltext(0, 0, queryString);
278 } catch (Throwable e) {
279 rollbackTransaction(repoSession);
280 if (logger.isDebugEnabled()) {
281 logger.debug("Caught exception trying to reindex Nuxeo repository ", e);
283 throw new NuxeoDocumentException(e);
285 if (repoSession != null) {
286 releaseRepositorySession(ctx, repoSession);
294 * Reindex Nuxeo's Elasticsearch index.
300 * @throws NuxeoDocumentException
301 * @throws TransactionException
303 private boolean reindexElasticsearch(DocumentHandler handler, String csid, String indexid) throws NuxeoDocumentException, TransactionException {
304 boolean result = false;
305 CoreSessionInterface repoSession = null;
306 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = handler.getServiceContext();
309 ElasticSearchIndexing esi = Framework.getService(ElasticSearchIndexing.class);
310 ElasticSearchAdmin esa = Framework.getService(ElasticSearchAdmin.class);
312 String queryString = handler.getDocumentsToIndexQuery(indexid, csid);
313 esa.initIndexes(true);
315 repoSession = getRepositorySession(ctx);
316 esi.runReindexingWorker(repoSession.getRepositoryName(), queryString);
318 } catch (Throwable e) {
319 rollbackTransaction(repoSession);
320 if (logger.isDebugEnabled()) {
321 logger.debug("Caught exception trying to reindex Nuxeo repository ", e);
323 throw new NuxeoDocumentException(e);
325 if (repoSession != null) {
326 releaseRepositorySession(ctx, repoSession);
334 public boolean synchronize(ServiceContext ctx, Object specifier, DocumentHandler handler)
335 throws DocumentNotFoundException, TransactionException, DocumentException {
336 boolean result = false;
338 if (handler == null) {
339 throw new IllegalArgumentException("RepositoryJavaClient.get: handler is missing");
342 CoreSessionInterface repoSession = null;
344 handler.prepare(Action.SYNC);
345 repoSession = getRepositorySession(ctx);
346 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
347 DocumentWrapper<Object> wrapDoc = new DocumentWrapperImpl<Object>(specifier);
348 result = handler.handle(Action.SYNC, wrapDoc);
349 handler.complete(Action.SYNC, wrapDoc);
350 } catch (IllegalArgumentException iae) {
351 rollbackTransaction(repoSession);
353 } catch (DocumentException de) {
354 rollbackTransaction(repoSession);
356 } catch (Throwable e) {
357 rollbackTransaction(repoSession);
358 if (logger.isDebugEnabled()) {
359 logger.debug("Caught exception ", e);
361 throw new NuxeoDocumentException(e);
363 if (repoSession != null) {
364 releaseRepositorySession(ctx, repoSession);
372 public boolean synchronizeItem(ServiceContext ctx, AuthorityItemSpecifier itemSpecifier, DocumentHandler handler)
373 throws DocumentNotFoundException, TransactionException, DocumentException {
374 boolean result = false;
376 if (handler == null) {
377 throw new IllegalArgumentException(
378 "RepositoryJavaClient.get: handler is missing");
381 CoreSessionInterface repoSession = null;
383 handler.prepare(Action.SYNC);
384 repoSession = getRepositorySession(ctx);
385 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
386 DocumentWrapper<AuthorityItemSpecifier> wrapDoc = new DocumentWrapperImpl<AuthorityItemSpecifier>(itemSpecifier);
387 result = handler.handle(Action.SYNC, wrapDoc);
388 handler.complete(Action.SYNC, wrapDoc);
389 } catch (IllegalArgumentException iae) {
390 rollbackTransaction(repoSession);
392 } catch (DocumentException de) {
393 rollbackTransaction(repoSession);
395 } catch (Throwable e) {
396 rollbackTransaction(repoSession);
397 throw new NuxeoDocumentException(e);
399 if (repoSession != null) {
400 releaseRepositorySession(ctx, repoSession);
408 * get document from the Nuxeo repository
410 * @param ctx service context under which this method is invoked
411 * @param id of the document to retrieve
412 * @param handler should be used by the caller to provide and transform the
414 * @throws DocumentNotFoundException if the document cannot be found in the
416 * @throws TransactionException
417 * @throws DocumentException
420 public void get(ServiceContext ctx, String id, DocumentHandler handler)
421 throws DocumentNotFoundException, TransactionException, DocumentException {
423 if (handler == null) {
424 throw new IllegalArgumentException(
425 "RepositoryJavaClient.get: handler is missing");
428 CoreSessionInterface repoSession = null;
430 handler.prepare(Action.GET);
431 repoSession = getRepositorySession(ctx);
432 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
433 DocumentModel docModel = null;
435 docModel = repoSession.getDocument(docRef);
436 assertWorkflowState(ctx, docModel);
437 } catch (org.nuxeo.ecm.core.api.DocumentNotFoundException ce) {
438 String msg = logException(ce,
439 String.format("Could not find %s resource/record with CSID=%s", ctx.getDocumentType(), id));
440 throw new DocumentNotFoundException(msg, ce);
443 // Set repository session to handle the document
445 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
446 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(docModel);
447 handler.handle(Action.GET, wrapDoc);
448 handler.complete(Action.GET, wrapDoc);
449 } catch (IllegalArgumentException iae) {
451 } catch (DocumentException de) {
452 if (logger.isDebugEnabled()) {
453 logger.debug(de.getMessage(), de);
456 } catch (Throwable e) {
457 if (logger.isDebugEnabled()) {
458 logger.debug("Caught exception ", e);
460 throw new NuxeoDocumentException(e);
462 if (repoSession != null) {
463 releaseRepositorySession(ctx, repoSession);
469 * get a document from the Nuxeo repository, using the docFilter params.
471 * @param ctx service context under which this method is invoked
472 * @param handler should be used by the caller to provide and transform the
473 * document. Handler must have a docFilter set to return a single item.
474 * @throws DocumentNotFoundException if the document cannot be found in the
476 * @throws TransactionException
477 * @throws DocumentException
480 public void get(ServiceContext ctx, DocumentHandler handler)
481 throws DocumentNotFoundException, TransactionException, DocumentException {
482 QueryContext queryContext = new QueryContext(ctx, handler);
483 CoreSessionInterface repoSession = null;
486 handler.prepare(Action.GET);
487 repoSession = getRepositorySession(ctx);
489 DocumentModelList docList = null;
490 // force limit to 1, and ignore totalSize
491 String query = NuxeoUtils.buildNXQLQuery(queryContext);
492 docList = repoSession.query(query, null, 1, 0, false);
493 if (docList.size() != 1) {
494 throw new DocumentNotFoundException("No document found matching filter params: " + query);
496 DocumentModel doc = docList.get(0);
498 if (logger.isDebugEnabled()) {
499 logger.debug("Executed NXQL query: " + query);
502 //set reposession to handle the document
503 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
504 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
505 handler.handle(Action.GET, wrapDoc);
506 handler.complete(Action.GET, wrapDoc);
507 } catch (IllegalArgumentException iae) {
509 } catch (DocumentException de) {
511 } catch (Throwable e) {
512 if (logger.isDebugEnabled()) {
513 logger.debug("Caught exception ", e);
515 throw new NuxeoDocumentException(e);
517 if (repoSession != null) {
518 releaseRepositorySession(ctx, repoSession);
523 public DocumentWrapper<DocumentModel> getDoc(
524 CoreSessionInterface repoSession,
525 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
526 String csid) throws DocumentNotFoundException, DocumentException {
527 DocumentWrapper<DocumentModel> wrapDoc = null;
530 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
531 DocumentModel doc = null;
533 doc = repoSession.getDocument(docRef);
534 } catch (ClientException ce) {
535 String msg = logException(ce, "Could not find document with CSID=" + csid);
536 throw new DocumentNotFoundException(msg, ce);
538 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
539 } catch (IllegalArgumentException iae) {
541 } catch (DocumentException de) {
549 * Get wrapped documentModel from the Nuxeo repository. The search is
550 * restricted to the workspace of the current context.
552 * @param ctx service context under which this method is invoked
553 * @param csid of the document to retrieve
554 * @throws DocumentNotFoundException
555 * @throws TransactionException
556 * @throws DocumentException
557 * @return a wrapped documentModel
560 public DocumentWrapper<DocumentModel> getDoc(
561 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
562 String csid) throws DocumentNotFoundException, TransactionException, DocumentException {
563 CoreSessionInterface repoSession = null;
564 DocumentWrapper<DocumentModel> wrapDoc = null;
567 // Open a new repository session
568 repoSession = getRepositorySession(ctx);
569 wrapDoc = getDoc(repoSession, ctx, csid);
570 } catch (IllegalArgumentException iae) {
572 } catch (DocumentException de) {
574 } catch (Exception e) {
575 if (logger.isDebugEnabled()) {
576 logger.debug("Caught exception ", e);
578 throw new NuxeoDocumentException(e);
580 if (repoSession != null) {
581 releaseRepositorySession(ctx, repoSession);
585 if (logger.isWarnEnabled() == true) {
586 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
591 public DocumentWrapper<DocumentModel> findDoc(
592 CoreSessionInterface repoSession,
593 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
595 throws DocumentNotFoundException, DocumentException {
596 DocumentWrapper<DocumentModel> wrapDoc = null;
599 QueryContext queryContext = new QueryContext(ctx, whereClause);
600 DocumentModelList docList = null;
601 // force limit to 1, and ignore totalSize
602 String query = NuxeoUtils.buildNXQLQuery(queryContext);
603 docList = repoSession.query(query,
608 if (docList.size() != 1) {
609 if (logger.isDebugEnabled()) {
610 logger.debug("findDoc: Query found: " + docList.size() + " items.");
611 logger.debug(" Query: " + query);
613 throw new DocumentNotFoundException("No document found matching filter params: " + query);
615 DocumentModel doc = docList.get(0);
616 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
617 } catch (IllegalArgumentException iae) {
619 } catch (DocumentException de) {
621 } catch (Exception e) {
622 if (logger.isDebugEnabled()) {
623 logger.debug("Caught exception ", e);
625 throw new NuxeoDocumentException(e);
632 * find wrapped documentModel from the Nuxeo repository
634 * @param ctx service context under which this method is invoked
635 * @param whereClause where NXQL where clause to get the document
636 * @throws DocumentNotFoundException
637 * @throws TransactionException
638 * @throws DocumentException
639 * @return a wrapped documentModel retrieved by the repository query
642 public DocumentWrapper<DocumentModel> findDoc(
643 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
645 throws DocumentNotFoundException, TransactionException, DocumentException {
646 CoreSessionInterface repoSession = null;
647 DocumentWrapper<DocumentModel> wrapDoc = null;
650 repoSession = getRepositorySession(ctx);
651 wrapDoc = findDoc(repoSession, ctx, whereClause);
652 } catch (DocumentNotFoundException dnfe) {
654 } catch (DocumentException de) {
656 } catch (Exception e) {
657 if (repoSession == null) {
658 throw new NuxeoDocumentException("Unable to create a Nuxeo repository session.", e);
660 throw new NuxeoDocumentException("Unexpected Nuxeo exception.", e);
663 if (repoSession != null) {
664 releaseRepositorySession(ctx, repoSession);
668 if (logger.isWarnEnabled() == true) {
669 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
676 * find doc and return CSID from the Nuxeo repository
679 * @param ctx service context under which this method is invoked
680 * @param whereClause where NXQL where clause to get the document
681 * @throws DocumentNotFoundException
682 * @throws TransactionException
683 * @throws DocumentException
684 * @return the CollectionSpace ID (CSID) of the requested document
687 public String findDocCSID(CoreSessionInterface repoSession,
688 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String whereClause)
689 throws DocumentNotFoundException, TransactionException, DocumentException {
691 boolean releaseSession = false;
693 if (repoSession == null) {
694 repoSession = this.getRepositorySession(ctx);
695 releaseSession = true;
697 DocumentWrapper<DocumentModel> wrapDoc = findDoc(repoSession, ctx, whereClause);
698 DocumentModel docModel = wrapDoc.getWrappedObject();
699 csid = NuxeoUtils.getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
700 } catch (DocumentNotFoundException dnfe) {
702 } catch (IllegalArgumentException iae) {
704 } catch (DocumentException de) {
706 } catch (Exception e) {
707 if (logger.isDebugEnabled()) {
708 logger.debug("Caught exception ", e);
710 throw new NuxeoDocumentException(e);
712 if (releaseSession && (repoSession != null)) {
713 this.releaseRepositorySession(ctx, repoSession);
719 public DocumentWrapper<DocumentModelList> findDocs(
720 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
721 CoreSessionInterface repoSession,
722 List<String> docTypes,
724 String orderByClause,
727 boolean useDefaultOrderByClause,
728 boolean computeTotal)
729 throws DocumentNotFoundException, DocumentException {
730 DocumentWrapper<DocumentModelList> wrapDoc = null;
733 if (docTypes == null || docTypes.size() < 1) {
734 throw new DocumentNotFoundException(
735 "The findDocs() method must specify at least one DocumentType.");
737 DocumentModelList docList = null;
738 QueryContext queryContext = new QueryContext(ctx, whereClause, orderByClause);
739 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext, useDefaultOrderByClause);
740 if (logger.isDebugEnabled()) {
741 logger.debug("findDocs() NXQL: " + query);
743 docList = repoSession.query(query, null, pageSize, pageSize * pageNum, computeTotal);
744 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
745 } catch (IllegalArgumentException iae) {
747 } catch (Exception e) {
748 if (logger.isDebugEnabled()) {
749 logger.debug("Caught exception ", e);
751 throw new NuxeoDocumentException(e);
757 protected static String buildInListForDocTypes(List<String> docTypes) {
758 StringBuilder sb = new StringBuilder();
760 boolean first = true;
761 for (String docType : docTypes) {
772 return sb.toString();
775 public DocumentWrapper<DocumentModelList> findDocs(
776 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
777 DocumentHandler handler,
778 CoreSessionInterface repoSession,
779 List<String> docTypes) throws DocumentNotFoundException, DocumentException {
780 DocumentWrapper<DocumentModelList> wrapDoc = null;
782 DocumentFilter filter = handler.getDocumentFilter();
783 String oldOrderBy = filter.getOrderByClause();
784 if (isClauseEmpty(oldOrderBy) == true) {
785 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
787 QueryContext queryContext = new QueryContext(ctx, handler);
790 if (docTypes == null || docTypes.size() < 1) {
791 throw new DocumentNotFoundException(
792 "The findDocs() method must specify at least one DocumentType.");
794 DocumentModelList docList = null;
795 if (handler.isCMISQuery() == true) {
796 String inList = buildInListForDocTypes(docTypes);
797 ctx.getQueryParams().add(IQueryManager.SEARCH_RELATED_MATCH_OBJ_DOCTYPES, inList);
798 if (isSubjectOrObjectQuery(ctx)) {
799 docList = getFilteredCMISForSubjectOrObject(repoSession, ctx, handler, queryContext);
801 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
804 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
805 if (logger.isDebugEnabled()) {
806 logger.debug("findDocs() NXQL: " + query);
808 docList = repoSession.query(query, null, filter.getPageSize(), filter.getOffset(), true);
810 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
811 } catch (IllegalArgumentException iae) {
813 } catch (Exception e) {
814 if (logger.isDebugEnabled()) {
815 logger.debug("Caught exception ", e);
817 throw new NuxeoDocumentException(e);
823 private DocumentModelList getFilteredCMISForSubjectOrObject(CoreSessionInterface repoSession,
824 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, DocumentHandler handler, QueryContext queryContext) throws DocumentNotFoundException, DocumentException {
825 DocumentModelList result = null;
827 if (isSubjectOrObjectQuery(ctx) == true) {
828 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
829 String asEitherCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_EITHER);
831 queryParams.remove(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT);
832 queryParams.remove(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT);
835 // First query for subjectCsid results.
837 queryParams.addFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT, asEitherCsid);
838 DocumentModelList subjectDocList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
839 queryParams.remove(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT);
842 // Next query for objectCsid results.
844 queryParams.addFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT, asEitherCsid);
845 DocumentModelList objectDocList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
846 queryParams.remove(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT);
849 // Finally, combine the two results
851 result = mergeDocumentModelLists(subjectDocList, objectDocList);
857 private DocumentModelList mergeDocumentModelLists(DocumentModelList subjectDocList,
858 DocumentModelList objectDocList) {
859 DocumentModelList result = null;
861 if (subjectDocList == null || subjectDocList.isEmpty()) {
862 return objectDocList;
865 if (objectDocList == null || objectDocList.isEmpty()) {
866 return subjectDocList;
869 result = new DocumentModelListImpl();
871 // Add the subject list
872 Iterator<DocumentModel> iterator = subjectDocList.iterator();
873 while (iterator.hasNext()) {
874 DocumentModel dm = iterator.next();
875 addToResults(result, dm);
878 // Add the object list
879 iterator = objectDocList.iterator();
880 while (iterator.hasNext()) {
881 DocumentModel dm = iterator.next();
882 addToResults(result, dm);
885 // Set the 'totalSize' value for book keeping sake
886 ((DocumentModelListImpl) result).setTotalSize(result.size());
892 // Only add if it is not already in the list
893 private void addToResults(DocumentModelList result, DocumentModel dm) {
894 Iterator<DocumentModel> iterator = result.iterator();
895 boolean found = false;
897 while (iterator.hasNext()) {
898 DocumentModel existingDm = iterator.next();
899 if (existingDm.getId().equals(dm.getId())) {
905 if (found == false) {
910 private boolean isSubjectOrObjectQuery(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
911 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
912 String asEitherCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_EITHER);
913 return asEitherCsid != null && !asEitherCsid.isEmpty();
917 * Find a list of documentModels from the Nuxeo repository
919 * @param docTypes a list of DocType names to match
920 * @param whereClause where the clause to qualify on
921 * @throws DocumentNotFoundException
922 * @throws TransactionException
923 * @throws DocumentException
924 * @return a list of documentModels
927 public DocumentWrapper<DocumentModelList> findDocs(
928 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
929 List<String> docTypes,
933 boolean useDefaultOrderByClause,
934 boolean computeTotal) throws DocumentNotFoundException, TransactionException, DocumentException {
935 CoreSessionInterface repoSession = null;
936 DocumentWrapper<DocumentModelList> wrapDoc = null;
939 repoSession = getRepositorySession(ctx);
940 wrapDoc = findDocs(ctx,
947 useDefaultOrderByClause,
949 } catch (IllegalArgumentException iae) {
951 } catch (Exception e) {
952 if (logger.isDebugEnabled()) {
953 logger.debug("Caught exception ", e);
955 throw new NuxeoDocumentException(e);
957 if (repoSession != null) {
958 releaseRepositorySession(ctx, repoSession);
962 if (logger.isWarnEnabled() == true) {
963 logger.warn("Returned DocumentModelList instance was created with a repository session that is now closed.");
970 * @see org.collectionspace.services.common.storage.StorageClient#get(org.collectionspace.services.common.context.ServiceContext, java.util.List, org.collectionspace.services.common.document.DocumentHandler)
973 public void get(ServiceContext ctx, List<String> csidList, DocumentHandler handler)
974 throws DocumentNotFoundException, TransactionException, DocumentException {
975 if (handler == null) {
976 throw new IllegalArgumentException(
977 "RepositoryJavaClient.getAll: handler is missing");
980 CoreSessionInterface repoSession = null;
982 handler.prepare(Action.GET_ALL);
983 repoSession = getRepositorySession(ctx);
984 DocumentModelList docModelList = new DocumentModelListImpl();
985 //FIXME: Should be using NuxeoUtils.createPathRef for security reasons
986 for (String csid : csidList) {
987 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
988 DocumentModel docModel = repoSession.getDocument(docRef);
989 docModelList.add(docModel);
992 //set reposession to handle the document
993 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
994 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docModelList);
995 handler.handle(Action.GET_ALL, wrapDoc);
996 handler.complete(Action.GET_ALL, wrapDoc);
997 } catch (DocumentException de) {
999 } catch (Exception e) {
1000 if (logger.isDebugEnabled()) {
1001 logger.debug("Caught exception ", e);
1003 throw new NuxeoDocumentException(e);
1005 if (repoSession != null) {
1006 releaseRepositorySession(ctx, repoSession);
1012 * getAll get all documents for an entity entity service from the Nuxeo
1015 * @param ctx service context under which this method is invoked
1016 * @param handler should be used by the caller to provide and transform the
1018 * @throws DocumentNotFoundException
1019 * @throws TransactionException
1020 * @throws DocumentException
1023 public void getAll(ServiceContext ctx, DocumentHandler handler)
1024 throws DocumentNotFoundException, TransactionException, DocumentException {
1025 if (handler == null) {
1026 throw new IllegalArgumentException(
1027 "RepositoryJavaClient.getAll: handler is missing");
1029 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
1030 if (nuxeoWspaceId == null) {
1031 throw new DocumentNotFoundException(
1032 "Unable to find workspace for service "
1033 + ctx.getServiceName()
1034 + " check if the workspace exists in the Nuxeo repository.");
1037 CoreSessionInterface repoSession = null;
1039 handler.prepare(Action.GET_ALL);
1040 repoSession = getRepositorySession(ctx);
1041 DocumentRef wsDocRef = new IdRef(nuxeoWspaceId);
1042 DocumentModelList docList = repoSession.getChildren(wsDocRef);
1043 //set reposession to handle the document
1044 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1045 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
1046 handler.handle(Action.GET_ALL, wrapDoc);
1047 handler.complete(Action.GET_ALL, wrapDoc);
1048 } catch (DocumentException de) {
1050 } catch (Exception e) {
1051 if (logger.isDebugEnabled()) {
1052 logger.debug("Caught exception ", e);
1054 throw new NuxeoDocumentException(e);
1056 if (repoSession != null) {
1057 releaseRepositorySession(ctx, repoSession);
1062 private boolean isClauseEmpty(String theString) {
1063 boolean result = true;
1064 if (theString != null && !theString.isEmpty()) {
1070 public DocumentWrapper<DocumentModel> getDocFromCsid(
1071 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1072 CoreSessionInterface repoSession,
1075 DocumentWrapper<DocumentModel> result = null;
1077 result = new DocumentWrapperImpl<DocumentModel>(NuxeoUtils.getDocFromCsid(ctx, repoSession, csid));
1083 * A method to find a CollectionSpace document (of any type) given just a service context and
1084 * its CSID. A search across *all* service workspaces (within a given tenant context) is performed to find
1087 * This query searches Nuxeo's Hierarchy table where our CSIDs are stored in the "name" column.
1090 public DocumentWrapper<DocumentModel> getDocFromCsid(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1093 DocumentWrapper<DocumentModel> result = null;
1094 CoreSessionInterface repoSession = null;
1096 repoSession = getRepositorySession(ctx);
1097 result = getDocFromCsid(ctx, repoSession, csid);
1099 if (repoSession != null) {
1100 releaseRepositorySession(ctx, repoSession);
1104 if (logger.isWarnEnabled() == true) {
1105 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
1112 * Returns a URI value for a document in the Nuxeo repository
1114 * @param wrappedDoc a wrapped documentModel
1115 * @throws ClientException
1116 * @return a document URI
1119 public String getDocURI(DocumentWrapper<DocumentModel> wrappedDoc) throws ClientException {
1120 DocumentModel docModel = wrappedDoc.getWrappedObject();
1121 String uri = (String) docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
1122 CollectionSpaceClient.COLLECTIONSPACE_CORE_URI);
1127 * See CSPACE-5036 - How to make CMISQL queries from Nuxeo
1129 private IterableQueryResult makeCMISQLQuery(CoreSessionInterface repoSession, String query, QueryContext queryContext) throws DocumentException {
1130 IterableQueryResult result = null;
1131 /** Threshold over which temporary files are not kept in memory. */
1132 final int THRESHOLD = 1024 * 1024;
1135 logger.debug(String.format("Performing a CMIS query on Nuxeo repository named %s",
1136 repoSession.getRepositoryName()));
1138 ThresholdOutputStreamFactory streamFactory = ThresholdOutputStreamFactory.newInstance(
1139 null, THRESHOLD, -1, false);
1140 CallContextImpl callContext = new CallContextImpl(
1141 CallContext.BINDING_LOCAL,
1142 CmisVersion.CMIS_1_1,
1143 repoSession.getRepositoryName(),
1144 null, // ServletContext
1145 null, // HttpServletRequest
1146 null, // HttpServletResponse
1147 new NuxeoCmisServiceFactory(),
1149 callContext.put(CallContext.USERNAME, repoSession.getPrincipal().getName());
1151 NuxeoCmisService cmisService = new NuxeoCmisService(repoSession.getCoreSession());
1152 result = repoSession.queryAndFetch(query, "CMISQL", cmisService);
1153 } catch (ClientException e) {
1154 // TODO Auto-generated catch block
1155 logger.error("Encounter trouble making the following CMIS query: " + query, e);
1156 throw new NuxeoDocumentException(e);
1163 * getFiltered get all documents for an entity service from the Document
1164 * repository, given filter parameters specified by the handler.
1166 * @param ctx service context under which this method is invoked
1167 * @param handler should be used by the caller to provide and transform the
1169 * @throws DocumentNotFoundException if workspace not found
1170 * @throws TransactionException
1171 * @throws DocumentException
1174 public void getFiltered(ServiceContext ctx, DocumentHandler handler)
1175 throws DocumentNotFoundException, TransactionException, DocumentException {
1177 DocumentFilter filter = handler.getDocumentFilter();
1178 String oldOrderBy = filter.getOrderByClause();
1179 if (isClauseEmpty(oldOrderBy) == true) {
1180 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
1182 QueryContext queryContext = new QueryContext(ctx, handler);
1184 CoreSessionInterface repoSession = null;
1186 handler.prepare(Action.GET_ALL);
1187 repoSession = getRepositorySession(ctx); //Keeps a refcount here for the repository session so you need to release this when finished
1189 DocumentModelList docList = null;
1191 if (handler.isJDBCQuery() == true) {
1192 docList = getFilteredJDBC(repoSession, ctx, handler);
1194 } else if (handler.isCMISQuery() == true) { //FIXME: REM - Need to deal with paging info in CMIS query
1195 if (isSubjectOrObjectQuery(ctx)) {
1196 docList = getFilteredCMISForSubjectOrObject(repoSession, ctx, handler, queryContext);
1198 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
1202 String query = NuxeoUtils.buildNXQLQuery(queryContext);
1203 if (logger.isDebugEnabled()) {
1204 logger.debug("Executing NXQL query: " + query.toString());
1206 Profiler profiler = new Profiler(this, 2);
1207 profiler.log("Executing NXQL query: " + query.toString());
1209 // If we have a page size and/or offset, then reflect those values
1210 // when constructing the query, and also pass 'true' to get totalSize
1211 // in the returned DocumentModelList.
1212 if ((queryContext.getDocFilter().getOffset() > 0) || (queryContext.getDocFilter().getPageSize() > 0)) {
1213 docList = repoSession.query(query, null,
1214 queryContext.getDocFilter().getPageSize(), queryContext.getDocFilter().getOffset(), true);
1216 docList = repoSession.query(query);
1221 //set repoSession to handle the document
1222 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1223 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
1224 handler.handle(Action.GET_ALL, wrapDoc);
1225 handler.complete(Action.GET_ALL, wrapDoc);
1226 } catch (DocumentException de) {
1228 } catch (Exception e) {
1229 if (logger.isDebugEnabled()) {
1230 logger.debug("Caught exception ", e); // REM - 1/17/2014: Check for org.nuxeo.ecm.core.api.ClientException and re-attempt
1232 throw new NuxeoDocumentException(e);
1234 if (repoSession != null) {
1235 releaseRepositorySession(ctx, repoSession);
1241 * Perform a database query, via JDBC and SQL, to retrieve matching records
1242 * based on filter criteria.
1244 * Although this method currently has a general-purpose name, it is
1245 * currently dedicated to a specific task: that of improving performance
1246 * for partial term matching queries on authority items / terms, via
1247 * the use of a hand-tuned SQL query, rather than via the generated SQL
1248 * produced by Nuxeo from an NXQL query. (See CSPACE-6361 for a task
1249 * to generalize this method.)
1251 * @param repoSession a repository session.
1252 * @param ctx the service context.
1253 * @param handler a relevant document handler.
1254 * @return a list of document models matching the search criteria.
1257 private DocumentModelList getFilteredJDBC(CoreSessionInterface repoSession, ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1258 DocumentHandler handler) throws Exception {
1259 DocumentModelList result = new DocumentModelListImpl();
1261 // FIXME: Get all of the following values from appropriate external constants.
1263 // At present, the two constants below are duplicated in both RepositoryClientImpl
1264 // and in AuthorityItemDocumentModelHandler.
1265 final String TERM_GROUP_LIST_NAME = "TERM_GROUP_LIST_NAME";
1266 final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
1267 final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
1268 // Get this from a constant in AuthorityResource or equivalent
1269 final String PARENT_WILDCARD = "_ALL_";
1271 // Build two SQL statements, to be executed within a single transaction:
1272 // the first statement to control join order, and the second statement
1273 // representing the actual 'get filtered' query
1275 // Build the join control statement
1277 // Per http://www.postgresql.org/docs/9.2/static/runtime-config-query.html#GUC-JOIN-COLLAPSE-LIMIT
1278 // "Setting [this value] to 1 prevents any reordering of explicit JOINs.
1279 // Thus, the explicit join order specified in the query will be the
1280 // actual order in which the relations are joined."
1281 // See CSPACE-5945 for further discussion of why this setting is needed.
1283 // Adding this statement is commented out here for now. It significantly
1284 // improved query performance for authority item / term queries where
1285 // large numbers of rows were retrieved, but appears to have resulted
1286 // in consistently slower-than-desired query performance where zero or
1287 // very few records were retrieved. See notes on CSPACE-5945. - ADR 2013-04-09
1288 // String joinControlSql = "SET LOCAL join_collapse_limit TO 1;";
1290 // Build the query statement
1292 // Start with the default query
1293 String selectStatement =
1294 "SELECT DISTINCT commonschema.id"
1295 + " FROM " + handler.getServiceContext().getCommonPartLabel() + " commonschema";
1297 String joinClauses =
1299 + " ON misc.id = commonschema.id"
1300 + " INNER JOIN hierarchy hierarchy_termgroup"
1301 + " ON hierarchy_termgroup.parentid = misc.id"
1302 + " INNER JOIN " + handler.getJDBCQueryParams().get(TERM_GROUP_TABLE_NAME_PARAM) + " termgroup"
1303 + " ON termgroup.id = hierarchy_termgroup.id ";
1306 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
1307 // Value for replaceable parameter 1 in the query
1308 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
1309 // If the value of the partial term query parameter is blank ('pt='),
1310 // return all records, subject to restriction by any limit clause
1311 if (Tools.isBlank(partialTerm)) {
1314 // Otherwise, return records that match the supplied partial term
1316 " WHERE (termgroup.termdisplayname ILIKE ?)";
1319 // At present, results are ordered in code, below, rather than in SQL,
1320 // and the orderByClause below is thus intentionally blank.
1322 // To implement the orderByClause below in SQL; e.g. via
1323 // 'ORDER BY termgroup.termdisplayname', the relevant column
1324 // must be returned by the SELECT statement.
1325 String orderByClause = "";
1328 TenantBindingConfigReaderImpl tReader =
1329 ServiceMain.getInstance().getTenantBindingConfigReader();
1330 TenantBindingType tenantBinding = tReader.getTenantBinding(ctx.getTenantId());
1331 String maxListItemsLimit = TenantBindingUtils.getPropertyValue(tenantBinding,
1332 IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES);
1334 " LIMIT " + getMaxItemsLimitOnJdbcQueries(maxListItemsLimit); // implicit int-to-String conversion
1336 // After building the individual parts of the query, set the values
1337 // of replaceable parameters that will be inserted into that query
1338 // and optionally add restrictions
1340 List<String> params = new ArrayList<>();
1342 if (Tools.notBlank(whereClause)) {
1344 // Read tenant bindings configuration to determine whether
1345 // to automatically insert leading, as well as trailing, wildcards
1346 // into the term matching string.
1347 String usesStartingWildcard = TenantBindingUtils.getPropertyValue(tenantBinding,
1348 IQueryManager.TENANT_USES_STARTING_WILDCARD_FOR_PARTIAL_TERM);
1349 // Handle user-provided leading wildcard characters, in the
1350 // configuration where a leading wildcard is not automatically inserted.
1351 // (The user-provided wildcard must be in the first, or "starting"
1352 // character position in the partial term value.)
1353 if (Tools.notBlank(usesStartingWildcard)) {
1354 if (usesStartingWildcard.equalsIgnoreCase(Boolean.FALSE.toString())) {
1355 partialTerm = handleProvidedStartingWildcard(partialTerm);
1356 // Otherwise, in the configuration where a leading wildcard
1357 // is usually automatically inserted, handle the cases where
1358 // a user has entered an anchor character in the first position
1359 // in the starting term value. In those cases, strip that
1360 // anchor character and don't add a leading wildcard
1362 if (partialTerm.startsWith(USER_SUPPLIED_ANCHOR_CHAR)) {
1363 partialTerm = partialTerm.substring(1, partialTerm.length());
1364 // Otherwise, automatically add a leading wildcard
1366 partialTerm = JDBCTools.SQL_WILDCARD + partialTerm;
1370 // Add SQL wildcards in the midst of the partial term match search
1371 // expression, whever user-supplied wildcards appear, except in the
1372 // first or last character positions of the search expression.
1373 partialTerm = subtituteWildcardsInPartialTerm(partialTerm);
1375 // If a designated 'anchor character' is present as the last character
1376 // in the search expression, strip that character and don't add
1377 // a trailing wildcard
1378 int lastCharPos = partialTerm.length() - 1;
1379 if (partialTerm.endsWith(USER_SUPPLIED_ANCHOR_CHAR) && lastCharPos > 0) {
1380 partialTerm = partialTerm.substring(0, lastCharPos);
1382 // Otherwise, automatically add a trailing wildcard
1383 partialTerm = partialTerm + JDBCTools.SQL_WILDCARD;
1385 params.add(partialTerm);
1388 // Optionally add restrictions to the default query, based on variables
1389 // in the current request
1391 // Restrict the query to filter out deleted records, if requested
1392 String includeDeleted = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_DELETED_QP);
1393 if (includeDeleted != null && includeDeleted.equalsIgnoreCase(Boolean.FALSE.toString())) {
1394 whereClause = whereClause
1395 + " AND (misc.lifecyclestate <> '" + WorkflowClient.WORKFLOWSTATE_DELETED + "')"
1396 + " AND (misc.lifecyclestate <> '" + WorkflowClient.WORKFLOWSTATE_LOCKED_DELETED + "')"
1397 + " AND (misc.lifecyclestate <> '" + WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED + "')";
1400 // If a particular authority is specified, restrict the query further
1401 // to return only records within that authority
1402 String inAuthorityValue = (String) handler.getJDBCQueryParams().get(IN_AUTHORITY_PARAM);
1403 if (Tools.notBlank(inAuthorityValue)) {
1404 // Handle the '_ALL_' case for inAuthority
1405 if (inAuthorityValue.equals(PARENT_WILDCARD)) {
1406 // Add nothing to the query here if it should match within all authorities
1408 whereClause = whereClause
1409 + " AND (commonschema.inauthority = ?)";
1410 params.add(inAuthorityValue); // Value for replaceable parameter 2 in the query
1414 // Restrict the query further to return only records pertaining to
1415 // the current tenant, unless:
1416 // * Data for this service, in this tenant, is stored in its own,
1417 // separate repository, rather than being intermingled with other
1418 // tenants' data in the default repository; or
1419 // * Restriction by tenant ID in JDBC queries has been disabled,
1420 // via configuration for this tenant,
1421 if (restrictJDBCQueryByTenantID(tenantBinding, ctx)) {
1422 joinClauses = joinClauses
1423 + " INNER JOIN collectionspace_core core"
1424 + " ON core.id = hierarchy_termgroup.parentid";
1425 whereClause = whereClause
1426 + " AND (core.tenantid = ?)";
1427 params.add(ctx.getTenantId()); // Value for replaceable parameter 3 in the query
1430 // Piece together the SQL query from its parts
1431 String querySql = selectStatement + joinClauses + whereClause + orderByClause + limitClause;
1433 // Note: PostgreSQL 9.2 introduced a change that may improve performance
1434 // of certain queries using JDBC PreparedStatements. See comments on
1435 // CSPACE-5943 for details.
1437 // See a comment above for the reason that the joinControl SQL statement,
1438 // along with its corresponding prepared statement builder, is commented out for now.
1439 // PreparedStatementBuilder joinControlBuilder = new PreparedStatementBuilder(joinControlSql);
1440 PreparedStatementSimpleBuilder queryBuilder = new PreparedStatementSimpleBuilder(querySql, params);
1441 List<PreparedStatementBuilder> builders = new ArrayList<>();
1442 // builders.add(joinControlBuilder);
1443 builders.add(queryBuilder);
1444 String dataSourceName = JDBCTools.NUXEO_DATASOURCE_NAME;
1445 String repositoryName = ctx.getRepositoryName();
1446 final Boolean EXECUTE_WITHIN_TRANSACTION = true;
1447 Set<String> docIds = new HashSet<>();
1449 String cspaceInstanceId = ServiceMain.getInstance().getCspaceInstanceId();
1450 List<CachedRowSet> resultsList = JDBCTools.executePreparedQueries(builders,
1451 dataSourceName, repositoryName, cspaceInstanceId, EXECUTE_WITHIN_TRANSACTION);
1453 // At least one set of results is expected, from the second prepared
1454 // statement to be executed.
1455 // If fewer results are returned, return an empty list of document models
1456 if (resultsList == null || resultsList.size() < 1) {
1457 return result; // return an empty list of document models
1459 // The join control query (if enabled - it is currently commented
1460 // out as per comments above) will not return results, so query results
1461 // will be the first set of results (rowSet) returned in the list
1462 CachedRowSet queryResults = resultsList.get(0);
1464 // If the result from executing the query is null or contains zero rows,
1465 // return an empty list of document models
1466 if (queryResults == null) {
1467 return result; // return an empty list of document models
1469 queryResults.last();
1470 if (queryResults.getRow() == 0) {
1471 return result; // return an empty list of document models
1474 // Otherwise, get the document IDs from the results of the query
1476 queryResults.beforeFirst();
1477 while (queryResults.next()) {
1478 id = queryResults.getString(1);
1479 if (Tools.notBlank(id)) {
1483 } catch (SQLException sqle) {
1484 logger.warn("Could not obtain document IDs via SQL query '" + querySql + "': " + sqle.getMessage());
1485 return result; // return an empty list of document models
1488 // Get a list of document models, using the list of IDs obtained from the query
1490 // FIXME: Check whether we have a 'get document models from list of CSIDs'
1491 // utility method like this, and if not, add this to the appropriate
1493 DocumentModel docModel;
1494 for (String docId : docIds) {
1495 docModel = NuxeoUtils.getDocumentModel(repoSession, docId);
1496 if (docModel == null) {
1497 logger.warn("Could not obtain document model for document with ID " + docId);
1499 result.add(docModel);
1503 // Order the results
1504 final String COMMON_PART_SCHEMA = handler.getServiceContext().getCommonPartLabel();
1505 final String DISPLAY_NAME_XPATH =
1506 "//" + handler.getJDBCQueryParams().get(TERM_GROUP_LIST_NAME) + "/[0]/termDisplayName";
1507 Collections.sort(result, new Comparator<DocumentModel>() {
1509 public int compare(DocumentModel doc1, DocumentModel doc2) {
1510 String termDisplayName1 = null;
1511 String termDisplayName2 = null;
1513 termDisplayName1 = (String) NuxeoUtils.getXPathValue(doc1, COMMON_PART_SCHEMA, DISPLAY_NAME_XPATH);
1514 termDisplayName2 = (String) NuxeoUtils.getXPathValue(doc2, COMMON_PART_SCHEMA, DISPLAY_NAME_XPATH);
1515 } catch (NuxeoDocumentException e) {
1516 throw new RuntimeException(e); // We need to throw a RuntimeException because the compare() method of the Comparator interface does not support throwing an Exception
1518 return termDisplayName1.compareToIgnoreCase(termDisplayName2);
1526 private DocumentModelList getFilteredCMIS(CoreSessionInterface repoSession,
1527 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, DocumentHandler handler, QueryContext queryContext)
1528 throws DocumentNotFoundException, DocumentException {
1530 DocumentModelList result = new DocumentModelListImpl();
1532 String query = handler.getCMISQuery(queryContext);
1534 DocumentFilter docFilter = handler.getDocumentFilter();
1535 int pageSize = docFilter.getPageSize();
1536 int offset = docFilter.getOffset();
1537 if (logger.isDebugEnabled()) {
1538 logger.debug("Executing CMIS query: " + query.toString()
1539 + "with pageSize: " + pageSize + " at offset: " + offset);
1542 // If we have limit and/or offset, then pass true to get totalSize
1543 // in returned DocumentModelList.
1544 Profiler profiler = new Profiler(this, 2);
1545 profiler.log("Executing CMIS query: " + query.toString());
1548 IterableQueryResult queryResult = makeCMISQLQuery(repoSession, query, queryContext);
1550 int totalSize = (int) queryResult.size();
1551 ((DocumentModelListImpl) result).setTotalSize(totalSize);
1552 // Skip the rows before our offset
1554 queryResult.skipTo(offset);
1557 for (Map<String, Serializable> row : queryResult) {
1558 if (logger.isTraceEnabled()) {
1559 logger.trace(" Hierarchy Table ID is:" + row.get(IQueryManager.CMIS_TARGET_NUXEO_ID)
1560 + " nuxeo:pathSegment is: " + row.get(IQueryManager.CMIS_TARGET_NAME));
1562 String nuxeoId = (String) row.get(IQueryManager.CMIS_TARGET_NUXEO_ID);
1563 DocumentModel docModel = NuxeoUtils.getDocumentModel(repoSession, nuxeoId);
1564 result.add(docModel);
1566 if (nRows >= pageSize && pageSize != 0) { // A page size of zero means that they want all of them
1567 logger.debug("Got page full of items - quitting");
1572 queryResult.close();
1577 } catch (Exception e) {
1578 if (logger.isDebugEnabled()) {
1579 logger.debug("Caught exception ", e);
1581 throw new NuxeoDocumentException(e);
1585 // Since we're not supporting paging yet for CMIS queries, we need to perform
1586 // a workaround for the paging information we return in our list of results
1589 if (result != null) {
1590 docFilter.setStartPage(0);
1591 if (totalSize > docFilter.getPageSize()) {
1592 docFilter.setPageSize(totalSize);
1593 ((DocumentModelListImpl)result).setTotalSize(totalSize);
1601 private String logException(Exception e, String msg) {
1602 String result = null;
1604 String exceptionMessage = e.getMessage();
1605 exceptionMessage = exceptionMessage != null ? exceptionMessage : "<No details provided>";
1606 result = msg = msg + ". Caught exception:" + exceptionMessage;
1608 if (logger.isTraceEnabled() == true) {
1609 logger.error(msg, e);
1618 * update given document in the Nuxeo repository
1620 * @param ctx service context under which this method is invoked
1621 * @param csid of the document
1622 * @param handler should be used by the caller to provide and transform the
1624 * @throws BadRequestException
1625 * @throws DocumentNotFoundException
1626 * @throws TransactionException if the transaction times out or otherwise
1627 * cannot be successfully completed
1628 * @throws DocumentException
1631 public void update(ServiceContext ctx, String csid, DocumentHandler handler)
1632 throws BadRequestException, DocumentNotFoundException, TransactionException,
1634 if (handler == null) {
1635 throw new IllegalArgumentException(
1636 "RepositoryJavaClient.update: document handler is missing.");
1639 CoreSessionInterface repoSession = null;
1641 handler.prepare(Action.UPDATE);
1642 repoSession = getRepositorySession(ctx);
1643 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
1644 DocumentModel doc = null;
1646 doc = repoSession.getDocument(docRef);
1647 } catch (org.nuxeo.ecm.core.api.DocumentNotFoundException ce) {
1648 String msg = logException(ce,
1649 String.format("Could not find %s resource/record to update with CSID=%s", ctx.getDocumentType(), csid));
1650 throw new DocumentNotFoundException(msg, ce);
1652 // Check for a versioned document, and check In and Out before we proceed.
1653 if (((DocumentModelHandler) handler).supportsVersioning()) {
1654 /* Once we advance to 5.5 or later, we can add this.
1655 * See also https://jira.nuxeo.com/browse/NXP-8506
1656 if(!doc.isVersionable()) {
1657 throw new NuxeoDocumentException("Configuration for: "
1658 +handler.getServiceContextPath()+" supports versioning, but Nuxeo config does not!");
1661 /* Force a version number - Not working. Apparently we need to configure the uid schema??
1662 if(doc.getProperty("uid","major_version") == null) {
1663 doc.setProperty("uid","major_version",1);
1665 if(doc.getProperty("uid","minor_version") == null) {
1666 doc.setProperty("uid","minor_version",0);
1669 doc.checkIn(VersioningOption.MINOR, null);
1674 // Set reposession to handle the document
1676 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1677 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
1678 handler.handle(Action.UPDATE, wrapDoc);
1679 repoSession.saveDocument(doc);
1681 // Refresh the doc after save, in case a documentModified event handler has modified
1682 // the document post-save. We want those changes to be reflected in the returned document.
1684 handler.complete(Action.UPDATE, wrapDoc);
1685 } catch (BadRequestException bre) {
1686 rollbackTransaction(repoSession);
1688 } catch (DocumentException de) {
1689 rollbackTransaction(repoSession);
1691 } catch (CSWebApplicationException wae) {
1692 rollbackTransaction(repoSession);
1694 } catch (Throwable e) {
1695 rollbackTransaction(repoSession);
1696 throw new NuxeoDocumentException(e);
1698 if (repoSession != null) {
1699 releaseRepositorySession(ctx, repoSession);
1705 * Save a documentModel to the Nuxeo repository.
1707 * @param ctx service context under which this method is invoked
1708 * @param repoSession
1709 * @param docModel the document to save
1710 * @param fSaveSession if TRUE, will call CoreSessionInterface.save() to save
1711 * accumulated changes.
1712 * @throws ClientException
1713 * @throws DocumentException
1716 public void saveDocWithoutHandlerProcessing(
1717 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1718 CoreSessionInterface repoSession,
1719 DocumentModel docModel,
1720 boolean fSaveSession)
1721 throws ClientException, DocumentException {
1724 repoSession.saveDocument(docModel);
1728 } catch (ClientException ce) {
1730 } catch (Exception e) {
1731 if (logger.isDebugEnabled()) {
1732 logger.debug("Caught exception ", e);
1734 throw new NuxeoDocumentException(e);
1739 * Save a list of documentModels to the Nuxeo repository.
1741 * @param ctx service context under which this method is invoked
1742 * @param repoSession a repository session
1743 * @param docModelList a list of document models
1744 * @param fSaveSession if TRUE, will call CoreSessionInterface.save() to save
1745 * accumulated changes.
1746 * @throws ClientException
1747 * @throws DocumentException
1749 public void saveDocListWithoutHandlerProcessing(
1750 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1751 CoreSessionInterface repoSession,
1752 DocumentModelList docList,
1753 boolean fSaveSession)
1754 throws ClientException, DocumentException {
1756 DocumentModel[] docModelArray = new DocumentModel[docList.size()];
1757 repoSession.saveDocuments(docList.toArray(docModelArray));
1761 } catch (ClientException ce) {
1763 } catch (Exception e) {
1764 logger.error("Caught exception ", e);
1765 throw new NuxeoDocumentException(e);
1770 public void deleteWithWhereClause(@SuppressWarnings("rawtypes") ServiceContext ctx, String whereClause,
1771 @SuppressWarnings("rawtypes") DocumentHandler handler) throws
1772 DocumentNotFoundException, DocumentException {
1774 throw new IllegalArgumentException(
1775 "delete(ctx, specifier): ctx is missing");
1777 if (logger.isDebugEnabled()) {
1778 logger.debug("Deleting document with whereClause=" + whereClause);
1781 DocumentWrapper<DocumentModel> foundDocWrapper = this.findDoc(ctx, whereClause);
1782 if (foundDocWrapper != null) {
1783 DocumentModel docModel = foundDocWrapper.getWrappedObject();
1784 String csid = docModel.getName();
1785 this.delete(ctx, csid, handler);
1790 * delete a document from the Nuxeo repository
1792 * @param ctx service context under which this method is invoked
1793 * @param id of the document
1794 * @throws DocumentException
1797 public boolean delete(ServiceContext ctx, List<String> idList, DocumentHandler handler) throws DocumentNotFoundException,
1798 DocumentException, TransactionException {
1799 boolean result = true;
1802 throw new IllegalArgumentException(
1803 "delete(ctx, ix, handler): ctx is missing");
1805 if (handler == null) {
1806 throw new IllegalArgumentException(
1807 "delete(ctx, ix, handler): handler is missing");
1810 CoreSessionInterface repoSession = null;
1812 handler.prepare(Action.DELETE);
1813 repoSession = getRepositorySession(ctx);
1815 for (String id : idList) {
1816 if (logger.isDebugEnabled()) {
1817 logger.debug("Deleting document with CSID=" + id);
1819 DocumentWrapper<DocumentModel> wrapDoc = null;
1821 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
1822 wrapDoc = new DocumentWrapperImpl<DocumentModel>(repoSession.getDocument(docRef));
1823 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1824 if (handler.handle(Action.DELETE, wrapDoc) == true) {
1825 repoSession.removeDocument(docRef);
1826 if (logger.isDebugEnabled()) {
1827 String msg = String.format("DELETE - User '%s' hard-deleted document CSID=%s of type %s.",
1828 ctx.getUserId(), id, ctx.getDocumentType());
1832 String msg = String.format("Could not delete %s resource with csid=%s.",
1833 handler.getServiceContext().getServiceName(), id);
1834 throw new DocumentException(msg);
1836 } catch (org.nuxeo.ecm.core.api.DocumentNotFoundException ce) {
1837 String msg = logException(ce,
1838 String.format("Could not find %s resource/record to delete with CSID=%s", ctx.getDocumentType(), id));
1839 throw new DocumentNotFoundException(msg, ce);
1842 handler.complete(Action.DELETE, wrapDoc);
1844 } catch (DocumentException de) {
1845 rollbackTransaction(repoSession);
1847 } catch (Throwable e) {
1848 rollbackTransaction(repoSession);
1849 throw new NuxeoDocumentException(e);
1851 if (repoSession != null) {
1852 releaseRepositorySession(ctx, repoSession);
1860 * delete a document from the Nuxeo repository
1862 * @param ctx service context under which this method is invoked
1863 * @param id of the document
1864 * @throws DocumentException
1867 public boolean delete(ServiceContext ctx, String id, DocumentHandler handler) throws DocumentNotFoundException,
1868 DocumentException, TransactionException {
1871 List<String> idList = new ArrayList<String>();
1873 result = delete(ctx, idList, handler);
1879 * @see org.collectionspace.services.common.storage.StorageClient#delete(org.collectionspace.services.common.context.ServiceContext, java.lang.String, org.collectionspace.services.common.document.DocumentHandler)
1883 public void delete(@SuppressWarnings("rawtypes") ServiceContext ctx, String id)
1884 throws DocumentNotFoundException, DocumentException {
1885 throw new UnsupportedOperationException();
1886 // Use the other delete instead
1890 public Hashtable<String, String> retrieveWorkspaceIds(RepositoryDomainType repoDomain) throws Exception {
1891 return NuxeoConnectorEmbedded.getInstance().retrieveWorkspaceIds(repoDomain);
1895 public String createDomain(RepositoryDomainType repositoryDomain) throws Exception {
1896 CoreSessionInterface repoSession = null;
1897 String domainId = null;
1900 // Open a connection to the domain's repo/db
1902 String repoName = repositoryDomain.getRepositoryName();
1903 repoSession = getRepositorySession(repoName); // domainName=storageName=repoName=databaseName
1905 // First create the top-level domain directory
1907 String domainName = repositoryDomain.getStorageName();
1908 DocumentRef parentDocRef = new PathRef("/");
1909 DocumentModel parentDoc = repoSession.getDocument(parentDocRef);
1910 DocumentModel domainDoc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1911 domainName, NUXEO_CORE_TYPE_DOMAIN);
1912 domainDoc.setPropertyValue("dc:title", domainName);
1913 domainDoc.setPropertyValue("dc:description", "A CollectionSpace domain "
1915 domainDoc = repoSession.createDocument(domainDoc);
1916 domainId = domainDoc.getId();
1919 // Next, create a "Workspaces" root directory to contain the workspace folders for the individual service documents
1921 DocumentModel workspacesRoot = repoSession.createDocumentModel(domainDoc.getPathAsString(),
1922 NuxeoUtils.Workspaces, NUXEO_CORE_TYPE_WORKSPACEROOT);
1923 workspacesRoot.setPropertyValue("dc:title", NuxeoUtils.Workspaces);
1924 workspacesRoot.setPropertyValue("dc:description", "A CollectionSpace workspaces directory for "
1925 + domainDoc.getPathAsString());
1926 workspacesRoot = repoSession.createDocument(workspacesRoot);
1927 String workspacesRootId = workspacesRoot.getId();
1930 if (logger.isDebugEnabled()) {
1931 logger.debug("Created tenant domain name=" + domainName
1932 + " id=" + domainId + " "
1933 + NuxeoUtils.Workspaces + " id=" + workspacesRootId);
1934 logger.debug("Path to Domain: " + domainDoc.getPathAsString());
1935 logger.debug("Path to Workspaces root: " + workspacesRoot.getPathAsString());
1937 } catch (Throwable e) {
1938 rollbackTransaction(repoSession);
1939 if (logger.isDebugEnabled()) {
1940 logger.debug("Could not create tenant domain name=" + repositoryDomain.getStorageName() + " caught exception ", e);
1944 if (repoSession != null) {
1945 releaseRepositorySession(null, repoSession);
1953 public String getDomainId(RepositoryDomainType repositoryDomain) throws Exception {
1954 String domainId = null;
1955 CoreSessionInterface repoSession = null;
1957 String repoName = repositoryDomain.getRepositoryName();
1958 String domainStorageName = repositoryDomain.getStorageName();
1959 if (domainStorageName != null && !domainStorageName.isEmpty()) {
1961 repoSession = getRepositorySession(repoName);
1962 DocumentRef docRef = new PathRef("/" + domainStorageName);
1963 DocumentModel domain = repoSession.getDocument(docRef);
1964 domainId = domain.getId();
1965 } catch (Exception e) {
1966 if (logger.isTraceEnabled()) {
1967 logger.trace("Caught exception ", e); // The document doesn't exist, this let's us know we need to create it
1970 if (repoSession != null) {
1971 releaseRepositorySession(null, repoSession);
1980 * Returns the workspaces root directory for a given domain.
1982 private DocumentModel getWorkspacesRoot(CoreSessionInterface repoSession,
1983 String domainName) throws Exception {
1984 DocumentModel result = null;
1986 String domainPath = "/" + domainName;
1987 DocumentRef parentDocRef = new PathRef(domainPath);
1988 DocumentModelList domainChildrenList = repoSession.getChildren(
1990 Iterator<DocumentModel> witer = domainChildrenList.iterator();
1991 while (witer.hasNext()) {
1992 DocumentModel childNode = witer.next();
1993 if (NuxeoUtils.Workspaces.equalsIgnoreCase(childNode.getName())) {
1995 logger.trace("Found workspaces directory at: " + result.getPathAsString());
2000 if (result == null) {
2001 throw new ClientException("Could not find workspace root directory in: "
2009 * @see org.collectionspace.services.common.repository.RepositoryClient#createWorkspace(java.lang.String, java.lang.String)
2012 public String createWorkspace(RepositoryDomainType repositoryDomain, String workspaceName) throws Exception {
2013 CoreSessionInterface repoSession = null;
2014 String workspaceId = null;
2016 String repoName = repositoryDomain.getRepositoryName();
2017 repoSession = getRepositorySession(repoName);
2019 String domainStorageName = repositoryDomain.getStorageName();
2020 DocumentModel parentDoc = getWorkspacesRoot(repoSession, domainStorageName);
2021 if (logger.isTraceEnabled()) {
2022 for (String facet : parentDoc.getFacets()) {
2023 logger.trace("Facet: " + facet);
2027 DocumentModel doc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
2028 workspaceName, NuxeoUtils.WORKSPACE_DOCUMENT_TYPE);
2029 doc.setPropertyValue("dc:title", workspaceName);
2030 doc.setPropertyValue("dc:description", "A CollectionSpace workspace for "
2032 doc = repoSession.createDocument(doc);
2033 workspaceId = doc.getId();
2035 if (logger.isDebugEnabled()) {
2036 logger.debug("Created workspace name=" + workspaceName
2037 + " id=" + workspaceId);
2039 } catch (Throwable e) {
2040 rollbackTransaction(repoSession);
2041 if (logger.isDebugEnabled()) {
2042 logger.debug("createWorkspace caught exception ", e);
2046 if (repoSession != null) {
2047 releaseRepositorySession(null, repoSession);
2054 * @see org.collectionspace.services.common.repository.RepositoryClient#getWorkspaceId(java.lang.String, java.lang.String)
2058 public String getWorkspaceId(String tenantDomain, String workspaceName) throws Exception {
2059 String workspaceId = null;
2061 CoreSessionInterface repoSession = null;
2063 repoSession = getRepositorySession((ServiceContext<PoxPayloadIn, PoxPayloadOut>) null);
2064 DocumentRef docRef = new PathRef(
2066 + "/" + NuxeoUtils.Workspaces
2067 + "/" + workspaceName);
2068 DocumentModel workspace = repoSession.getDocument(docRef);
2069 workspaceId = workspace.getId();
2070 } catch (DocumentException de) {
2072 } catch (Exception e) {
2073 if (logger.isDebugEnabled()) {
2074 logger.debug("Caught exception ", e);
2076 throw new NuxeoDocumentException(e);
2078 if (repoSession != null) {
2079 releaseRepositorySession(null, repoSession);
2087 public CoreSessionInterface getRepositorySession(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) throws Exception {
2088 return getRepositorySession(ctx, ctx.getRepositoryName(), ctx.getTimeoutSecs());
2091 public CoreSessionInterface getRepositorySession(String repoName) throws Exception {
2092 return getRepositorySession(null, repoName, ServiceContext.DEFAULT_TX_TIMEOUT);
2096 * Gets the repository session. - Package access only. If the 'ctx' param is
2097 * null then the repo name must be non-mull and vice-versa
2099 * @return the repository session
2100 * @throws Exception the exception
2102 public CoreSessionInterface getRepositorySession(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
2104 int timeoutSeconds) throws Exception {
2105 CoreSessionInterface repoSession = null;
2107 Profiler profiler = new Profiler("getRepositorySession():", 2);
2110 // To get a connection to the Nuxeo repo, we need either a valid ServiceContext instance or a repository name
2113 repoSession = (CoreSessionInterface) ctx.getCurrentRepositorySession(); // First see if the context already has a repo session
2114 if (repoSession == null) {
2115 repoName = ctx.getRepositoryName(); // Notice we are overriding the passed in 'repoName' since we have a valid service context passed in to us
2117 } else if (Tools.isBlank(repoName)) {
2118 String errMsg = String.format("Either a valid session context or repository name are required to get a new connection.");
2119 logger.error(errMsg);
2120 throw new Exception(errMsg);
2123 if (repoSession == null) {
2125 // 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
2126 // just the repository name.
2128 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
2129 repoSession = client.openRepository(repoName, timeoutSeconds);
2131 if (logger.isTraceEnabled() == true) {
2132 logger.trace("Reusing the current context's repository session.");
2136 // Debugging only code
2138 if (logger.isTraceEnabled()) {
2140 if (logger.isTraceEnabled()) {
2141 logger.trace("Testing call to getRepository() repository root: " + repoSession.getRootDocument());
2143 } catch (Throwable e) {
2144 logger.trace("Test call to Nuxeo's getRepository() repository root failed", e);
2151 ctx.setCurrentRepositorySession(repoSession); // For reusing, save the repository session in the current service context. The context will reference count it.
2158 * Release repository session. - Package access only.
2160 * @param repoSession the repo session
2163 public void releaseRepositorySession(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, Object repositorySession) throws TransactionException {
2165 CoreSessionInterface repoSession = (CoreSessionInterface)repositorySession;
2166 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
2169 ctx.clearCurrentRepositorySession(); //clear the current context of the now closed repo session
2170 if (ctx.getCurrentRepositorySession() == null) {
2171 client.releaseRepository(repoSession); //release the repo session if the service context's ref count is zeo.
2174 client.releaseRepository(repoSession); //repo session was acquired without a service context
2176 } catch (TransactionRuntimeException tre) {
2177 String causeMsg = null;
2178 Throwable cause = tre.getCause();
2179 if (cause != null) {
2180 causeMsg = cause.getMessage();
2183 TransactionException te; // a CollectionSpace specific tx exception
2184 if (causeMsg != null) {
2185 te = new TransactionException(causeMsg, tre);
2187 te = new TransactionException(tre);
2190 logger.error(te.getMessage(), tre); // Log the standard transaction exception message, plus an exception-specific stack trace
2192 } catch (Exception e) {
2193 logger.error("Could not close the repository session.", e);
2194 // no need to throw this service specific exception
2199 public void doWorkflowTransition(ServiceContext ctx, String id,
2200 DocumentHandler handler, TransitionDef transitionDef)
2201 throws BadRequestException, DocumentNotFoundException,
2203 // 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
2206 private String handleProvidedStartingWildcard(String partialTerm) {
2207 if (Tools.notBlank(partialTerm)) {
2208 if (partialTerm.substring(0, 1).equals(USER_SUPPLIED_WILDCARD)) {
2209 StringBuffer buffer = new StringBuffer(partialTerm);
2210 buffer.setCharAt(0, JDBCTools.SQL_WILDCARD.charAt(0));
2211 partialTerm = buffer.toString();
2218 * Replaces user-supplied wildcards with SQL wildcards, in a partial term
2219 * matching search expression.
2221 * The scope of this replacement excludes the beginning character
2222 * in that search expression, as that character is treated specially.
2224 * @param partialTerm
2225 * @return the partial term, with any user-supplied wildcards replaced
2228 private String subtituteWildcardsInPartialTerm(String partialTerm) {
2229 if (Tools.isBlank(partialTerm)) {
2232 if (! partialTerm.contains(USER_SUPPLIED_WILDCARD)) {
2235 int len = partialTerm.length();
2236 // Partial term search expressions of 2 or fewer characters
2237 // currently aren't amenable to the use of wildcards
2239 logger.warn("Partial term match search expression of just 1-2 characters in length contains a user-supplied wildcard: " + partialTerm);
2240 logger.warn("Will handle that character as a literal value, rather than as a wildcard ...");
2243 return partialTerm.substring(0, 1) // first char
2244 + partialTerm.substring(1, len).replaceAll(USER_SUPPLIED_WILDCARD_REGEX, JDBCTools.SQL_WILDCARD);
2248 private int getMaxItemsLimitOnJdbcQueries(String maxListItemsLimit) {
2249 final int DEFAULT_ITEMS_LIMIT = 40;
2250 if (maxListItemsLimit == null) {
2251 return DEFAULT_ITEMS_LIMIT;
2255 itemsLimit = Integer.parseInt(maxListItemsLimit);
2256 if (itemsLimit < 1) {
2257 logger.warn("Value of configuration setting "
2258 + IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES
2259 + " must be a positive integer; invalid current value is " + maxListItemsLimit);
2260 logger.warn("Reverting to default value of " + DEFAULT_ITEMS_LIMIT);
2261 itemsLimit = DEFAULT_ITEMS_LIMIT;
2263 } catch (NumberFormatException nfe) {
2264 logger.warn("Value of configuration setting "
2265 + IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES
2266 + " must be a positive integer; invalid current value is " + maxListItemsLimit);
2267 logger.warn("Reverting to default value of " + DEFAULT_ITEMS_LIMIT);
2268 itemsLimit = DEFAULT_ITEMS_LIMIT;
2274 * Identifies whether a restriction on tenant ID - to return only records
2275 * pertaining to the current tenant - is required in a JDBC query.
2277 * @param tenantBinding a tenant binding configuration.
2278 * @param ctx a service context.
2279 * @return true if a restriction on tenant ID is required in the query;
2280 * false if a restriction is not required.
2282 private boolean restrictJDBCQueryByTenantID(TenantBindingType tenantBinding, ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
2283 boolean restrict = true;
2284 // If data for the current service, in the current tenant, is isolated
2285 // within its own separate, per-tenant repository, as contrasted with
2286 // being intermingled with other tenants' data in the default repository,
2287 // no restriction on Tenant ID is required in the query.
2288 String repositoryDomainName = ConfigUtils.getRepositoryName(tenantBinding, ctx.getRepositoryDomainName());
2289 if (!(repositoryDomainName.equals(ConfigUtils.DEFAULT_NUXEO_REPOSITORY_NAME))) {
2292 // If a configuration setting for this tenant identifies that JDBC
2293 // queries should not be restricted by tenant ID (perhaps because
2294 // there is always expected to be only one tenant's data present in
2295 // the system), no restriction on Tenant ID is required in the query.
2296 String queriesRestrictedByTenantId = TenantBindingUtils.getPropertyValue(tenantBinding,
2297 IQueryManager.JDBC_QUERIES_ARE_TENANT_ID_RESTRICTED);
2298 if (Tools.notBlank(queriesRestrictedByTenantId) &&
2299 queriesRestrictedByTenantId.equalsIgnoreCase(Boolean.FALSE.toString())) {
2305 private void rollbackTransaction(CoreSessionInterface repoSession) {
2306 if (repoSession != null) {
2307 repoSession.setTransactionRollbackOnly();
2312 * Should never get called.
2315 public boolean delete(ServiceContext ctx, Object entityFound, DocumentHandler handler)
2316 throws DocumentNotFoundException, DocumentException {
2317 throw new UnsupportedOperationException();