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.Connection;
21 import java.sql.PreparedStatement;
22 import java.sql.ResultSet;
23 import java.sql.SQLException;
24 import java.sql.Statement;
25 import java.util.ArrayList;
26 import java.util.Collections;
27 import java.util.Comparator;
28 import java.util.HashSet;
29 import java.util.Hashtable;
30 import java.util.Iterator;
31 import java.util.List;
34 import java.util.UUID;
35 import javax.sql.rowset.CachedRowSet;
37 import javax.ws.rs.WebApplicationException;
38 import javax.ws.rs.core.MultivaluedMap;
40 import org.collectionspace.services.client.CollectionSpaceClient;
41 import org.collectionspace.services.client.IQueryManager;
42 import org.collectionspace.services.client.PoxPayloadIn;
43 import org.collectionspace.services.client.PoxPayloadOut;
44 import org.collectionspace.services.client.Profiler;
45 import org.collectionspace.services.client.workflow.WorkflowClient;
46 import org.collectionspace.services.common.context.ServiceContext;
47 import org.collectionspace.services.common.query.QueryContext;
48 import org.collectionspace.services.common.repository.RepositoryClient;
49 import org.collectionspace.services.common.storage.JDBCTools;
50 import org.collectionspace.services.common.storage.PreparedStatementSimpleBuilder;
51 import org.collectionspace.services.lifecycle.TransitionDef;
52 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
54 import org.collectionspace.services.common.document.BadRequestException;
55 import org.collectionspace.services.common.document.DocumentException;
56 import org.collectionspace.services.common.document.DocumentFilter;
57 import org.collectionspace.services.common.document.DocumentHandler;
58 import org.collectionspace.services.common.document.DocumentNotFoundException;
59 import org.collectionspace.services.common.document.DocumentHandler.Action;
60 import org.collectionspace.services.common.document.DocumentWrapper;
61 import org.collectionspace.services.common.document.DocumentWrapperImpl;
62 import org.collectionspace.services.common.document.TransactionException;
63 import org.collectionspace.services.config.tenant.RepositoryDomainType;
65 import org.nuxeo.common.utils.IdUtils;
66 import org.nuxeo.ecm.core.api.ClientException;
67 import org.nuxeo.ecm.core.api.DocumentModel;
68 import org.nuxeo.ecm.core.api.DocumentModelList;
69 import org.nuxeo.ecm.core.api.IterableQueryResult;
70 import org.nuxeo.ecm.core.api.VersioningOption;
71 import org.nuxeo.ecm.core.api.impl.DocumentModelListImpl;
72 import org.nuxeo.ecm.core.api.DocumentRef;
73 import org.nuxeo.ecm.core.api.IdRef;
74 import org.nuxeo.ecm.core.api.PathRef;
75 import org.nuxeo.ecm.core.api.repository.RepositoryInstance;
76 import org.nuxeo.runtime.transaction.TransactionRuntimeException;
79 // CSPACE-5036 - How to make CMISQL queries from Nuxeo
81 import org.apache.chemistry.opencmis.commons.server.CallContext;
82 import org.apache.chemistry.opencmis.server.impl.CallContextImpl;
83 import org.collectionspace.services.common.ServiceMain;
84 import org.collectionspace.services.common.api.Tools;
85 import org.collectionspace.services.common.config.ConfigUtils;
86 import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl;
87 import org.collectionspace.services.common.config.TenantBindingUtils;
88 import org.collectionspace.services.common.storage.PreparedStatementBuilder;
89 import org.collectionspace.services.config.tenant.TenantBindingType;
90 import org.nuxeo.ecm.core.opencmis.impl.server.NuxeoCmisService;
91 import org.nuxeo.ecm.core.opencmis.impl.server.NuxeoRepository;
93 import org.slf4j.Logger;
94 import org.slf4j.LoggerFactory;
97 * RepositoryJavaClient 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 RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn, PoxPayloadOut> {
109 private final Logger logger = LoggerFactory.getLogger(RepositoryJavaClientImpl.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 private static final String USER_SUPPLIED_WILDCARD = "*";
116 private static final String USER_SUPPLIED_WILDCARD_REGEX = "\\" + USER_SUPPLIED_WILDCARD;
119 * Instantiates a new repository java client impl.
121 public RepositoryJavaClientImpl() {
125 public void assertWorkflowState(ServiceContext ctx,
126 DocumentModel docModel) throws DocumentNotFoundException, ClientException {
127 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
128 if (queryParams != null) {
130 // Look for the workflow "delete" query param and see if we need to assert that the
131 // docModel is in a non-deleted workflow state.
133 String currentState = docModel.getCurrentLifeCycleState();
134 String includeDeletedStr = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_NONDELETED);
135 boolean includeDeleted = includeDeletedStr == null ? true : Boolean.parseBoolean(includeDeletedStr);
136 if (includeDeleted == false) {
138 // We don't wanted soft-deleted object, so throw an exception if this one is soft-deleted.
140 if (currentState.equalsIgnoreCase(WorkflowClient.WORKFLOWSTATE_DELETED)) {
141 String msg = "The GET assertion that docModel not be in 'deleted' workflow state failed.";
143 throw new DocumentNotFoundException(msg);
150 * create document in the Nuxeo repository
152 * @param ctx service context under which this method is invoked
153 * @param handler should be used by the caller to provide and transform the
155 * @return id in repository of the newly created document
156 * @throws BadRequestException
157 * @throws TransactionException
158 * @throws DocumentException
161 public String create(ServiceContext ctx,
162 DocumentHandler handler) throws BadRequestException,
163 TransactionException, DocumentException {
165 String docType = NuxeoUtils.getTenantQualifiedDocType(ctx); //ctx.getDocumentType();
166 if (docType == null) {
167 throw new IllegalArgumentException(
168 "RepositoryJavaClient.create: docType is missing");
171 if (handler == null) {
172 throw new IllegalArgumentException(
173 "RepositoryJavaClient.create: handler is missing");
175 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
176 if (nuxeoWspaceId == null) {
177 throw new DocumentNotFoundException(
178 "Unable to find workspace for service " + ctx.getServiceName()
179 + " check if the workspace exists in the Nuxeo repository");
182 RepositoryInstance repoSession = null;
184 handler.prepare(Action.CREATE);
185 repoSession = getRepositorySession(ctx);
186 DocumentRef nuxeoWspace = new IdRef(nuxeoWspaceId);
187 DocumentModel wspaceDoc = repoSession.getDocument(nuxeoWspace);
188 String wspacePath = wspaceDoc.getPathAsString();
189 //give our own ID so PathRef could be constructed later on
190 String id = IdUtils.generateId(UUID.randomUUID().toString());
191 // create document model
192 DocumentModel doc = repoSession.createDocumentModel(wspacePath, id, docType);
193 /* Check for a versioned document, and check In and Out before we proceed.
194 * This does not work as we do not have the uid schema on our docs.
195 if(((DocumentModelHandler) handler).supportsVersioning()) {
196 doc.setProperty("uid","major_version",1);
197 doc.setProperty("uid","minor_version",0);
200 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
201 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
202 handler.handle(Action.CREATE, wrapDoc);
203 // create document with documentmodel
204 doc = repoSession.createDocument(doc);
206 // TODO for sub-docs need to call into the handler to let it deal with subitems. Pass in the id,
207 // and assume the handler has the state it needs (doc fragments).
208 handler.complete(Action.CREATE, wrapDoc);
210 } catch (BadRequestException bre) {
212 } catch (Exception e) {
213 logger.error("Caught exception ", e);
214 throw new DocumentException(e);
216 if (repoSession != null) {
217 releaseRepositorySession(ctx, repoSession);
224 * get document from the Nuxeo repository
226 * @param ctx service context under which this method is invoked
227 * @param id of the document to retrieve
228 * @param handler should be used by the caller to provide and transform the
230 * @throws DocumentNotFoundException if the document cannot be found in the
232 * @throws TransactionException
233 * @throws DocumentException
236 public void get(ServiceContext ctx, String id, DocumentHandler handler)
237 throws DocumentNotFoundException, TransactionException, DocumentException {
239 if (handler == null) {
240 throw new IllegalArgumentException(
241 "RepositoryJavaClient.get: handler is missing");
244 RepositoryInstance repoSession = null;
246 handler.prepare(Action.GET);
247 repoSession = getRepositorySession(ctx);
248 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
249 DocumentModel docModel = null;
251 docModel = repoSession.getDocument(docRef);
252 assertWorkflowState(ctx, docModel);
253 } catch (ClientException ce) {
254 String msg = logException(ce, "Could not find document with CSID=" + id);
255 throw new DocumentNotFoundException(msg, ce);
258 // Set repository session to handle the document
260 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
261 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(docModel);
262 handler.handle(Action.GET, wrapDoc);
263 handler.complete(Action.GET, wrapDoc);
264 } catch (IllegalArgumentException iae) {
266 } catch (DocumentException de) {
268 } catch (Exception e) {
269 if (logger.isDebugEnabled()) {
270 logger.debug("Caught exception ", e);
272 throw new DocumentException(e);
274 if (repoSession != null) {
275 releaseRepositorySession(ctx, repoSession);
281 * get a document from the Nuxeo repository, using the docFilter params.
283 * @param ctx service context under which this method is invoked
284 * @param handler should be used by the caller to provide and transform the
285 * document. Handler must have a docFilter set to return a single item.
286 * @throws DocumentNotFoundException if the document cannot be found in the
288 * @throws TransactionException
289 * @throws DocumentException
292 public void get(ServiceContext ctx, DocumentHandler handler)
293 throws DocumentNotFoundException, TransactionException, DocumentException {
294 QueryContext queryContext = new QueryContext(ctx, handler);
295 RepositoryInstance repoSession = null;
298 handler.prepare(Action.GET);
299 repoSession = getRepositorySession(ctx);
301 DocumentModelList docList = null;
302 // force limit to 1, and ignore totalSize
303 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
304 docList = repoSession.query(query, null, 1, 0, false);
305 if (docList.size() != 1) {
306 throw new DocumentNotFoundException("No document found matching filter params: " + query);
308 DocumentModel doc = docList.get(0);
310 if (logger.isDebugEnabled()) {
311 logger.debug("Executed NXQL query: " + query);
314 //set reposession to handle the document
315 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
316 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
317 handler.handle(Action.GET, wrapDoc);
318 handler.complete(Action.GET, wrapDoc);
319 } catch (IllegalArgumentException iae) {
321 } catch (DocumentException de) {
323 } catch (Exception e) {
324 if (logger.isDebugEnabled()) {
325 logger.debug("Caught exception ", e);
327 throw new DocumentException(e);
329 if (repoSession != null) {
330 releaseRepositorySession(ctx, repoSession);
335 public DocumentWrapper<DocumentModel> getDoc(
336 RepositoryInstance repoSession,
337 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
338 String csid) throws DocumentNotFoundException, DocumentException {
339 DocumentWrapper<DocumentModel> wrapDoc = null;
342 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
343 DocumentModel doc = null;
345 doc = repoSession.getDocument(docRef);
346 } catch (ClientException ce) {
347 String msg = logException(ce, "Could not find document with CSID=" + csid);
348 throw new DocumentNotFoundException(msg, ce);
350 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
351 } catch (IllegalArgumentException iae) {
353 } catch (DocumentException de) {
361 * Get wrapped documentModel from the Nuxeo repository. The search is
362 * restricted to the workspace of the current context.
364 * @param ctx service context under which this method is invoked
365 * @param csid of the document to retrieve
366 * @throws DocumentNotFoundException
367 * @throws TransactionException
368 * @throws DocumentException
369 * @return a wrapped documentModel
372 public DocumentWrapper<DocumentModel> getDoc(
373 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
374 String csid) throws DocumentNotFoundException, TransactionException, DocumentException {
375 RepositoryInstance repoSession = null;
376 DocumentWrapper<DocumentModel> wrapDoc = null;
379 // Open a new repository session
380 repoSession = getRepositorySession(ctx);
381 wrapDoc = getDoc(repoSession, ctx, csid);
382 } catch (IllegalArgumentException iae) {
384 } catch (DocumentException de) {
386 } catch (Exception e) {
387 if (logger.isDebugEnabled()) {
388 logger.debug("Caught exception ", e);
390 throw new DocumentException(e);
392 if (repoSession != null) {
393 releaseRepositorySession(ctx, repoSession);
397 if (logger.isWarnEnabled() == true) {
398 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
403 public DocumentWrapper<DocumentModel> findDoc(
404 RepositoryInstance repoSession,
405 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
407 throws DocumentNotFoundException, DocumentException {
408 DocumentWrapper<DocumentModel> wrapDoc = null;
411 QueryContext queryContext = new QueryContext(ctx, whereClause);
412 DocumentModelList docList = null;
413 // force limit to 1, and ignore totalSize
414 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
415 docList = repoSession.query(query,
420 if (docList.size() != 1) {
421 if (logger.isDebugEnabled()) {
422 logger.debug("findDoc: Query found: " + docList.size() + " items.");
423 logger.debug(" Query: " + query);
425 throw new DocumentNotFoundException("No document found matching filter params: " + query);
427 DocumentModel doc = docList.get(0);
428 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
429 } catch (IllegalArgumentException iae) {
431 } catch (DocumentException de) {
433 } catch (Exception e) {
434 if (logger.isDebugEnabled()) {
435 logger.debug("Caught exception ", e);
437 throw new DocumentException(e);
444 * find wrapped documentModel from the Nuxeo repository
446 * @param ctx service context under which this method is invoked
447 * @param whereClause where NXQL where clause to get the document
448 * @throws DocumentNotFoundException
449 * @throws TransactionException
450 * @throws DocumentException
451 * @return a wrapped documentModel retrieved by the repository query
454 public DocumentWrapper<DocumentModel> findDoc(
455 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
457 throws DocumentNotFoundException, TransactionException, DocumentException {
458 RepositoryInstance repoSession = null;
459 DocumentWrapper<DocumentModel> wrapDoc = null;
462 repoSession = getRepositorySession(ctx);
463 wrapDoc = findDoc(repoSession, ctx, whereClause);
464 } catch (Exception e) {
465 throw new DocumentException("Unable to create a Nuxeo repository session.", e);
467 if (repoSession != null) {
468 releaseRepositorySession(ctx, repoSession);
472 if (logger.isWarnEnabled() == true) {
473 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
480 * find doc and return CSID from the Nuxeo repository
483 * @param ctx service context under which this method is invoked
484 * @param whereClause where NXQL where clause to get the document
485 * @throws DocumentNotFoundException
486 * @throws TransactionException
487 * @throws DocumentException
488 * @return the CollectionSpace ID (CSID) of the requested document
491 public String findDocCSID(RepositoryInstance repoSession,
492 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String whereClause)
493 throws DocumentNotFoundException, TransactionException, DocumentException {
495 boolean releaseSession = false;
497 if (repoSession == null) {
498 repoSession = this.getRepositorySession(ctx);
499 releaseSession = true;
501 DocumentWrapper<DocumentModel> wrapDoc = findDoc(repoSession, ctx, whereClause);
502 DocumentModel docModel = wrapDoc.getWrappedObject();
503 csid = NuxeoUtils.getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
504 } catch (DocumentNotFoundException dnfe) {
506 } catch (IllegalArgumentException iae) {
508 } catch (DocumentException de) {
510 } catch (Exception e) {
511 if (logger.isDebugEnabled()) {
512 logger.debug("Caught exception ", e);
514 throw new DocumentException(e);
516 if (releaseSession && (repoSession != null)) {
517 this.releaseRepositorySession(ctx, repoSession);
523 public DocumentWrapper<DocumentModelList> findDocs(
524 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
525 RepositoryInstance repoSession,
526 List<String> docTypes,
528 String orderByClause,
531 boolean computeTotal)
532 throws DocumentNotFoundException, DocumentException {
533 DocumentWrapper<DocumentModelList> wrapDoc = null;
536 if (docTypes == null || docTypes.size() < 1) {
537 throw new DocumentNotFoundException(
538 "The findDocs() method must specify at least one DocumentType.");
540 DocumentModelList docList = null;
541 QueryContext queryContext = new QueryContext(ctx, whereClause, orderByClause);
542 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
543 if (logger.isDebugEnabled()) {
544 logger.debug("findDocs() NXQL: " + query);
546 docList = repoSession.query(query, null, pageSize, pageSize * pageNum, computeTotal);
547 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
548 } catch (IllegalArgumentException iae) {
550 } catch (Exception e) {
551 if (logger.isDebugEnabled()) {
552 logger.debug("Caught exception ", e);
554 throw new DocumentException(e);
560 protected static String buildInListForDocTypes(List<String> docTypes) {
561 StringBuilder sb = new StringBuilder();
563 boolean first = true;
564 for (String docType : docTypes) {
575 return sb.toString();
578 public DocumentWrapper<DocumentModelList> findDocs(
579 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
580 DocumentHandler handler,
581 RepositoryInstance repoSession,
582 List<String> docTypes)
583 throws DocumentNotFoundException, DocumentException {
584 DocumentWrapper<DocumentModelList> wrapDoc = null;
586 DocumentFilter filter = handler.getDocumentFilter();
587 String oldOrderBy = filter.getOrderByClause();
588 if (isClauseEmpty(oldOrderBy) == true) {
589 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
591 QueryContext queryContext = new QueryContext(ctx, handler);
594 if (docTypes == null || docTypes.size() < 1) {
595 throw new DocumentNotFoundException(
596 "The findDocs() method must specify at least one DocumentType.");
598 DocumentModelList docList = null;
599 if (handler.isCMISQuery() == true) {
600 String inList = buildInListForDocTypes(docTypes);
601 ctx.getQueryParams().add(IQueryManager.SEARCH_RELATED_MATCH_OBJ_DOCTYPES, inList);
602 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
604 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
605 if (logger.isDebugEnabled()) {
606 logger.debug("findDocs() NXQL: " + query);
608 docList = repoSession.query(query, null, filter.getPageSize(), filter.getOffset(), true);
610 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
611 } catch (IllegalArgumentException iae) {
613 } catch (Exception e) {
614 if (logger.isDebugEnabled()) {
615 logger.debug("Caught exception ", e);
617 throw new DocumentException(e);
624 * Find a list of documentModels from the Nuxeo repository
626 * @param docTypes a list of DocType names to match
627 * @param whereClause where the clause to qualify on
628 * @throws DocumentNotFoundException
629 * @throws TransactionException
630 * @throws DocumentException
631 * @return a list of documentModels
634 public DocumentWrapper<DocumentModelList> findDocs(
635 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
636 List<String> docTypes,
638 int pageSize, int pageNum, boolean computeTotal)
639 throws DocumentNotFoundException, TransactionException, DocumentException {
640 RepositoryInstance repoSession = null;
641 DocumentWrapper<DocumentModelList> wrapDoc = null;
644 repoSession = getRepositorySession(ctx);
645 wrapDoc = findDocs(ctx, repoSession, docTypes, whereClause, null,
646 pageSize, pageNum, computeTotal);
647 } catch (IllegalArgumentException iae) {
649 } catch (Exception e) {
650 if (logger.isDebugEnabled()) {
651 logger.debug("Caught exception ", e);
653 throw new DocumentException(e);
655 if (repoSession != null) {
656 releaseRepositorySession(ctx, repoSession);
660 if (logger.isWarnEnabled() == true) {
661 logger.warn("Returned DocumentModelList instance was created with a repository session that is now closed.");
668 * @see org.collectionspace.services.common.storage.StorageClient#get(org.collectionspace.services.common.context.ServiceContext, java.util.List, org.collectionspace.services.common.document.DocumentHandler)
671 public void get(ServiceContext ctx, List<String> csidList, DocumentHandler handler)
672 throws DocumentNotFoundException, TransactionException, DocumentException {
673 if (handler == null) {
674 throw new IllegalArgumentException(
675 "RepositoryJavaClient.getAll: handler is missing");
678 RepositoryInstance repoSession = null;
680 handler.prepare(Action.GET_ALL);
681 repoSession = getRepositorySession(ctx);
682 DocumentModelList docModelList = new DocumentModelListImpl();
683 //FIXME: Should be using NuxeoUtils.createPathRef for security reasons
684 for (String csid : csidList) {
685 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
686 DocumentModel docModel = repoSession.getDocument(docRef);
687 docModelList.add(docModel);
690 //set reposession to handle the document
691 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
692 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docModelList);
693 handler.handle(Action.GET_ALL, wrapDoc);
694 handler.complete(Action.GET_ALL, wrapDoc);
695 } catch (DocumentException de) {
697 } catch (Exception e) {
698 if (logger.isDebugEnabled()) {
699 logger.debug("Caught exception ", e);
701 throw new DocumentException(e);
703 if (repoSession != null) {
704 releaseRepositorySession(ctx, repoSession);
710 * getAll get all documents for an entity entity service from the Nuxeo
713 * @param ctx service context under which this method is invoked
714 * @param handler should be used by the caller to provide and transform the
716 * @throws DocumentNotFoundException
717 * @throws TransactionException
718 * @throws DocumentException
721 public void getAll(ServiceContext ctx, DocumentHandler handler)
722 throws DocumentNotFoundException, TransactionException, DocumentException {
723 if (handler == null) {
724 throw new IllegalArgumentException(
725 "RepositoryJavaClient.getAll: handler is missing");
727 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
728 if (nuxeoWspaceId == null) {
729 throw new DocumentNotFoundException(
730 "Unable to find workspace for service "
731 + ctx.getServiceName()
732 + " check if the workspace exists in the Nuxeo repository.");
735 RepositoryInstance repoSession = null;
737 handler.prepare(Action.GET_ALL);
738 repoSession = getRepositorySession(ctx);
739 DocumentRef wsDocRef = new IdRef(nuxeoWspaceId);
740 DocumentModelList docList = repoSession.getChildren(wsDocRef);
741 //set reposession to handle the document
742 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
743 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
744 handler.handle(Action.GET_ALL, wrapDoc);
745 handler.complete(Action.GET_ALL, wrapDoc);
746 } catch (DocumentException de) {
748 } catch (Exception e) {
749 if (logger.isDebugEnabled()) {
750 logger.debug("Caught exception ", e);
752 throw new DocumentException(e);
754 if (repoSession != null) {
755 releaseRepositorySession(ctx, repoSession);
760 private boolean isClauseEmpty(String theString) {
761 boolean result = true;
762 if (theString != null && !theString.isEmpty()) {
768 public DocumentWrapper<DocumentModel> getDocFromCsid(
769 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
770 RepositoryInstance repoSession,
773 DocumentWrapper<DocumentModel> result = null;
775 result = new DocumentWrapperImpl(NuxeoUtils.getDocFromCsid(ctx, repoSession, csid));
781 * A method to find a CollectionSpace document (of any type) given just a service context and
782 * its CSID. A search across *all* service workspaces (within a given tenant context) is performed to find
785 * This query searches Nuxeo's Hierarchy table where our CSIDs are stored in the "name" column.
788 public DocumentWrapper<DocumentModel> getDocFromCsid(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
791 DocumentWrapper<DocumentModel> result = null;
792 RepositoryInstance repoSession = null;
794 repoSession = getRepositorySession(ctx);
795 result = getDocFromCsid(ctx, repoSession, csid);
797 if (repoSession != null) {
798 releaseRepositorySession(ctx, repoSession);
802 if (logger.isWarnEnabled() == true) {
803 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
810 * Returns a URI value for a document in the Nuxeo repository
812 * @param wrappedDoc a wrapped documentModel
813 * @throws ClientException
814 * @return a document URI
817 public String getDocURI(DocumentWrapper<DocumentModel> wrappedDoc) throws ClientException {
818 DocumentModel docModel = wrappedDoc.getWrappedObject();
819 String uri = (String) docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
820 CollectionSpaceClient.COLLECTIONSPACE_CORE_URI);
825 * See CSPACE-5036 - How to make CMISQL queries from Nuxeo
827 private IterableQueryResult makeCMISQLQuery(RepositoryInstance repoSession, String query, QueryContext queryContext) {
828 IterableQueryResult result = null;
830 // the NuxeoRepository should be constructed only once, then cached
831 // (its construction is expensive)
833 NuxeoRepository repo = new NuxeoRepository(
834 repoSession.getRepositoryName(), repoSession
835 .getRootDocument().getId());
836 logger.debug("Repository ID:" + repo.getId() + " Root folder:"
837 + repo.getRootFolderId());
839 CallContextImpl callContext = new CallContextImpl(
840 CallContext.BINDING_LOCAL, repo.getId(), false);
841 callContext.put(CallContext.USERNAME, repoSession.getPrincipal()
843 NuxeoCmisService cmisService = new NuxeoCmisService(repo,
844 callContext, repoSession);
846 result = repoSession.queryAndFetch(query, "CMISQL", cmisService);
847 } catch (ClientException e) {
848 // TODO Auto-generated catch block
849 logger.error("Encounter trouble making the following CMIS query: " + query, e);
856 * getFiltered get all documents for an entity service from the Document
857 * repository, given filter parameters specified by the handler.
859 * @param ctx service context under which this method is invoked
860 * @param handler should be used by the caller to provide and transform the
862 * @throws DocumentNotFoundException if workspace not found
863 * @throws TransactionException
864 * @throws DocumentException
867 public void getFiltered(ServiceContext ctx, DocumentHandler handler)
868 throws DocumentNotFoundException, TransactionException, DocumentException {
870 DocumentFilter filter = handler.getDocumentFilter();
871 String oldOrderBy = filter.getOrderByClause();
872 if (isClauseEmpty(oldOrderBy) == true) {
873 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
875 QueryContext queryContext = new QueryContext(ctx, handler);
877 RepositoryInstance repoSession = null;
879 handler.prepare(Action.GET_ALL);
880 repoSession = getRepositorySession(ctx); //Keeps a refcount here for the repository session so you need to release this when finished
882 DocumentModelList docList = null;
883 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
885 if (logger.isDebugEnabled()) {
886 logger.debug("Executing NXQL query: " + query.toString());
889 // If we have limit and/or offset, then pass true to get totalSize
890 // in returned DocumentModelList.
891 Profiler profiler = new Profiler(this, 2);
892 profiler.log("Executing NXQL query: " + query.toString());
894 if (handler.isJDBCQuery() == true) {
895 docList = getFilteredJDBC(repoSession, ctx, handler);
896 } else if (handler.isCMISQuery() == true) {
897 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext); //FIXME: REM - Need to deal with paging info in CMIS query
898 } else if ((queryContext.getDocFilter().getOffset() > 0) || (queryContext.getDocFilter().getPageSize() > 0)) {
899 docList = repoSession.query(query, null,
900 queryContext.getDocFilter().getPageSize(), queryContext.getDocFilter().getOffset(), true);
902 docList = repoSession.query(query);
906 //set repoSession to handle the document
907 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
908 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
909 handler.handle(Action.GET_ALL, wrapDoc);
910 handler.complete(Action.GET_ALL, wrapDoc);
911 } catch (DocumentException de) {
913 } catch (Exception e) {
914 if (logger.isDebugEnabled()) {
915 logger.debug("Caught exception ", e);
917 throw new DocumentException(e);
919 if (repoSession != null) {
920 releaseRepositorySession(ctx, repoSession);
926 * Perform a database query, via JDBC and SQL, to retrieve matching records
927 * based on filter criteria.
929 * Although this method currently has a general-purpose name, it is
930 * currently dedicated to a specific task: improving performance for
931 * partial term matching queries on authority items / terms, via
932 * the use of a hand-tuned SQL query, rather than the generated SQL
933 * produced by Nuxeo from an NXQL query.
935 * @param repoSession a repository session.
936 * @param ctx the service context.
937 * @param handler a relevant document handler.
938 * @return a list of document models matching the search criteria.
941 private DocumentModelList getFilteredJDBC(RepositoryInstance repoSession, ServiceContext ctx,
942 DocumentHandler handler) throws Exception {
943 DocumentModelList result = new DocumentModelListImpl();
945 // FIXME: Get all of the following values from appropriate external constants.
947 // At present, the two constants below are duplicated in both RepositoryJavaClientImpl
948 // and in AuthorityItemDocumentModelHandler.
949 final String TERM_GROUP_LIST_NAME = "TERM_GROUP_LIST_NAME";
950 final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
951 final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
952 // Get this from a constant in AuthorityResource or equivalent
953 final String PARENT_WILDCARD = "_ALL_";
955 // Build two SQL statements, to be executed within a single transaction:
956 // the first statement to control join order, and the second statement
957 // representing the actual 'get filtered' query
959 // Build the join control statement
961 // Per http://www.postgresql.org/docs/9.2/static/runtime-config-query.html#GUC-JOIN-COLLAPSE-LIMIT
962 // "Setting [this value] to 1 prevents any reordering of explicit JOINs.
963 // Thus, the explicit join order specified in the query will be the
964 // actual order in which the relations are joined."
965 // See CSPACE-5945 for further discussion of why this setting is needed.
967 // Adding this statement is commented out here for now. It significantly
968 // improved query performance for authority item / term queries where
969 // large numbers of rows were retrieved, but appears to have resulted
970 // in consistently slower-than-desired query performance where zero or
971 // very few records were retrieved. See notes on CSPACE-5945. - ADR 2013-04-09
972 // String joinControlSql = "SET LOCAL join_collapse_limit TO 1;";
974 // Build the query statement
976 // Start with the default query
977 String selectStatement =
978 "SELECT DISTINCT commonschema.id"
979 + " FROM " + handler.getServiceContext().getCommonPartLabel() + " commonschema";
983 + " ON misc.id = commonschema.id"
984 + " INNER JOIN hierarchy hierarchy_termgroup"
985 + " ON hierarchy_termgroup.parentid = misc.id"
986 + " INNER JOIN " + handler.getJDBCQueryParams().get(TERM_GROUP_TABLE_NAME_PARAM) + " termgroup"
987 + " ON termgroup.id = hierarchy_termgroup.id ";
990 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
991 // Value for replaceable parameter 1 in the query
992 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
993 // If the value of the partial term query parameter is blank ('pt='),
994 // return all records, subject to restriction by any limit clause
995 if (Tools.isBlank(partialTerm)) {
998 // Otherwise, return records that match the supplied partial term
1000 " WHERE (termgroup.termdisplayname ILIKE ?)";
1003 // At present, results are ordered in code, below, rather than in SQL,
1004 // and the orderByClause below is thus intentionally blank.
1006 // To implement the orderByClause below in SQL; e.g. via
1007 // 'ORDER BY termgroup.termdisplayname', the relevant column
1008 // must be returned by the SELECT statement.
1009 String orderByClause = "";
1012 TenantBindingConfigReaderImpl tReader =
1013 ServiceMain.getInstance().getTenantBindingConfigReader();
1014 TenantBindingType tenantBinding = tReader.getTenantBinding(ctx.getTenantId());
1015 String maxListItemsLimit = TenantBindingUtils.getPropertyValue(tenantBinding,
1016 IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES);
1018 " LIMIT " + getMaxItemsLimitOnJdbcQueries(maxListItemsLimit); // implicit int-to-String conversion
1020 List<String> params = new ArrayList<>();
1022 // Read tenant bindings configuration to determine whether
1023 // to automatically insert leading, as well as trailing, wildcards
1024 // into the term matching string.
1025 String usesStartingWildcard = TenantBindingUtils.getPropertyValue(tenantBinding,
1026 IQueryManager.TENANT_USES_STARTING_WILDCARD_FOR_PARTIAL_TERM);
1027 // Handle user-provided leading wildcard characters, in the
1028 // configuration where a leading wildcard is not automatically inserted.
1029 // (The user-provided wildcard must be in the first, or "starting"
1030 // character position in the partial term value.)
1031 if (Tools.notBlank(usesStartingWildcard) && usesStartingWildcard.equalsIgnoreCase(Boolean.FALSE.toString())) {
1032 partialTerm = handleProvidedStartingWildcard(partialTerm);
1033 // Otherwise, automatically insert a leading wildcard
1035 partialTerm = JDBCTools.SQL_WILDCARD + partialTerm;
1037 // Add SQL wildcards in the midst of the partial term match search
1038 // expression, whever user-supplied wildcards appear, except in the
1039 // first or last character positions of the search expression.
1040 partialTerm = subtituteWildcardsInPartialTerm(partialTerm);
1042 // FIXME: We may wish to handle instances where a designated 'stop
1043 // character' has been inserted by the user as the last character in
1044 // the search expression, whereupon we would strip that stop character
1045 // and skip the automatic adding of a trailing wildcard, below.
1047 // Automatically add a trailing wildcard
1048 params.add(partialTerm + JDBCTools.SQL_WILDCARD);
1050 // Optionally add restrictions to the default query, based on variables
1051 // in the current request
1053 // Restrict the query to filter out deleted records, if requested
1054 String includeDeleted = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_NONDELETED);
1055 if (includeDeleted != null && includeDeleted.equalsIgnoreCase(Boolean.FALSE.toString())) {
1056 whereClause = whereClause
1057 + " AND (misc.lifecyclestate <> '" + WorkflowClient.WORKFLOWSTATE_DELETED + "')";
1060 // If a particular authority is specified, restrict the query further
1061 // to return only records within that authority
1062 String inAuthorityValue = (String) handler.getJDBCQueryParams().get(IN_AUTHORITY_PARAM);
1063 if (Tools.notBlank(inAuthorityValue)) {
1064 // Handle the '_ALL_' case for inAuthority
1065 if (inAuthorityValue.equals(PARENT_WILDCARD)) {
1066 // Add nothing to the query here if it should match within all authorities
1068 whereClause = whereClause
1069 + " AND (commonschema.inauthority = ?)";
1070 params.add(inAuthorityValue); // Value for replaceable parameter 2 in the query
1074 // Restrict the query further to return only records pertaining to
1075 // the current tenant, unless:
1076 // * Data for this service, in this tenant, is stored in its own,
1077 // separate repository, rather than being intermingled with other
1078 // tenants' data in the default repository; or
1079 // * Restriction by tenant ID in JDBC queries has been disabled,
1080 // via configuration for this tenant,
1081 if (restrictJDBCQueryByTenantID(tenantBinding, ctx)) {
1082 joinClauses = joinClauses
1083 + " INNER JOIN collectionspace_core core"
1084 + " ON core.id = hierarchy_termgroup.parentid";
1085 whereClause = whereClause
1086 + " AND (core.tenantid = ?)";
1087 params.add(ctx.getTenantId()); // Value for replaceable parameter 3 in the query
1090 // Piece together the SQL query from its parts
1091 String querySql = selectStatement + joinClauses + whereClause + orderByClause + limitClause;
1093 // Note: PostgreSQL 9.2 introduced a change that may improve performance
1094 // of certain queries using JDBC PreparedStatements. See comments on
1095 // CSPACE-5943 for details.
1097 // See a comment above for the reason that the joinControl SQL statement,
1098 // along with its corresponding prepared statement builder, is commented out for now.
1099 // PreparedStatementBuilder joinControlBuilder = new PreparedStatementBuilder(joinControlSql);
1100 PreparedStatementSimpleBuilder queryBuilder = new PreparedStatementSimpleBuilder(querySql, params);
1101 List<PreparedStatementBuilder> builders = new ArrayList<>();
1102 // builders.add(joinControlBuilder);
1103 builders.add(queryBuilder);
1104 String dataSourceName = JDBCTools.NUXEO_DATASOURCE_NAME;
1105 String repositoryName = ctx.getRepositoryName();
1106 final Boolean EXECUTE_WITHIN_TRANSACTION = true;
1107 Set<String> docIds = new HashSet<>();
1109 List<CachedRowSet> resultsList = JDBCTools.executePreparedQueries(builders,
1110 dataSourceName, repositoryName, EXECUTE_WITHIN_TRANSACTION);
1112 // At least one set of results is expected, from the second prepared
1113 // statement to be executed.
1114 // If fewer results are returned, return an empty list of document models
1115 if (resultsList == null || resultsList.size() < 1) {
1116 return result; // return an empty list of document models
1118 // The join control query (if enabled - it is currently commented
1119 // out as per comments above) will not return results, so query results
1120 // will be the first set of results (rowSet) returned in the list
1121 CachedRowSet queryResults = resultsList.get(0);
1123 // If the result from executing the query is null or contains zero rows,
1124 // return an empty list of document models
1125 if (queryResults == null) {
1126 return result; // return an empty list of document models
1128 queryResults.last();
1129 if (queryResults.getRow() == 0) {
1130 return result; // return an empty list of document models
1133 // Otherwise, get the document IDs from the results of the query
1135 queryResults.beforeFirst();
1136 while (queryResults.next()) {
1137 id = queryResults.getString(1);
1138 if (Tools.notBlank(id)) {
1142 } catch (SQLException sqle) {
1143 logger.warn("Could not obtain document IDs via SQL query '" + querySql + "': " + sqle.getMessage());
1144 return result; // return an empty list of document models
1147 // Get a list of document models, using the IDs obtained from the query
1148 DocumentModel docModel;
1149 for (String docId : docIds) {
1150 docModel = NuxeoUtils.getDocumentModel(repoSession, docId);
1151 if (docModel == null) {
1152 logger.warn("Could not obtain document model for document with ID " + docId);
1154 result.add(NuxeoUtils.getDocumentModel(repoSession, docId));
1158 // Order the results
1159 final String COMMON_PART_SCHEMA = handler.getServiceContext().getCommonPartLabel();
1160 final String DISPLAY_NAME_XPATH =
1161 "//" + handler.getJDBCQueryParams().get(TERM_GROUP_LIST_NAME) + "/[0]/termDisplayName";
1162 Collections.sort(result, new Comparator<DocumentModel>() {
1164 public int compare(DocumentModel doc1, DocumentModel doc2) {
1165 String termDisplayName1 = (String) NuxeoUtils.getXPathValue(doc1, COMMON_PART_SCHEMA, DISPLAY_NAME_XPATH);
1166 String termDisplayName2 = (String) NuxeoUtils.getXPathValue(doc2, COMMON_PART_SCHEMA, DISPLAY_NAME_XPATH);
1167 return termDisplayName1.compareToIgnoreCase(termDisplayName2);
1175 private DocumentModelList getFilteredCMIS(RepositoryInstance repoSession, ServiceContext ctx, DocumentHandler handler, QueryContext queryContext)
1176 throws DocumentNotFoundException, DocumentException {
1178 DocumentModelList result = new DocumentModelListImpl();
1180 String query = handler.getCMISQuery(queryContext);
1182 DocumentFilter docFilter = handler.getDocumentFilter();
1183 int pageSize = docFilter.getPageSize();
1184 int offset = docFilter.getOffset();
1185 if (logger.isDebugEnabled()) {
1186 logger.debug("Executing CMIS query: " + query.toString()
1187 + "with pageSize: " + pageSize + " at offset: " + offset);
1190 // If we have limit and/or offset, then pass true to get totalSize
1191 // in returned DocumentModelList.
1192 Profiler profiler = new Profiler(this, 2);
1193 profiler.log("Executing CMIS query: " + query.toString());
1196 IterableQueryResult queryResult = makeCMISQLQuery(repoSession, query, queryContext);
1198 int totalSize = (int) queryResult.size();
1199 ((DocumentModelListImpl) result).setTotalSize(totalSize);
1200 // Skip the rows before our offset
1202 queryResult.skipTo(offset);
1205 for (Map<String, Serializable> row : queryResult) {
1206 if (logger.isTraceEnabled()) {
1207 logger.trace(" Hierarchy Table ID is:" + row.get(IQueryManager.CMIS_TARGET_NUXEO_ID)
1208 + " nuxeo:pathSegment is: " + row.get(IQueryManager.CMIS_TARGET_NAME));
1210 String nuxeoId = (String) row.get(IQueryManager.CMIS_TARGET_NUXEO_ID);
1211 DocumentModel docModel = NuxeoUtils.getDocumentModel(repoSession, nuxeoId);
1212 result.add(docModel);
1214 if (nRows >= pageSize && pageSize != 0) { // A page size of zero means that they want all of them
1215 logger.debug("Got page full of items - quitting");
1220 queryResult.close();
1225 } catch (Exception e) {
1226 if (logger.isDebugEnabled()) {
1227 logger.debug("Caught exception ", e);
1229 throw new DocumentException(e);
1233 // Since we're not supporting paging yet for CMIS queries, we need to perform
1234 // a workaround for the paging information we return in our list of results
1237 if (result != null) {
1238 docFilter.setStartPage(0);
1239 if (totalSize > docFilter.getPageSize()) {
1240 docFilter.setPageSize(totalSize);
1241 ((DocumentModelListImpl)result).setTotalSize(totalSize);
1249 private String logException(Exception e, String msg) {
1250 String result = null;
1252 String exceptionMessage = e.getMessage();
1253 exceptionMessage = exceptionMessage != null ? exceptionMessage : "<No details provided>";
1254 result = msg = msg + ". Caught exception:" + exceptionMessage;
1256 if (logger.isTraceEnabled() == true) {
1257 logger.error(msg, e);
1266 * update given document in the Nuxeo repository
1268 * @param ctx service context under which this method is invoked
1269 * @param csid of the document
1270 * @param handler should be used by the caller to provide and transform the
1272 * @throws BadRequestException
1273 * @throws DocumentNotFoundException
1274 * @throws TransactionException if the transaction times out or otherwise
1275 * cannot be successfully completed
1276 * @throws DocumentException
1279 public void update(ServiceContext ctx, String csid, DocumentHandler handler)
1280 throws BadRequestException, DocumentNotFoundException, TransactionException,
1282 if (handler == null) {
1283 throw new IllegalArgumentException(
1284 "RepositoryJavaClient.update: document handler is missing.");
1287 RepositoryInstance repoSession = null;
1289 handler.prepare(Action.UPDATE);
1290 repoSession = getRepositorySession(ctx);
1291 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
1292 DocumentModel doc = null;
1294 doc = repoSession.getDocument(docRef);
1295 } catch (ClientException ce) {
1296 String msg = logException(ce, "Could not find document to update with CSID=" + csid);
1297 throw new DocumentNotFoundException(msg, ce);
1299 // Check for a versioned document, and check In and Out before we proceed.
1300 if (((DocumentModelHandler) handler).supportsVersioning()) {
1301 /* Once we advance to 5.5 or later, we can add this.
1302 * See also https://jira.nuxeo.com/browse/NXP-8506
1303 if(!doc.isVersionable()) {
1304 throw new DocumentException("Configuration for: "
1305 +handler.getServiceContextPath()+" supports versioning, but Nuxeo config does not!");
1308 /* Force a version number - Not working. Apparently we need to configure the uid schema??
1309 if(doc.getProperty("uid","major_version") == null) {
1310 doc.setProperty("uid","major_version",1);
1312 if(doc.getProperty("uid","minor_version") == null) {
1313 doc.setProperty("uid","minor_version",0);
1316 doc.checkIn(VersioningOption.MINOR, null);
1321 // Set reposession to handle the document
1323 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1324 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
1325 handler.handle(Action.UPDATE, wrapDoc);
1326 repoSession.saveDocument(doc);
1328 handler.complete(Action.UPDATE, wrapDoc);
1329 } catch (BadRequestException bre) {
1331 } catch (DocumentException de) {
1333 } catch (WebApplicationException wae) {
1335 } catch (Exception e) {
1336 if (logger.isDebugEnabled()) {
1337 logger.debug("Caught exception ", e);
1339 throw new DocumentException(e);
1341 if (repoSession != null) {
1342 releaseRepositorySession(ctx, repoSession);
1348 * Save a documentModel to the Nuxeo repository.
1350 * @param ctx service context under which this method is invoked
1351 * @param repoSession
1352 * @param docModel the document to save
1353 * @param fSaveSession if TRUE, will call CoreSession.save() to save
1354 * accumulated changes.
1355 * @throws ClientException
1356 * @throws DocumentException
1358 public void saveDocWithoutHandlerProcessing(
1359 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1360 RepositoryInstance repoSession,
1361 DocumentModel docModel,
1362 boolean fSaveSession)
1363 throws ClientException, DocumentException {
1366 repoSession.saveDocument(docModel);
1370 } catch (ClientException ce) {
1372 } catch (Exception e) {
1373 if (logger.isDebugEnabled()) {
1374 logger.debug("Caught exception ", e);
1376 throw new DocumentException(e);
1381 * Save a list of documentModels to the Nuxeo repository.
1383 * @param ctx service context under which this method is invoked
1384 * @param repoSession a repository session
1385 * @param docModelList a list of document models
1386 * @param fSaveSession if TRUE, will call CoreSession.save() to save
1387 * accumulated changes.
1388 * @throws ClientException
1389 * @throws DocumentException
1391 public void saveDocListWithoutHandlerProcessing(
1392 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1393 RepositoryInstance repoSession,
1394 DocumentModelList docList,
1395 boolean fSaveSession)
1396 throws ClientException, DocumentException {
1398 DocumentModel[] docModelArray = new DocumentModel[docList.size()];
1399 repoSession.saveDocuments(docList.toArray(docModelArray));
1403 } catch (ClientException ce) {
1405 } catch (Exception e) {
1406 logger.error("Caught exception ", e);
1407 throw new DocumentException(e);
1412 * delete a document from the Nuxeo repository
1414 * @param ctx service context under which this method is invoked
1415 * @param id of the document
1416 * @throws DocumentException
1419 public void delete(ServiceContext ctx, String id, DocumentHandler handler) throws DocumentNotFoundException,
1420 DocumentException, TransactionException {
1422 throw new IllegalArgumentException(
1423 "delete(ctx, ix, handler): ctx is missing");
1425 if (handler == null) {
1426 throw new IllegalArgumentException(
1427 "delete(ctx, ix, handler): handler is missing");
1429 if (logger.isDebugEnabled()) {
1430 logger.debug("Deleting document with CSID=" + id);
1432 RepositoryInstance repoSession = null;
1434 handler.prepare(Action.DELETE);
1435 repoSession = getRepositorySession(ctx);
1436 DocumentWrapper<DocumentModel> wrapDoc = null;
1438 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
1439 wrapDoc = new DocumentWrapperImpl<DocumentModel>(repoSession.getDocument(docRef));
1440 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1441 handler.handle(Action.DELETE, wrapDoc);
1442 repoSession.removeDocument(docRef);
1443 } catch (ClientException ce) {
1444 String msg = logException(ce, "Could not find document to delete with CSID=" + id);
1445 throw new DocumentNotFoundException(msg, ce);
1448 handler.complete(Action.DELETE, wrapDoc);
1449 } catch (DocumentException de) {
1451 } catch (Exception e) {
1452 if (logger.isDebugEnabled()) {
1453 logger.debug("Caught exception ", e);
1455 throw new DocumentException(e);
1457 if (repoSession != null) {
1458 releaseRepositorySession(ctx, repoSession);
1464 * @see org.collectionspace.services.common.storage.StorageClient#delete(org.collectionspace.services.common.context.ServiceContext, java.lang.String, org.collectionspace.services.common.document.DocumentHandler)
1468 public void delete(@SuppressWarnings("rawtypes") ServiceContext ctx, String id)
1469 throws DocumentNotFoundException, DocumentException {
1470 throw new UnsupportedOperationException();
1471 // Use the other delete instead
1475 public Hashtable<String, String> retrieveWorkspaceIds(RepositoryDomainType repoDomain) throws Exception {
1476 return NuxeoConnectorEmbedded.getInstance().retrieveWorkspaceIds(repoDomain);
1480 public String createDomain(RepositoryDomainType repositoryDomain) throws Exception {
1481 RepositoryInstance repoSession = null;
1482 String domainId = null;
1485 // Open a connection to the domain's repo/db
1487 String repoName = repositoryDomain.getRepositoryName();
1488 repoSession = getRepositorySession(repoName); // domainName=storageName=repoName=databaseName
1490 // First create the top-level domain directory
1492 String domainName = repositoryDomain.getStorageName();
1493 DocumentRef parentDocRef = new PathRef("/");
1494 DocumentModel parentDoc = repoSession.getDocument(parentDocRef);
1495 DocumentModel domainDoc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1496 domainName, NUXEO_CORE_TYPE_DOMAIN);
1497 domainDoc.setPropertyValue("dc:title", domainName);
1498 domainDoc.setPropertyValue("dc:description", "A CollectionSpace domain "
1500 domainDoc = repoSession.createDocument(domainDoc);
1501 domainId = domainDoc.getId();
1504 // Next, create a "Workspaces" root directory to contain the workspace folders for the individual service documents
1506 DocumentModel workspacesRoot = repoSession.createDocumentModel(domainDoc.getPathAsString(),
1507 NuxeoUtils.Workspaces, NUXEO_CORE_TYPE_WORKSPACEROOT);
1508 workspacesRoot.setPropertyValue("dc:title", NuxeoUtils.Workspaces);
1509 workspacesRoot.setPropertyValue("dc:description", "A CollectionSpace workspaces directory for "
1510 + domainDoc.getPathAsString());
1511 workspacesRoot = repoSession.createDocument(workspacesRoot);
1512 String workspacesRootId = workspacesRoot.getId();
1515 if (logger.isDebugEnabled()) {
1516 logger.debug("Created tenant domain name=" + domainName
1517 + " id=" + domainId + " "
1518 + NuxeoUtils.Workspaces + " id=" + workspacesRootId);
1519 logger.debug("Path to Domain: " + domainDoc.getPathAsString());
1520 logger.debug("Path to Workspaces root: " + workspacesRoot.getPathAsString());
1522 } catch (Exception e) {
1523 if (logger.isDebugEnabled()) {
1524 logger.debug("Could not create tenant domain name=" + repositoryDomain.getStorageName() + " caught exception ", e);
1528 if (repoSession != null) {
1529 releaseRepositorySession(null, repoSession);
1537 public String getDomainId(RepositoryDomainType repositoryDomain) throws Exception {
1538 String domainId = null;
1539 RepositoryInstance repoSession = null;
1541 String repoName = repositoryDomain.getRepositoryName();
1542 String domainStorageName = repositoryDomain.getStorageName();
1543 if (domainStorageName != null && !domainStorageName.isEmpty()) {
1545 repoSession = getRepositorySession(repoName);
1546 DocumentRef docRef = new PathRef("/" + domainStorageName);
1547 DocumentModel domain = repoSession.getDocument(docRef);
1548 domainId = domain.getId();
1549 } catch (Exception e) {
1550 if (logger.isTraceEnabled()) {
1551 logger.trace("Caught exception ", e); // The document doesn't exist, this let's us know we need to create it
1553 //there is no way to identify if document does not exist due to
1554 //lack of typed exception for getDocument method
1557 if (repoSession != null) {
1558 releaseRepositorySession(null, repoSession);
1567 * Returns the workspaces root directory for a given domain.
1569 private DocumentModel getWorkspacesRoot(RepositoryInstance repoSession,
1570 String domainName) throws Exception {
1571 DocumentModel result = null;
1573 String domainPath = "/" + domainName;
1574 DocumentRef parentDocRef = new PathRef(domainPath);
1575 DocumentModelList domainChildrenList = repoSession.getChildren(
1577 Iterator<DocumentModel> witer = domainChildrenList.iterator();
1578 while (witer.hasNext()) {
1579 DocumentModel childNode = witer.next();
1580 if (NuxeoUtils.Workspaces.equalsIgnoreCase(childNode.getName())) {
1582 logger.trace("Found workspaces directory at: " + result.getPathAsString());
1587 if (result == null) {
1588 throw new ClientException("Could not find workspace root directory in: "
1596 * @see org.collectionspace.services.common.repository.RepositoryClient#createWorkspace(java.lang.String, java.lang.String)
1599 public String createWorkspace(RepositoryDomainType repositoryDomain, String workspaceName) throws Exception {
1600 RepositoryInstance repoSession = null;
1601 String workspaceId = null;
1603 String repoName = repositoryDomain.getRepositoryName();
1604 repoSession = getRepositorySession(repoName);
1606 String domainStorageName = repositoryDomain.getStorageName();
1607 DocumentModel parentDoc = getWorkspacesRoot(repoSession, domainStorageName);
1608 if (logger.isTraceEnabled()) {
1609 for (String facet : parentDoc.getFacets()) {
1610 logger.trace("Facet: " + facet);
1614 DocumentModel doc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1615 workspaceName, NuxeoUtils.WORKSPACE_DOCUMENT_TYPE);
1616 doc.setPropertyValue("dc:title", workspaceName);
1617 doc.setPropertyValue("dc:description", "A CollectionSpace workspace for "
1619 doc = repoSession.createDocument(doc);
1620 workspaceId = doc.getId();
1622 if (logger.isDebugEnabled()) {
1623 logger.debug("Created workspace name=" + workspaceName
1624 + " id=" + workspaceId);
1626 } catch (Exception e) {
1627 if (logger.isDebugEnabled()) {
1628 logger.debug("createWorkspace caught exception ", e);
1632 if (repoSession != null) {
1633 releaseRepositorySession(null, repoSession);
1640 * @see org.collectionspace.services.common.repository.RepositoryClient#getWorkspaceId(java.lang.String, java.lang.String)
1644 public String getWorkspaceId(String tenantDomain, String workspaceName) throws Exception {
1645 String workspaceId = null;
1647 RepositoryInstance repoSession = null;
1649 repoSession = getRepositorySession((ServiceContext) null);
1650 DocumentRef docRef = new PathRef(
1652 + "/" + NuxeoUtils.Workspaces
1653 + "/" + workspaceName);
1654 DocumentModel workspace = repoSession.getDocument(docRef);
1655 workspaceId = workspace.getId();
1656 } catch (DocumentException de) {
1658 } catch (Exception e) {
1659 if (logger.isDebugEnabled()) {
1660 logger.debug("Caught exception ", e);
1662 throw new DocumentException(e);
1664 if (repoSession != null) {
1665 releaseRepositorySession(null, repoSession);
1672 public RepositoryInstance getRepositorySession(ServiceContext ctx) throws Exception {
1673 return getRepositorySession(ctx, ctx.getRepositoryName());
1676 public RepositoryInstance getRepositorySession(String repoName) throws Exception {
1677 return getRepositorySession(null, repoName);
1681 * Gets the repository session. - Package access only. If the 'ctx' param is
1682 * null then the repo name must be non-mull and vice-versa
1684 * @return the repository session
1685 * @throws Exception the exception
1687 public RepositoryInstance getRepositorySession(ServiceContext ctx, String repoName) throws Exception {
1688 RepositoryInstance repoSession = null;
1690 Profiler profiler = new Profiler("getRepositorySession():", 2);
1693 // To get a connection to the Nuxeo repo, we need either a valid ServiceContext instance or a repository name
1696 repoName = ctx.getRepositoryName(); // Notice we are overriding the passed in 'repoName' since we have a valid service context passed in to us
1697 repoSession = (RepositoryInstance) ctx.getCurrentRepositorySession(); // Look to see if one exists in the context before creating one
1698 } else if (repoName == null || repoName.trim().isEmpty()) {
1699 String errMsg = String.format("We can't get a connection to the Nuxeo repo because the service context passed in was null and no repository name was passed in either.");
1700 logger.error(errMsg);
1701 throw new Exception(errMsg);
1704 // 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
1705 // just the repo name
1707 if (repoSession == null) {
1708 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1709 repoSession = client.openRepository(repoName);
1711 if (logger.isDebugEnabled() == true) {
1712 logger.warn("Reusing the current context's repository session.");
1716 if (logger.isTraceEnabled()) {
1717 logger.trace("Testing call to getRepository() repository root: " + repoSession.getRootDocument());
1723 ctx.setCurrentRepositorySession(repoSession); // For reusing, save the repository session in the current service context
1730 * Release repository session. - Package access only.
1732 * @param repoSession the repo session
1734 public void releaseRepositorySession(ServiceContext ctx, RepositoryInstance repoSession) throws TransactionException {
1736 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1739 ctx.clearCurrentRepositorySession(); //clear the current context of the now closed repo session
1740 if (ctx.getCurrentRepositorySession() == null) {
1741 client.releaseRepository(repoSession); //release the repo session if the service context's ref count is zeo.
1744 client.releaseRepository(repoSession); //repo session was acquired without a service context
1746 } catch (TransactionRuntimeException tre) {
1747 TransactionException te = new TransactionException(tre);
1748 logger.error(te.getMessage(), tre); // Log the standard transaction exception message, plus an exception-specific stack trace
1750 } catch (Exception e) {
1751 logger.error("Could not close the repository session", e);
1752 // no need to throw this service specific exception
1757 public void doWorkflowTransition(ServiceContext ctx, String id,
1758 DocumentHandler handler, TransitionDef transitionDef)
1759 throws BadRequestException, DocumentNotFoundException,
1761 // 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
1764 private String handleProvidedStartingWildcard(String partialTerm) {
1765 if (Tools.notBlank(partialTerm)) {
1766 if (partialTerm.substring(0, 1).equals(USER_SUPPLIED_WILDCARD)) {
1767 StringBuffer buffer = new StringBuffer(partialTerm);
1768 buffer.setCharAt(0, JDBCTools.SQL_WILDCARD.charAt(0));
1769 partialTerm = buffer.toString();
1776 * Replaces user-supplied wildcards with SQL wildcards, in a partial term
1777 * matching search expression.
1779 * The scope of this replacement excludes the beginning and ending
1780 * characters in that search expression, as those are treated specially.
1782 * @param partialTerm
1783 * @return the partial term, with any user-supplied wildcards replaced
1786 private String subtituteWildcardsInPartialTerm(String partialTerm) {
1787 if (Tools.isBlank(partialTerm)) {
1790 if (! partialTerm.contains(USER_SUPPLIED_WILDCARD)) {
1793 int len = partialTerm.length();
1794 // Partial term search expressions of 2 or fewer characters
1795 // currently aren't amenable to the use of wildcards
1797 logger.warn("Partial term match search expression of just 1-2 characters in length contains a user-supplied wildcard: " + partialTerm);
1798 logger.warn("Will handle that character as a literal value, rather than as a wildcard ...");
1801 int lastCharPos = len - 1;
1802 return partialTerm.substring(0, 1) // first char
1803 + partialTerm.substring(1, lastCharPos).replaceAll(USER_SUPPLIED_WILDCARD_REGEX, JDBCTools.SQL_WILDCARD) // middle of search expression, excluding first and last
1804 + partialTerm.substring(lastCharPos); // last char
1808 private int getMaxItemsLimitOnJdbcQueries(String maxListItemsLimit) {
1809 final int DEFAULT_ITEMS_LIMIT = 40;
1810 if (maxListItemsLimit == null) {
1811 return DEFAULT_ITEMS_LIMIT;
1815 itemsLimit = Integer.parseInt(maxListItemsLimit);
1816 if (itemsLimit < 1) {
1817 logger.warn("Value of configuration setting "
1818 + IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES
1819 + " must be a positive integer; invalid current value is " + maxListItemsLimit);
1820 logger.warn("Reverting to default value of " + DEFAULT_ITEMS_LIMIT);
1821 itemsLimit = DEFAULT_ITEMS_LIMIT;
1823 } catch (NumberFormatException nfe) {
1824 logger.warn("Value of configuration setting "
1825 + IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES
1826 + " must be a positive integer; invalid current value is " + maxListItemsLimit);
1827 logger.warn("Reverting to default value of " + DEFAULT_ITEMS_LIMIT);
1828 itemsLimit = DEFAULT_ITEMS_LIMIT;
1834 * Identifies whether a restriction on tenant ID - to return only records
1835 * pertaining to the current tenant - is required in a JDBC query.
1837 * @param tenantBinding a tenant binding configuration.
1838 * @param ctx a service context.
1839 * @return true if a restriction on tenant ID is required in the query;
1840 * false if a restriction is not required.
1842 private boolean restrictJDBCQueryByTenantID(TenantBindingType tenantBinding, ServiceContext ctx) {
1843 boolean restrict = true;
1844 // If data for the current service, in the current tenant, is isolated
1845 // within its own separate, per-tenant repository, as contrasted with
1846 // being intermingled with other tenants' data in the default repository,
1847 // no restriction on Tenant ID is required in the query.
1848 String repositoryDomainName = ConfigUtils.getRepositoryName(tenantBinding, ctx.getRepositoryDomainName());
1849 if (!(repositoryDomainName.equals(ConfigUtils.DEFAULT_NUXEO_REPOSITORY_NAME))) {
1852 // If a configuration setting for this tenant identifies that JDBC
1853 // queries should not be restricted by tenant ID (perhaps because
1854 // there is always expected to be only one tenant's data present in
1855 // the system), no restriction on Tenant ID is required in the query.
1856 String queriesRestrictedByTenantId = TenantBindingUtils.getPropertyValue(tenantBinding,
1857 IQueryManager.JDBC_QUERIES_ARE_TENANT_ID_RESTRICTED);
1858 if (Tools.notBlank(queriesRestrictedByTenantId) &&
1859 queriesRestrictedByTenantId.equalsIgnoreCase(Boolean.FALSE.toString())) {