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;
117 private static final String USER_SUPPLIED_STOP_CHAR = "|";
121 * Instantiates a new repository java client impl.
123 public RepositoryJavaClientImpl() {
127 public void assertWorkflowState(ServiceContext ctx,
128 DocumentModel docModel) throws DocumentNotFoundException, ClientException {
129 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
130 if (queryParams != null) {
132 // Look for the workflow "delete" query param and see if we need to assert that the
133 // docModel is in a non-deleted workflow state.
135 String currentState = docModel.getCurrentLifeCycleState();
136 String includeDeletedStr = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_NONDELETED);
137 boolean includeDeleted = includeDeletedStr == null ? true : Boolean.parseBoolean(includeDeletedStr);
138 if (includeDeleted == false) {
140 // We don't wanted soft-deleted object, so throw an exception if this one is soft-deleted.
142 if (currentState.equalsIgnoreCase(WorkflowClient.WORKFLOWSTATE_DELETED)) {
143 String msg = "The GET assertion that docModel not be in 'deleted' workflow state failed.";
145 throw new DocumentNotFoundException(msg);
152 * create document in the Nuxeo repository
154 * @param ctx service context under which this method is invoked
155 * @param handler should be used by the caller to provide and transform the
157 * @return id in repository of the newly created document
158 * @throws BadRequestException
159 * @throws TransactionException
160 * @throws DocumentException
163 public String create(ServiceContext ctx,
164 DocumentHandler handler) throws BadRequestException,
165 TransactionException, DocumentException {
167 String docType = NuxeoUtils.getTenantQualifiedDocType(ctx); //ctx.getDocumentType();
168 if (docType == null) {
169 throw new IllegalArgumentException(
170 "RepositoryJavaClient.create: docType is missing");
173 if (handler == null) {
174 throw new IllegalArgumentException(
175 "RepositoryJavaClient.create: handler is missing");
177 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
178 if (nuxeoWspaceId == null) {
179 throw new DocumentNotFoundException(
180 "Unable to find workspace for service " + ctx.getServiceName()
181 + " check if the workspace exists in the Nuxeo repository");
184 RepositoryInstance repoSession = null;
186 handler.prepare(Action.CREATE);
187 repoSession = getRepositorySession(ctx);
188 DocumentRef nuxeoWspace = new IdRef(nuxeoWspaceId);
189 DocumentModel wspaceDoc = repoSession.getDocument(nuxeoWspace);
190 String wspacePath = wspaceDoc.getPathAsString();
191 //give our own ID so PathRef could be constructed later on
192 String id = IdUtils.generateId(UUID.randomUUID().toString());
193 // create document model
194 DocumentModel doc = repoSession.createDocumentModel(wspacePath, id, docType);
195 /* Check for a versioned document, and check In and Out before we proceed.
196 * This does not work as we do not have the uid schema on our docs.
197 if(((DocumentModelHandler) handler).supportsVersioning()) {
198 doc.setProperty("uid","major_version",1);
199 doc.setProperty("uid","minor_version",0);
202 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
203 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
204 handler.handle(Action.CREATE, wrapDoc);
205 // create document with documentmodel
206 doc = repoSession.createDocument(doc);
208 // TODO for sub-docs need to call into the handler to let it deal with subitems. Pass in the id,
209 // and assume the handler has the state it needs (doc fragments).
210 handler.complete(Action.CREATE, wrapDoc);
212 } catch (BadRequestException bre) {
214 } catch (Exception e) {
215 logger.error("Caught exception ", e);
216 throw new DocumentException(e);
218 if (repoSession != null) {
219 releaseRepositorySession(ctx, repoSession);
226 * get document from the Nuxeo repository
228 * @param ctx service context under which this method is invoked
229 * @param id of the document to retrieve
230 * @param handler should be used by the caller to provide and transform the
232 * @throws DocumentNotFoundException if the document cannot be found in the
234 * @throws TransactionException
235 * @throws DocumentException
238 public void get(ServiceContext ctx, String id, DocumentHandler handler)
239 throws DocumentNotFoundException, TransactionException, DocumentException {
241 if (handler == null) {
242 throw new IllegalArgumentException(
243 "RepositoryJavaClient.get: handler is missing");
246 RepositoryInstance repoSession = null;
248 handler.prepare(Action.GET);
249 repoSession = getRepositorySession(ctx);
250 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
251 DocumentModel docModel = null;
253 docModel = repoSession.getDocument(docRef);
254 assertWorkflowState(ctx, docModel);
255 } catch (ClientException ce) {
256 String msg = logException(ce, "Could not find document with CSID=" + id);
257 throw new DocumentNotFoundException(msg, ce);
260 // Set repository session to handle the document
262 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
263 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(docModel);
264 handler.handle(Action.GET, wrapDoc);
265 handler.complete(Action.GET, wrapDoc);
266 } catch (IllegalArgumentException iae) {
268 } catch (DocumentException de) {
270 } catch (Exception e) {
271 if (logger.isDebugEnabled()) {
272 logger.debug("Caught exception ", e);
274 throw new DocumentException(e);
276 if (repoSession != null) {
277 releaseRepositorySession(ctx, repoSession);
283 * get a document from the Nuxeo repository, using the docFilter params.
285 * @param ctx service context under which this method is invoked
286 * @param handler should be used by the caller to provide and transform the
287 * document. Handler must have a docFilter set to return a single item.
288 * @throws DocumentNotFoundException if the document cannot be found in the
290 * @throws TransactionException
291 * @throws DocumentException
294 public void get(ServiceContext ctx, DocumentHandler handler)
295 throws DocumentNotFoundException, TransactionException, DocumentException {
296 QueryContext queryContext = new QueryContext(ctx, handler);
297 RepositoryInstance repoSession = null;
300 handler.prepare(Action.GET);
301 repoSession = getRepositorySession(ctx);
303 DocumentModelList docList = null;
304 // force limit to 1, and ignore totalSize
305 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
306 docList = repoSession.query(query, null, 1, 0, false);
307 if (docList.size() != 1) {
308 throw new DocumentNotFoundException("No document found matching filter params: " + query);
310 DocumentModel doc = docList.get(0);
312 if (logger.isDebugEnabled()) {
313 logger.debug("Executed NXQL query: " + query);
316 //set reposession to handle the document
317 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
318 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
319 handler.handle(Action.GET, wrapDoc);
320 handler.complete(Action.GET, wrapDoc);
321 } catch (IllegalArgumentException iae) {
323 } catch (DocumentException de) {
325 } catch (Exception e) {
326 if (logger.isDebugEnabled()) {
327 logger.debug("Caught exception ", e);
329 throw new DocumentException(e);
331 if (repoSession != null) {
332 releaseRepositorySession(ctx, repoSession);
337 public DocumentWrapper<DocumentModel> getDoc(
338 RepositoryInstance repoSession,
339 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
340 String csid) throws DocumentNotFoundException, DocumentException {
341 DocumentWrapper<DocumentModel> wrapDoc = null;
344 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
345 DocumentModel doc = null;
347 doc = repoSession.getDocument(docRef);
348 } catch (ClientException ce) {
349 String msg = logException(ce, "Could not find document with CSID=" + csid);
350 throw new DocumentNotFoundException(msg, ce);
352 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
353 } catch (IllegalArgumentException iae) {
355 } catch (DocumentException de) {
363 * Get wrapped documentModel from the Nuxeo repository. The search is
364 * restricted to the workspace of the current context.
366 * @param ctx service context under which this method is invoked
367 * @param csid of the document to retrieve
368 * @throws DocumentNotFoundException
369 * @throws TransactionException
370 * @throws DocumentException
371 * @return a wrapped documentModel
374 public DocumentWrapper<DocumentModel> getDoc(
375 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
376 String csid) throws DocumentNotFoundException, TransactionException, DocumentException {
377 RepositoryInstance repoSession = null;
378 DocumentWrapper<DocumentModel> wrapDoc = null;
381 // Open a new repository session
382 repoSession = getRepositorySession(ctx);
383 wrapDoc = getDoc(repoSession, ctx, csid);
384 } catch (IllegalArgumentException iae) {
386 } catch (DocumentException de) {
388 } catch (Exception e) {
389 if (logger.isDebugEnabled()) {
390 logger.debug("Caught exception ", e);
392 throw new DocumentException(e);
394 if (repoSession != null) {
395 releaseRepositorySession(ctx, repoSession);
399 if (logger.isWarnEnabled() == true) {
400 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
405 public DocumentWrapper<DocumentModel> findDoc(
406 RepositoryInstance repoSession,
407 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
409 throws DocumentNotFoundException, DocumentException {
410 DocumentWrapper<DocumentModel> wrapDoc = null;
413 QueryContext queryContext = new QueryContext(ctx, whereClause);
414 DocumentModelList docList = null;
415 // force limit to 1, and ignore totalSize
416 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
417 docList = repoSession.query(query,
422 if (docList.size() != 1) {
423 if (logger.isDebugEnabled()) {
424 logger.debug("findDoc: Query found: " + docList.size() + " items.");
425 logger.debug(" Query: " + query);
427 throw new DocumentNotFoundException("No document found matching filter params: " + query);
429 DocumentModel doc = docList.get(0);
430 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
431 } catch (IllegalArgumentException iae) {
433 } catch (DocumentException de) {
435 } catch (Exception e) {
436 if (logger.isDebugEnabled()) {
437 logger.debug("Caught exception ", e);
439 throw new DocumentException(e);
446 * find wrapped documentModel from the Nuxeo repository
448 * @param ctx service context under which this method is invoked
449 * @param whereClause where NXQL where clause to get the document
450 * @throws DocumentNotFoundException
451 * @throws TransactionException
452 * @throws DocumentException
453 * @return a wrapped documentModel retrieved by the repository query
456 public DocumentWrapper<DocumentModel> findDoc(
457 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
459 throws DocumentNotFoundException, TransactionException, DocumentException {
460 RepositoryInstance repoSession = null;
461 DocumentWrapper<DocumentModel> wrapDoc = null;
464 repoSession = getRepositorySession(ctx);
465 wrapDoc = findDoc(repoSession, ctx, whereClause);
466 } catch (Exception e) {
467 throw new DocumentException("Unable to create a Nuxeo repository session.", e);
469 if (repoSession != null) {
470 releaseRepositorySession(ctx, repoSession);
474 if (logger.isWarnEnabled() == true) {
475 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
482 * find doc and return CSID from the Nuxeo repository
485 * @param ctx service context under which this method is invoked
486 * @param whereClause where NXQL where clause to get the document
487 * @throws DocumentNotFoundException
488 * @throws TransactionException
489 * @throws DocumentException
490 * @return the CollectionSpace ID (CSID) of the requested document
493 public String findDocCSID(RepositoryInstance repoSession,
494 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String whereClause)
495 throws DocumentNotFoundException, TransactionException, DocumentException {
497 boolean releaseSession = false;
499 if (repoSession == null) {
500 repoSession = this.getRepositorySession(ctx);
501 releaseSession = true;
503 DocumentWrapper<DocumentModel> wrapDoc = findDoc(repoSession, ctx, whereClause);
504 DocumentModel docModel = wrapDoc.getWrappedObject();
505 csid = NuxeoUtils.getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
506 } catch (DocumentNotFoundException dnfe) {
508 } catch (IllegalArgumentException iae) {
510 } catch (DocumentException de) {
512 } catch (Exception e) {
513 if (logger.isDebugEnabled()) {
514 logger.debug("Caught exception ", e);
516 throw new DocumentException(e);
518 if (releaseSession && (repoSession != null)) {
519 this.releaseRepositorySession(ctx, repoSession);
525 public DocumentWrapper<DocumentModelList> findDocs(
526 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
527 RepositoryInstance repoSession,
528 List<String> docTypes,
530 String orderByClause,
533 boolean computeTotal)
534 throws DocumentNotFoundException, DocumentException {
535 DocumentWrapper<DocumentModelList> wrapDoc = null;
538 if (docTypes == null || docTypes.size() < 1) {
539 throw new DocumentNotFoundException(
540 "The findDocs() method must specify at least one DocumentType.");
542 DocumentModelList docList = null;
543 QueryContext queryContext = new QueryContext(ctx, whereClause, orderByClause);
544 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
545 if (logger.isDebugEnabled()) {
546 logger.debug("findDocs() NXQL: " + query);
548 docList = repoSession.query(query, null, pageSize, pageSize * pageNum, computeTotal);
549 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
550 } catch (IllegalArgumentException iae) {
552 } catch (Exception e) {
553 if (logger.isDebugEnabled()) {
554 logger.debug("Caught exception ", e);
556 throw new DocumentException(e);
562 protected static String buildInListForDocTypes(List<String> docTypes) {
563 StringBuilder sb = new StringBuilder();
565 boolean first = true;
566 for (String docType : docTypes) {
577 return sb.toString();
580 public DocumentWrapper<DocumentModelList> findDocs(
581 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
582 DocumentHandler handler,
583 RepositoryInstance repoSession,
584 List<String> docTypes)
585 throws DocumentNotFoundException, DocumentException {
586 DocumentWrapper<DocumentModelList> wrapDoc = null;
588 DocumentFilter filter = handler.getDocumentFilter();
589 String oldOrderBy = filter.getOrderByClause();
590 if (isClauseEmpty(oldOrderBy) == true) {
591 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
593 QueryContext queryContext = new QueryContext(ctx, handler);
596 if (docTypes == null || docTypes.size() < 1) {
597 throw new DocumentNotFoundException(
598 "The findDocs() method must specify at least one DocumentType.");
600 DocumentModelList docList = null;
601 if (handler.isCMISQuery() == true) {
602 String inList = buildInListForDocTypes(docTypes);
603 ctx.getQueryParams().add(IQueryManager.SEARCH_RELATED_MATCH_OBJ_DOCTYPES, inList);
604 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
606 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
607 if (logger.isDebugEnabled()) {
608 logger.debug("findDocs() NXQL: " + query);
610 docList = repoSession.query(query, null, filter.getPageSize(), filter.getOffset(), true);
612 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
613 } catch (IllegalArgumentException iae) {
615 } catch (Exception e) {
616 if (logger.isDebugEnabled()) {
617 logger.debug("Caught exception ", e);
619 throw new DocumentException(e);
626 * Find a list of documentModels from the Nuxeo repository
628 * @param docTypes a list of DocType names to match
629 * @param whereClause where the clause to qualify on
630 * @throws DocumentNotFoundException
631 * @throws TransactionException
632 * @throws DocumentException
633 * @return a list of documentModels
636 public DocumentWrapper<DocumentModelList> findDocs(
637 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
638 List<String> docTypes,
640 int pageSize, int pageNum, boolean computeTotal)
641 throws DocumentNotFoundException, TransactionException, DocumentException {
642 RepositoryInstance repoSession = null;
643 DocumentWrapper<DocumentModelList> wrapDoc = null;
646 repoSession = getRepositorySession(ctx);
647 wrapDoc = findDocs(ctx, repoSession, docTypes, whereClause, null,
648 pageSize, pageNum, computeTotal);
649 } catch (IllegalArgumentException iae) {
651 } catch (Exception e) {
652 if (logger.isDebugEnabled()) {
653 logger.debug("Caught exception ", e);
655 throw new DocumentException(e);
657 if (repoSession != null) {
658 releaseRepositorySession(ctx, repoSession);
662 if (logger.isWarnEnabled() == true) {
663 logger.warn("Returned DocumentModelList instance was created with a repository session that is now closed.");
670 * @see org.collectionspace.services.common.storage.StorageClient#get(org.collectionspace.services.common.context.ServiceContext, java.util.List, org.collectionspace.services.common.document.DocumentHandler)
673 public void get(ServiceContext ctx, List<String> csidList, DocumentHandler handler)
674 throws DocumentNotFoundException, TransactionException, DocumentException {
675 if (handler == null) {
676 throw new IllegalArgumentException(
677 "RepositoryJavaClient.getAll: handler is missing");
680 RepositoryInstance repoSession = null;
682 handler.prepare(Action.GET_ALL);
683 repoSession = getRepositorySession(ctx);
684 DocumentModelList docModelList = new DocumentModelListImpl();
685 //FIXME: Should be using NuxeoUtils.createPathRef for security reasons
686 for (String csid : csidList) {
687 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
688 DocumentModel docModel = repoSession.getDocument(docRef);
689 docModelList.add(docModel);
692 //set reposession to handle the document
693 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
694 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docModelList);
695 handler.handle(Action.GET_ALL, wrapDoc);
696 handler.complete(Action.GET_ALL, wrapDoc);
697 } catch (DocumentException de) {
699 } catch (Exception e) {
700 if (logger.isDebugEnabled()) {
701 logger.debug("Caught exception ", e);
703 throw new DocumentException(e);
705 if (repoSession != null) {
706 releaseRepositorySession(ctx, repoSession);
712 * getAll get all documents for an entity entity service from the Nuxeo
715 * @param ctx service context under which this method is invoked
716 * @param handler should be used by the caller to provide and transform the
718 * @throws DocumentNotFoundException
719 * @throws TransactionException
720 * @throws DocumentException
723 public void getAll(ServiceContext ctx, DocumentHandler handler)
724 throws DocumentNotFoundException, TransactionException, DocumentException {
725 if (handler == null) {
726 throw new IllegalArgumentException(
727 "RepositoryJavaClient.getAll: handler is missing");
729 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
730 if (nuxeoWspaceId == null) {
731 throw new DocumentNotFoundException(
732 "Unable to find workspace for service "
733 + ctx.getServiceName()
734 + " check if the workspace exists in the Nuxeo repository.");
737 RepositoryInstance repoSession = null;
739 handler.prepare(Action.GET_ALL);
740 repoSession = getRepositorySession(ctx);
741 DocumentRef wsDocRef = new IdRef(nuxeoWspaceId);
742 DocumentModelList docList = repoSession.getChildren(wsDocRef);
743 //set reposession to handle the document
744 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
745 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
746 handler.handle(Action.GET_ALL, wrapDoc);
747 handler.complete(Action.GET_ALL, wrapDoc);
748 } catch (DocumentException de) {
750 } catch (Exception e) {
751 if (logger.isDebugEnabled()) {
752 logger.debug("Caught exception ", e);
754 throw new DocumentException(e);
756 if (repoSession != null) {
757 releaseRepositorySession(ctx, repoSession);
762 private boolean isClauseEmpty(String theString) {
763 boolean result = true;
764 if (theString != null && !theString.isEmpty()) {
770 public DocumentWrapper<DocumentModel> getDocFromCsid(
771 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
772 RepositoryInstance repoSession,
775 DocumentWrapper<DocumentModel> result = null;
777 result = new DocumentWrapperImpl(NuxeoUtils.getDocFromCsid(ctx, repoSession, csid));
783 * A method to find a CollectionSpace document (of any type) given just a service context and
784 * its CSID. A search across *all* service workspaces (within a given tenant context) is performed to find
787 * This query searches Nuxeo's Hierarchy table where our CSIDs are stored in the "name" column.
790 public DocumentWrapper<DocumentModel> getDocFromCsid(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
793 DocumentWrapper<DocumentModel> result = null;
794 RepositoryInstance repoSession = null;
796 repoSession = getRepositorySession(ctx);
797 result = getDocFromCsid(ctx, repoSession, csid);
799 if (repoSession != null) {
800 releaseRepositorySession(ctx, repoSession);
804 if (logger.isWarnEnabled() == true) {
805 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
812 * Returns a URI value for a document in the Nuxeo repository
814 * @param wrappedDoc a wrapped documentModel
815 * @throws ClientException
816 * @return a document URI
819 public String getDocURI(DocumentWrapper<DocumentModel> wrappedDoc) throws ClientException {
820 DocumentModel docModel = wrappedDoc.getWrappedObject();
821 String uri = (String) docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
822 CollectionSpaceClient.COLLECTIONSPACE_CORE_URI);
827 * See CSPACE-5036 - How to make CMISQL queries from Nuxeo
829 private IterableQueryResult makeCMISQLQuery(RepositoryInstance repoSession, String query, QueryContext queryContext) {
830 IterableQueryResult result = null;
832 // the NuxeoRepository should be constructed only once, then cached
833 // (its construction is expensive)
835 NuxeoRepository repo = new NuxeoRepository(
836 repoSession.getRepositoryName(), repoSession
837 .getRootDocument().getId());
838 logger.debug("Repository ID:" + repo.getId() + " Root folder:"
839 + repo.getRootFolderId());
841 CallContextImpl callContext = new CallContextImpl(
842 CallContext.BINDING_LOCAL, repo.getId(), false);
843 callContext.put(CallContext.USERNAME, repoSession.getPrincipal()
845 NuxeoCmisService cmisService = new NuxeoCmisService(repo,
846 callContext, repoSession);
848 result = repoSession.queryAndFetch(query, "CMISQL", cmisService);
849 } catch (ClientException e) {
850 // TODO Auto-generated catch block
851 logger.error("Encounter trouble making the following CMIS query: " + query, e);
858 * getFiltered get all documents for an entity service from the Document
859 * repository, given filter parameters specified by the handler.
861 * @param ctx service context under which this method is invoked
862 * @param handler should be used by the caller to provide and transform the
864 * @throws DocumentNotFoundException if workspace not found
865 * @throws TransactionException
866 * @throws DocumentException
869 public void getFiltered(ServiceContext ctx, DocumentHandler handler)
870 throws DocumentNotFoundException, TransactionException, DocumentException {
872 DocumentFilter filter = handler.getDocumentFilter();
873 String oldOrderBy = filter.getOrderByClause();
874 if (isClauseEmpty(oldOrderBy) == true) {
875 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
877 QueryContext queryContext = new QueryContext(ctx, handler);
879 RepositoryInstance repoSession = null;
881 handler.prepare(Action.GET_ALL);
882 repoSession = getRepositorySession(ctx); //Keeps a refcount here for the repository session so you need to release this when finished
884 DocumentModelList docList = null;
885 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
887 if (logger.isDebugEnabled()) {
888 logger.debug("Executing NXQL query: " + query.toString());
891 // If we have limit and/or offset, then pass true to get totalSize
892 // in returned DocumentModelList.
893 Profiler profiler = new Profiler(this, 2);
894 profiler.log("Executing NXQL query: " + query.toString());
896 if (handler.isJDBCQuery() == true) {
897 docList = getFilteredJDBC(repoSession, ctx, handler);
898 } else if (handler.isCMISQuery() == true) {
899 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext); //FIXME: REM - Need to deal with paging info in CMIS query
900 } else if ((queryContext.getDocFilter().getOffset() > 0) || (queryContext.getDocFilter().getPageSize() > 0)) {
901 docList = repoSession.query(query, null,
902 queryContext.getDocFilter().getPageSize(), queryContext.getDocFilter().getOffset(), true);
904 docList = repoSession.query(query);
908 //set repoSession to handle the document
909 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
910 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
911 handler.handle(Action.GET_ALL, wrapDoc);
912 handler.complete(Action.GET_ALL, wrapDoc);
913 } catch (DocumentException de) {
915 } catch (Exception e) {
916 if (logger.isDebugEnabled()) {
917 logger.debug("Caught exception ", e);
919 throw new DocumentException(e);
921 if (repoSession != null) {
922 releaseRepositorySession(ctx, repoSession);
928 * Perform a database query, via JDBC and SQL, to retrieve matching records
929 * based on filter criteria.
931 * Although this method currently has a general-purpose name, it is
932 * currently dedicated to a specific task: improving performance for
933 * partial term matching queries on authority items / terms, via
934 * the use of a hand-tuned SQL query, rather than the generated SQL
935 * produced by Nuxeo from an NXQL query.
937 * @param repoSession a repository session.
938 * @param ctx the service context.
939 * @param handler a relevant document handler.
940 * @return a list of document models matching the search criteria.
943 private DocumentModelList getFilteredJDBC(RepositoryInstance repoSession, ServiceContext ctx,
944 DocumentHandler handler) throws Exception {
945 DocumentModelList result = new DocumentModelListImpl();
947 // FIXME: Get all of the following values from appropriate external constants.
949 // At present, the two constants below are duplicated in both RepositoryJavaClientImpl
950 // and in AuthorityItemDocumentModelHandler.
951 final String TERM_GROUP_LIST_NAME = "TERM_GROUP_LIST_NAME";
952 final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
953 final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
954 // Get this from a constant in AuthorityResource or equivalent
955 final String PARENT_WILDCARD = "_ALL_";
957 // Build two SQL statements, to be executed within a single transaction:
958 // the first statement to control join order, and the second statement
959 // representing the actual 'get filtered' query
961 // Build the join control statement
963 // Per http://www.postgresql.org/docs/9.2/static/runtime-config-query.html#GUC-JOIN-COLLAPSE-LIMIT
964 // "Setting [this value] to 1 prevents any reordering of explicit JOINs.
965 // Thus, the explicit join order specified in the query will be the
966 // actual order in which the relations are joined."
967 // See CSPACE-5945 for further discussion of why this setting is needed.
969 // Adding this statement is commented out here for now. It significantly
970 // improved query performance for authority item / term queries where
971 // large numbers of rows were retrieved, but appears to have resulted
972 // in consistently slower-than-desired query performance where zero or
973 // very few records were retrieved. See notes on CSPACE-5945. - ADR 2013-04-09
974 // String joinControlSql = "SET LOCAL join_collapse_limit TO 1;";
976 // Build the query statement
978 // Start with the default query
979 String selectStatement =
980 "SELECT DISTINCT commonschema.id"
981 + " FROM " + handler.getServiceContext().getCommonPartLabel() + " commonschema";
985 + " ON misc.id = commonschema.id"
986 + " INNER JOIN hierarchy hierarchy_termgroup"
987 + " ON hierarchy_termgroup.parentid = misc.id"
988 + " INNER JOIN " + handler.getJDBCQueryParams().get(TERM_GROUP_TABLE_NAME_PARAM) + " termgroup"
989 + " ON termgroup.id = hierarchy_termgroup.id ";
992 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
993 // Value for replaceable parameter 1 in the query
994 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
995 // If the value of the partial term query parameter is blank ('pt='),
996 // return all records, subject to restriction by any limit clause
997 if (Tools.isBlank(partialTerm)) {
1000 // Otherwise, return records that match the supplied partial term
1002 " WHERE (termgroup.termdisplayname ILIKE ?)";
1005 // At present, results are ordered in code, below, rather than in SQL,
1006 // and the orderByClause below is thus intentionally blank.
1008 // To implement the orderByClause below in SQL; e.g. via
1009 // 'ORDER BY termgroup.termdisplayname', the relevant column
1010 // must be returned by the SELECT statement.
1011 String orderByClause = "";
1014 TenantBindingConfigReaderImpl tReader =
1015 ServiceMain.getInstance().getTenantBindingConfigReader();
1016 TenantBindingType tenantBinding = tReader.getTenantBinding(ctx.getTenantId());
1017 String maxListItemsLimit = TenantBindingUtils.getPropertyValue(tenantBinding,
1018 IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES);
1020 " LIMIT " + getMaxItemsLimitOnJdbcQueries(maxListItemsLimit); // implicit int-to-String conversion
1022 // After building the individual parts of the query, set the values
1023 // of replaceable parameters that will be inserted into that query
1024 // and optionally add restrictions
1026 List<String> params = new ArrayList<>();
1028 if (Tools.notBlank(whereClause)) {
1030 // Read tenant bindings configuration to determine whether
1031 // to automatically insert leading, as well as trailing, wildcards
1032 // into the term matching string.
1033 String usesStartingWildcard = TenantBindingUtils.getPropertyValue(tenantBinding,
1034 IQueryManager.TENANT_USES_STARTING_WILDCARD_FOR_PARTIAL_TERM);
1035 // Handle user-provided leading wildcard characters, in the
1036 // configuration where a leading wildcard is not automatically inserted.
1037 // (The user-provided wildcard must be in the first, or "starting"
1038 // character position in the partial term value.)
1039 if (Tools.notBlank(usesStartingWildcard) && usesStartingWildcard.equalsIgnoreCase(Boolean.FALSE.toString())) {
1040 partialTerm = handleProvidedStartingWildcard(partialTerm);
1041 // Otherwise, automatically insert a leading wildcard
1043 partialTerm = JDBCTools.SQL_WILDCARD + partialTerm;
1045 // Add SQL wildcards in the midst of the partial term match search
1046 // expression, whever user-supplied wildcards appear, except in the
1047 // first or last character positions of the search expression.
1048 partialTerm = subtituteWildcardsInPartialTerm(partialTerm);
1050 // If a designated 'stop character' is present as the last character
1051 // in the search expression, strip that character and don't add
1052 // a trailing wildcard
1053 int lastCharPos = partialTerm.length() - 1;
1054 if (partialTerm.endsWith(USER_SUPPLIED_STOP_CHAR) && lastCharPos > 0) {
1055 partialTerm = partialTerm.substring(0, lastCharPos);
1057 // Otherwise, automatically add a trailing wildcard
1058 partialTerm = partialTerm + JDBCTools.SQL_WILDCARD;
1060 params.add(partialTerm);
1063 // Optionally add restrictions to the default query, based on variables
1064 // in the current request
1066 // Restrict the query to filter out deleted records, if requested
1067 String includeDeleted = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_NONDELETED);
1068 if (includeDeleted != null && includeDeleted.equalsIgnoreCase(Boolean.FALSE.toString())) {
1069 whereClause = whereClause
1070 + " AND (misc.lifecyclestate <> '" + WorkflowClient.WORKFLOWSTATE_DELETED + "')";
1073 // If a particular authority is specified, restrict the query further
1074 // to return only records within that authority
1075 String inAuthorityValue = (String) handler.getJDBCQueryParams().get(IN_AUTHORITY_PARAM);
1076 if (Tools.notBlank(inAuthorityValue)) {
1077 // Handle the '_ALL_' case for inAuthority
1078 if (inAuthorityValue.equals(PARENT_WILDCARD)) {
1079 // Add nothing to the query here if it should match within all authorities
1081 whereClause = whereClause
1082 + " AND (commonschema.inauthority = ?)";
1083 params.add(inAuthorityValue); // Value for replaceable parameter 2 in the query
1087 // Restrict the query further to return only records pertaining to
1088 // the current tenant, unless:
1089 // * Data for this service, in this tenant, is stored in its own,
1090 // separate repository, rather than being intermingled with other
1091 // tenants' data in the default repository; or
1092 // * Restriction by tenant ID in JDBC queries has been disabled,
1093 // via configuration for this tenant,
1094 if (restrictJDBCQueryByTenantID(tenantBinding, ctx)) {
1095 joinClauses = joinClauses
1096 + " INNER JOIN collectionspace_core core"
1097 + " ON core.id = hierarchy_termgroup.parentid";
1098 whereClause = whereClause
1099 + " AND (core.tenantid = ?)";
1100 params.add(ctx.getTenantId()); // Value for replaceable parameter 3 in the query
1103 // Piece together the SQL query from its parts
1104 String querySql = selectStatement + joinClauses + whereClause + orderByClause + limitClause;
1106 // Note: PostgreSQL 9.2 introduced a change that may improve performance
1107 // of certain queries using JDBC PreparedStatements. See comments on
1108 // CSPACE-5943 for details.
1110 // See a comment above for the reason that the joinControl SQL statement,
1111 // along with its corresponding prepared statement builder, is commented out for now.
1112 // PreparedStatementBuilder joinControlBuilder = new PreparedStatementBuilder(joinControlSql);
1113 PreparedStatementSimpleBuilder queryBuilder = new PreparedStatementSimpleBuilder(querySql, params);
1114 List<PreparedStatementBuilder> builders = new ArrayList<>();
1115 // builders.add(joinControlBuilder);
1116 builders.add(queryBuilder);
1117 String dataSourceName = JDBCTools.NUXEO_DATASOURCE_NAME;
1118 String repositoryName = ctx.getRepositoryName();
1119 final Boolean EXECUTE_WITHIN_TRANSACTION = true;
1120 Set<String> docIds = new HashSet<>();
1122 List<CachedRowSet> resultsList = JDBCTools.executePreparedQueries(builders,
1123 dataSourceName, repositoryName, EXECUTE_WITHIN_TRANSACTION);
1125 // At least one set of results is expected, from the second prepared
1126 // statement to be executed.
1127 // If fewer results are returned, return an empty list of document models
1128 if (resultsList == null || resultsList.size() < 1) {
1129 return result; // return an empty list of document models
1131 // The join control query (if enabled - it is currently commented
1132 // out as per comments above) will not return results, so query results
1133 // will be the first set of results (rowSet) returned in the list
1134 CachedRowSet queryResults = resultsList.get(0);
1136 // If the result from executing the query is null or contains zero rows,
1137 // return an empty list of document models
1138 if (queryResults == null) {
1139 return result; // return an empty list of document models
1141 queryResults.last();
1142 if (queryResults.getRow() == 0) {
1143 return result; // return an empty list of document models
1146 // Otherwise, get the document IDs from the results of the query
1148 queryResults.beforeFirst();
1149 while (queryResults.next()) {
1150 id = queryResults.getString(1);
1151 if (Tools.notBlank(id)) {
1155 } catch (SQLException sqle) {
1156 logger.warn("Could not obtain document IDs via SQL query '" + querySql + "': " + sqle.getMessage());
1157 return result; // return an empty list of document models
1160 // Get a list of document models, using the list of IDs obtained from the query
1162 // FIXME: Check whether we have a 'get document models from list of CSIDs'
1163 // utility method like this, and if not, add this to the appropriate
1165 DocumentModel docModel;
1166 for (String docId : docIds) {
1167 docModel = NuxeoUtils.getDocumentModel(repoSession, docId);
1168 if (docModel == null) {
1169 logger.warn("Could not obtain document model for document with ID " + docId);
1171 result.add(NuxeoUtils.getDocumentModel(repoSession, docId));
1175 // Order the results
1176 final String COMMON_PART_SCHEMA = handler.getServiceContext().getCommonPartLabel();
1177 final String DISPLAY_NAME_XPATH =
1178 "//" + handler.getJDBCQueryParams().get(TERM_GROUP_LIST_NAME) + "/[0]/termDisplayName";
1179 Collections.sort(result, new Comparator<DocumentModel>() {
1181 public int compare(DocumentModel doc1, DocumentModel doc2) {
1182 String termDisplayName1 = (String) NuxeoUtils.getXPathValue(doc1, COMMON_PART_SCHEMA, DISPLAY_NAME_XPATH);
1183 String termDisplayName2 = (String) NuxeoUtils.getXPathValue(doc2, COMMON_PART_SCHEMA, DISPLAY_NAME_XPATH);
1184 return termDisplayName1.compareToIgnoreCase(termDisplayName2);
1192 private DocumentModelList getFilteredCMIS(RepositoryInstance repoSession, ServiceContext ctx, DocumentHandler handler, QueryContext queryContext)
1193 throws DocumentNotFoundException, DocumentException {
1195 DocumentModelList result = new DocumentModelListImpl();
1197 String query = handler.getCMISQuery(queryContext);
1199 DocumentFilter docFilter = handler.getDocumentFilter();
1200 int pageSize = docFilter.getPageSize();
1201 int offset = docFilter.getOffset();
1202 if (logger.isDebugEnabled()) {
1203 logger.debug("Executing CMIS query: " + query.toString()
1204 + "with pageSize: " + pageSize + " at offset: " + offset);
1207 // If we have limit and/or offset, then pass true to get totalSize
1208 // in returned DocumentModelList.
1209 Profiler profiler = new Profiler(this, 2);
1210 profiler.log("Executing CMIS query: " + query.toString());
1213 IterableQueryResult queryResult = makeCMISQLQuery(repoSession, query, queryContext);
1215 int totalSize = (int) queryResult.size();
1216 ((DocumentModelListImpl) result).setTotalSize(totalSize);
1217 // Skip the rows before our offset
1219 queryResult.skipTo(offset);
1222 for (Map<String, Serializable> row : queryResult) {
1223 if (logger.isTraceEnabled()) {
1224 logger.trace(" Hierarchy Table ID is:" + row.get(IQueryManager.CMIS_TARGET_NUXEO_ID)
1225 + " nuxeo:pathSegment is: " + row.get(IQueryManager.CMIS_TARGET_NAME));
1227 String nuxeoId = (String) row.get(IQueryManager.CMIS_TARGET_NUXEO_ID);
1228 DocumentModel docModel = NuxeoUtils.getDocumentModel(repoSession, nuxeoId);
1229 result.add(docModel);
1231 if (nRows >= pageSize && pageSize != 0) { // A page size of zero means that they want all of them
1232 logger.debug("Got page full of items - quitting");
1237 queryResult.close();
1242 } catch (Exception e) {
1243 if (logger.isDebugEnabled()) {
1244 logger.debug("Caught exception ", e);
1246 throw new DocumentException(e);
1250 // Since we're not supporting paging yet for CMIS queries, we need to perform
1251 // a workaround for the paging information we return in our list of results
1254 if (result != null) {
1255 docFilter.setStartPage(0);
1256 if (totalSize > docFilter.getPageSize()) {
1257 docFilter.setPageSize(totalSize);
1258 ((DocumentModelListImpl)result).setTotalSize(totalSize);
1266 private String logException(Exception e, String msg) {
1267 String result = null;
1269 String exceptionMessage = e.getMessage();
1270 exceptionMessage = exceptionMessage != null ? exceptionMessage : "<No details provided>";
1271 result = msg = msg + ". Caught exception:" + exceptionMessage;
1273 if (logger.isTraceEnabled() == true) {
1274 logger.error(msg, e);
1283 * update given document in the Nuxeo repository
1285 * @param ctx service context under which this method is invoked
1286 * @param csid of the document
1287 * @param handler should be used by the caller to provide and transform the
1289 * @throws BadRequestException
1290 * @throws DocumentNotFoundException
1291 * @throws TransactionException if the transaction times out or otherwise
1292 * cannot be successfully completed
1293 * @throws DocumentException
1296 public void update(ServiceContext ctx, String csid, DocumentHandler handler)
1297 throws BadRequestException, DocumentNotFoundException, TransactionException,
1299 if (handler == null) {
1300 throw new IllegalArgumentException(
1301 "RepositoryJavaClient.update: document handler is missing.");
1304 RepositoryInstance repoSession = null;
1306 handler.prepare(Action.UPDATE);
1307 repoSession = getRepositorySession(ctx);
1308 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
1309 DocumentModel doc = null;
1311 doc = repoSession.getDocument(docRef);
1312 } catch (ClientException ce) {
1313 String msg = logException(ce, "Could not find document to update with CSID=" + csid);
1314 throw new DocumentNotFoundException(msg, ce);
1316 // Check for a versioned document, and check In and Out before we proceed.
1317 if (((DocumentModelHandler) handler).supportsVersioning()) {
1318 /* Once we advance to 5.5 or later, we can add this.
1319 * See also https://jira.nuxeo.com/browse/NXP-8506
1320 if(!doc.isVersionable()) {
1321 throw new DocumentException("Configuration for: "
1322 +handler.getServiceContextPath()+" supports versioning, but Nuxeo config does not!");
1325 /* Force a version number - Not working. Apparently we need to configure the uid schema??
1326 if(doc.getProperty("uid","major_version") == null) {
1327 doc.setProperty("uid","major_version",1);
1329 if(doc.getProperty("uid","minor_version") == null) {
1330 doc.setProperty("uid","minor_version",0);
1333 doc.checkIn(VersioningOption.MINOR, null);
1338 // Set reposession to handle the document
1340 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1341 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
1342 handler.handle(Action.UPDATE, wrapDoc);
1343 repoSession.saveDocument(doc);
1345 handler.complete(Action.UPDATE, wrapDoc);
1346 } catch (BadRequestException bre) {
1348 } catch (DocumentException de) {
1350 } catch (WebApplicationException wae) {
1352 } catch (Exception e) {
1353 if (logger.isDebugEnabled()) {
1354 logger.debug("Caught exception ", e);
1356 throw new DocumentException(e);
1358 if (repoSession != null) {
1359 releaseRepositorySession(ctx, repoSession);
1365 * Save a documentModel to the Nuxeo repository.
1367 * @param ctx service context under which this method is invoked
1368 * @param repoSession
1369 * @param docModel the document to save
1370 * @param fSaveSession if TRUE, will call CoreSession.save() to save
1371 * accumulated changes.
1372 * @throws ClientException
1373 * @throws DocumentException
1375 public void saveDocWithoutHandlerProcessing(
1376 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1377 RepositoryInstance repoSession,
1378 DocumentModel docModel,
1379 boolean fSaveSession)
1380 throws ClientException, DocumentException {
1383 repoSession.saveDocument(docModel);
1387 } catch (ClientException ce) {
1389 } catch (Exception e) {
1390 if (logger.isDebugEnabled()) {
1391 logger.debug("Caught exception ", e);
1393 throw new DocumentException(e);
1398 * Save a list of documentModels to the Nuxeo repository.
1400 * @param ctx service context under which this method is invoked
1401 * @param repoSession a repository session
1402 * @param docModelList a list of document models
1403 * @param fSaveSession if TRUE, will call CoreSession.save() to save
1404 * accumulated changes.
1405 * @throws ClientException
1406 * @throws DocumentException
1408 public void saveDocListWithoutHandlerProcessing(
1409 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1410 RepositoryInstance repoSession,
1411 DocumentModelList docList,
1412 boolean fSaveSession)
1413 throws ClientException, DocumentException {
1415 DocumentModel[] docModelArray = new DocumentModel[docList.size()];
1416 repoSession.saveDocuments(docList.toArray(docModelArray));
1420 } catch (ClientException ce) {
1422 } catch (Exception e) {
1423 logger.error("Caught exception ", e);
1424 throw new DocumentException(e);
1429 * delete a document from the Nuxeo repository
1431 * @param ctx service context under which this method is invoked
1432 * @param id of the document
1433 * @throws DocumentException
1436 public void delete(ServiceContext ctx, String id, DocumentHandler handler) throws DocumentNotFoundException,
1437 DocumentException, TransactionException {
1439 throw new IllegalArgumentException(
1440 "delete(ctx, ix, handler): ctx is missing");
1442 if (handler == null) {
1443 throw new IllegalArgumentException(
1444 "delete(ctx, ix, handler): handler is missing");
1446 if (logger.isDebugEnabled()) {
1447 logger.debug("Deleting document with CSID=" + id);
1449 RepositoryInstance repoSession = null;
1451 handler.prepare(Action.DELETE);
1452 repoSession = getRepositorySession(ctx);
1453 DocumentWrapper<DocumentModel> wrapDoc = null;
1455 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
1456 wrapDoc = new DocumentWrapperImpl<DocumentModel>(repoSession.getDocument(docRef));
1457 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1458 handler.handle(Action.DELETE, wrapDoc);
1459 repoSession.removeDocument(docRef);
1460 } catch (ClientException ce) {
1461 String msg = logException(ce, "Could not find document to delete with CSID=" + id);
1462 throw new DocumentNotFoundException(msg, ce);
1465 handler.complete(Action.DELETE, wrapDoc);
1466 } catch (DocumentException de) {
1468 } catch (Exception e) {
1469 if (logger.isDebugEnabled()) {
1470 logger.debug("Caught exception ", e);
1472 throw new DocumentException(e);
1474 if (repoSession != null) {
1475 releaseRepositorySession(ctx, repoSession);
1481 * @see org.collectionspace.services.common.storage.StorageClient#delete(org.collectionspace.services.common.context.ServiceContext, java.lang.String, org.collectionspace.services.common.document.DocumentHandler)
1485 public void delete(@SuppressWarnings("rawtypes") ServiceContext ctx, String id)
1486 throws DocumentNotFoundException, DocumentException {
1487 throw new UnsupportedOperationException();
1488 // Use the other delete instead
1492 public Hashtable<String, String> retrieveWorkspaceIds(RepositoryDomainType repoDomain) throws Exception {
1493 return NuxeoConnectorEmbedded.getInstance().retrieveWorkspaceIds(repoDomain);
1497 public String createDomain(RepositoryDomainType repositoryDomain) throws Exception {
1498 RepositoryInstance repoSession = null;
1499 String domainId = null;
1502 // Open a connection to the domain's repo/db
1504 String repoName = repositoryDomain.getRepositoryName();
1505 repoSession = getRepositorySession(repoName); // domainName=storageName=repoName=databaseName
1507 // First create the top-level domain directory
1509 String domainName = repositoryDomain.getStorageName();
1510 DocumentRef parentDocRef = new PathRef("/");
1511 DocumentModel parentDoc = repoSession.getDocument(parentDocRef);
1512 DocumentModel domainDoc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1513 domainName, NUXEO_CORE_TYPE_DOMAIN);
1514 domainDoc.setPropertyValue("dc:title", domainName);
1515 domainDoc.setPropertyValue("dc:description", "A CollectionSpace domain "
1517 domainDoc = repoSession.createDocument(domainDoc);
1518 domainId = domainDoc.getId();
1521 // Next, create a "Workspaces" root directory to contain the workspace folders for the individual service documents
1523 DocumentModel workspacesRoot = repoSession.createDocumentModel(domainDoc.getPathAsString(),
1524 NuxeoUtils.Workspaces, NUXEO_CORE_TYPE_WORKSPACEROOT);
1525 workspacesRoot.setPropertyValue("dc:title", NuxeoUtils.Workspaces);
1526 workspacesRoot.setPropertyValue("dc:description", "A CollectionSpace workspaces directory for "
1527 + domainDoc.getPathAsString());
1528 workspacesRoot = repoSession.createDocument(workspacesRoot);
1529 String workspacesRootId = workspacesRoot.getId();
1532 if (logger.isDebugEnabled()) {
1533 logger.debug("Created tenant domain name=" + domainName
1534 + " id=" + domainId + " "
1535 + NuxeoUtils.Workspaces + " id=" + workspacesRootId);
1536 logger.debug("Path to Domain: " + domainDoc.getPathAsString());
1537 logger.debug("Path to Workspaces root: " + workspacesRoot.getPathAsString());
1539 } catch (Exception e) {
1540 if (logger.isDebugEnabled()) {
1541 logger.debug("Could not create tenant domain name=" + repositoryDomain.getStorageName() + " caught exception ", e);
1545 if (repoSession != null) {
1546 releaseRepositorySession(null, repoSession);
1554 public String getDomainId(RepositoryDomainType repositoryDomain) throws Exception {
1555 String domainId = null;
1556 RepositoryInstance repoSession = null;
1558 String repoName = repositoryDomain.getRepositoryName();
1559 String domainStorageName = repositoryDomain.getStorageName();
1560 if (domainStorageName != null && !domainStorageName.isEmpty()) {
1562 repoSession = getRepositorySession(repoName);
1563 DocumentRef docRef = new PathRef("/" + domainStorageName);
1564 DocumentModel domain = repoSession.getDocument(docRef);
1565 domainId = domain.getId();
1566 } catch (Exception e) {
1567 if (logger.isTraceEnabled()) {
1568 logger.trace("Caught exception ", e); // The document doesn't exist, this let's us know we need to create it
1570 //there is no way to identify if document does not exist due to
1571 //lack of typed exception for getDocument method
1574 if (repoSession != null) {
1575 releaseRepositorySession(null, repoSession);
1584 * Returns the workspaces root directory for a given domain.
1586 private DocumentModel getWorkspacesRoot(RepositoryInstance repoSession,
1587 String domainName) throws Exception {
1588 DocumentModel result = null;
1590 String domainPath = "/" + domainName;
1591 DocumentRef parentDocRef = new PathRef(domainPath);
1592 DocumentModelList domainChildrenList = repoSession.getChildren(
1594 Iterator<DocumentModel> witer = domainChildrenList.iterator();
1595 while (witer.hasNext()) {
1596 DocumentModel childNode = witer.next();
1597 if (NuxeoUtils.Workspaces.equalsIgnoreCase(childNode.getName())) {
1599 logger.trace("Found workspaces directory at: " + result.getPathAsString());
1604 if (result == null) {
1605 throw new ClientException("Could not find workspace root directory in: "
1613 * @see org.collectionspace.services.common.repository.RepositoryClient#createWorkspace(java.lang.String, java.lang.String)
1616 public String createWorkspace(RepositoryDomainType repositoryDomain, String workspaceName) throws Exception {
1617 RepositoryInstance repoSession = null;
1618 String workspaceId = null;
1620 String repoName = repositoryDomain.getRepositoryName();
1621 repoSession = getRepositorySession(repoName);
1623 String domainStorageName = repositoryDomain.getStorageName();
1624 DocumentModel parentDoc = getWorkspacesRoot(repoSession, domainStorageName);
1625 if (logger.isTraceEnabled()) {
1626 for (String facet : parentDoc.getFacets()) {
1627 logger.trace("Facet: " + facet);
1631 DocumentModel doc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1632 workspaceName, NuxeoUtils.WORKSPACE_DOCUMENT_TYPE);
1633 doc.setPropertyValue("dc:title", workspaceName);
1634 doc.setPropertyValue("dc:description", "A CollectionSpace workspace for "
1636 doc = repoSession.createDocument(doc);
1637 workspaceId = doc.getId();
1639 if (logger.isDebugEnabled()) {
1640 logger.debug("Created workspace name=" + workspaceName
1641 + " id=" + workspaceId);
1643 } catch (Exception e) {
1644 if (logger.isDebugEnabled()) {
1645 logger.debug("createWorkspace caught exception ", e);
1649 if (repoSession != null) {
1650 releaseRepositorySession(null, repoSession);
1657 * @see org.collectionspace.services.common.repository.RepositoryClient#getWorkspaceId(java.lang.String, java.lang.String)
1661 public String getWorkspaceId(String tenantDomain, String workspaceName) throws Exception {
1662 String workspaceId = null;
1664 RepositoryInstance repoSession = null;
1666 repoSession = getRepositorySession((ServiceContext) null);
1667 DocumentRef docRef = new PathRef(
1669 + "/" + NuxeoUtils.Workspaces
1670 + "/" + workspaceName);
1671 DocumentModel workspace = repoSession.getDocument(docRef);
1672 workspaceId = workspace.getId();
1673 } catch (DocumentException de) {
1675 } catch (Exception e) {
1676 if (logger.isDebugEnabled()) {
1677 logger.debug("Caught exception ", e);
1679 throw new DocumentException(e);
1681 if (repoSession != null) {
1682 releaseRepositorySession(null, repoSession);
1689 public RepositoryInstance getRepositorySession(ServiceContext ctx) throws Exception {
1690 return getRepositorySession(ctx, ctx.getRepositoryName());
1693 public RepositoryInstance getRepositorySession(String repoName) throws Exception {
1694 return getRepositorySession(null, repoName);
1698 * Gets the repository session. - Package access only. If the 'ctx' param is
1699 * null then the repo name must be non-mull and vice-versa
1701 * @return the repository session
1702 * @throws Exception the exception
1704 public RepositoryInstance getRepositorySession(ServiceContext ctx, String repoName) throws Exception {
1705 RepositoryInstance repoSession = null;
1707 Profiler profiler = new Profiler("getRepositorySession():", 2);
1710 // To get a connection to the Nuxeo repo, we need either a valid ServiceContext instance or a repository name
1713 repoName = ctx.getRepositoryName(); // Notice we are overriding the passed in 'repoName' since we have a valid service context passed in to us
1714 repoSession = (RepositoryInstance) ctx.getCurrentRepositorySession(); // Look to see if one exists in the context before creating one
1715 } else if (repoName == null || repoName.trim().isEmpty()) {
1716 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.");
1717 logger.error(errMsg);
1718 throw new Exception(errMsg);
1721 // 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
1722 // just the repo name
1724 if (repoSession == null) {
1725 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1726 repoSession = client.openRepository(repoName);
1728 if (logger.isDebugEnabled() == true) {
1729 logger.warn("Reusing the current context's repository session.");
1733 if (logger.isTraceEnabled()) {
1734 logger.trace("Testing call to getRepository() repository root: " + repoSession.getRootDocument());
1740 ctx.setCurrentRepositorySession(repoSession); // For reusing, save the repository session in the current service context
1747 * Release repository session. - Package access only.
1749 * @param repoSession the repo session
1751 public void releaseRepositorySession(ServiceContext ctx, RepositoryInstance repoSession) throws TransactionException {
1753 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1756 ctx.clearCurrentRepositorySession(); //clear the current context of the now closed repo session
1757 if (ctx.getCurrentRepositorySession() == null) {
1758 client.releaseRepository(repoSession); //release the repo session if the service context's ref count is zeo.
1761 client.releaseRepository(repoSession); //repo session was acquired without a service context
1763 } catch (TransactionRuntimeException tre) {
1764 TransactionException te = new TransactionException(tre);
1765 logger.error(te.getMessage(), tre); // Log the standard transaction exception message, plus an exception-specific stack trace
1767 } catch (Exception e) {
1768 logger.error("Could not close the repository session", e);
1769 // no need to throw this service specific exception
1774 public void doWorkflowTransition(ServiceContext ctx, String id,
1775 DocumentHandler handler, TransitionDef transitionDef)
1776 throws BadRequestException, DocumentNotFoundException,
1778 // 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
1781 private String handleProvidedStartingWildcard(String partialTerm) {
1782 if (Tools.notBlank(partialTerm)) {
1783 if (partialTerm.substring(0, 1).equals(USER_SUPPLIED_WILDCARD)) {
1784 StringBuffer buffer = new StringBuffer(partialTerm);
1785 buffer.setCharAt(0, JDBCTools.SQL_WILDCARD.charAt(0));
1786 partialTerm = buffer.toString();
1793 * Replaces user-supplied wildcards with SQL wildcards, in a partial term
1794 * matching search expression.
1796 * The scope of this replacement excludes the beginning character
1797 * in that search expression, as that character is treated specially.
1799 * @param partialTerm
1800 * @return the partial term, with any user-supplied wildcards replaced
1803 private String subtituteWildcardsInPartialTerm(String partialTerm) {
1804 if (Tools.isBlank(partialTerm)) {
1807 if (! partialTerm.contains(USER_SUPPLIED_WILDCARD)) {
1810 int len = partialTerm.length();
1811 // Partial term search expressions of 2 or fewer characters
1812 // currently aren't amenable to the use of wildcards
1814 logger.warn("Partial term match search expression of just 1-2 characters in length contains a user-supplied wildcard: " + partialTerm);
1815 logger.warn("Will handle that character as a literal value, rather than as a wildcard ...");
1818 return partialTerm.substring(0, 1) // first char
1819 + partialTerm.substring(1, len).replaceAll(USER_SUPPLIED_WILDCARD_REGEX, JDBCTools.SQL_WILDCARD);
1823 private int getMaxItemsLimitOnJdbcQueries(String maxListItemsLimit) {
1824 final int DEFAULT_ITEMS_LIMIT = 40;
1825 if (maxListItemsLimit == null) {
1826 return DEFAULT_ITEMS_LIMIT;
1830 itemsLimit = Integer.parseInt(maxListItemsLimit);
1831 if (itemsLimit < 1) {
1832 logger.warn("Value of configuration setting "
1833 + IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES
1834 + " must be a positive integer; invalid current value is " + maxListItemsLimit);
1835 logger.warn("Reverting to default value of " + DEFAULT_ITEMS_LIMIT);
1836 itemsLimit = DEFAULT_ITEMS_LIMIT;
1838 } catch (NumberFormatException nfe) {
1839 logger.warn("Value of configuration setting "
1840 + IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES
1841 + " must be a positive integer; invalid current value is " + maxListItemsLimit);
1842 logger.warn("Reverting to default value of " + DEFAULT_ITEMS_LIMIT);
1843 itemsLimit = DEFAULT_ITEMS_LIMIT;
1849 * Identifies whether a restriction on tenant ID - to return only records
1850 * pertaining to the current tenant - is required in a JDBC query.
1852 * @param tenantBinding a tenant binding configuration.
1853 * @param ctx a service context.
1854 * @return true if a restriction on tenant ID is required in the query;
1855 * false if a restriction is not required.
1857 private boolean restrictJDBCQueryByTenantID(TenantBindingType tenantBinding, ServiceContext ctx) {
1858 boolean restrict = true;
1859 // If data for the current service, in the current tenant, is isolated
1860 // within its own separate, per-tenant repository, as contrasted with
1861 // being intermingled with other tenants' data in the default repository,
1862 // no restriction on Tenant ID is required in the query.
1863 String repositoryDomainName = ConfigUtils.getRepositoryName(tenantBinding, ctx.getRepositoryDomainName());
1864 if (!(repositoryDomainName.equals(ConfigUtils.DEFAULT_NUXEO_REPOSITORY_NAME))) {
1867 // If a configuration setting for this tenant identifies that JDBC
1868 // queries should not be restricted by tenant ID (perhaps because
1869 // there is always expected to be only one tenant's data present in
1870 // the system), no restriction on Tenant ID is required in the query.
1871 String queriesRestrictedByTenantId = TenantBindingUtils.getPropertyValue(tenantBinding,
1872 IQueryManager.JDBC_QUERIES_ARE_TENANT_ID_RESTRICTED);
1873 if (Tools.notBlank(queriesRestrictedByTenantId) &&
1874 queriesRestrictedByTenantId.equalsIgnoreCase(Boolean.FALSE.toString())) {