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 if (!Framework.isBooleanPropertyTrue("elasticsearch.enabled")) {
306 logger.info("Request to reindex Elasticsearch failed because Elasticsearch is not enabled.");
310 CoreSessionInterface repoSession = null;
311 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = handler.getServiceContext();
314 ElasticSearchIndexing esi = Framework.getService(ElasticSearchIndexing.class);
315 ElasticSearchAdmin esa = Framework.getService(ElasticSearchAdmin.class);
317 String queryString = handler.getDocumentsToIndexQuery(indexid, csid);
318 esa.initIndexes(true);
320 repoSession = getRepositorySession(ctx);
321 esi.runReindexingWorker(repoSession.getRepositoryName(), queryString);
323 } catch (Throwable e) {
324 rollbackTransaction(repoSession);
325 if (logger.isDebugEnabled()) {
326 logger.debug("Caught exception trying to reindex Nuxeo repository ", e);
328 throw new NuxeoDocumentException(e);
330 if (repoSession != null) {
331 releaseRepositorySession(ctx, repoSession);
339 public boolean synchronize(ServiceContext ctx, Object specifier, DocumentHandler handler)
340 throws DocumentNotFoundException, TransactionException, DocumentException {
341 boolean result = false;
343 if (handler == null) {
344 throw new IllegalArgumentException("RepositoryJavaClient.get: handler is missing");
347 CoreSessionInterface repoSession = null;
349 handler.prepare(Action.SYNC);
350 repoSession = getRepositorySession(ctx);
351 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
352 DocumentWrapper<Object> wrapDoc = new DocumentWrapperImpl<Object>(specifier);
353 result = handler.handle(Action.SYNC, wrapDoc);
354 handler.complete(Action.SYNC, wrapDoc);
355 } catch (IllegalArgumentException iae) {
356 rollbackTransaction(repoSession);
358 } catch (DocumentException de) {
359 rollbackTransaction(repoSession);
361 } catch (Throwable e) {
362 rollbackTransaction(repoSession);
363 if (logger.isDebugEnabled()) {
364 logger.debug("Caught exception ", e);
366 throw new NuxeoDocumentException(e);
368 if (repoSession != null) {
369 releaseRepositorySession(ctx, repoSession);
377 public boolean synchronizeItem(ServiceContext ctx, AuthorityItemSpecifier itemSpecifier, DocumentHandler handler)
378 throws DocumentNotFoundException, TransactionException, DocumentException {
379 boolean result = false;
381 if (handler == null) {
382 throw new IllegalArgumentException(
383 "RepositoryJavaClient.get: handler is missing");
386 CoreSessionInterface repoSession = null;
388 handler.prepare(Action.SYNC);
389 repoSession = getRepositorySession(ctx);
390 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
391 DocumentWrapper<AuthorityItemSpecifier> wrapDoc = new DocumentWrapperImpl<AuthorityItemSpecifier>(itemSpecifier);
392 result = handler.handle(Action.SYNC, wrapDoc);
393 handler.complete(Action.SYNC, wrapDoc);
394 } catch (IllegalArgumentException iae) {
395 rollbackTransaction(repoSession);
397 } catch (DocumentException de) {
398 rollbackTransaction(repoSession);
400 } catch (Throwable e) {
401 rollbackTransaction(repoSession);
402 throw new NuxeoDocumentException(e);
404 if (repoSession != null) {
405 releaseRepositorySession(ctx, repoSession);
413 * get document from the Nuxeo repository
415 * @param ctx service context under which this method is invoked
416 * @param id of the document to retrieve
417 * @param handler should be used by the caller to provide and transform the
419 * @throws DocumentNotFoundException if the document cannot be found in the
421 * @throws TransactionException
422 * @throws DocumentException
425 public void get(ServiceContext ctx, String id, DocumentHandler handler)
426 throws DocumentNotFoundException, TransactionException, DocumentException {
428 if (handler == null) {
429 throw new IllegalArgumentException(
430 "RepositoryJavaClient.get: handler is missing");
433 CoreSessionInterface repoSession = null;
435 handler.prepare(Action.GET);
436 repoSession = getRepositorySession(ctx);
437 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
438 DocumentModel docModel = null;
440 docModel = repoSession.getDocument(docRef);
441 assertWorkflowState(ctx, docModel);
442 } catch (org.nuxeo.ecm.core.api.DocumentNotFoundException ce) {
443 String msg = logException(ce,
444 String.format("Could not find %s resource/record with CSID=%s", ctx.getDocumentType(), id));
445 throw new DocumentNotFoundException(msg, ce);
448 // Set repository session to handle the document
450 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
451 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(docModel);
452 handler.handle(Action.GET, wrapDoc);
453 handler.complete(Action.GET, wrapDoc);
454 } catch (IllegalArgumentException iae) {
456 } catch (DocumentException de) {
457 if (logger.isDebugEnabled()) {
458 logger.debug(de.getMessage(), de);
461 } catch (Throwable e) {
462 if (logger.isDebugEnabled()) {
463 logger.debug("Caught exception ", e);
465 throw new NuxeoDocumentException(e);
467 if (repoSession != null) {
468 releaseRepositorySession(ctx, repoSession);
474 * get a document from the Nuxeo repository, using the docFilter params.
476 * @param ctx service context under which this method is invoked
477 * @param handler should be used by the caller to provide and transform the
478 * document. Handler must have a docFilter set to return a single item.
479 * @throws DocumentNotFoundException if the document cannot be found in the
481 * @throws TransactionException
482 * @throws DocumentException
485 public void get(ServiceContext ctx, DocumentHandler handler)
486 throws DocumentNotFoundException, TransactionException, DocumentException {
487 QueryContext queryContext = new QueryContext(ctx, handler);
488 CoreSessionInterface repoSession = null;
491 handler.prepare(Action.GET);
492 repoSession = getRepositorySession(ctx);
494 DocumentModelList docList = null;
495 // force limit to 1, and ignore totalSize
496 String query = NuxeoUtils.buildNXQLQuery(queryContext);
497 docList = repoSession.query(query, null, 1, 0, false);
498 if (docList.size() != 1) {
499 throw new DocumentNotFoundException("No document found matching filter params: " + query);
501 DocumentModel doc = docList.get(0);
503 if (logger.isDebugEnabled()) {
504 logger.debug("Executed NXQL query: " + query);
507 //set reposession to handle the document
508 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
509 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
510 handler.handle(Action.GET, wrapDoc);
511 handler.complete(Action.GET, wrapDoc);
512 } catch (IllegalArgumentException iae) {
514 } catch (DocumentException de) {
516 } catch (Throwable e) {
517 if (logger.isDebugEnabled()) {
518 logger.debug("Caught exception ", e);
520 throw new NuxeoDocumentException(e);
522 if (repoSession != null) {
523 releaseRepositorySession(ctx, repoSession);
528 public DocumentWrapper<DocumentModel> getDoc(
529 CoreSessionInterface repoSession,
530 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
531 String csid) throws DocumentNotFoundException, DocumentException {
532 DocumentWrapper<DocumentModel> wrapDoc = null;
535 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
536 DocumentModel doc = null;
538 doc = repoSession.getDocument(docRef);
539 } catch (ClientException ce) {
540 String msg = logException(ce, "Could not find document with CSID=" + csid);
541 throw new DocumentNotFoundException(msg, ce);
543 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
544 } catch (IllegalArgumentException iae) {
546 } catch (DocumentException de) {
554 * Get wrapped documentModel from the Nuxeo repository. The search is
555 * restricted to the workspace of the current context.
557 * @param ctx service context under which this method is invoked
558 * @param csid of the document to retrieve
559 * @throws DocumentNotFoundException
560 * @throws TransactionException
561 * @throws DocumentException
562 * @return a wrapped documentModel
565 public DocumentWrapper<DocumentModel> getDoc(
566 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
567 String csid) throws DocumentNotFoundException, TransactionException, DocumentException {
568 CoreSessionInterface repoSession = null;
569 DocumentWrapper<DocumentModel> wrapDoc = null;
572 // Open a new repository session
573 repoSession = getRepositorySession(ctx);
574 wrapDoc = getDoc(repoSession, ctx, csid);
575 } catch (IllegalArgumentException iae) {
577 } catch (DocumentException de) {
579 } catch (Exception e) {
580 if (logger.isDebugEnabled()) {
581 logger.debug("Caught exception ", e);
583 throw new NuxeoDocumentException(e);
585 if (repoSession != null) {
586 releaseRepositorySession(ctx, repoSession);
590 if (logger.isWarnEnabled() == true) {
591 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
596 public DocumentWrapper<DocumentModel> findDoc(
597 CoreSessionInterface repoSession,
598 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
600 throws DocumentNotFoundException, DocumentException {
601 DocumentWrapper<DocumentModel> wrapDoc = null;
604 QueryContext queryContext = new QueryContext(ctx, whereClause);
605 DocumentModelList docList = null;
606 // force limit to 1, and ignore totalSize
607 String query = NuxeoUtils.buildNXQLQuery(queryContext);
608 docList = repoSession.query(query,
613 if (docList.size() != 1) {
614 if (logger.isDebugEnabled()) {
615 logger.debug("findDoc: Query found: " + docList.size() + " items.");
616 logger.debug(" Query: " + query);
618 throw new DocumentNotFoundException("No document found matching filter params: " + query);
620 DocumentModel doc = docList.get(0);
621 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
622 } catch (IllegalArgumentException iae) {
624 } catch (DocumentException de) {
626 } catch (Exception e) {
627 if (logger.isDebugEnabled()) {
628 logger.debug("Caught exception ", e);
630 throw new NuxeoDocumentException(e);
637 * find wrapped documentModel from the Nuxeo repository
639 * @param ctx service context under which this method is invoked
640 * @param whereClause where NXQL where clause to get the document
641 * @throws DocumentNotFoundException
642 * @throws TransactionException
643 * @throws DocumentException
644 * @return a wrapped documentModel retrieved by the repository query
647 public DocumentWrapper<DocumentModel> findDoc(
648 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
650 throws DocumentNotFoundException, TransactionException, DocumentException {
651 CoreSessionInterface repoSession = null;
652 DocumentWrapper<DocumentModel> wrapDoc = null;
655 repoSession = getRepositorySession(ctx);
656 wrapDoc = findDoc(repoSession, ctx, whereClause);
657 } catch (DocumentNotFoundException dnfe) {
659 } catch (DocumentException de) {
661 } catch (Exception e) {
662 if (repoSession == null) {
663 throw new NuxeoDocumentException("Unable to create a Nuxeo repository session.", e);
665 throw new NuxeoDocumentException("Unexpected Nuxeo exception.", e);
668 if (repoSession != null) {
669 releaseRepositorySession(ctx, repoSession);
673 if (logger.isWarnEnabled() == true) {
674 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
681 * find doc and return CSID from the Nuxeo repository
684 * @param ctx service context under which this method is invoked
685 * @param whereClause where NXQL where clause to get the document
686 * @throws DocumentNotFoundException
687 * @throws TransactionException
688 * @throws DocumentException
689 * @return the CollectionSpace ID (CSID) of the requested document
692 public String findDocCSID(CoreSessionInterface repoSession,
693 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String whereClause)
694 throws DocumentNotFoundException, TransactionException, DocumentException {
696 boolean releaseSession = false;
698 if (repoSession == null) {
699 repoSession = this.getRepositorySession(ctx);
700 releaseSession = true;
702 DocumentWrapper<DocumentModel> wrapDoc = findDoc(repoSession, ctx, whereClause);
703 DocumentModel docModel = wrapDoc.getWrappedObject();
704 csid = NuxeoUtils.getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
705 } catch (DocumentNotFoundException dnfe) {
707 } catch (IllegalArgumentException iae) {
709 } catch (DocumentException de) {
711 } catch (Exception e) {
712 if (logger.isDebugEnabled()) {
713 logger.debug("Caught exception ", e);
715 throw new NuxeoDocumentException(e);
717 if (releaseSession && (repoSession != null)) {
718 this.releaseRepositorySession(ctx, repoSession);
724 public DocumentWrapper<DocumentModelList> findDocs(
725 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
726 CoreSessionInterface repoSession,
727 List<String> docTypes,
729 String orderByClause,
732 boolean useDefaultOrderByClause,
733 boolean computeTotal)
734 throws DocumentNotFoundException, DocumentException {
735 DocumentWrapper<DocumentModelList> wrapDoc = null;
738 if (docTypes == null || docTypes.size() < 1) {
739 throw new DocumentNotFoundException(
740 "The findDocs() method must specify at least one DocumentType.");
742 DocumentModelList docList = null;
743 QueryContext queryContext = new QueryContext(ctx, whereClause, orderByClause);
744 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext, useDefaultOrderByClause);
745 if (logger.isDebugEnabled()) {
746 logger.debug("findDocs() NXQL: " + query);
748 docList = repoSession.query(query, null, pageSize, pageSize * pageNum, computeTotal);
749 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
750 } catch (IllegalArgumentException iae) {
752 } catch (Exception e) {
753 if (logger.isDebugEnabled()) {
754 logger.debug("Caught exception ", e);
756 throw new NuxeoDocumentException(e);
762 protected static String buildInListForDocTypes(List<String> docTypes) {
763 StringBuilder sb = new StringBuilder();
765 boolean first = true;
766 for (String docType : docTypes) {
777 return sb.toString();
780 public DocumentWrapper<DocumentModelList> findDocs(
781 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
782 DocumentHandler handler,
783 CoreSessionInterface repoSession,
784 List<String> docTypes) throws DocumentNotFoundException, DocumentException {
785 DocumentWrapper<DocumentModelList> wrapDoc = null;
787 DocumentFilter filter = handler.getDocumentFilter();
788 String oldOrderBy = filter.getOrderByClause();
789 if (isClauseEmpty(oldOrderBy) == true) {
790 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
792 QueryContext queryContext = new QueryContext(ctx, handler);
795 if (docTypes == null || docTypes.size() < 1) {
796 throw new DocumentNotFoundException(
797 "The findDocs() method must specify at least one DocumentType.");
799 DocumentModelList docList = null;
800 if (handler.isCMISQuery() == true) {
801 String inList = buildInListForDocTypes(docTypes);
802 ctx.getQueryParams().add(IQueryManager.SEARCH_RELATED_MATCH_OBJ_DOCTYPES, inList);
803 if (isSubjectOrObjectQuery(ctx)) {
804 docList = getFilteredCMISForSubjectOrObject(repoSession, ctx, handler, queryContext);
806 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
809 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
810 if (logger.isDebugEnabled()) {
811 logger.debug("findDocs() NXQL: " + query);
813 docList = repoSession.query(query, null, filter.getPageSize(), filter.getOffset(), true);
815 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
816 } catch (IllegalArgumentException iae) {
818 } catch (Exception e) {
819 if (logger.isDebugEnabled()) {
820 logger.debug("Caught exception ", e);
822 throw new NuxeoDocumentException(e);
828 private DocumentModelList getFilteredCMISForSubjectOrObject(CoreSessionInterface repoSession,
829 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, DocumentHandler handler, QueryContext queryContext) throws DocumentNotFoundException, DocumentException {
830 DocumentModelList result = null;
832 if (isSubjectOrObjectQuery(ctx) == true) {
833 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
834 String asEitherCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_EITHER);
836 queryParams.remove(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT);
837 queryParams.remove(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT);
840 // First query for subjectCsid results.
842 queryParams.addFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT, asEitherCsid);
843 DocumentModelList subjectDocList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
844 queryParams.remove(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT);
847 // Next query for objectCsid results.
849 queryParams.addFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT, asEitherCsid);
850 DocumentModelList objectDocList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
851 queryParams.remove(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT);
854 // Finally, combine the two results
856 result = mergeDocumentModelLists(subjectDocList, objectDocList);
862 private DocumentModelList mergeDocumentModelLists(DocumentModelList subjectDocList,
863 DocumentModelList objectDocList) {
864 DocumentModelList result = null;
866 if (subjectDocList == null || subjectDocList.isEmpty()) {
867 return objectDocList;
870 if (objectDocList == null || objectDocList.isEmpty()) {
871 return subjectDocList;
874 result = new DocumentModelListImpl();
876 // Add the subject list
877 Iterator<DocumentModel> iterator = subjectDocList.iterator();
878 while (iterator.hasNext()) {
879 DocumentModel dm = iterator.next();
880 addToResults(result, dm);
883 // Add the object list
884 iterator = objectDocList.iterator();
885 while (iterator.hasNext()) {
886 DocumentModel dm = iterator.next();
887 addToResults(result, dm);
890 // Set the 'totalSize' value for book keeping sake
891 ((DocumentModelListImpl) result).setTotalSize(result.size());
897 // Only add if it is not already in the list
898 private void addToResults(DocumentModelList result, DocumentModel dm) {
899 Iterator<DocumentModel> iterator = result.iterator();
900 boolean found = false;
902 while (iterator.hasNext()) {
903 DocumentModel existingDm = iterator.next();
904 if (existingDm.getId().equals(dm.getId())) {
910 if (found == false) {
915 private boolean isSubjectOrObjectQuery(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
916 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
917 String asEitherCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_EITHER);
918 return asEitherCsid != null && !asEitherCsid.isEmpty();
922 * Find a list of documentModels from the Nuxeo repository
924 * @param docTypes a list of DocType names to match
925 * @param whereClause where the clause to qualify on
926 * @throws DocumentNotFoundException
927 * @throws TransactionException
928 * @throws DocumentException
929 * @return a list of documentModels
932 public DocumentWrapper<DocumentModelList> findDocs(
933 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
934 List<String> docTypes,
938 boolean useDefaultOrderByClause,
939 boolean computeTotal) throws DocumentNotFoundException, TransactionException, DocumentException {
940 CoreSessionInterface repoSession = null;
941 DocumentWrapper<DocumentModelList> wrapDoc = null;
944 repoSession = getRepositorySession(ctx);
945 wrapDoc = findDocs(ctx,
952 useDefaultOrderByClause,
954 } catch (IllegalArgumentException iae) {
956 } catch (Exception e) {
957 if (logger.isDebugEnabled()) {
958 logger.debug("Caught exception ", e);
960 throw new NuxeoDocumentException(e);
962 if (repoSession != null) {
963 releaseRepositorySession(ctx, repoSession);
967 if (logger.isWarnEnabled() == true) {
968 logger.warn("Returned DocumentModelList instance was created with a repository session that is now closed.");
975 * @see org.collectionspace.services.common.storage.StorageClient#get(org.collectionspace.services.common.context.ServiceContext, java.util.List, org.collectionspace.services.common.document.DocumentHandler)
978 public void get(ServiceContext ctx, List<String> csidList, DocumentHandler handler)
979 throws DocumentNotFoundException, TransactionException, DocumentException {
980 if (handler == null) {
981 throw new IllegalArgumentException(
982 "RepositoryJavaClient.getAll: handler is missing");
985 CoreSessionInterface repoSession = null;
987 handler.prepare(Action.GET_ALL);
988 repoSession = getRepositorySession(ctx);
989 DocumentModelList docModelList = new DocumentModelListImpl();
990 //FIXME: Should be using NuxeoUtils.createPathRef for security reasons
991 for (String csid : csidList) {
992 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
993 DocumentModel docModel = repoSession.getDocument(docRef);
994 docModelList.add(docModel);
997 //set reposession to handle the document
998 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
999 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docModelList);
1000 handler.handle(Action.GET_ALL, wrapDoc);
1001 handler.complete(Action.GET_ALL, wrapDoc);
1002 } catch (DocumentException de) {
1004 } catch (Exception e) {
1005 if (logger.isDebugEnabled()) {
1006 logger.debug("Caught exception ", e);
1008 throw new NuxeoDocumentException(e);
1010 if (repoSession != null) {
1011 releaseRepositorySession(ctx, repoSession);
1017 * getAll get all documents for an entity entity service from the Nuxeo
1020 * @param ctx service context under which this method is invoked
1021 * @param handler should be used by the caller to provide and transform the
1023 * @throws DocumentNotFoundException
1024 * @throws TransactionException
1025 * @throws DocumentException
1028 public void getAll(ServiceContext ctx, DocumentHandler handler)
1029 throws DocumentNotFoundException, TransactionException, DocumentException {
1030 if (handler == null) {
1031 throw new IllegalArgumentException(
1032 "RepositoryJavaClient.getAll: handler is missing");
1034 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
1035 if (nuxeoWspaceId == null) {
1036 throw new DocumentNotFoundException(
1037 "Unable to find workspace for service "
1038 + ctx.getServiceName()
1039 + " check if the workspace exists in the Nuxeo repository.");
1042 CoreSessionInterface repoSession = null;
1044 handler.prepare(Action.GET_ALL);
1045 repoSession = getRepositorySession(ctx);
1046 DocumentRef wsDocRef = new IdRef(nuxeoWspaceId);
1047 DocumentModelList docList = repoSession.getChildren(wsDocRef);
1048 //set reposession to handle the document
1049 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1050 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
1051 handler.handle(Action.GET_ALL, wrapDoc);
1052 handler.complete(Action.GET_ALL, wrapDoc);
1053 } catch (DocumentException de) {
1055 } catch (Exception e) {
1056 if (logger.isDebugEnabled()) {
1057 logger.debug("Caught exception ", e);
1059 throw new NuxeoDocumentException(e);
1061 if (repoSession != null) {
1062 releaseRepositorySession(ctx, repoSession);
1067 private boolean isClauseEmpty(String theString) {
1068 boolean result = true;
1069 if (theString != null && !theString.isEmpty()) {
1075 public DocumentWrapper<DocumentModel> getDocFromCsid(
1076 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1077 CoreSessionInterface repoSession,
1080 DocumentWrapper<DocumentModel> result = null;
1082 result = new DocumentWrapperImpl<DocumentModel>(NuxeoUtils.getDocFromCsid(ctx, repoSession, csid));
1088 * A method to find a CollectionSpace document (of any type) given just a service context and
1089 * its CSID. A search across *all* service workspaces (within a given tenant context) is performed to find
1092 * This query searches Nuxeo's Hierarchy table where our CSIDs are stored in the "name" column.
1095 public DocumentWrapper<DocumentModel> getDocFromCsid(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1098 DocumentWrapper<DocumentModel> result = null;
1099 CoreSessionInterface repoSession = null;
1101 repoSession = getRepositorySession(ctx);
1102 result = getDocFromCsid(ctx, repoSession, csid);
1104 if (repoSession != null) {
1105 releaseRepositorySession(ctx, repoSession);
1109 if (logger.isWarnEnabled() == true) {
1110 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
1117 * Returns a URI value for a document in the Nuxeo repository
1119 * @param wrappedDoc a wrapped documentModel
1120 * @throws ClientException
1121 * @return a document URI
1124 public String getDocURI(DocumentWrapper<DocumentModel> wrappedDoc) throws ClientException {
1125 DocumentModel docModel = wrappedDoc.getWrappedObject();
1126 String uri = (String) docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
1127 CollectionSpaceClient.COLLECTIONSPACE_CORE_URI);
1132 * See CSPACE-5036 - How to make CMISQL queries from Nuxeo
1134 private IterableQueryResult makeCMISQLQuery(CoreSessionInterface repoSession, String query, QueryContext queryContext) throws DocumentException {
1135 IterableQueryResult result = null;
1136 /** Threshold over which temporary files are not kept in memory. */
1137 final int THRESHOLD = 1024 * 1024;
1140 logger.debug(String.format("Performing a CMIS query on Nuxeo repository named %s",
1141 repoSession.getRepositoryName()));
1143 ThresholdOutputStreamFactory streamFactory = ThresholdOutputStreamFactory.newInstance(
1144 null, THRESHOLD, -1, false);
1145 CallContextImpl callContext = new CallContextImpl(
1146 CallContext.BINDING_LOCAL,
1147 CmisVersion.CMIS_1_1,
1148 repoSession.getRepositoryName(),
1149 null, // ServletContext
1150 null, // HttpServletRequest
1151 null, // HttpServletResponse
1152 new NuxeoCmisServiceFactory(),
1154 callContext.put(CallContext.USERNAME, repoSession.getPrincipal().getName());
1156 NuxeoCmisService cmisService = new NuxeoCmisService(repoSession.getCoreSession());
1157 result = repoSession.queryAndFetch(query, "CMISQL", cmisService);
1158 } catch (ClientException e) {
1159 // TODO Auto-generated catch block
1160 logger.error("Encounter trouble making the following CMIS query: " + query, e);
1161 throw new NuxeoDocumentException(e);
1168 * getFiltered get all documents for an entity service from the Document
1169 * repository, given filter parameters specified by the handler.
1171 * @param ctx service context under which this method is invoked
1172 * @param handler should be used by the caller to provide and transform the
1174 * @throws DocumentNotFoundException if workspace not found
1175 * @throws TransactionException
1176 * @throws DocumentException
1179 public void getFiltered(ServiceContext ctx, DocumentHandler handler)
1180 throws DocumentNotFoundException, TransactionException, DocumentException {
1182 DocumentFilter filter = handler.getDocumentFilter();
1183 String oldOrderBy = filter.getOrderByClause();
1184 if (isClauseEmpty(oldOrderBy) == true) {
1185 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
1187 QueryContext queryContext = new QueryContext(ctx, handler);
1189 CoreSessionInterface repoSession = null;
1191 handler.prepare(Action.GET_ALL);
1192 repoSession = getRepositorySession(ctx); //Keeps a refcount here for the repository session so you need to release this when finished
1194 DocumentModelList docList = null;
1196 if (handler.isJDBCQuery() == true) {
1197 docList = getFilteredJDBC(repoSession, ctx, handler);
1199 } else if (handler.isCMISQuery() == true) { //FIXME: REM - Need to deal with paging info in CMIS query
1200 if (isSubjectOrObjectQuery(ctx)) {
1201 docList = getFilteredCMISForSubjectOrObject(repoSession, ctx, handler, queryContext);
1203 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
1207 String query = NuxeoUtils.buildNXQLQuery(queryContext);
1208 if (logger.isDebugEnabled()) {
1209 logger.debug("Executing NXQL query: " + query.toString());
1211 Profiler profiler = new Profiler(this, 2);
1212 profiler.log("Executing NXQL query: " + query.toString());
1214 // If we have a page size and/or offset, then reflect those values
1215 // when constructing the query, and also pass 'true' to get totalSize
1216 // in the returned DocumentModelList.
1217 if ((queryContext.getDocFilter().getOffset() > 0) || (queryContext.getDocFilter().getPageSize() > 0)) {
1218 docList = repoSession.query(query, null,
1219 queryContext.getDocFilter().getPageSize(), queryContext.getDocFilter().getOffset(), true);
1221 docList = repoSession.query(query);
1226 //set repoSession to handle the document
1227 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1228 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
1229 handler.handle(Action.GET_ALL, wrapDoc);
1230 handler.complete(Action.GET_ALL, wrapDoc);
1231 } catch (DocumentException de) {
1233 } catch (Exception e) {
1234 if (logger.isDebugEnabled()) {
1235 logger.debug("Caught exception ", e); // REM - 1/17/2014: Check for org.nuxeo.ecm.core.api.ClientException and re-attempt
1237 throw new NuxeoDocumentException(e);
1239 if (repoSession != null) {
1240 releaseRepositorySession(ctx, repoSession);
1246 * Perform a database query, via JDBC and SQL, to retrieve matching records
1247 * based on filter criteria.
1249 * Although this method currently has a general-purpose name, it is
1250 * currently dedicated to a specific task: that of improving performance
1251 * for partial term matching queries on authority items / terms, via
1252 * the use of a hand-tuned SQL query, rather than via the generated SQL
1253 * produced by Nuxeo from an NXQL query. (See CSPACE-6361 for a task
1254 * to generalize this method.)
1256 * @param repoSession a repository session.
1257 * @param ctx the service context.
1258 * @param handler a relevant document handler.
1259 * @return a list of document models matching the search criteria.
1262 private DocumentModelList getFilteredJDBC(CoreSessionInterface repoSession, ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1263 DocumentHandler handler) throws Exception {
1264 DocumentModelList result = new DocumentModelListImpl();
1266 // FIXME: Get all of the following values from appropriate external constants.
1268 // At present, the two constants below are duplicated in both RepositoryClientImpl
1269 // and in AuthorityItemDocumentModelHandler.
1270 final String TERM_GROUP_LIST_NAME = "TERM_GROUP_LIST_NAME";
1271 final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
1272 final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
1273 // Get this from a constant in AuthorityResource or equivalent
1274 final String PARENT_WILDCARD = "_ALL_";
1276 // Build two SQL statements, to be executed within a single transaction:
1277 // the first statement to control join order, and the second statement
1278 // representing the actual 'get filtered' query
1280 // Build the join control statement
1282 // Per http://www.postgresql.org/docs/9.2/static/runtime-config-query.html#GUC-JOIN-COLLAPSE-LIMIT
1283 // "Setting [this value] to 1 prevents any reordering of explicit JOINs.
1284 // Thus, the explicit join order specified in the query will be the
1285 // actual order in which the relations are joined."
1286 // See CSPACE-5945 for further discussion of why this setting is needed.
1288 // Adding this statement is commented out here for now. It significantly
1289 // improved query performance for authority item / term queries where
1290 // large numbers of rows were retrieved, but appears to have resulted
1291 // in consistently slower-than-desired query performance where zero or
1292 // very few records were retrieved. See notes on CSPACE-5945. - ADR 2013-04-09
1293 // String joinControlSql = "SET LOCAL join_collapse_limit TO 1;";
1295 // Build the query statement
1297 // Start with the default query
1298 String selectStatement =
1299 "SELECT DISTINCT commonschema.id"
1300 + " FROM " + handler.getServiceContext().getCommonPartLabel() + " commonschema";
1302 String joinClauses =
1304 + " ON misc.id = commonschema.id"
1305 + " INNER JOIN hierarchy hierarchy_termgroup"
1306 + " ON hierarchy_termgroup.parentid = misc.id"
1307 + " INNER JOIN " + handler.getJDBCQueryParams().get(TERM_GROUP_TABLE_NAME_PARAM) + " termgroup"
1308 + " ON termgroup.id = hierarchy_termgroup.id ";
1311 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
1312 // Value for replaceable parameter 1 in the query
1313 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
1314 // If the value of the partial term query parameter is blank ('pt='),
1315 // return all records, subject to restriction by any limit clause
1316 if (Tools.isBlank(partialTerm)) {
1319 // Otherwise, return records that match the supplied partial term
1321 " WHERE (termgroup.termdisplayname ILIKE ?)";
1324 // At present, results are ordered in code, below, rather than in SQL,
1325 // and the orderByClause below is thus intentionally blank.
1327 // To implement the orderByClause below in SQL; e.g. via
1328 // 'ORDER BY termgroup.termdisplayname', the relevant column
1329 // must be returned by the SELECT statement.
1330 String orderByClause = "";
1333 TenantBindingConfigReaderImpl tReader =
1334 ServiceMain.getInstance().getTenantBindingConfigReader();
1335 TenantBindingType tenantBinding = tReader.getTenantBinding(ctx.getTenantId());
1336 String maxListItemsLimit = TenantBindingUtils.getPropertyValue(tenantBinding,
1337 IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES);
1339 " LIMIT " + getMaxItemsLimitOnJdbcQueries(maxListItemsLimit); // implicit int-to-String conversion
1341 // After building the individual parts of the query, set the values
1342 // of replaceable parameters that will be inserted into that query
1343 // and optionally add restrictions
1345 List<String> params = new ArrayList<>();
1347 if (Tools.notBlank(whereClause)) {
1349 // Read tenant bindings configuration to determine whether
1350 // to automatically insert leading, as well as trailing, wildcards
1351 // into the term matching string.
1352 String usesStartingWildcard = TenantBindingUtils.getPropertyValue(tenantBinding,
1353 IQueryManager.TENANT_USES_STARTING_WILDCARD_FOR_PARTIAL_TERM);
1354 // Handle user-provided leading wildcard characters, in the
1355 // configuration where a leading wildcard is not automatically inserted.
1356 // (The user-provided wildcard must be in the first, or "starting"
1357 // character position in the partial term value.)
1358 if (Tools.notBlank(usesStartingWildcard)) {
1359 if (usesStartingWildcard.equalsIgnoreCase(Boolean.FALSE.toString())) {
1360 partialTerm = handleProvidedStartingWildcard(partialTerm);
1361 // Otherwise, in the configuration where a leading wildcard
1362 // is usually automatically inserted, handle the cases where
1363 // a user has entered an anchor character in the first position
1364 // in the starting term value. In those cases, strip that
1365 // anchor character and don't add a leading wildcard
1367 if (partialTerm.startsWith(USER_SUPPLIED_ANCHOR_CHAR)) {
1368 partialTerm = partialTerm.substring(1, partialTerm.length());
1369 // Otherwise, automatically add a leading wildcard
1371 partialTerm = JDBCTools.SQL_WILDCARD + partialTerm;
1375 // Add SQL wildcards in the midst of the partial term match search
1376 // expression, whever user-supplied wildcards appear, except in the
1377 // first or last character positions of the search expression.
1378 partialTerm = subtituteWildcardsInPartialTerm(partialTerm);
1380 // If a designated 'anchor character' is present as the last character
1381 // in the search expression, strip that character and don't add
1382 // a trailing wildcard
1383 int lastCharPos = partialTerm.length() - 1;
1384 if (partialTerm.endsWith(USER_SUPPLIED_ANCHOR_CHAR) && lastCharPos > 0) {
1385 partialTerm = partialTerm.substring(0, lastCharPos);
1387 // Otherwise, automatically add a trailing wildcard
1388 partialTerm = partialTerm + JDBCTools.SQL_WILDCARD;
1390 params.add(partialTerm);
1393 // Optionally add restrictions to the default query, based on variables
1394 // in the current request
1396 // Restrict the query to filter out deleted records, if requested
1397 String includeDeleted = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_DELETED_QP);
1398 if (includeDeleted != null && includeDeleted.equalsIgnoreCase(Boolean.FALSE.toString())) {
1399 whereClause = whereClause
1400 + " AND (misc.lifecyclestate <> '" + WorkflowClient.WORKFLOWSTATE_DELETED + "')"
1401 + " AND (misc.lifecyclestate <> '" + WorkflowClient.WORKFLOWSTATE_LOCKED_DELETED + "')"
1402 + " AND (misc.lifecyclestate <> '" + WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED + "')";
1405 // If a particular authority is specified, restrict the query further
1406 // to return only records within that authority
1407 String inAuthorityValue = (String) handler.getJDBCQueryParams().get(IN_AUTHORITY_PARAM);
1408 if (Tools.notBlank(inAuthorityValue)) {
1409 // Handle the '_ALL_' case for inAuthority
1410 if (inAuthorityValue.equals(PARENT_WILDCARD)) {
1411 // Add nothing to the query here if it should match within all authorities
1413 whereClause = whereClause
1414 + " AND (commonschema.inauthority = ?)";
1415 params.add(inAuthorityValue); // Value for replaceable parameter 2 in the query
1419 // Restrict the query further to return only records pertaining to
1420 // the current tenant, unless:
1421 // * Data for this service, in this tenant, is stored in its own,
1422 // separate repository, rather than being intermingled with other
1423 // tenants' data in the default repository; or
1424 // * Restriction by tenant ID in JDBC queries has been disabled,
1425 // via configuration for this tenant,
1426 if (restrictJDBCQueryByTenantID(tenantBinding, ctx)) {
1427 joinClauses = joinClauses
1428 + " INNER JOIN collectionspace_core core"
1429 + " ON core.id = hierarchy_termgroup.parentid";
1430 whereClause = whereClause
1431 + " AND (core.tenantid = ?)";
1432 params.add(ctx.getTenantId()); // Value for replaceable parameter 3 in the query
1435 // Piece together the SQL query from its parts
1436 String querySql = selectStatement + joinClauses + whereClause + orderByClause + limitClause;
1438 // Note: PostgreSQL 9.2 introduced a change that may improve performance
1439 // of certain queries using JDBC PreparedStatements. See comments on
1440 // CSPACE-5943 for details.
1442 // See a comment above for the reason that the joinControl SQL statement,
1443 // along with its corresponding prepared statement builder, is commented out for now.
1444 // PreparedStatementBuilder joinControlBuilder = new PreparedStatementBuilder(joinControlSql);
1445 PreparedStatementSimpleBuilder queryBuilder = new PreparedStatementSimpleBuilder(querySql, params);
1446 List<PreparedStatementBuilder> builders = new ArrayList<>();
1447 // builders.add(joinControlBuilder);
1448 builders.add(queryBuilder);
1449 String dataSourceName = JDBCTools.NUXEO_DATASOURCE_NAME;
1450 String repositoryName = ctx.getRepositoryName();
1451 final Boolean EXECUTE_WITHIN_TRANSACTION = true;
1452 Set<String> docIds = new HashSet<>();
1454 String cspaceInstanceId = ServiceMain.getInstance().getCspaceInstanceId();
1455 List<CachedRowSet> resultsList = JDBCTools.executePreparedQueries(builders,
1456 dataSourceName, repositoryName, cspaceInstanceId, EXECUTE_WITHIN_TRANSACTION);
1458 // At least one set of results is expected, from the second prepared
1459 // statement to be executed.
1460 // If fewer results are returned, return an empty list of document models
1461 if (resultsList == null || resultsList.size() < 1) {
1462 return result; // return an empty list of document models
1464 // The join control query (if enabled - it is currently commented
1465 // out as per comments above) will not return results, so query results
1466 // will be the first set of results (rowSet) returned in the list
1467 CachedRowSet queryResults = resultsList.get(0);
1469 // If the result from executing the query is null or contains zero rows,
1470 // return an empty list of document models
1471 if (queryResults == null) {
1472 return result; // return an empty list of document models
1474 queryResults.last();
1475 if (queryResults.getRow() == 0) {
1476 return result; // return an empty list of document models
1479 // Otherwise, get the document IDs from the results of the query
1481 queryResults.beforeFirst();
1482 while (queryResults.next()) {
1483 id = queryResults.getString(1);
1484 if (Tools.notBlank(id)) {
1488 } catch (SQLException sqle) {
1489 logger.warn("Could not obtain document IDs via SQL query '" + querySql + "': " + sqle.getMessage());
1490 return result; // return an empty list of document models
1493 // Get a list of document models, using the list of IDs obtained from the query
1495 // FIXME: Check whether we have a 'get document models from list of CSIDs'
1496 // utility method like this, and if not, add this to the appropriate
1498 DocumentModel docModel;
1499 for (String docId : docIds) {
1500 docModel = NuxeoUtils.getDocumentModel(repoSession, docId);
1501 if (docModel == null) {
1502 logger.warn("Could not obtain document model for document with ID " + docId);
1504 result.add(docModel);
1508 // Order the results
1509 final String COMMON_PART_SCHEMA = handler.getServiceContext().getCommonPartLabel();
1510 final String DISPLAY_NAME_XPATH =
1511 "//" + handler.getJDBCQueryParams().get(TERM_GROUP_LIST_NAME) + "/[0]/termDisplayName";
1512 Collections.sort(result, new Comparator<DocumentModel>() {
1514 public int compare(DocumentModel doc1, DocumentModel doc2) {
1515 String termDisplayName1 = null;
1516 String termDisplayName2 = null;
1518 termDisplayName1 = (String) NuxeoUtils.getXPathValue(doc1, COMMON_PART_SCHEMA, DISPLAY_NAME_XPATH);
1519 termDisplayName2 = (String) NuxeoUtils.getXPathValue(doc2, COMMON_PART_SCHEMA, DISPLAY_NAME_XPATH);
1520 } catch (NuxeoDocumentException e) {
1521 throw new RuntimeException(e); // We need to throw a RuntimeException because the compare() method of the Comparator interface does not support throwing an Exception
1523 return termDisplayName1.compareToIgnoreCase(termDisplayName2);
1531 private DocumentModelList getFilteredCMIS(CoreSessionInterface repoSession,
1532 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, DocumentHandler handler, QueryContext queryContext)
1533 throws DocumentNotFoundException, DocumentException {
1535 DocumentModelList result = new DocumentModelListImpl();
1537 String query = handler.getCMISQuery(queryContext);
1539 DocumentFilter docFilter = handler.getDocumentFilter();
1540 int pageSize = docFilter.getPageSize();
1541 int offset = docFilter.getOffset();
1542 if (logger.isDebugEnabled()) {
1543 logger.debug("Executing CMIS query: " + query.toString()
1544 + "with pageSize: " + pageSize + " at offset: " + offset);
1547 // If we have limit and/or offset, then pass true to get totalSize
1548 // in returned DocumentModelList.
1549 Profiler profiler = new Profiler(this, 2);
1550 profiler.log("Executing CMIS query: " + query.toString());
1553 IterableQueryResult queryResult = makeCMISQLQuery(repoSession, query, queryContext);
1555 int totalSize = (int) queryResult.size();
1556 ((DocumentModelListImpl) result).setTotalSize(totalSize);
1557 // Skip the rows before our offset
1559 queryResult.skipTo(offset);
1562 for (Map<String, Serializable> row : queryResult) {
1563 if (logger.isTraceEnabled()) {
1564 logger.trace(" Hierarchy Table ID is:" + row.get(IQueryManager.CMIS_TARGET_NUXEO_ID)
1565 + " nuxeo:pathSegment is: " + row.get(IQueryManager.CMIS_TARGET_NAME));
1567 String nuxeoId = (String) row.get(IQueryManager.CMIS_TARGET_NUXEO_ID);
1568 DocumentModel docModel = NuxeoUtils.getDocumentModel(repoSession, nuxeoId);
1569 result.add(docModel);
1571 if (nRows >= pageSize && pageSize != 0) { // A page size of zero means that they want all of them
1572 logger.debug("Got page full of items - quitting");
1577 queryResult.close();
1582 } catch (Exception e) {
1583 if (logger.isDebugEnabled()) {
1584 logger.debug("Caught exception ", e);
1586 throw new NuxeoDocumentException(e);
1590 // Since we're not supporting paging yet for CMIS queries, we need to perform
1591 // a workaround for the paging information we return in our list of results
1594 if (result != null) {
1595 docFilter.setStartPage(0);
1596 if (totalSize > docFilter.getPageSize()) {
1597 docFilter.setPageSize(totalSize);
1598 ((DocumentModelListImpl)result).setTotalSize(totalSize);
1606 private String logException(Exception e, String msg) {
1607 String result = null;
1609 String exceptionMessage = e.getMessage();
1610 exceptionMessage = exceptionMessage != null ? exceptionMessage : "<No details provided>";
1611 result = msg = msg + ". Caught exception:" + exceptionMessage;
1613 if (logger.isTraceEnabled() == true) {
1614 logger.error(msg, e);
1623 * update given document in the Nuxeo repository
1625 * @param ctx service context under which this method is invoked
1626 * @param csid of the document
1627 * @param handler should be used by the caller to provide and transform the
1629 * @throws BadRequestException
1630 * @throws DocumentNotFoundException
1631 * @throws TransactionException if the transaction times out or otherwise
1632 * cannot be successfully completed
1633 * @throws DocumentException
1636 public void update(ServiceContext ctx, String csid, DocumentHandler handler)
1637 throws BadRequestException, DocumentNotFoundException, TransactionException,
1639 if (handler == null) {
1640 throw new IllegalArgumentException(
1641 "RepositoryJavaClient.update: document handler is missing.");
1644 CoreSessionInterface repoSession = null;
1646 handler.prepare(Action.UPDATE);
1647 repoSession = getRepositorySession(ctx);
1648 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
1649 DocumentModel doc = null;
1651 doc = repoSession.getDocument(docRef);
1652 } catch (org.nuxeo.ecm.core.api.DocumentNotFoundException ce) {
1653 String msg = logException(ce,
1654 String.format("Could not find %s resource/record to update with CSID=%s", ctx.getDocumentType(), csid));
1655 throw new DocumentNotFoundException(msg, ce);
1657 // Check for a versioned document, and check In and Out before we proceed.
1658 if (((DocumentModelHandler) handler).supportsVersioning()) {
1659 /* Once we advance to 5.5 or later, we can add this.
1660 * See also https://jira.nuxeo.com/browse/NXP-8506
1661 if(!doc.isVersionable()) {
1662 throw new NuxeoDocumentException("Configuration for: "
1663 +handler.getServiceContextPath()+" supports versioning, but Nuxeo config does not!");
1666 /* Force a version number - Not working. Apparently we need to configure the uid schema??
1667 if(doc.getProperty("uid","major_version") == null) {
1668 doc.setProperty("uid","major_version",1);
1670 if(doc.getProperty("uid","minor_version") == null) {
1671 doc.setProperty("uid","minor_version",0);
1674 doc.checkIn(VersioningOption.MINOR, null);
1679 // Set reposession to handle the document
1681 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1682 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
1683 handler.handle(Action.UPDATE, wrapDoc);
1684 repoSession.saveDocument(doc);
1686 // Refresh the doc after save, in case a documentModified event handler has modified
1687 // the document post-save. We want those changes to be reflected in the returned document.
1689 handler.complete(Action.UPDATE, wrapDoc);
1690 } catch (BadRequestException bre) {
1691 rollbackTransaction(repoSession);
1693 } catch (DocumentException de) {
1694 rollbackTransaction(repoSession);
1696 } catch (CSWebApplicationException wae) {
1697 rollbackTransaction(repoSession);
1699 } catch (Throwable e) {
1700 rollbackTransaction(repoSession);
1701 throw new NuxeoDocumentException(e);
1703 if (repoSession != null) {
1704 releaseRepositorySession(ctx, repoSession);
1710 * Save a documentModel to the Nuxeo repository.
1712 * @param ctx service context under which this method is invoked
1713 * @param repoSession
1714 * @param docModel the document to save
1715 * @param fSaveSession if TRUE, will call CoreSessionInterface.save() to save
1716 * accumulated changes.
1717 * @throws ClientException
1718 * @throws DocumentException
1721 public void saveDocWithoutHandlerProcessing(
1722 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1723 CoreSessionInterface repoSession,
1724 DocumentModel docModel,
1725 boolean fSaveSession)
1726 throws ClientException, DocumentException {
1729 repoSession.saveDocument(docModel);
1733 } catch (ClientException ce) {
1735 } catch (Exception e) {
1736 if (logger.isDebugEnabled()) {
1737 logger.debug("Caught exception ", e);
1739 throw new NuxeoDocumentException(e);
1744 * Save a list of documentModels to the Nuxeo repository.
1746 * @param ctx service context under which this method is invoked
1747 * @param repoSession a repository session
1748 * @param docModelList a list of document models
1749 * @param fSaveSession if TRUE, will call CoreSessionInterface.save() to save
1750 * accumulated changes.
1751 * @throws ClientException
1752 * @throws DocumentException
1754 public void saveDocListWithoutHandlerProcessing(
1755 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1756 CoreSessionInterface repoSession,
1757 DocumentModelList docList,
1758 boolean fSaveSession)
1759 throws ClientException, DocumentException {
1761 DocumentModel[] docModelArray = new DocumentModel[docList.size()];
1762 repoSession.saveDocuments(docList.toArray(docModelArray));
1766 } catch (ClientException ce) {
1768 } catch (Exception e) {
1769 logger.error("Caught exception ", e);
1770 throw new NuxeoDocumentException(e);
1775 public void deleteWithWhereClause(@SuppressWarnings("rawtypes") ServiceContext ctx, String whereClause,
1776 @SuppressWarnings("rawtypes") DocumentHandler handler) throws
1777 DocumentNotFoundException, DocumentException {
1779 throw new IllegalArgumentException(
1780 "delete(ctx, specifier): ctx is missing");
1782 if (logger.isDebugEnabled()) {
1783 logger.debug("Deleting document with whereClause=" + whereClause);
1786 DocumentWrapper<DocumentModel> foundDocWrapper = this.findDoc(ctx, whereClause);
1787 if (foundDocWrapper != null) {
1788 DocumentModel docModel = foundDocWrapper.getWrappedObject();
1789 String csid = docModel.getName();
1790 this.delete(ctx, csid, handler);
1795 * delete a document from the Nuxeo repository
1797 * @param ctx service context under which this method is invoked
1798 * @param id of the document
1799 * @throws DocumentException
1802 public boolean delete(ServiceContext ctx, List<String> idList, DocumentHandler handler) throws DocumentNotFoundException,
1803 DocumentException, TransactionException {
1804 boolean result = true;
1807 throw new IllegalArgumentException(
1808 "delete(ctx, ix, handler): ctx is missing");
1810 if (handler == null) {
1811 throw new IllegalArgumentException(
1812 "delete(ctx, ix, handler): handler is missing");
1815 CoreSessionInterface repoSession = null;
1817 handler.prepare(Action.DELETE);
1818 repoSession = getRepositorySession(ctx);
1820 for (String id : idList) {
1821 if (logger.isDebugEnabled()) {
1822 logger.debug("Deleting document with CSID=" + id);
1824 DocumentWrapper<DocumentModel> wrapDoc = null;
1826 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
1827 wrapDoc = new DocumentWrapperImpl<DocumentModel>(repoSession.getDocument(docRef));
1828 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1829 if (handler.handle(Action.DELETE, wrapDoc) == true) {
1830 repoSession.removeDocument(docRef);
1831 if (logger.isDebugEnabled()) {
1832 String msg = String.format("DELETE - User '%s' hard-deleted document CSID=%s of type %s.",
1833 ctx.getUserId(), id, ctx.getDocumentType());
1837 String msg = String.format("Could not delete %s resource with csid=%s.",
1838 handler.getServiceContext().getServiceName(), id);
1839 throw new DocumentException(msg);
1841 } catch (org.nuxeo.ecm.core.api.DocumentNotFoundException ce) {
1842 String msg = logException(ce,
1843 String.format("Could not find %s resource/record to delete with CSID=%s", ctx.getDocumentType(), id));
1844 throw new DocumentNotFoundException(msg, ce);
1847 handler.complete(Action.DELETE, wrapDoc);
1849 } catch (DocumentException de) {
1850 rollbackTransaction(repoSession);
1852 } catch (Throwable e) {
1853 rollbackTransaction(repoSession);
1854 throw new NuxeoDocumentException(e);
1856 if (repoSession != null) {
1857 releaseRepositorySession(ctx, repoSession);
1865 * delete a document from the Nuxeo repository
1867 * @param ctx service context under which this method is invoked
1868 * @param id of the document
1869 * @throws DocumentException
1872 public boolean delete(ServiceContext ctx, String id, DocumentHandler handler) throws DocumentNotFoundException,
1873 DocumentException, TransactionException {
1876 List<String> idList = new ArrayList<String>();
1878 result = delete(ctx, idList, handler);
1884 * @see org.collectionspace.services.common.storage.StorageClient#delete(org.collectionspace.services.common.context.ServiceContext, java.lang.String, org.collectionspace.services.common.document.DocumentHandler)
1888 public void delete(@SuppressWarnings("rawtypes") ServiceContext ctx, String id)
1889 throws DocumentNotFoundException, DocumentException {
1890 throw new UnsupportedOperationException();
1891 // Use the other delete instead
1895 public Hashtable<String, String> retrieveWorkspaceIds(RepositoryDomainType repoDomain) throws Exception {
1896 return NuxeoConnectorEmbedded.getInstance().retrieveWorkspaceIds(repoDomain);
1900 public String createDomain(RepositoryDomainType repositoryDomain) throws Exception {
1901 CoreSessionInterface repoSession = null;
1902 String domainId = null;
1905 // Open a connection to the domain's repo/db
1907 String repoName = repositoryDomain.getRepositoryName();
1908 repoSession = getRepositorySession(repoName); // domainName=storageName=repoName=databaseName
1910 // First create the top-level domain directory
1912 String domainName = repositoryDomain.getStorageName();
1913 DocumentRef parentDocRef = new PathRef("/");
1914 DocumentModel parentDoc = repoSession.getDocument(parentDocRef);
1915 DocumentModel domainDoc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1916 domainName, NUXEO_CORE_TYPE_DOMAIN);
1917 domainDoc.setPropertyValue("dc:title", domainName);
1918 domainDoc.setPropertyValue("dc:description", "A CollectionSpace domain "
1920 domainDoc = repoSession.createDocument(domainDoc);
1921 domainId = domainDoc.getId();
1924 // Next, create a "Workspaces" root directory to contain the workspace folders for the individual service documents
1926 DocumentModel workspacesRoot = repoSession.createDocumentModel(domainDoc.getPathAsString(),
1927 NuxeoUtils.Workspaces, NUXEO_CORE_TYPE_WORKSPACEROOT);
1928 workspacesRoot.setPropertyValue("dc:title", NuxeoUtils.Workspaces);
1929 workspacesRoot.setPropertyValue("dc:description", "A CollectionSpace workspaces directory for "
1930 + domainDoc.getPathAsString());
1931 workspacesRoot = repoSession.createDocument(workspacesRoot);
1932 String workspacesRootId = workspacesRoot.getId();
1935 if (logger.isDebugEnabled()) {
1936 logger.debug("Created tenant domain name=" + domainName
1937 + " id=" + domainId + " "
1938 + NuxeoUtils.Workspaces + " id=" + workspacesRootId);
1939 logger.debug("Path to Domain: " + domainDoc.getPathAsString());
1940 logger.debug("Path to Workspaces root: " + workspacesRoot.getPathAsString());
1942 } catch (Throwable e) {
1943 rollbackTransaction(repoSession);
1944 if (logger.isDebugEnabled()) {
1945 logger.debug("Could not create tenant domain name=" + repositoryDomain.getStorageName() + " caught exception ", e);
1949 if (repoSession != null) {
1950 releaseRepositorySession(null, repoSession);
1958 public String getDomainId(RepositoryDomainType repositoryDomain) throws Exception {
1959 String domainId = null;
1960 CoreSessionInterface repoSession = null;
1962 String repoName = repositoryDomain.getRepositoryName();
1963 String domainStorageName = repositoryDomain.getStorageName();
1964 if (domainStorageName != null && !domainStorageName.isEmpty()) {
1966 repoSession = getRepositorySession(repoName);
1967 DocumentRef docRef = new PathRef("/" + domainStorageName);
1968 DocumentModel domain = repoSession.getDocument(docRef);
1969 domainId = domain.getId();
1970 } catch (Exception e) {
1971 if (logger.isTraceEnabled()) {
1972 logger.trace("Caught exception ", e); // The document doesn't exist, this let's us know we need to create it
1975 if (repoSession != null) {
1976 releaseRepositorySession(null, repoSession);
1985 * Returns the workspaces root directory for a given domain.
1987 private DocumentModel getWorkspacesRoot(CoreSessionInterface repoSession,
1988 String domainName) throws Exception {
1989 DocumentModel result = null;
1991 String domainPath = "/" + domainName;
1992 DocumentRef parentDocRef = new PathRef(domainPath);
1993 DocumentModelList domainChildrenList = repoSession.getChildren(
1995 Iterator<DocumentModel> witer = domainChildrenList.iterator();
1996 while (witer.hasNext()) {
1997 DocumentModel childNode = witer.next();
1998 if (NuxeoUtils.Workspaces.equalsIgnoreCase(childNode.getName())) {
2000 logger.trace("Found workspaces directory at: " + result.getPathAsString());
2005 if (result == null) {
2006 throw new ClientException("Could not find workspace root directory in: "
2014 * @see org.collectionspace.services.common.repository.RepositoryClient#createWorkspace(java.lang.String, java.lang.String)
2017 public String createWorkspace(RepositoryDomainType repositoryDomain, String workspaceName) throws Exception {
2018 CoreSessionInterface repoSession = null;
2019 String workspaceId = null;
2021 String repoName = repositoryDomain.getRepositoryName();
2022 repoSession = getRepositorySession(repoName);
2024 String domainStorageName = repositoryDomain.getStorageName();
2025 DocumentModel parentDoc = getWorkspacesRoot(repoSession, domainStorageName);
2026 if (logger.isTraceEnabled()) {
2027 for (String facet : parentDoc.getFacets()) {
2028 logger.trace("Facet: " + facet);
2032 DocumentModel doc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
2033 workspaceName, NuxeoUtils.WORKSPACE_DOCUMENT_TYPE);
2034 doc.setPropertyValue("dc:title", workspaceName);
2035 doc.setPropertyValue("dc:description", "A CollectionSpace workspace for "
2037 doc = repoSession.createDocument(doc);
2038 workspaceId = doc.getId();
2040 if (logger.isDebugEnabled()) {
2041 logger.debug("Created workspace name=" + workspaceName
2042 + " id=" + workspaceId);
2044 } catch (Throwable e) {
2045 rollbackTransaction(repoSession);
2046 if (logger.isDebugEnabled()) {
2047 logger.debug("createWorkspace caught exception ", e);
2051 if (repoSession != null) {
2052 releaseRepositorySession(null, repoSession);
2059 * @see org.collectionspace.services.common.repository.RepositoryClient#getWorkspaceId(java.lang.String, java.lang.String)
2063 public String getWorkspaceId(String tenantDomain, String workspaceName) throws Exception {
2064 String workspaceId = null;
2066 CoreSessionInterface repoSession = null;
2068 repoSession = getRepositorySession((ServiceContext<PoxPayloadIn, PoxPayloadOut>) null);
2069 DocumentRef docRef = new PathRef(
2071 + "/" + NuxeoUtils.Workspaces
2072 + "/" + workspaceName);
2073 DocumentModel workspace = repoSession.getDocument(docRef);
2074 workspaceId = workspace.getId();
2075 } catch (DocumentException de) {
2077 } catch (Exception e) {
2078 if (logger.isDebugEnabled()) {
2079 logger.debug("Caught exception ", e);
2081 throw new NuxeoDocumentException(e);
2083 if (repoSession != null) {
2084 releaseRepositorySession(null, repoSession);
2092 public CoreSessionInterface getRepositorySession(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) throws Exception {
2093 return getRepositorySession(ctx, ctx.getRepositoryName(), ctx.getTimeoutSecs());
2096 public CoreSessionInterface getRepositorySession(String repoName) throws Exception {
2097 return getRepositorySession(null, repoName, ServiceContext.DEFAULT_TX_TIMEOUT);
2101 * Gets the repository session. - Package access only. If the 'ctx' param is
2102 * null then the repo name must be non-mull and vice-versa
2104 * @return the repository session
2105 * @throws Exception the exception
2107 public CoreSessionInterface getRepositorySession(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
2109 int timeoutSeconds) throws Exception {
2110 CoreSessionInterface repoSession = null;
2112 Profiler profiler = new Profiler("getRepositorySession():", 2);
2115 // To get a connection to the Nuxeo repo, we need either a valid ServiceContext instance or a repository name
2118 repoSession = (CoreSessionInterface) ctx.getCurrentRepositorySession(); // First see if the context already has a repo session
2119 if (repoSession == null) {
2120 repoName = ctx.getRepositoryName(); // Notice we are overriding the passed in 'repoName' since we have a valid service context passed in to us
2122 } else if (Tools.isBlank(repoName)) {
2123 String errMsg = String.format("Either a valid session context or repository name are required to get a new connection.");
2124 logger.error(errMsg);
2125 throw new Exception(errMsg);
2128 if (repoSession == null) {
2130 // 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
2131 // just the repository name.
2133 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
2134 repoSession = client.openRepository(repoName, timeoutSeconds);
2136 if (logger.isTraceEnabled() == true) {
2137 logger.trace("Reusing the current context's repository session.");
2141 // Debugging only code
2143 if (logger.isTraceEnabled()) {
2145 if (logger.isTraceEnabled()) {
2146 logger.trace("Testing call to getRepository() repository root: " + repoSession.getRootDocument());
2148 } catch (Throwable e) {
2149 logger.trace("Test call to Nuxeo's getRepository() repository root failed", e);
2156 ctx.setCurrentRepositorySession(repoSession); // For reusing, save the repository session in the current service context. The context will reference count it.
2163 * Release repository session. - Package access only.
2165 * @param repoSession the repo session
2168 public void releaseRepositorySession(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, Object repositorySession) throws TransactionException {
2170 CoreSessionInterface repoSession = (CoreSessionInterface)repositorySession;
2171 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
2174 ctx.clearCurrentRepositorySession(); //clear the current context of the now closed repo session
2175 if (ctx.getCurrentRepositorySession() == null) {
2176 client.releaseRepository(repoSession); //release the repo session if the service context's ref count is zeo.
2179 client.releaseRepository(repoSession); //repo session was acquired without a service context
2181 } catch (TransactionRuntimeException tre) {
2182 String causeMsg = null;
2183 Throwable cause = tre.getCause();
2184 if (cause != null) {
2185 causeMsg = cause.getMessage();
2188 TransactionException te; // a CollectionSpace specific tx exception
2189 if (causeMsg != null) {
2190 te = new TransactionException(causeMsg, tre);
2192 te = new TransactionException(tre);
2195 logger.error(te.getMessage(), tre); // Log the standard transaction exception message, plus an exception-specific stack trace
2197 } catch (Exception e) {
2198 logger.error("Could not close the repository session.", e);
2199 // no need to throw this service specific exception
2204 public void doWorkflowTransition(ServiceContext ctx, String id,
2205 DocumentHandler handler, TransitionDef transitionDef)
2206 throws BadRequestException, DocumentNotFoundException,
2208 // 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
2211 private String handleProvidedStartingWildcard(String partialTerm) {
2212 if (Tools.notBlank(partialTerm)) {
2213 if (partialTerm.substring(0, 1).equals(USER_SUPPLIED_WILDCARD)) {
2214 StringBuffer buffer = new StringBuffer(partialTerm);
2215 buffer.setCharAt(0, JDBCTools.SQL_WILDCARD.charAt(0));
2216 partialTerm = buffer.toString();
2223 * Replaces user-supplied wildcards with SQL wildcards, in a partial term
2224 * matching search expression.
2226 * The scope of this replacement excludes the beginning character
2227 * in that search expression, as that character is treated specially.
2229 * @param partialTerm
2230 * @return the partial term, with any user-supplied wildcards replaced
2233 private String subtituteWildcardsInPartialTerm(String partialTerm) {
2234 if (Tools.isBlank(partialTerm)) {
2237 if (! partialTerm.contains(USER_SUPPLIED_WILDCARD)) {
2240 int len = partialTerm.length();
2241 // Partial term search expressions of 2 or fewer characters
2242 // currently aren't amenable to the use of wildcards
2244 logger.warn("Partial term match search expression of just 1-2 characters in length contains a user-supplied wildcard: " + partialTerm);
2245 logger.warn("Will handle that character as a literal value, rather than as a wildcard ...");
2248 return partialTerm.substring(0, 1) // first char
2249 + partialTerm.substring(1, len).replaceAll(USER_SUPPLIED_WILDCARD_REGEX, JDBCTools.SQL_WILDCARD);
2253 private int getMaxItemsLimitOnJdbcQueries(String maxListItemsLimit) {
2254 final int DEFAULT_ITEMS_LIMIT = 40;
2255 if (maxListItemsLimit == null) {
2256 return DEFAULT_ITEMS_LIMIT;
2260 itemsLimit = Integer.parseInt(maxListItemsLimit);
2261 if (itemsLimit < 1) {
2262 logger.warn("Value of configuration setting "
2263 + IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES
2264 + " must be a positive integer; invalid current value is " + maxListItemsLimit);
2265 logger.warn("Reverting to default value of " + DEFAULT_ITEMS_LIMIT);
2266 itemsLimit = DEFAULT_ITEMS_LIMIT;
2268 } catch (NumberFormatException nfe) {
2269 logger.warn("Value of configuration setting "
2270 + IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES
2271 + " must be a positive integer; invalid current value is " + maxListItemsLimit);
2272 logger.warn("Reverting to default value of " + DEFAULT_ITEMS_LIMIT);
2273 itemsLimit = DEFAULT_ITEMS_LIMIT;
2279 * Identifies whether a restriction on tenant ID - to return only records
2280 * pertaining to the current tenant - is required in a JDBC query.
2282 * @param tenantBinding a tenant binding configuration.
2283 * @param ctx a service context.
2284 * @return true if a restriction on tenant ID is required in the query;
2285 * false if a restriction is not required.
2287 private boolean restrictJDBCQueryByTenantID(TenantBindingType tenantBinding, ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
2288 boolean restrict = true;
2289 // If data for the current service, in the current tenant, is isolated
2290 // within its own separate, per-tenant repository, as contrasted with
2291 // being intermingled with other tenants' data in the default repository,
2292 // no restriction on Tenant ID is required in the query.
2293 String repositoryDomainName = ConfigUtils.getRepositoryName(tenantBinding, ctx.getRepositoryDomainName());
2294 if (!(repositoryDomainName.equals(ConfigUtils.DEFAULT_NUXEO_REPOSITORY_NAME))) {
2297 // If a configuration setting for this tenant identifies that JDBC
2298 // queries should not be restricted by tenant ID (perhaps because
2299 // there is always expected to be only one tenant's data present in
2300 // the system), no restriction on Tenant ID is required in the query.
2301 String queriesRestrictedByTenantId = TenantBindingUtils.getPropertyValue(tenantBinding,
2302 IQueryManager.JDBC_QUERIES_ARE_TENANT_ID_RESTRICTED);
2303 if (Tools.notBlank(queriesRestrictedByTenantId) &&
2304 queriesRestrictedByTenantId.equalsIgnoreCase(Boolean.FALSE.toString())) {
2310 private void rollbackTransaction(CoreSessionInterface repoSession) {
2311 if (repoSession != null) {
2312 repoSession.setTransactionRollbackOnly();
2317 * Should never get called.
2320 public boolean delete(ServiceContext ctx, Object entityFound, DocumentHandler handler)
2321 throws DocumentNotFoundException, DocumentException {
2322 throw new UnsupportedOperationException();