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;
36 // CSPACE-5036 - How to make CMISQL queries from Nuxeo
38 import org.apache.chemistry.opencmis.commons.enums.CmisVersion;
39 import org.apache.chemistry.opencmis.commons.server.CallContext;
40 import org.apache.chemistry.opencmis.server.impl.CallContextImpl;
41 import org.apache.chemistry.opencmis.server.shared.ThresholdOutputStreamFactory;
42 import org.collectionspace.services.client.CollectionSpaceClient;
43 import org.collectionspace.services.client.IQueryManager;
44 import org.collectionspace.services.client.PoxPayloadIn;
45 import org.collectionspace.services.client.PoxPayloadOut;
46 import org.collectionspace.services.client.Profiler;
47 import org.collectionspace.services.client.index.IndexClient;
48 import org.collectionspace.services.client.workflow.WorkflowClient;
49 import org.collectionspace.services.common.CSWebApplicationException;
50 import org.collectionspace.services.common.ServiceMain;
51 import org.collectionspace.services.common.api.Tools;
52 import org.collectionspace.services.common.config.ConfigUtils;
53 import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl;
54 import org.collectionspace.services.common.config.TenantBindingUtils;
55 import org.collectionspace.services.common.context.ServiceContext;
56 import org.collectionspace.services.common.document.BadRequestException;
57 import org.collectionspace.services.common.document.DocumentException;
58 import org.collectionspace.services.common.document.DocumentFilter;
59 import org.collectionspace.services.common.document.DocumentHandler;
60 import org.collectionspace.services.common.document.DocumentHandler.Action;
61 import org.collectionspace.services.common.document.DocumentNotFoundException;
62 import org.collectionspace.services.common.document.DocumentWrapper;
63 import org.collectionspace.services.common.document.DocumentWrapperImpl;
64 import org.collectionspace.services.common.document.TransactionException;
65 import org.collectionspace.services.common.query.QueryContext;
66 import org.collectionspace.services.common.repository.RepositoryClient;
67 import org.collectionspace.services.common.storage.JDBCTools;
68 import org.collectionspace.services.common.storage.PreparedStatementBuilder;
69 import org.collectionspace.services.common.storage.PreparedStatementSimpleBuilder;
70 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.AuthorityItemSpecifier;
71 import org.collectionspace.services.config.service.ServiceBindingType;
72 import org.collectionspace.services.config.tenant.RepositoryDomainType;
73 import org.collectionspace.services.config.tenant.TenantBindingType;
74 import org.collectionspace.services.lifecycle.TransitionDef;
75 import org.collectionspace.services.nuxeo.util.CSReindexFulltextRoot;
76 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
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.DocumentRef;
82 import org.nuxeo.ecm.core.api.IdRef;
83 import org.nuxeo.ecm.core.api.IterableQueryResult;
84 import org.nuxeo.ecm.core.api.PathRef;
85 import org.nuxeo.ecm.core.api.VersioningOption;
86 import org.nuxeo.ecm.core.api.impl.DocumentModelListImpl;
87 import org.nuxeo.ecm.core.opencmis.bindings.NuxeoCmisServiceFactory;
88 import org.nuxeo.ecm.core.opencmis.impl.server.NuxeoCmisService;
89 import org.nuxeo.elasticsearch.ElasticSearchComponent;
90 import org.nuxeo.elasticsearch.api.ElasticSearchService;
91 import org.nuxeo.runtime.api.Framework;
92 import org.nuxeo.runtime.transaction.TransactionRuntimeException;
93 import org.slf4j.Logger;
94 import org.slf4j.LoggerFactory;
97 * RepositoryClientImpl is used to perform CRUD operations on documents in Nuxeo
98 * repository using Remote Java APIs. It uses
100 * @see DocumentHandler as IOHandler with the client.
102 * $LastChangedRevision: $ $LastChangedDate: $
104 public class NuxeoRepositoryClientImpl implements RepositoryClient<PoxPayloadIn, PoxPayloadOut> {
109 private final Logger logger = LoggerFactory.getLogger(NuxeoRepositoryClientImpl.class);
110 // private final Logger profilerLogger = LoggerFactory.getLogger("remperf");
111 // private String foo = Profiler.createLogger();
112 public static final String NUXEO_CORE_TYPE_DOMAIN = "Domain";
113 public static final String NUXEO_CORE_TYPE_WORKSPACEROOT = "WorkspaceRoot";
114 // FIXME: Get this value from an existing constant, if available
115 public static final String BACKSLASH = "\\";
116 public static final String USER_SUPPLIED_WILDCARD = "*";
117 public static final String USER_SUPPLIED_WILDCARD_REGEX = BACKSLASH + USER_SUPPLIED_WILDCARD;
118 public static final String USER_SUPPLIED_ANCHOR_CHAR = "^";
119 public static final String USER_SUPPLIED_ANCHOR_CHAR_REGEX = BACKSLASH + USER_SUPPLIED_ANCHOR_CHAR;
120 public static final String ENDING_ANCHOR_CHAR = "$";
121 public static final String ENDING_ANCHOR_CHAR_REGEX = BACKSLASH + ENDING_ANCHOR_CHAR;
125 * Instantiates a new repository java client impl.
127 public NuxeoRepositoryClientImpl() {
131 public void assertWorkflowState(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, DocumentModel docModel) throws DocumentNotFoundException, ClientException {
132 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
133 if (queryParams != null) {
135 // Look for the workflow "delete" query param and see if we need to assert that the
136 // docModel is in a non-deleted workflow state.
138 String currentState = docModel.getCurrentLifeCycleState();
139 String includeDeletedStr = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_DELETED_QP);
140 boolean includeDeleted = (includeDeletedStr == null) ? true : Boolean.parseBoolean(includeDeletedStr);
141 if (includeDeleted == false) {
143 // We don't wanted soft-deleted objects, so throw an exception if this one is soft-deleted.
145 if (currentState.contains(WorkflowClient.WORKFLOWSTATE_DELETED)) {
146 String msg = "The GET assertion that docModel not be in 'deleted' workflow state failed.";
148 throw new DocumentNotFoundException(msg);
155 * create document in the Nuxeo repository
157 * @param ctx service context under which this method is invoked
158 * @param handler should be used by the caller to provide and transform the
160 * @return id in repository of the newly created document
161 * @throws BadRequestException
162 * @throws TransactionException
163 * @throws DocumentException
166 public String create(ServiceContext ctx,
167 DocumentHandler handler) throws BadRequestException,
168 TransactionException, DocumentException {
170 String docType = NuxeoUtils.getTenantQualifiedDocType(ctx); //ctx.getDocumentType();
171 if (docType == null) {
172 throw new IllegalArgumentException(
173 "RepositoryJavaClient.create: docType is missing");
176 if (handler == null) {
177 throw new IllegalArgumentException(
178 "RepositoryJavaClient.create: handler is missing");
180 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
181 if (nuxeoWspaceId == null) {
182 throw new DocumentNotFoundException(
183 "Unable to find workspace for service " + ctx.getServiceName()
184 + " check if the workspace exists in the Nuxeo repository");
187 CoreSessionInterface repoSession = null;
189 handler.prepare(Action.CREATE);
190 repoSession = getRepositorySession(ctx);
191 DocumentRef nuxeoWspace = new IdRef(nuxeoWspaceId);
192 DocumentModel wspaceDoc = repoSession.getDocument(nuxeoWspace);
193 String wspacePath = wspaceDoc.getPathAsString();
194 //give our own ID so PathRef could be constructed later on
195 String id = IdUtils.generateId(UUID.randomUUID().toString(), "-", true, 24);
196 // create document model
197 DocumentModel doc = repoSession.createDocumentModel(wspacePath, id, docType);
198 /* Check for a versioned document, and check In and Out before we proceed.
199 * This does not work as we do not have the uid schema on our docs.
200 if(((DocumentModelHandler) handler).supportsVersioning()) {
201 doc.setProperty("uid","major_version",1);
202 doc.setProperty("uid","minor_version",0);
205 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
206 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
207 handler.handle(Action.CREATE, wrapDoc);
208 // create document with documentmodel
209 doc = repoSession.createDocument(doc);
211 // TODO for sub-docs need to call into the handler to let it deal with subitems. Pass in the id,
212 // and assume the handler has the state it needs (doc fragments).
213 handler.complete(Action.CREATE, wrapDoc);
215 } catch (BadRequestException bre) {
216 if (ctx.isRollbackOnException()) {
217 rollbackTransaction(repoSession);
220 } catch (Throwable e) {
221 if (ctx.isRollbackOnException()) {
222 rollbackTransaction(repoSession);
224 if (logger.isDebugEnabled()) {
225 logger.debug("Call to low-level Nuxeo document create call failed: ", e);
227 throw new NuxeoDocumentException(e);
229 if (repoSession != null) {
230 releaseRepositorySession(ctx, repoSession);
236 public boolean reindex(DocumentHandler handler, String indexid) throws DocumentNotFoundException, DocumentException
238 return reindex(handler, null, indexid);
242 public boolean reindex(DocumentHandler handler, String csid, String indexid) throws DocumentNotFoundException, DocumentException
244 boolean result = true;
247 case IndexClient.FULLTEXT_ID:
248 result = reindexFulltext(handler, csid, indexid);
250 case IndexClient.ELASTICSEARCH_ID:
251 result = reindexElasticsearch(handler, csid, indexid);
254 throw new NuxeoDocumentException(String.format("Unknown index '%s'. Reindex request failed.",
262 * Reindex Nuxeo's fulltext index.
268 * @throws NuxeoDocumentException
269 * @throws TransactionException
271 private boolean reindexFulltext(DocumentHandler handler, String csid, String indexid) throws NuxeoDocumentException, TransactionException {
272 boolean result = true;
273 CoreSessionInterface repoSession = null;
274 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = handler.getServiceContext();
277 String queryString = handler.getDocumentsToIndexQuery(indexid, csid);
278 repoSession = getRepositorySession(ctx);
279 CSReindexFulltextRoot indexer = new CSReindexFulltextRoot(repoSession);
280 indexer.reindexFulltext(0, 0, queryString);
281 } catch (Throwable e) {
282 if (ctx.isRollbackOnException()) {
283 rollbackTransaction(repoSession);
285 if (logger.isDebugEnabled()) {
286 logger.debug("Caught exception trying to reindex Nuxeo repository ", e);
288 throw new NuxeoDocumentException(e);
290 if (repoSession != null) {
291 releaseRepositorySession(ctx, repoSession);
299 * Reindex Nuxeo's Elasticsearch index.
305 * @throws NuxeoDocumentException
306 * @throws TransactionException
308 private boolean reindexElasticsearch(DocumentHandler handler, String csid, String indexid) throws NuxeoDocumentException, TransactionException {
309 boolean result = false;
311 if (!Framework.isBooleanPropertyTrue("elasticsearch.enabled")) {
312 throw new NuxeoDocumentException("Request to reindex Elasticsearch failed because Elasticsearch is not enabled.");
315 CoreSessionInterface repoSession = null;
316 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = handler.getServiceContext();
319 repoSession = getRepositorySession(ctx);
321 ElasticSearchComponent es = (ElasticSearchComponent) Framework.getService(ElasticSearchService.class);
322 String repositoryName = repoSession.getRepositoryName();
324 logger.info(String.format("Rebuilding Elasticsearch index for repository %s", repositoryName));
326 es.dropAndInitRepositoryIndex(repositoryName);
328 TenantBindingConfigReaderImpl tReader = ServiceMain.getInstance().getTenantBindingConfigReader();
329 TenantBindingType tenantBinding = tReader.getTenantBinding(ctx.getTenantId());
331 for (ServiceBindingType serviceBinding : tenantBinding.getServiceBindings()) {
332 Boolean isElasticsearchIndexed = serviceBinding.isElasticsearchIndexed();
333 String servicesRepoDomainName = serviceBinding.getRepositoryDomain();
335 if (isElasticsearchIndexed && servicesRepoDomainName != null && servicesRepoDomainName.trim().isEmpty() == false) {
336 String docType = NuxeoUtils.getTenantQualifiedDocType(tenantBinding.getId(), serviceBinding.getObject().getName());
337 String queryString = handler.getDocumentsToIndexQuery(indexid, docType, csid);
339 logger.info(String.format("Starting Elasticsearch reindexing for docType %s in repository %s", docType, repositoryName));
340 logger.debug(queryString);
342 es.runReindexingWorker(repositoryName, queryString);
347 } catch (Throwable e) {
348 if (ctx.isRollbackOnException()) {
349 rollbackTransaction(repoSession);
351 if (logger.isDebugEnabled()) {
352 logger.debug("Caught exception trying to reindex Nuxeo repository ", e);
354 throw new NuxeoDocumentException(e);
356 if (repoSession != null) {
357 releaseRepositorySession(ctx, repoSession);
365 public boolean synchronize(ServiceContext ctx, Object specifier, DocumentHandler handler)
366 throws DocumentNotFoundException, TransactionException, DocumentException {
367 boolean result = false;
369 if (handler == null) {
370 throw new IllegalArgumentException("RepositoryJavaClient.get: handler is missing");
373 CoreSessionInterface repoSession = null;
375 handler.prepare(Action.SYNC);
376 repoSession = getRepositorySession(ctx);
377 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
378 DocumentWrapper<Object> wrapDoc = new DocumentWrapperImpl<Object>(specifier);
379 result = handler.handle(Action.SYNC, wrapDoc);
380 handler.complete(Action.SYNC, wrapDoc);
381 } catch (IllegalArgumentException iae) {
382 if (ctx.isRollbackOnException()) {
383 rollbackTransaction(repoSession);
386 } catch (DocumentException de) {
387 if (ctx.isRollbackOnException()) {
388 rollbackTransaction(repoSession);
391 } catch (Throwable e) {
392 if (ctx.isRollbackOnException()) {
393 rollbackTransaction(repoSession);
395 if (logger.isDebugEnabled()) {
396 logger.debug("Caught exception ", e);
398 throw new NuxeoDocumentException(e);
400 if (repoSession != null) {
401 releaseRepositorySession(ctx, repoSession);
409 public boolean synchronizeItem(ServiceContext ctx, AuthorityItemSpecifier itemSpecifier, DocumentHandler handler)
410 throws DocumentNotFoundException, TransactionException, DocumentException {
411 boolean result = false;
413 if (handler == null) {
414 throw new IllegalArgumentException(
415 "RepositoryJavaClient.get: handler is missing");
418 CoreSessionInterface repoSession = null;
420 handler.prepare(Action.SYNC);
421 repoSession = getRepositorySession(ctx);
422 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
423 DocumentWrapper<AuthorityItemSpecifier> wrapDoc = new DocumentWrapperImpl<AuthorityItemSpecifier>(itemSpecifier);
424 result = handler.handle(Action.SYNC, wrapDoc);
425 handler.complete(Action.SYNC, wrapDoc);
426 } catch (IllegalArgumentException iae) {
427 if (ctx.isRollbackOnException()) {
428 rollbackTransaction(repoSession);
431 } catch (DocumentException de) {
432 if (ctx.isRollbackOnException()) {
433 rollbackTransaction(repoSession);
436 } catch (Throwable e) {
437 if (ctx.isRollbackOnException()) {
438 rollbackTransaction(repoSession);
440 throw new NuxeoDocumentException(e);
442 if (repoSession != null) {
443 releaseRepositorySession(ctx, repoSession);
451 * get document from the Nuxeo repository
453 * @param ctx service context under which this method is invoked
454 * @param id of the document to retrieve
455 * @param handler should be used by the caller to provide and transform the
457 * @throws DocumentNotFoundException if the document cannot be found in the
459 * @throws TransactionException
460 * @throws DocumentException
463 public void get(ServiceContext ctx, String id, DocumentHandler handler)
464 throws DocumentNotFoundException, TransactionException, DocumentException {
466 if (handler == null) {
467 throw new IllegalArgumentException(
468 "RepositoryJavaClient.get: handler is missing");
471 CoreSessionInterface repoSession = null;
473 handler.prepare(Action.GET);
474 repoSession = getRepositorySession(ctx);
475 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
476 DocumentModel docModel = null;
478 docModel = repoSession.getDocument(docRef);
479 assertWorkflowState(ctx, docModel);
480 } catch (org.nuxeo.ecm.core.api.DocumentNotFoundException ce) {
481 String msg = logException(ce,
482 String.format("Could not find %s resource/record with CSID=%s", ctx.getDocumentType(), id));
483 throw new DocumentNotFoundException(msg, ce);
486 // Set repository session to handle the document
488 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
489 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(docModel);
490 handler.handle(Action.GET, wrapDoc);
491 handler.complete(Action.GET, wrapDoc);
492 } catch (IllegalArgumentException iae) {
494 } catch (DocumentException de) {
495 if (logger.isDebugEnabled()) {
496 logger.debug(de.getMessage(), de);
499 } catch (Throwable e) {
500 if (logger.isDebugEnabled()) {
501 logger.debug("Caught exception ", e);
503 throw new NuxeoDocumentException(e);
505 if (repoSession != null) {
506 releaseRepositorySession(ctx, repoSession);
512 * get a document from the Nuxeo repository, using the docFilter params.
514 * @param ctx service context under which this method is invoked
515 * @param handler should be used by the caller to provide and transform the
516 * document. Handler must have a docFilter set to return a single item.
517 * @throws DocumentNotFoundException if the document cannot be found in the
519 * @throws TransactionException
520 * @throws DocumentException
523 public void get(ServiceContext ctx, DocumentHandler handler)
524 throws DocumentNotFoundException, TransactionException, DocumentException {
525 QueryContext queryContext = new QueryContext(ctx, handler);
526 CoreSessionInterface repoSession = null;
529 handler.prepare(Action.GET);
530 repoSession = getRepositorySession(ctx);
532 DocumentModelList docList = null;
533 // force limit to 1, and ignore totalSize
534 String query = NuxeoUtils.buildNXQLQuery(queryContext);
535 docList = repoSession.query(query, null, 1, 0, false);
536 if (docList.size() != 1) {
537 throw new DocumentNotFoundException("No document found matching filter params: " + query);
539 DocumentModel doc = docList.get(0);
541 if (logger.isDebugEnabled()) {
542 logger.debug("Executed NXQL query: " + query);
545 //set reposession to handle the document
546 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
547 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
548 handler.handle(Action.GET, wrapDoc);
549 handler.complete(Action.GET, wrapDoc);
550 } catch (IllegalArgumentException iae) {
552 } catch (DocumentException de) {
554 } catch (Throwable e) {
555 if (logger.isDebugEnabled()) {
556 logger.debug("Caught exception ", e);
558 throw new NuxeoDocumentException(e);
560 if (repoSession != null) {
561 releaseRepositorySession(ctx, repoSession);
566 public DocumentWrapper<DocumentModel> getDoc(
567 CoreSessionInterface repoSession,
568 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
569 String csid) throws DocumentNotFoundException, DocumentException {
570 DocumentWrapper<DocumentModel> wrapDoc = null;
573 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
574 DocumentModel doc = null;
576 doc = repoSession.getDocument(docRef);
577 } catch (ClientException ce) {
578 String msg = logException(ce, "Could not find document with CSID=" + csid);
579 throw new DocumentNotFoundException(msg, ce);
581 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
582 } catch (IllegalArgumentException iae) {
584 } catch (DocumentException de) {
592 * Get wrapped documentModel from the Nuxeo repository. The search is
593 * restricted to the workspace of the current context.
595 * @param ctx service context under which this method is invoked
596 * @param csid of the document to retrieve
597 * @throws DocumentNotFoundException
598 * @throws TransactionException
599 * @throws DocumentException
600 * @return a wrapped documentModel
603 public DocumentWrapper<DocumentModel> getDoc(
604 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
605 String csid) throws DocumentNotFoundException, TransactionException, DocumentException {
606 CoreSessionInterface repoSession = null;
607 DocumentWrapper<DocumentModel> wrapDoc = null;
610 // Open a new repository session
611 repoSession = getRepositorySession(ctx);
612 wrapDoc = getDoc(repoSession, ctx, csid);
613 } catch (IllegalArgumentException iae) {
615 } catch (DocumentException de) {
617 } catch (Exception e) {
618 if (logger.isDebugEnabled()) {
619 logger.debug("Caught exception ", e);
621 throw new NuxeoDocumentException(e);
623 if (repoSession != null) {
624 releaseRepositorySession(ctx, repoSession);
628 if (logger.isWarnEnabled() == true) {
629 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
634 public DocumentWrapper<DocumentModel> findDoc(
635 CoreSessionInterface repoSession,
636 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
638 throws DocumentNotFoundException, DocumentException {
639 DocumentWrapper<DocumentModel> wrapDoc = null;
642 QueryContext queryContext = new QueryContext(ctx, whereClause);
643 DocumentModelList docList = null;
644 // force limit to 1, and ignore totalSize
645 String query = NuxeoUtils.buildNXQLQuery(queryContext);
646 docList = repoSession.query(query,
651 if (docList.size() != 1) {
652 if (logger.isDebugEnabled()) {
653 logger.debug("findDoc: Query found: " + docList.size() + " items.");
654 logger.debug(" Query: " + query);
656 throw new DocumentNotFoundException("No document found matching filter params: " + query);
658 DocumentModel doc = docList.get(0);
659 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
660 } catch (IllegalArgumentException iae) {
662 } catch (DocumentException de) {
664 } catch (Exception e) {
665 if (logger.isDebugEnabled()) {
666 logger.debug("Caught exception ", e);
668 throw new NuxeoDocumentException(e);
675 * find wrapped documentModel from the Nuxeo repository
677 * @param ctx service context under which this method is invoked
678 * @param whereClause where NXQL where clause to get the document
679 * @throws DocumentNotFoundException
680 * @throws TransactionException
681 * @throws DocumentException
682 * @return a wrapped documentModel retrieved by the repository query
685 public DocumentWrapper<DocumentModel> findDoc(
686 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
688 throws DocumentNotFoundException, TransactionException, DocumentException {
689 CoreSessionInterface repoSession = null;
690 DocumentWrapper<DocumentModel> wrapDoc = null;
693 repoSession = getRepositorySession(ctx);
694 wrapDoc = findDoc(repoSession, ctx, whereClause);
695 } catch (DocumentNotFoundException dnfe) {
697 } catch (DocumentException de) {
699 } catch (Exception e) {
700 if (repoSession == null) {
701 throw new NuxeoDocumentException("Unable to create a Nuxeo repository session.", e);
703 throw new NuxeoDocumentException("Unexpected Nuxeo exception.", e);
706 if (repoSession != null) {
707 releaseRepositorySession(ctx, repoSession);
711 if (logger.isWarnEnabled() == true) {
712 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
719 * find doc and return CSID from the Nuxeo repository
722 * @param ctx service context under which this method is invoked
723 * @param whereClause where NXQL where clause to get the document
724 * @throws DocumentNotFoundException
725 * @throws TransactionException
726 * @throws DocumentException
727 * @return the CollectionSpace ID (CSID) of the requested document
730 public String findDocCSID(CoreSessionInterface repoSession,
731 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String whereClause)
732 throws DocumentNotFoundException, TransactionException, DocumentException {
734 boolean releaseSession = false;
736 if (repoSession == null) {
737 repoSession = this.getRepositorySession(ctx);
738 releaseSession = true;
740 DocumentWrapper<DocumentModel> wrapDoc = findDoc(repoSession, ctx, whereClause);
741 DocumentModel docModel = wrapDoc.getWrappedObject();
742 csid = NuxeoUtils.getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
743 } catch (DocumentNotFoundException dnfe) {
745 } catch (IllegalArgumentException iae) {
747 } catch (DocumentException de) {
749 } catch (Exception e) {
750 if (logger.isDebugEnabled()) {
751 logger.debug("Caught exception ", e);
753 throw new NuxeoDocumentException(e);
755 if (releaseSession && (repoSession != null)) {
756 this.releaseRepositorySession(ctx, repoSession);
762 public DocumentWrapper<DocumentModelList> findDocs(
763 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
764 CoreSessionInterface repoSession,
765 List<String> docTypes,
767 String orderByClause,
770 boolean useDefaultOrderByClause,
771 boolean computeTotal)
772 throws DocumentNotFoundException, DocumentException {
773 DocumentWrapper<DocumentModelList> wrapDoc = null;
776 if (docTypes == null || docTypes.size() < 1) {
777 throw new DocumentNotFoundException(
778 "The findDocs() method must specify at least one DocumentType.");
780 DocumentModelList docList = null;
781 QueryContext queryContext = new QueryContext(ctx, whereClause, orderByClause);
782 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext, useDefaultOrderByClause);
783 if (logger.isDebugEnabled()) {
784 logger.debug("findDocs() NXQL: " + query);
786 docList = repoSession.query(query, null, pageSize, pageSize * pageNum, computeTotal);
787 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
788 } catch (IllegalArgumentException iae) {
790 } catch (Exception e) {
791 if (logger.isDebugEnabled()) {
792 logger.debug("Caught exception ", e);
794 throw new NuxeoDocumentException(e);
800 protected static String buildInListForDocTypes(List<String> docTypes) {
801 StringBuilder sb = new StringBuilder();
803 boolean first = true;
804 for (String docType : docTypes) {
815 return sb.toString();
818 public DocumentWrapper<DocumentModelList> findDocs(
819 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
820 DocumentHandler handler,
821 CoreSessionInterface repoSession,
822 List<String> docTypes) throws DocumentNotFoundException, DocumentException {
823 DocumentWrapper<DocumentModelList> wrapDoc = null;
825 DocumentFilter filter = handler.getDocumentFilter();
826 String oldOrderBy = filter.getOrderByClause();
827 if (isClauseEmpty(oldOrderBy) == true) {
828 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
830 QueryContext queryContext = new QueryContext(ctx, handler);
833 if (docTypes == null || docTypes.size() < 1) {
834 throw new DocumentNotFoundException(
835 "The findDocs() method must specify at least one DocumentType.");
837 DocumentModelList docList = null;
838 if (handler.isCMISQuery() == true) {
839 String inList = buildInListForDocTypes(docTypes);
840 ctx.getQueryParams().add(IQueryManager.SEARCH_RELATED_MATCH_OBJ_DOCTYPES, inList);
841 if (isSubjectOrObjectQuery(ctx)) {
842 docList = getFilteredCMISForSubjectOrObject(repoSession, ctx, handler, queryContext);
844 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
847 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
848 if (logger.isDebugEnabled()) {
849 logger.debug("findDocs() NXQL: " + query);
851 docList = repoSession.query(query, null, filter.getPageSize(), filter.getOffset(), true);
853 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
854 } catch (IllegalArgumentException iae) {
856 } catch (Exception e) {
857 if (logger.isDebugEnabled()) {
858 logger.debug("Caught exception ", e);
860 throw new NuxeoDocumentException(e);
866 private DocumentModelList getFilteredCMISForSubjectOrObject(CoreSessionInterface repoSession,
867 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, DocumentHandler handler, QueryContext queryContext) throws DocumentNotFoundException, DocumentException {
868 DocumentModelList result = null;
870 if (isSubjectOrObjectQuery(ctx) == true) {
871 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
872 String asEitherCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_EITHER);
874 queryParams.remove(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT);
875 queryParams.remove(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT);
878 // First query for subjectCsid results.
880 queryParams.addFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT, asEitherCsid);
881 DocumentModelList subjectDocList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
882 queryParams.remove(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT);
885 // Next query for objectCsid results.
887 queryParams.addFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT, asEitherCsid);
888 DocumentModelList objectDocList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
889 queryParams.remove(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT);
892 // Finally, combine the two results
894 result = mergeDocumentModelLists(subjectDocList, objectDocList);
900 private DocumentModelList mergeDocumentModelLists(DocumentModelList subjectDocList,
901 DocumentModelList objectDocList) {
902 DocumentModelList result = null;
904 if (subjectDocList == null || subjectDocList.isEmpty()) {
905 return objectDocList;
908 if (objectDocList == null || objectDocList.isEmpty()) {
909 return subjectDocList;
912 result = new DocumentModelListImpl();
914 // Add the subject list
915 Iterator<DocumentModel> iterator = subjectDocList.iterator();
916 while (iterator.hasNext()) {
917 DocumentModel dm = iterator.next();
918 addToResults(result, dm);
921 // Add the object list
922 iterator = objectDocList.iterator();
923 while (iterator.hasNext()) {
924 DocumentModel dm = iterator.next();
925 addToResults(result, dm);
928 // Set the 'totalSize' value for book keeping sake
929 ((DocumentModelListImpl) result).setTotalSize(result.size());
935 // Only add if it is not already in the list
936 private void addToResults(DocumentModelList result, DocumentModel dm) {
937 Iterator<DocumentModel> iterator = result.iterator();
938 boolean found = false;
940 while (iterator.hasNext()) {
941 DocumentModel existingDm = iterator.next();
942 if (existingDm.getId().equals(dm.getId())) {
948 if (found == false) {
953 private boolean isSubjectOrObjectQuery(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
954 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
955 String asEitherCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_EITHER);
956 return asEitherCsid != null && !asEitherCsid.isEmpty();
960 * Find a list of documentModels from the Nuxeo repository
962 * @param docTypes a list of DocType names to match
963 * @param whereClause where the clause to qualify on
964 * @throws DocumentNotFoundException
965 * @throws TransactionException
966 * @throws DocumentException
967 * @return a list of documentModels
970 public DocumentWrapper<DocumentModelList> findDocs(
971 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
972 List<String> docTypes,
976 boolean useDefaultOrderByClause,
977 boolean computeTotal) throws DocumentNotFoundException, TransactionException, DocumentException {
978 CoreSessionInterface repoSession = null;
979 DocumentWrapper<DocumentModelList> wrapDoc = null;
982 repoSession = getRepositorySession(ctx);
983 wrapDoc = findDocs(ctx,
990 useDefaultOrderByClause,
992 } catch (IllegalArgumentException iae) {
994 } catch (Exception e) {
995 if (logger.isDebugEnabled()) {
996 logger.debug("Caught exception ", e);
998 throw new NuxeoDocumentException(e);
1000 if (repoSession != null) {
1001 releaseRepositorySession(ctx, repoSession);
1005 if (logger.isWarnEnabled() == true) {
1006 logger.warn("Returned DocumentModelList instance was created with a repository session that is now closed.");
1013 * @see org.collectionspace.services.common.storage.StorageClient#get(org.collectionspace.services.common.context.ServiceContext, java.util.List, org.collectionspace.services.common.document.DocumentHandler)
1016 public void get(ServiceContext ctx, List<String> csidList, DocumentHandler handler)
1017 throws DocumentNotFoundException, TransactionException, DocumentException {
1018 if (handler == null) {
1019 throw new IllegalArgumentException(
1020 "RepositoryJavaClient.getAll: handler is missing");
1023 CoreSessionInterface repoSession = null;
1025 handler.prepare(Action.GET_ALL);
1026 repoSession = getRepositorySession(ctx);
1027 DocumentModelList docModelList = new DocumentModelListImpl();
1028 //FIXME: Should be using NuxeoUtils.createPathRef for security reasons
1029 for (String csid : csidList) {
1030 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
1031 DocumentModel docModel = repoSession.getDocument(docRef);
1032 docModelList.add(docModel);
1035 //set reposession to handle the document
1036 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1037 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docModelList);
1038 handler.handle(Action.GET_ALL, wrapDoc);
1039 handler.complete(Action.GET_ALL, wrapDoc);
1040 } catch (DocumentException de) {
1042 } catch (Exception e) {
1043 if (logger.isDebugEnabled()) {
1044 logger.debug("Caught exception ", e);
1046 throw new NuxeoDocumentException(e);
1048 if (repoSession != null) {
1049 releaseRepositorySession(ctx, repoSession);
1055 * getAll get all documents for an entity entity service from the Nuxeo
1058 * @param ctx service context under which this method is invoked
1059 * @param handler should be used by the caller to provide and transform the
1061 * @throws DocumentNotFoundException
1062 * @throws TransactionException
1063 * @throws DocumentException
1066 public void getAll(ServiceContext ctx, DocumentHandler handler)
1067 throws DocumentNotFoundException, TransactionException, DocumentException {
1068 if (handler == null) {
1069 throw new IllegalArgumentException(
1070 "RepositoryJavaClient.getAll: handler is missing");
1072 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
1073 if (nuxeoWspaceId == null) {
1074 throw new DocumentNotFoundException(
1075 "Unable to find workspace for service "
1076 + ctx.getServiceName()
1077 + " check if the workspace exists in the Nuxeo repository.");
1080 CoreSessionInterface repoSession = null;
1082 handler.prepare(Action.GET_ALL);
1083 repoSession = getRepositorySession(ctx);
1084 DocumentRef wsDocRef = new IdRef(nuxeoWspaceId);
1085 DocumentModelList docList = repoSession.getChildren(wsDocRef);
1086 //set reposession to handle the document
1087 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1088 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
1089 handler.handle(Action.GET_ALL, wrapDoc);
1090 handler.complete(Action.GET_ALL, wrapDoc);
1091 } catch (DocumentException de) {
1093 } catch (Exception e) {
1094 if (logger.isDebugEnabled()) {
1095 logger.debug("Caught exception ", e);
1097 throw new NuxeoDocumentException(e);
1099 if (repoSession != null) {
1100 releaseRepositorySession(ctx, repoSession);
1105 private boolean isClauseEmpty(String theString) {
1106 boolean result = true;
1107 if (theString != null && !theString.isEmpty()) {
1113 public DocumentWrapper<DocumentModel> getDocFromCsid(
1114 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1115 CoreSessionInterface repoSession,
1118 DocumentWrapper<DocumentModel> result = null;
1120 result = new DocumentWrapperImpl<DocumentModel>(NuxeoUtils.getDocFromCsid(ctx, repoSession, csid));
1126 * A method to find a CollectionSpace document (of any type) given just a service context and
1127 * its CSID. A search across *all* service workspaces (within a given tenant context) is performed to find
1130 * This query searches Nuxeo's Hierarchy table where our CSIDs are stored in the "name" column.
1133 public DocumentWrapper<DocumentModel> getDocFromCsid(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1136 DocumentWrapper<DocumentModel> result = null;
1137 CoreSessionInterface repoSession = null;
1139 repoSession = getRepositorySession(ctx);
1140 result = getDocFromCsid(ctx, repoSession, csid);
1142 if (repoSession != null) {
1143 releaseRepositorySession(ctx, repoSession);
1147 if (logger.isWarnEnabled() == true) {
1148 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
1155 * Returns a URI value for a document in the Nuxeo repository
1157 * @param wrappedDoc a wrapped documentModel
1158 * @throws ClientException
1159 * @return a document URI
1162 public String getDocURI(DocumentWrapper<DocumentModel> wrappedDoc) throws ClientException {
1163 DocumentModel docModel = wrappedDoc.getWrappedObject();
1164 String uri = (String) docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
1165 CollectionSpaceClient.COLLECTIONSPACE_CORE_URI);
1170 * See CSPACE-5036 - How to make CMISQL queries from Nuxeo
1172 private IterableQueryResult makeCMISQLQuery(CoreSessionInterface repoSession, String query, QueryContext queryContext) throws DocumentException {
1173 IterableQueryResult result = null;
1174 /** Threshold over which temporary files are not kept in memory. */
1175 final int THRESHOLD = 1024 * 1024;
1178 logger.debug(String.format("Performing a CMIS query on Nuxeo repository named %s",
1179 repoSession.getRepositoryName()));
1181 ThresholdOutputStreamFactory streamFactory = ThresholdOutputStreamFactory.newInstance(
1182 null, THRESHOLD, -1, false);
1183 CallContextImpl callContext = new CallContextImpl(
1184 CallContext.BINDING_LOCAL,
1185 CmisVersion.CMIS_1_1,
1186 repoSession.getRepositoryName(),
1187 null, // ServletContext
1188 null, // HttpServletRequest
1189 null, // HttpServletResponse
1190 new NuxeoCmisServiceFactory(),
1192 callContext.put(CallContext.USERNAME, repoSession.getPrincipal().getName());
1194 NuxeoCmisService cmisService = new NuxeoCmisService(repoSession.getCoreSession());
1195 result = repoSession.queryAndFetch(query, "CMISQL", cmisService);
1196 } catch (ClientException e) {
1197 // TODO Auto-generated catch block
1198 logger.error("Encounter trouble making the following CMIS query: " + query, e);
1199 throw new NuxeoDocumentException(e);
1206 * getFiltered get all documents for an entity service from the Document
1207 * repository, given filter parameters specified by the handler.
1209 * @param ctx service context under which this method is invoked
1210 * @param handler should be used by the caller to provide and transform the
1212 * @throws DocumentNotFoundException if workspace not found
1213 * @throws TransactionException
1214 * @throws DocumentException
1217 public void getFiltered(ServiceContext ctx, DocumentHandler handler)
1218 throws DocumentNotFoundException, TransactionException, DocumentException {
1220 DocumentFilter filter = handler.getDocumentFilter();
1221 String oldOrderBy = filter.getOrderByClause();
1222 if (isClauseEmpty(oldOrderBy) == true) {
1223 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
1225 QueryContext queryContext = new QueryContext(ctx, handler);
1227 CoreSessionInterface repoSession = null;
1229 handler.prepare(Action.GET_ALL);
1230 repoSession = getRepositorySession(ctx); //Keeps a refcount here for the repository session so you need to release this when finished
1232 DocumentModelList docList = null;
1234 if (handler.isJDBCQuery() == true) {
1235 docList = getFilteredJDBC(repoSession, ctx, handler);
1237 } else if (handler.isCMISQuery() == true) { //FIXME: REM - Need to deal with paging info in CMIS query
1238 if (isSubjectOrObjectQuery(ctx)) {
1239 docList = getFilteredCMISForSubjectOrObject(repoSession, ctx, handler, queryContext);
1241 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
1245 String query = NuxeoUtils.buildNXQLQuery(queryContext);
1246 if (logger.isDebugEnabled()) {
1247 logger.debug("Executing NXQL query: " + query.toString());
1249 Profiler profiler = new Profiler(this, 2);
1250 profiler.log("Executing NXQL query: " + query.toString());
1252 // If we have a page size and/or offset, then reflect those values
1253 // when constructing the query, and also pass 'true' to get totalSize
1254 // in the returned DocumentModelList.
1255 if ((queryContext.getDocFilter().getOffset() > 0) || (queryContext.getDocFilter().getPageSize() > 0)) {
1256 docList = repoSession.query(query, null,
1257 queryContext.getDocFilter().getPageSize(), queryContext.getDocFilter().getOffset(), true);
1259 docList = repoSession.query(query);
1264 //set repoSession to handle the document
1265 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1266 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
1267 handler.handle(Action.GET_ALL, wrapDoc);
1268 handler.complete(Action.GET_ALL, wrapDoc);
1269 } catch (DocumentException de) {
1271 } catch (Exception e) {
1272 if (logger.isDebugEnabled()) {
1273 logger.debug("Caught exception ", e); // REM - 1/17/2014: Check for org.nuxeo.ecm.core.api.ClientException and re-attempt
1275 throw new NuxeoDocumentException(e);
1277 if (repoSession != null) {
1278 releaseRepositorySession(ctx, repoSession);
1284 * Perform a database query, via JDBC and SQL, to retrieve matching records
1285 * based on filter criteria.
1287 * Although this method currently has a general-purpose name, it is
1288 * currently dedicated to a specific task: that of improving performance
1289 * for partial term matching queries on authority items / terms, via
1290 * the use of a hand-tuned SQL query, rather than via the generated SQL
1291 * produced by Nuxeo from an NXQL query. (See CSPACE-6361 for a task
1292 * to generalize this method.)
1294 * @param repoSession a repository session.
1295 * @param ctx the service context.
1296 * @param handler a relevant document handler.
1297 * @return a list of document models matching the search criteria.
1300 private DocumentModelList getFilteredJDBC(CoreSessionInterface repoSession, ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1301 DocumentHandler handler) throws Exception {
1302 DocumentModelList result = new DocumentModelListImpl();
1304 // FIXME: Get all of the following values from appropriate external constants.
1306 // At present, the two constants below are duplicated in both RepositoryClientImpl
1307 // and in AuthorityItemDocumentModelHandler.
1308 final String TERM_GROUP_LIST_NAME = "TERM_GROUP_LIST_NAME";
1309 final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
1310 final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
1311 // Get this from a constant in AuthorityResource or equivalent
1312 final String PARENT_WILDCARD = "_ALL_";
1314 // Build two SQL statements, to be executed within a single transaction:
1315 // the first statement to control join order, and the second statement
1316 // representing the actual 'get filtered' query
1318 // Build the join control statement
1320 // Per http://www.postgresql.org/docs/9.2/static/runtime-config-query.html#GUC-JOIN-COLLAPSE-LIMIT
1321 // "Setting [this value] to 1 prevents any reordering of explicit JOINs.
1322 // Thus, the explicit join order specified in the query will be the
1323 // actual order in which the relations are joined."
1324 // See CSPACE-5945 for further discussion of why this setting is needed.
1326 // Adding this statement is commented out here for now. It significantly
1327 // improved query performance for authority item / term queries where
1328 // large numbers of rows were retrieved, but appears to have resulted
1329 // in consistently slower-than-desired query performance where zero or
1330 // very few records were retrieved. See notes on CSPACE-5945. - ADR 2013-04-09
1331 // String joinControlSql = "SET LOCAL join_collapse_limit TO 1;";
1333 // Build the query statement
1335 // Start with the default query
1336 String selectStatement =
1337 "SELECT DISTINCT commonschema.id"
1338 + " FROM " + handler.getServiceContext().getCommonPartLabel() + " commonschema";
1340 String joinClauses =
1342 + " ON misc.id = commonschema.id"
1343 + " INNER JOIN hierarchy hierarchy_termgroup"
1344 + " ON hierarchy_termgroup.parentid = misc.id"
1345 + " INNER JOIN " + handler.getJDBCQueryParams().get(TERM_GROUP_TABLE_NAME_PARAM) + " termgroup"
1346 + " ON termgroup.id = hierarchy_termgroup.id ";
1349 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
1350 // Value for replaceable parameter 1 in the query
1351 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
1352 // If the value of the partial term query parameter is blank ('pt='),
1353 // return all records, subject to restriction by any limit clause
1354 if (Tools.isBlank(partialTerm)) {
1357 // Otherwise, return records that match the supplied partial term
1359 " WHERE (termgroup.termdisplayname ILIKE ?)";
1362 // At present, results are ordered in code, below, rather than in SQL,
1363 // and the orderByClause below is thus intentionally blank.
1365 // To implement the orderByClause below in SQL; e.g. via
1366 // 'ORDER BY termgroup.termdisplayname', the relevant column
1367 // must be returned by the SELECT statement.
1368 String orderByClause = "";
1371 TenantBindingConfigReaderImpl tReader =
1372 ServiceMain.getInstance().getTenantBindingConfigReader();
1373 TenantBindingType tenantBinding = tReader.getTenantBinding(ctx.getTenantId());
1374 String maxListItemsLimit = TenantBindingUtils.getPropertyValue(tenantBinding,
1375 IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES);
1377 " LIMIT " + getMaxItemsLimitOnJdbcQueries(maxListItemsLimit); // implicit int-to-String conversion
1379 // After building the individual parts of the query, set the values
1380 // of replaceable parameters that will be inserted into that query
1381 // and optionally add restrictions
1383 List<String> params = new ArrayList<>();
1385 if (Tools.notBlank(whereClause)) {
1387 // Read tenant bindings configuration to determine whether
1388 // to automatically insert leading, as well as trailing, wildcards
1389 // into the term matching string.
1390 String usesStartingWildcard = TenantBindingUtils.getPropertyValue(tenantBinding,
1391 IQueryManager.TENANT_USES_STARTING_WILDCARD_FOR_PARTIAL_TERM);
1392 // Handle user-provided leading wildcard characters, in the
1393 // configuration where a leading wildcard is not automatically inserted.
1394 // (The user-provided wildcard must be in the first, or "starting"
1395 // character position in the partial term value.)
1396 if (Tools.notBlank(usesStartingWildcard)) {
1397 if (usesStartingWildcard.equalsIgnoreCase(Boolean.FALSE.toString())) {
1398 partialTerm = handleProvidedStartingWildcard(partialTerm);
1399 // Otherwise, in the configuration where a leading wildcard
1400 // is usually automatically inserted, handle the cases where
1401 // a user has entered an anchor character in the first position
1402 // in the starting term value. In those cases, strip that
1403 // anchor character and don't add a leading wildcard
1405 if (partialTerm.startsWith(USER_SUPPLIED_ANCHOR_CHAR)) {
1406 partialTerm = partialTerm.substring(1, partialTerm.length());
1407 // Otherwise, automatically add a leading wildcard
1409 partialTerm = JDBCTools.SQL_WILDCARD + partialTerm;
1413 // Add SQL wildcards in the midst of the partial term match search
1414 // expression, whever user-supplied wildcards appear, except in the
1415 // first or last character positions of the search expression.
1416 partialTerm = subtituteWildcardsInPartialTerm(partialTerm);
1418 // If a designated 'anchor character' is present as the last character
1419 // in the search expression, strip that character and don't add
1420 // a trailing wildcard
1421 int lastCharPos = partialTerm.length() - 1;
1422 if (partialTerm.endsWith(USER_SUPPLIED_ANCHOR_CHAR) && lastCharPos > 0) {
1423 partialTerm = partialTerm.substring(0, lastCharPos);
1425 // Otherwise, automatically add a trailing wildcard
1426 partialTerm = partialTerm + JDBCTools.SQL_WILDCARD;
1428 params.add(partialTerm);
1431 // Optionally add restrictions to the default query, based on variables
1432 // in the current request
1434 // Restrict the query to filter out deleted records, if requested
1435 String includeDeleted = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_DELETED_QP);
1436 if (includeDeleted != null && includeDeleted.equalsIgnoreCase(Boolean.FALSE.toString())) {
1437 whereClause = whereClause
1438 + " AND (misc.lifecyclestate <> '" + WorkflowClient.WORKFLOWSTATE_DELETED + "')"
1439 + " AND (misc.lifecyclestate <> '" + WorkflowClient.WORKFLOWSTATE_LOCKED_DELETED + "')"
1440 + " AND (misc.lifecyclestate <> '" + WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED + "')";
1443 // If a particular authority is specified, restrict the query further
1444 // to return only records within that authority
1445 String inAuthorityValue = (String) handler.getJDBCQueryParams().get(IN_AUTHORITY_PARAM);
1446 if (Tools.notBlank(inAuthorityValue)) {
1447 // Handle the '_ALL_' case for inAuthority
1448 if (inAuthorityValue.equals(PARENT_WILDCARD)) {
1449 // Add nothing to the query here if it should match within all authorities
1451 whereClause = whereClause
1452 + " AND (commonschema.inauthority = ?)";
1453 params.add(inAuthorityValue); // Value for replaceable parameter 2 in the query
1457 // Restrict the query further to return only records pertaining to
1458 // the current tenant, unless:
1459 // * Data for this service, in this tenant, is stored in its own,
1460 // separate repository, rather than being intermingled with other
1461 // tenants' data in the default repository; or
1462 // * Restriction by tenant ID in JDBC queries has been disabled,
1463 // via configuration for this tenant,
1464 if (restrictJDBCQueryByTenantID(tenantBinding, ctx)) {
1465 joinClauses = joinClauses
1466 + " INNER JOIN collectionspace_core core"
1467 + " ON core.id = hierarchy_termgroup.parentid";
1468 whereClause = whereClause
1469 + " AND (core.tenantid = ?)";
1470 params.add(ctx.getTenantId()); // Value for replaceable parameter 3 in the query
1473 // Piece together the SQL query from its parts
1474 String querySql = selectStatement + joinClauses + whereClause + orderByClause + limitClause;
1476 // Note: PostgreSQL 9.2 introduced a change that may improve performance
1477 // of certain queries using JDBC PreparedStatements. See comments on
1478 // CSPACE-5943 for details.
1480 // See a comment above for the reason that the joinControl SQL statement,
1481 // along with its corresponding prepared statement builder, is commented out for now.
1482 // PreparedStatementBuilder joinControlBuilder = new PreparedStatementBuilder(joinControlSql);
1483 PreparedStatementSimpleBuilder queryBuilder = new PreparedStatementSimpleBuilder(querySql, params);
1484 List<PreparedStatementBuilder> builders = new ArrayList<>();
1485 // builders.add(joinControlBuilder);
1486 builders.add(queryBuilder);
1487 String dataSourceName = JDBCTools.NUXEO_DATASOURCE_NAME;
1488 String repositoryName = ctx.getRepositoryName();
1489 final Boolean EXECUTE_WITHIN_TRANSACTION = true;
1490 Set<String> docIds = new HashSet<>();
1492 String cspaceInstanceId = ServiceMain.getInstance().getCspaceInstanceId();
1493 List<CachedRowSet> resultsList = JDBCTools.executePreparedQueries(builders,
1494 dataSourceName, repositoryName, cspaceInstanceId, EXECUTE_WITHIN_TRANSACTION);
1496 // At least one set of results is expected, from the second prepared
1497 // statement to be executed.
1498 // If fewer results are returned, return an empty list of document models
1499 if (resultsList == null || resultsList.size() < 1) {
1500 return result; // return an empty list of document models
1502 // The join control query (if enabled - it is currently commented
1503 // out as per comments above) will not return results, so query results
1504 // will be the first set of results (rowSet) returned in the list
1505 CachedRowSet queryResults = resultsList.get(0);
1507 // If the result from executing the query is null or contains zero rows,
1508 // return an empty list of document models
1509 if (queryResults == null) {
1510 return result; // return an empty list of document models
1512 queryResults.last();
1513 if (queryResults.getRow() == 0) {
1514 return result; // return an empty list of document models
1517 // Otherwise, get the document IDs from the results of the query
1519 queryResults.beforeFirst();
1520 while (queryResults.next()) {
1521 id = queryResults.getString(1);
1522 if (Tools.notBlank(id)) {
1526 } catch (SQLException sqle) {
1527 logger.warn("Could not obtain document IDs via SQL query '" + querySql + "': " + sqle.getMessage());
1528 return result; // return an empty list of document models
1531 // Get a list of document models, using the list of IDs obtained from the query
1533 // FIXME: Check whether we have a 'get document models from list of CSIDs'
1534 // utility method like this, and if not, add this to the appropriate
1536 DocumentModel docModel;
1537 for (String docId : docIds) {
1538 docModel = NuxeoUtils.getDocumentModel(repoSession, docId);
1539 if (docModel == null) {
1540 logger.warn("Could not obtain document model for document with ID " + docId);
1542 result.add(docModel);
1546 // Order the results
1547 final String COMMON_PART_SCHEMA = handler.getServiceContext().getCommonPartLabel();
1548 final String DISPLAY_NAME_XPATH =
1549 "//" + handler.getJDBCQueryParams().get(TERM_GROUP_LIST_NAME) + "/[0]/termDisplayName";
1550 Collections.sort(result, new Comparator<DocumentModel>() {
1552 public int compare(DocumentModel doc1, DocumentModel doc2) {
1553 String termDisplayName1 = null;
1554 String termDisplayName2 = null;
1556 termDisplayName1 = (String) NuxeoUtils.getXPathValue(doc1, COMMON_PART_SCHEMA, DISPLAY_NAME_XPATH);
1557 termDisplayName2 = (String) NuxeoUtils.getXPathValue(doc2, COMMON_PART_SCHEMA, DISPLAY_NAME_XPATH);
1558 } catch (NuxeoDocumentException e) {
1559 throw new RuntimeException(e); // We need to throw a RuntimeException because the compare() method of the Comparator interface does not support throwing an Exception
1561 return termDisplayName1.compareToIgnoreCase(termDisplayName2);
1569 private DocumentModelList getFilteredCMIS(CoreSessionInterface repoSession,
1570 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, DocumentHandler handler, QueryContext queryContext)
1571 throws DocumentNotFoundException, DocumentException {
1573 DocumentModelList result = new DocumentModelListImpl();
1575 String query = handler.getCMISQuery(queryContext);
1577 DocumentFilter docFilter = handler.getDocumentFilter();
1578 int pageSize = docFilter.getPageSize();
1579 int offset = docFilter.getOffset();
1580 if (logger.isDebugEnabled()) {
1581 logger.debug("Executing CMIS query: " + query.toString()
1582 + "with pageSize: " + pageSize + " at offset: " + offset);
1585 // If we have limit and/or offset, then pass true to get totalSize
1586 // in returned DocumentModelList.
1587 Profiler profiler = new Profiler(this, 2);
1588 profiler.log("Executing CMIS query: " + query.toString());
1591 IterableQueryResult queryResult = makeCMISQLQuery(repoSession, query, queryContext);
1593 int totalSize = (int) queryResult.size();
1594 ((DocumentModelListImpl) result).setTotalSize(totalSize);
1595 // Skip the rows before our offset
1597 queryResult.skipTo(offset);
1600 for (Map<String, Serializable> row : queryResult) {
1601 if (logger.isTraceEnabled()) {
1602 logger.trace(" Hierarchy Table ID is:" + row.get(IQueryManager.CMIS_TARGET_NUXEO_ID)
1603 + " nuxeo:pathSegment is: " + row.get(IQueryManager.CMIS_TARGET_NAME));
1605 String nuxeoId = (String) row.get(IQueryManager.CMIS_TARGET_NUXEO_ID);
1606 DocumentModel docModel = NuxeoUtils.getDocumentModel(repoSession, nuxeoId);
1607 result.add(docModel);
1609 if (nRows >= pageSize && pageSize != 0) { // A page size of zero means that they want all of them
1610 logger.debug("Got page full of items - quitting");
1615 queryResult.close();
1620 } catch (Exception e) {
1621 if (logger.isDebugEnabled()) {
1622 logger.debug("Caught exception ", e);
1624 throw new NuxeoDocumentException(e);
1628 // Since we're not supporting paging yet for CMIS queries, we need to perform
1629 // a workaround for the paging information we return in our list of results
1632 if (result != null) {
1633 docFilter.setStartPage(0);
1634 if (totalSize > docFilter.getPageSize()) {
1635 docFilter.setPageSize(totalSize);
1636 ((DocumentModelListImpl)result).setTotalSize(totalSize);
1644 private String logException(Exception e, String msg) {
1645 String result = null;
1647 String exceptionMessage = e.getMessage();
1648 exceptionMessage = exceptionMessage != null ? exceptionMessage : "<No details provided>";
1649 result = msg = msg + ". Caught exception:" + exceptionMessage;
1651 if (logger.isTraceEnabled() == true) {
1652 logger.error(msg, e);
1661 * update given document in the Nuxeo repository
1663 * @param ctx service context under which this method is invoked
1664 * @param csid of the document
1665 * @param handler should be used by the caller to provide and transform the
1667 * @throws BadRequestException
1668 * @throws DocumentNotFoundException
1669 * @throws TransactionException if the transaction times out or otherwise
1670 * cannot be successfully completed
1671 * @throws DocumentException
1674 public void update(ServiceContext ctx, String csid, DocumentHandler handler)
1675 throws BadRequestException, DocumentNotFoundException, TransactionException,
1677 if (handler == null) {
1678 throw new IllegalArgumentException(
1679 "RepositoryJavaClient.update: document handler is missing.");
1682 CoreSessionInterface repoSession = null;
1684 handler.prepare(Action.UPDATE);
1685 repoSession = getRepositorySession(ctx);
1686 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
1687 DocumentModel doc = null;
1689 doc = repoSession.getDocument(docRef);
1690 } catch (org.nuxeo.ecm.core.api.DocumentNotFoundException ce) {
1691 String msg = logException(ce,
1692 String.format("Could not find %s resource/record to update with CSID=%s", ctx.getDocumentType(), csid));
1693 throw new DocumentNotFoundException(msg, ce);
1695 // Check for a versioned document, and check In and Out before we proceed.
1696 if (((DocumentModelHandler) handler).supportsVersioning()) {
1697 /* Once we advance to 5.5 or later, we can add this.
1698 * See also https://jira.nuxeo.com/browse/NXP-8506
1699 if(!doc.isVersionable()) {
1700 throw new NuxeoDocumentException("Configuration for: "
1701 +handler.getServiceContextPath()+" supports versioning, but Nuxeo config does not!");
1704 /* Force a version number - Not working. Apparently we need to configure the uid schema??
1705 if(doc.getProperty("uid","major_version") == null) {
1706 doc.setProperty("uid","major_version",1);
1708 if(doc.getProperty("uid","minor_version") == null) {
1709 doc.setProperty("uid","minor_version",0);
1712 doc.checkIn(VersioningOption.MINOR, null);
1717 // Set reposession to handle the document
1719 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1720 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
1721 handler.handle(Action.UPDATE, wrapDoc);
1722 repoSession.saveDocument(doc);
1724 // Refresh the doc after save, in case a documentModified event handler has modified
1725 // the document post-save. We want those changes to be reflected in the returned document.
1727 handler.complete(Action.UPDATE, wrapDoc);
1728 } catch (BadRequestException bre) {
1729 if (ctx.isRollbackOnException()) {
1730 rollbackTransaction(repoSession);
1733 } catch (DocumentException de) {
1734 if (ctx.isRollbackOnException()) {
1735 rollbackTransaction(repoSession);
1739 } catch (CSWebApplicationException wae) {
1740 if (ctx.isRollbackOnException()) {
1741 rollbackTransaction(repoSession);
1744 } catch (Throwable e) {
1745 if (ctx.isRollbackOnException()) {
1746 rollbackTransaction(repoSession);
1748 throw new NuxeoDocumentException(e);
1750 if (repoSession != null) {
1751 releaseRepositorySession(ctx, repoSession);
1757 * Save a documentModel to the Nuxeo repository.
1759 * @param ctx service context under which this method is invoked
1760 * @param repoSession
1761 * @param docModel the document to save
1762 * @param fSaveSession if TRUE, will call CoreSessionInterface.save() to save
1763 * accumulated changes.
1764 * @throws ClientException
1765 * @throws DocumentException
1768 public void saveDocWithoutHandlerProcessing(
1769 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1770 CoreSessionInterface repoSession,
1771 DocumentModel docModel,
1772 boolean fSaveSession)
1773 throws ClientException, DocumentException {
1776 repoSession.saveDocument(docModel);
1780 } catch (ClientException ce) {
1782 } catch (Exception e) {
1783 if (logger.isDebugEnabled()) {
1784 logger.debug("Caught exception ", e);
1786 throw new NuxeoDocumentException(e);
1791 * Save a list of documentModels to the Nuxeo repository.
1793 * @param ctx service context under which this method is invoked
1794 * @param repoSession a repository session
1795 * @param docModelList a list of document models
1796 * @param fSaveSession if TRUE, will call CoreSessionInterface.save() to save
1797 * accumulated changes.
1798 * @throws ClientException
1799 * @throws DocumentException
1801 public void saveDocListWithoutHandlerProcessing(
1802 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1803 CoreSessionInterface repoSession,
1804 DocumentModelList docList,
1805 boolean fSaveSession)
1806 throws ClientException, DocumentException {
1808 DocumentModel[] docModelArray = new DocumentModel[docList.size()];
1809 repoSession.saveDocuments(docList.toArray(docModelArray));
1813 } catch (ClientException ce) {
1815 } catch (Exception e) {
1816 logger.error("Caught exception ", e);
1817 throw new NuxeoDocumentException(e);
1822 public void deleteWithWhereClause(@SuppressWarnings("rawtypes") ServiceContext ctx, String whereClause,
1823 @SuppressWarnings("rawtypes") DocumentHandler handler) throws
1824 DocumentNotFoundException, DocumentException {
1826 throw new IllegalArgumentException(
1827 "delete(ctx, specifier): ctx is missing");
1829 if (logger.isDebugEnabled()) {
1830 logger.debug("Deleting document with whereClause=" + whereClause);
1833 DocumentWrapper<DocumentModel> foundDocWrapper = this.findDoc(ctx, whereClause);
1834 if (foundDocWrapper != null) {
1835 DocumentModel docModel = foundDocWrapper.getWrappedObject();
1836 String csid = docModel.getName();
1837 this.delete(ctx, csid, handler);
1842 * delete a document from the Nuxeo repository
1844 * @param ctx service context under which this method is invoked
1845 * @param id of the document
1846 * @throws DocumentException
1849 public boolean delete(ServiceContext ctx, List<String> idList, DocumentHandler handler) throws DocumentNotFoundException,
1850 DocumentException, TransactionException {
1851 boolean result = true;
1854 throw new IllegalArgumentException(
1855 "delete(ctx, ix, handler): ctx is missing");
1857 if (handler == null) {
1858 throw new IllegalArgumentException(
1859 "delete(ctx, ix, handler): handler is missing");
1862 CoreSessionInterface repoSession = null;
1864 handler.prepare(Action.DELETE);
1865 repoSession = getRepositorySession(ctx);
1867 for (String id : idList) {
1868 if (logger.isDebugEnabled()) {
1869 logger.debug("Deleting document with CSID=" + id);
1871 DocumentWrapper<DocumentModel> wrapDoc = null;
1873 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
1874 wrapDoc = new DocumentWrapperImpl<DocumentModel>(repoSession.getDocument(docRef));
1875 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1876 if (handler.handle(Action.DELETE, wrapDoc) == true) {
1877 repoSession.removeDocument(docRef);
1878 if (logger.isDebugEnabled()) {
1879 String msg = String.format("DELETE - User '%s' hard-deleted document CSID=%s of type %s.",
1880 ctx.getUserId(), id, ctx.getDocumentType());
1884 String msg = String.format("Could not delete %s resource with csid=%s.",
1885 handler.getServiceContext().getServiceName(), id);
1886 throw new DocumentException(msg);
1888 } catch (org.nuxeo.ecm.core.api.DocumentNotFoundException ce) {
1889 String msg = logException(ce,
1890 String.format("Could not find %s resource/record to delete with CSID=%s", ctx.getDocumentType(), id));
1891 throw new DocumentNotFoundException(msg, ce);
1894 handler.complete(Action.DELETE, wrapDoc);
1896 } catch (DocumentException de) {
1897 if (ctx.isRollbackOnException()) {
1898 rollbackTransaction(repoSession);
1901 } catch (Throwable e) {
1902 if (ctx.isRollbackOnException()) {
1903 rollbackTransaction(repoSession);
1905 throw new NuxeoDocumentException(e);
1907 if (repoSession != null) {
1908 releaseRepositorySession(ctx, repoSession);
1916 * delete a document from the Nuxeo repository
1918 * @param ctx service context under which this method is invoked
1919 * @param id of the document
1920 * @throws DocumentException
1923 public boolean delete(ServiceContext ctx, String id, DocumentHandler handler) throws DocumentNotFoundException,
1924 DocumentException, TransactionException {
1927 List<String> idList = new ArrayList<String>();
1929 result = delete(ctx, idList, handler);
1935 * @see org.collectionspace.services.common.storage.StorageClient#delete(org.collectionspace.services.common.context.ServiceContext, java.lang.String, org.collectionspace.services.common.document.DocumentHandler)
1939 public void delete(@SuppressWarnings("rawtypes") ServiceContext ctx, String id)
1940 throws DocumentNotFoundException, DocumentException {
1941 throw new UnsupportedOperationException();
1942 // Use the other delete instead
1946 public Hashtable<String, String> retrieveWorkspaceIds(RepositoryDomainType repoDomain) throws Exception {
1947 return NuxeoConnectorEmbedded.getInstance().retrieveWorkspaceIds(repoDomain);
1951 public String createDomain(RepositoryDomainType repositoryDomain) throws Exception {
1952 CoreSessionInterface repoSession = null;
1953 String domainId = null;
1956 // Open a connection to the domain's repo/db
1958 String repoName = repositoryDomain.getRepositoryName();
1959 repoSession = getRepositorySession(repoName); // domainName=storageName=repoName=databaseName
1961 // First create the top-level domain directory
1963 String domainName = repositoryDomain.getStorageName();
1964 DocumentRef parentDocRef = new PathRef("/");
1965 DocumentModel parentDoc = repoSession.getDocument(parentDocRef);
1966 DocumentModel domainDoc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1967 domainName, NUXEO_CORE_TYPE_DOMAIN);
1968 domainDoc.setPropertyValue("dc:title", domainName);
1969 domainDoc.setPropertyValue("dc:description", "A CollectionSpace domain "
1971 domainDoc = repoSession.createDocument(domainDoc);
1972 domainId = domainDoc.getId();
1975 // Next, create a "Workspaces" root directory to contain the workspace folders for the individual service documents
1977 DocumentModel workspacesRoot = repoSession.createDocumentModel(domainDoc.getPathAsString(),
1978 NuxeoUtils.Workspaces, NUXEO_CORE_TYPE_WORKSPACEROOT);
1979 workspacesRoot.setPropertyValue("dc:title", NuxeoUtils.Workspaces);
1980 workspacesRoot.setPropertyValue("dc:description", "A CollectionSpace workspaces directory for "
1981 + domainDoc.getPathAsString());
1982 workspacesRoot = repoSession.createDocument(workspacesRoot);
1983 String workspacesRootId = workspacesRoot.getId();
1986 if (logger.isDebugEnabled()) {
1987 logger.debug("Created tenant domain name=" + domainName
1988 + " id=" + domainId + " "
1989 + NuxeoUtils.Workspaces + " id=" + workspacesRootId);
1990 logger.debug("Path to Domain: " + domainDoc.getPathAsString());
1991 logger.debug("Path to Workspaces root: " + workspacesRoot.getPathAsString());
1993 } catch (Throwable e) {
1994 rollbackTransaction(repoSession);
1995 if (logger.isDebugEnabled()) {
1996 logger.debug("Could not create tenant domain name=" + repositoryDomain.getStorageName() + " caught exception ", e);
2000 if (repoSession != null) {
2001 releaseRepositorySession(null, repoSession);
2009 public String getDomainId(RepositoryDomainType repositoryDomain) throws Exception {
2010 String domainId = null;
2011 CoreSessionInterface repoSession = null;
2013 String repoName = repositoryDomain.getRepositoryName();
2014 String domainStorageName = repositoryDomain.getStorageName();
2015 if (domainStorageName != null && !domainStorageName.isEmpty()) {
2017 repoSession = getRepositorySession(repoName);
2018 DocumentRef docRef = new PathRef("/" + domainStorageName);
2019 DocumentModel domain = repoSession.getDocument(docRef);
2020 domainId = domain.getId();
2021 } catch (Exception e) {
2022 if (logger.isTraceEnabled()) {
2023 logger.trace("Caught exception ", e); // The document doesn't exist, this let's us know we need to create it
2026 if (repoSession != null) {
2027 releaseRepositorySession(null, repoSession);
2036 * Returns the workspaces root directory for a given domain.
2038 private DocumentModel getWorkspacesRoot(CoreSessionInterface repoSession,
2039 String domainName) throws Exception {
2040 DocumentModel result = null;
2042 String domainPath = "/" + domainName;
2043 DocumentRef parentDocRef = new PathRef(domainPath);
2044 DocumentModelList domainChildrenList = repoSession.getChildren(
2046 Iterator<DocumentModel> witer = domainChildrenList.iterator();
2047 while (witer.hasNext()) {
2048 DocumentModel childNode = witer.next();
2049 if (NuxeoUtils.Workspaces.equalsIgnoreCase(childNode.getName())) {
2051 logger.trace("Found workspaces directory at: " + result.getPathAsString());
2056 if (result == null) {
2057 throw new ClientException("Could not find workspace root directory in: "
2065 * @see org.collectionspace.services.common.repository.RepositoryClient#createWorkspace(java.lang.String, java.lang.String)
2068 public String createWorkspace(RepositoryDomainType repositoryDomain, String workspaceName) throws Exception {
2069 CoreSessionInterface repoSession = null;
2070 String workspaceId = null;
2072 String repoName = repositoryDomain.getRepositoryName();
2073 repoSession = getRepositorySession(repoName);
2075 String domainStorageName = repositoryDomain.getStorageName();
2076 DocumentModel parentDoc = getWorkspacesRoot(repoSession, domainStorageName);
2077 if (logger.isTraceEnabled()) {
2078 for (String facet : parentDoc.getFacets()) {
2079 logger.trace("Facet: " + facet);
2083 DocumentModel doc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
2084 workspaceName, NuxeoUtils.WORKSPACE_DOCUMENT_TYPE);
2085 doc.setPropertyValue("dc:title", workspaceName);
2086 doc.setPropertyValue("dc:description", "A CollectionSpace workspace for "
2088 doc = repoSession.createDocument(doc);
2089 workspaceId = doc.getId();
2091 if (logger.isDebugEnabled()) {
2092 logger.debug("Created workspace name=" + workspaceName
2093 + " id=" + workspaceId);
2095 } catch (Throwable e) {
2096 rollbackTransaction(repoSession);
2097 if (logger.isDebugEnabled()) {
2098 logger.debug("createWorkspace caught exception ", e);
2102 if (repoSession != null) {
2103 releaseRepositorySession(null, repoSession);
2110 * @see org.collectionspace.services.common.repository.RepositoryClient#getWorkspaceId(java.lang.String, java.lang.String)
2114 public String getWorkspaceId(String tenantDomain, String workspaceName) throws Exception {
2115 String workspaceId = null;
2117 CoreSessionInterface repoSession = null;
2119 repoSession = getRepositorySession((ServiceContext<PoxPayloadIn, PoxPayloadOut>) null);
2120 DocumentRef docRef = new PathRef(
2122 + "/" + NuxeoUtils.Workspaces
2123 + "/" + workspaceName);
2124 DocumentModel workspace = repoSession.getDocument(docRef);
2125 workspaceId = workspace.getId();
2126 } catch (DocumentException de) {
2128 } catch (Exception e) {
2129 if (logger.isDebugEnabled()) {
2130 logger.debug("Caught exception ", e);
2132 throw new NuxeoDocumentException(e);
2134 if (repoSession != null) {
2135 releaseRepositorySession(null, repoSession);
2143 public CoreSessionInterface getRepositorySession(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) throws Exception {
2144 return getRepositorySession(ctx, ctx.getRepositoryName(), ctx.getTimeoutSecs());
2147 public CoreSessionInterface getRepositorySession(String repoName) throws Exception {
2148 return getRepositorySession(null, repoName, ServiceContext.DEFAULT_TX_TIMEOUT);
2152 * Gets the repository session. - Package access only. If the 'ctx' param is
2153 * null then the repo name must be non-mull and vice-versa
2155 * @return the repository session
2156 * @throws Exception the exception
2158 public CoreSessionInterface getRepositorySession(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
2160 int timeoutSeconds) throws Exception {
2161 CoreSessionInterface repoSession = null;
2163 Profiler profiler = new Profiler("getRepositorySession():", 2);
2166 // To get a connection to the Nuxeo repo, we need either a valid ServiceContext instance or a repository name
2169 repoSession = (CoreSessionInterface) ctx.getCurrentRepositorySession(); // First see if the context already has a repo session
2170 if (repoSession == null) {
2171 repoName = ctx.getRepositoryName(); // Notice we are overriding the passed in 'repoName' since we have a valid service context passed in to us
2173 } else if (Tools.isBlank(repoName)) {
2174 String errMsg = String.format("Either a valid session context or repository name are required to get a new connection.");
2175 logger.error(errMsg);
2176 throw new Exception(errMsg);
2179 if (repoSession == null) {
2181 // 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
2182 // just the repository name.
2184 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
2185 repoSession = client.openRepository(repoName, timeoutSeconds);
2187 if (logger.isTraceEnabled() == true) {
2188 logger.trace("Reusing the current context's repository session.");
2192 // Debugging only code
2194 if (logger.isTraceEnabled()) {
2196 if (logger.isTraceEnabled()) {
2197 logger.trace("Testing call to getRepository() repository root: " + repoSession.getRootDocument());
2199 } catch (Throwable e) {
2200 logger.trace("Test call to Nuxeo's getRepository() repository root failed", e);
2207 ctx.setCurrentRepositorySession(repoSession); // For reusing, save the repository session in the current service context. The context will reference count it.
2214 * Release repository session. - Package access only.
2216 * @param repoSession the repo session
2219 public void releaseRepositorySession(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, Object repositorySession) throws TransactionException {
2221 CoreSessionInterface repoSession = (CoreSessionInterface)repositorySession;
2222 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
2225 ctx.clearCurrentRepositorySession(); //clear the current context of the now closed repo session
2226 if (ctx.getCurrentRepositorySession() == null) {
2227 client.releaseRepository(repoSession); //release the repo session if the service context's ref count is zeo.
2230 client.releaseRepository(repoSession); //repo session was acquired without a service context
2232 } catch (TransactionRuntimeException tre) {
2233 String causeMsg = null;
2234 Throwable cause = tre.getCause();
2235 if (cause != null) {
2236 causeMsg = cause.getMessage();
2239 TransactionException te; // a CollectionSpace specific tx exception
2240 if (causeMsg != null) {
2241 te = new TransactionException(causeMsg, tre);
2243 te = new TransactionException(tre);
2246 logger.error(te.getMessage(), tre); // Log the standard transaction exception message, plus an exception-specific stack trace
2248 } catch (Exception e) {
2249 logger.error("Could not close the repository session.", e);
2250 // no need to throw this service specific exception
2255 public void doWorkflowTransition(ServiceContext ctx, String id,
2256 DocumentHandler handler, TransitionDef transitionDef)
2257 throws BadRequestException, DocumentNotFoundException,
2259 // 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
2262 private String handleProvidedStartingWildcard(String partialTerm) {
2263 if (Tools.notBlank(partialTerm)) {
2264 if (partialTerm.substring(0, 1).equals(USER_SUPPLIED_WILDCARD)) {
2265 StringBuffer buffer = new StringBuffer(partialTerm);
2266 buffer.setCharAt(0, JDBCTools.SQL_WILDCARD.charAt(0));
2267 partialTerm = buffer.toString();
2274 * Replaces user-supplied wildcards with SQL wildcards, in a partial term
2275 * matching search expression.
2277 * The scope of this replacement excludes the beginning character
2278 * in that search expression, as that character is treated specially.
2280 * @param partialTerm
2281 * @return the partial term, with any user-supplied wildcards replaced
2284 private String subtituteWildcardsInPartialTerm(String partialTerm) {
2285 if (Tools.isBlank(partialTerm)) {
2288 if (! partialTerm.contains(USER_SUPPLIED_WILDCARD)) {
2291 int len = partialTerm.length();
2292 // Partial term search expressions of 2 or fewer characters
2293 // currently aren't amenable to the use of wildcards
2295 logger.warn("Partial term match search expression of just 1-2 characters in length contains a user-supplied wildcard: " + partialTerm);
2296 logger.warn("Will handle that character as a literal value, rather than as a wildcard ...");
2299 return partialTerm.substring(0, 1) // first char
2300 + partialTerm.substring(1, len).replaceAll(USER_SUPPLIED_WILDCARD_REGEX, JDBCTools.SQL_WILDCARD);
2304 private int getMaxItemsLimitOnJdbcQueries(String maxListItemsLimit) {
2305 final int DEFAULT_ITEMS_LIMIT = 40;
2306 if (maxListItemsLimit == null) {
2307 return DEFAULT_ITEMS_LIMIT;
2311 itemsLimit = Integer.parseInt(maxListItemsLimit);
2312 if (itemsLimit < 1) {
2313 logger.warn("Value of configuration setting "
2314 + IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES
2315 + " must be a positive integer; invalid current value is " + maxListItemsLimit);
2316 logger.warn("Reverting to default value of " + DEFAULT_ITEMS_LIMIT);
2317 itemsLimit = DEFAULT_ITEMS_LIMIT;
2319 } catch (NumberFormatException nfe) {
2320 logger.warn("Value of configuration setting "
2321 + IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES
2322 + " must be a positive integer; invalid current value is " + maxListItemsLimit);
2323 logger.warn("Reverting to default value of " + DEFAULT_ITEMS_LIMIT);
2324 itemsLimit = DEFAULT_ITEMS_LIMIT;
2330 * Identifies whether a restriction on tenant ID - to return only records
2331 * pertaining to the current tenant - is required in a JDBC query.
2333 * @param tenantBinding a tenant binding configuration.
2334 * @param ctx a service context.
2335 * @return true if a restriction on tenant ID is required in the query;
2336 * false if a restriction is not required.
2338 private boolean restrictJDBCQueryByTenantID(TenantBindingType tenantBinding, ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
2339 boolean restrict = true;
2340 // If data for the current service, in the current tenant, is isolated
2341 // within its own separate, per-tenant repository, as contrasted with
2342 // being intermingled with other tenants' data in the default repository,
2343 // no restriction on Tenant ID is required in the query.
2344 String repositoryDomainName = ConfigUtils.getRepositoryName(tenantBinding, ctx.getRepositoryDomainName());
2345 if (!(repositoryDomainName.equals(ConfigUtils.DEFAULT_NUXEO_REPOSITORY_NAME))) {
2348 // If a configuration setting for this tenant identifies that JDBC
2349 // queries should not be restricted by tenant ID (perhaps because
2350 // there is always expected to be only one tenant's data present in
2351 // the system), no restriction on Tenant ID is required in the query.
2352 String queriesRestrictedByTenantId = TenantBindingUtils.getPropertyValue(tenantBinding,
2353 IQueryManager.JDBC_QUERIES_ARE_TENANT_ID_RESTRICTED);
2354 if (Tools.notBlank(queriesRestrictedByTenantId) &&
2355 queriesRestrictedByTenantId.equalsIgnoreCase(Boolean.FALSE.toString())) {
2361 private void rollbackTransaction(CoreSessionInterface repoSession) {
2362 if (repoSession != null) {
2363 repoSession.setTransactionRollbackOnly();
2368 * Should never get called.
2371 public boolean delete(ServiceContext ctx, Object entityFound, DocumentHandler handler)
2372 throws DocumentNotFoundException, DocumentException {
2373 throw new UnsupportedOperationException();