2 * This document is a part of the source code and related artifacts for
3 * CollectionSpace, an open source collections management system for museums and
4 * related institutions:
6 * http://www.collectionspace.org http://wiki.collectionspace.org
8 * Copyright 2009 University of California at Berkeley
10 * Licensed under the Educational Community License (ECL), Version 2.0. You may
11 * not use this file except in compliance with this License.
13 * You may obtain a copy of the ECL 2.0 License at
15 * https://source.collectionspace.org/collection-space/LICENSE.txt
17 package org.collectionspace.services.nuxeo.client.java;
19 import java.io.Serializable;
20 import java.sql.SQLException;
21 import java.util.ArrayList;
22 import java.util.Collections;
23 import java.util.Comparator;
24 import java.util.HashSet;
25 import java.util.Hashtable;
26 import java.util.Iterator;
27 import java.util.List;
30 import java.util.UUID;
31 import javax.sql.rowset.CachedRowSet;
33 import javax.ws.rs.WebApplicationException;
34 import javax.ws.rs.core.MultivaluedMap;
36 import org.collectionspace.services.client.CollectionSpaceClient;
37 import org.collectionspace.services.client.IQueryManager;
38 import org.collectionspace.services.client.PoxPayloadIn;
39 import org.collectionspace.services.client.PoxPayloadOut;
40 import org.collectionspace.services.client.Profiler;
41 import org.collectionspace.services.client.workflow.WorkflowClient;
42 import org.collectionspace.services.common.context.ServiceContext;
43 import org.collectionspace.services.common.query.QueryContext;
44 import org.collectionspace.services.common.repository.RepositoryClient;
45 import org.collectionspace.services.common.storage.JDBCTools;
46 import org.collectionspace.services.common.storage.PreparedStatementSimpleBuilder;
47 import org.collectionspace.services.lifecycle.TransitionDef;
48 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
50 import org.collectionspace.services.common.document.BadRequestException;
51 import org.collectionspace.services.common.document.DocumentException;
52 import org.collectionspace.services.common.document.DocumentFilter;
53 import org.collectionspace.services.common.document.DocumentHandler;
54 import org.collectionspace.services.common.document.DocumentNotFoundException;
55 import org.collectionspace.services.common.document.DocumentHandler.Action;
56 import org.collectionspace.services.common.document.DocumentWrapper;
57 import org.collectionspace.services.common.document.DocumentWrapperImpl;
58 import org.collectionspace.services.common.document.TransactionException;
59 import org.collectionspace.services.config.tenant.RepositoryDomainType;
61 import org.nuxeo.common.utils.IdUtils;
62 import org.nuxeo.ecm.core.api.ClientException;
63 import org.nuxeo.ecm.core.api.DocumentModel;
64 import org.nuxeo.ecm.core.api.DocumentModelList;
65 import org.nuxeo.ecm.core.api.IterableQueryResult;
66 import org.nuxeo.ecm.core.api.VersioningOption;
67 import org.nuxeo.ecm.core.api.impl.DocumentModelListImpl;
68 import org.nuxeo.ecm.core.api.DocumentRef;
69 import org.nuxeo.ecm.core.api.IdRef;
70 import org.nuxeo.ecm.core.api.PathRef;
71 import org.nuxeo.ecm.core.api.repository.RepositoryInstance;
72 import org.nuxeo.runtime.transaction.TransactionRuntimeException;
75 // CSPACE-5036 - How to make CMISQL queries from Nuxeo
77 import org.apache.chemistry.opencmis.commons.server.CallContext;
78 import org.apache.chemistry.opencmis.server.impl.CallContextImpl;
79 import org.collectionspace.services.common.ServiceMain;
80 import org.collectionspace.services.common.api.Tools;
81 import org.collectionspace.services.common.config.ConfigUtils;
82 import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl;
83 import org.collectionspace.services.common.config.TenantBindingUtils;
84 import org.collectionspace.services.common.storage.PreparedStatementBuilder;
85 import org.collectionspace.services.config.tenant.TenantBindingType;
86 import org.nuxeo.ecm.core.opencmis.impl.server.NuxeoCmisService;
87 import org.nuxeo.ecm.core.opencmis.impl.server.NuxeoRepository;
89 import org.slf4j.Logger;
90 import org.slf4j.LoggerFactory;
93 * RepositoryJavaClient is used to perform CRUD operations on documents in Nuxeo
94 * repository using Remote Java APIs. It uses
96 * @see DocumentHandler as IOHandler with the client.
98 * $LastChangedRevision: $ $LastChangedDate: $
100 public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn, PoxPayloadOut> {
105 private final Logger logger = LoggerFactory.getLogger(RepositoryJavaClientImpl.class);
106 // private final Logger profilerLogger = LoggerFactory.getLogger("remperf");
107 // private String foo = Profiler.createLogger();
108 public static final String NUXEO_CORE_TYPE_DOMAIN = "Domain";
109 public static final String NUXEO_CORE_TYPE_WORKSPACEROOT = "WorkspaceRoot";
110 // FIXME: Get this value from an existing constant, if available
111 private static final String USER_SUPPLIED_WILDCARD = "*";
112 private static final String USER_SUPPLIED_WILDCARD_REGEX = "\\" + USER_SUPPLIED_WILDCARD;
113 private static final String USER_SUPPLIED_ANCHOR_CHAR = "^";
117 * Instantiates a new repository java client impl.
119 public RepositoryJavaClientImpl() {
123 public void assertWorkflowState(ServiceContext ctx,
124 DocumentModel docModel) throws DocumentNotFoundException, ClientException {
125 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
126 if (queryParams != null) {
128 // Look for the workflow "delete" query param and see if we need to assert that the
129 // docModel is in a non-deleted workflow state.
131 String currentState = docModel.getCurrentLifeCycleState();
132 String includeDeletedStr = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_NONDELETED);
133 boolean includeDeleted = includeDeletedStr == null ? true : Boolean.parseBoolean(includeDeletedStr);
134 if (includeDeleted == false) {
136 // We don't wanted soft-deleted object, so throw an exception if this one is soft-deleted.
138 if (currentState.equalsIgnoreCase(WorkflowClient.WORKFLOWSTATE_DELETED)) {
139 String msg = "The GET assertion that docModel not be in 'deleted' workflow state failed.";
141 throw new DocumentNotFoundException(msg);
148 * create document in the Nuxeo repository
150 * @param ctx service context under which this method is invoked
151 * @param handler should be used by the caller to provide and transform the
153 * @return id in repository of the newly created document
154 * @throws BadRequestException
155 * @throws TransactionException
156 * @throws DocumentException
159 public String create(ServiceContext ctx,
160 DocumentHandler handler) throws BadRequestException,
161 TransactionException, DocumentException {
163 String docType = NuxeoUtils.getTenantQualifiedDocType(ctx); //ctx.getDocumentType();
164 if (docType == null) {
165 throw new IllegalArgumentException(
166 "RepositoryJavaClient.create: docType is missing");
169 if (handler == null) {
170 throw new IllegalArgumentException(
171 "RepositoryJavaClient.create: handler is missing");
173 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
174 if (nuxeoWspaceId == null) {
175 throw new DocumentNotFoundException(
176 "Unable to find workspace for service " + ctx.getServiceName()
177 + " check if the workspace exists in the Nuxeo repository");
180 RepositoryInstance repoSession = null;
182 handler.prepare(Action.CREATE);
183 repoSession = getRepositorySession(ctx);
184 DocumentRef nuxeoWspace = new IdRef(nuxeoWspaceId);
185 DocumentModel wspaceDoc = repoSession.getDocument(nuxeoWspace);
186 String wspacePath = wspaceDoc.getPathAsString();
187 //give our own ID so PathRef could be constructed later on
188 String id = IdUtils.generateId(UUID.randomUUID().toString());
189 // create document model
190 DocumentModel doc = repoSession.createDocumentModel(wspacePath, id, docType);
191 /* Check for a versioned document, and check In and Out before we proceed.
192 * This does not work as we do not have the uid schema on our docs.
193 if(((DocumentModelHandler) handler).supportsVersioning()) {
194 doc.setProperty("uid","major_version",1);
195 doc.setProperty("uid","minor_version",0);
198 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
199 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
200 handler.handle(Action.CREATE, wrapDoc);
201 // create document with documentmodel
202 doc = repoSession.createDocument(doc);
204 // TODO for sub-docs need to call into the handler to let it deal with subitems. Pass in the id,
205 // and assume the handler has the state it needs (doc fragments).
206 handler.complete(Action.CREATE, wrapDoc);
208 } catch (BadRequestException bre) {
210 } catch (Exception e) {
211 logger.error("Caught exception ", e);
212 throw new DocumentException(e);
214 if (repoSession != null) {
215 releaseRepositorySession(ctx, repoSession);
222 * get document from the Nuxeo repository
224 * @param ctx service context under which this method is invoked
225 * @param id of the document to retrieve
226 * @param handler should be used by the caller to provide and transform the
228 * @throws DocumentNotFoundException if the document cannot be found in the
230 * @throws TransactionException
231 * @throws DocumentException
234 public void get(ServiceContext ctx, String id, DocumentHandler handler)
235 throws DocumentNotFoundException, TransactionException, DocumentException {
237 if (handler == null) {
238 throw new IllegalArgumentException(
239 "RepositoryJavaClient.get: handler is missing");
242 RepositoryInstance repoSession = null;
244 handler.prepare(Action.GET);
245 repoSession = getRepositorySession(ctx);
246 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
247 DocumentModel docModel = null;
249 docModel = repoSession.getDocument(docRef);
250 assertWorkflowState(ctx, docModel);
251 } catch (ClientException ce) {
252 String msg = logException(ce, "Could not find document with CSID=" + id);
253 throw new DocumentNotFoundException(msg, ce);
256 // Set repository session to handle the document
258 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
259 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(docModel);
260 handler.handle(Action.GET, wrapDoc);
261 handler.complete(Action.GET, wrapDoc);
262 } catch (IllegalArgumentException iae) {
264 } catch (DocumentException de) {
266 } catch (Exception e) {
267 if (logger.isDebugEnabled()) {
268 logger.debug("Caught exception ", e);
270 throw new DocumentException(e);
272 if (repoSession != null) {
273 releaseRepositorySession(ctx, repoSession);
279 * get a document from the Nuxeo repository, using the docFilter params.
281 * @param ctx service context under which this method is invoked
282 * @param handler should be used by the caller to provide and transform the
283 * document. Handler must have a docFilter set to return a single item.
284 * @throws DocumentNotFoundException if the document cannot be found in the
286 * @throws TransactionException
287 * @throws DocumentException
290 public void get(ServiceContext ctx, DocumentHandler handler)
291 throws DocumentNotFoundException, TransactionException, DocumentException {
292 QueryContext queryContext = new QueryContext(ctx, handler);
293 RepositoryInstance repoSession = null;
296 handler.prepare(Action.GET);
297 repoSession = getRepositorySession(ctx);
299 DocumentModelList docList = null;
300 // force limit to 1, and ignore totalSize
301 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
302 docList = repoSession.query(query, null, 1, 0, false);
303 if (docList.size() != 1) {
304 throw new DocumentNotFoundException("No document found matching filter params: " + query);
306 DocumentModel doc = docList.get(0);
308 if (logger.isDebugEnabled()) {
309 logger.debug("Executed NXQL query: " + query);
312 //set reposession to handle the document
313 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
314 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
315 handler.handle(Action.GET, wrapDoc);
316 handler.complete(Action.GET, wrapDoc);
317 } catch (IllegalArgumentException iae) {
319 } catch (DocumentException de) {
321 } catch (Exception e) {
322 if (logger.isDebugEnabled()) {
323 logger.debug("Caught exception ", e);
325 throw new DocumentException(e);
327 if (repoSession != null) {
328 releaseRepositorySession(ctx, repoSession);
333 public DocumentWrapper<DocumentModel> getDoc(
334 RepositoryInstance repoSession,
335 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
336 String csid) throws DocumentNotFoundException, DocumentException {
337 DocumentWrapper<DocumentModel> wrapDoc = null;
340 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
341 DocumentModel doc = null;
343 doc = repoSession.getDocument(docRef);
344 } catch (ClientException ce) {
345 String msg = logException(ce, "Could not find document with CSID=" + csid);
346 throw new DocumentNotFoundException(msg, ce);
348 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
349 } catch (IllegalArgumentException iae) {
351 } catch (DocumentException de) {
359 * Get wrapped documentModel from the Nuxeo repository. The search is
360 * restricted to the workspace of the current context.
362 * @param ctx service context under which this method is invoked
363 * @param csid of the document to retrieve
364 * @throws DocumentNotFoundException
365 * @throws TransactionException
366 * @throws DocumentException
367 * @return a wrapped documentModel
370 public DocumentWrapper<DocumentModel> getDoc(
371 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
372 String csid) throws DocumentNotFoundException, TransactionException, DocumentException {
373 RepositoryInstance repoSession = null;
374 DocumentWrapper<DocumentModel> wrapDoc = null;
377 // Open a new repository session
378 repoSession = getRepositorySession(ctx);
379 wrapDoc = getDoc(repoSession, ctx, csid);
380 } catch (IllegalArgumentException iae) {
382 } catch (DocumentException de) {
384 } catch (Exception e) {
385 if (logger.isDebugEnabled()) {
386 logger.debug("Caught exception ", e);
388 throw new DocumentException(e);
390 if (repoSession != null) {
391 releaseRepositorySession(ctx, repoSession);
395 if (logger.isWarnEnabled() == true) {
396 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
401 public DocumentWrapper<DocumentModel> findDoc(
402 RepositoryInstance repoSession,
403 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
405 throws DocumentNotFoundException, DocumentException {
406 DocumentWrapper<DocumentModel> wrapDoc = null;
409 QueryContext queryContext = new QueryContext(ctx, whereClause);
410 DocumentModelList docList = null;
411 // force limit to 1, and ignore totalSize
412 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
413 docList = repoSession.query(query,
418 if (docList.size() != 1) {
419 if (logger.isDebugEnabled()) {
420 logger.debug("findDoc: Query found: " + docList.size() + " items.");
421 logger.debug(" Query: " + query);
423 throw new DocumentNotFoundException("No document found matching filter params: " + query);
425 DocumentModel doc = docList.get(0);
426 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
427 } catch (IllegalArgumentException iae) {
429 } catch (DocumentException de) {
431 } catch (Exception e) {
432 if (logger.isDebugEnabled()) {
433 logger.debug("Caught exception ", e);
435 throw new DocumentException(e);
442 * find wrapped documentModel from the Nuxeo repository
444 * @param ctx service context under which this method is invoked
445 * @param whereClause where NXQL where clause to get the document
446 * @throws DocumentNotFoundException
447 * @throws TransactionException
448 * @throws DocumentException
449 * @return a wrapped documentModel retrieved by the repository query
452 public DocumentWrapper<DocumentModel> findDoc(
453 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
455 throws DocumentNotFoundException, TransactionException, DocumentException {
456 RepositoryInstance repoSession = null;
457 DocumentWrapper<DocumentModel> wrapDoc = null;
460 repoSession = getRepositorySession(ctx);
461 wrapDoc = findDoc(repoSession, ctx, whereClause);
462 } catch (Exception e) {
463 throw new DocumentException("Unable to create a Nuxeo repository session.", e);
465 if (repoSession != null) {
466 releaseRepositorySession(ctx, repoSession);
470 if (logger.isWarnEnabled() == true) {
471 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
478 * find doc and return CSID from the Nuxeo repository
481 * @param ctx service context under which this method is invoked
482 * @param whereClause where NXQL where clause to get the document
483 * @throws DocumentNotFoundException
484 * @throws TransactionException
485 * @throws DocumentException
486 * @return the CollectionSpace ID (CSID) of the requested document
489 public String findDocCSID(RepositoryInstance repoSession,
490 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String whereClause)
491 throws DocumentNotFoundException, TransactionException, DocumentException {
493 boolean releaseSession = false;
495 if (repoSession == null) {
496 repoSession = this.getRepositorySession(ctx);
497 releaseSession = true;
499 DocumentWrapper<DocumentModel> wrapDoc = findDoc(repoSession, ctx, whereClause);
500 DocumentModel docModel = wrapDoc.getWrappedObject();
501 csid = NuxeoUtils.getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
502 } catch (DocumentNotFoundException dnfe) {
504 } catch (IllegalArgumentException iae) {
506 } catch (DocumentException de) {
508 } catch (Exception e) {
509 if (logger.isDebugEnabled()) {
510 logger.debug("Caught exception ", e);
512 throw new DocumentException(e);
514 if (releaseSession && (repoSession != null)) {
515 this.releaseRepositorySession(ctx, repoSession);
521 public DocumentWrapper<DocumentModelList> findDocs(
522 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
523 RepositoryInstance repoSession,
524 List<String> docTypes,
526 String orderByClause,
529 boolean computeTotal)
530 throws DocumentNotFoundException, DocumentException {
531 DocumentWrapper<DocumentModelList> wrapDoc = null;
534 if (docTypes == null || docTypes.size() < 1) {
535 throw new DocumentNotFoundException(
536 "The findDocs() method must specify at least one DocumentType.");
538 DocumentModelList docList = null;
539 QueryContext queryContext = new QueryContext(ctx, whereClause, orderByClause);
540 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
541 if (logger.isDebugEnabled()) {
542 logger.debug("findDocs() NXQL: " + query);
544 docList = repoSession.query(query, null, pageSize, pageSize * pageNum, computeTotal);
545 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
546 } catch (IllegalArgumentException iae) {
548 } catch (Exception e) {
549 if (logger.isDebugEnabled()) {
550 logger.debug("Caught exception ", e);
552 throw new DocumentException(e);
558 protected static String buildInListForDocTypes(List<String> docTypes) {
559 StringBuilder sb = new StringBuilder();
561 boolean first = true;
562 for (String docType : docTypes) {
573 return sb.toString();
576 public DocumentWrapper<DocumentModelList> findDocs(
577 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
578 DocumentHandler handler,
579 RepositoryInstance repoSession,
580 List<String> docTypes)
581 throws DocumentNotFoundException, DocumentException {
582 DocumentWrapper<DocumentModelList> wrapDoc = null;
584 DocumentFilter filter = handler.getDocumentFilter();
585 String oldOrderBy = filter.getOrderByClause();
586 if (isClauseEmpty(oldOrderBy) == true) {
587 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
589 QueryContext queryContext = new QueryContext(ctx, handler);
592 if (docTypes == null || docTypes.size() < 1) {
593 throw new DocumentNotFoundException(
594 "The findDocs() method must specify at least one DocumentType.");
596 DocumentModelList docList = null;
597 if (handler.isCMISQuery() == true) {
598 String inList = buildInListForDocTypes(docTypes);
599 ctx.getQueryParams().add(IQueryManager.SEARCH_RELATED_MATCH_OBJ_DOCTYPES, inList);
600 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
602 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
603 if (logger.isDebugEnabled()) {
604 logger.debug("findDocs() NXQL: " + query);
606 docList = repoSession.query(query, null, filter.getPageSize(), filter.getOffset(), true);
608 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
609 } catch (IllegalArgumentException iae) {
611 } catch (Exception e) {
612 if (logger.isDebugEnabled()) {
613 logger.debug("Caught exception ", e);
615 throw new DocumentException(e);
622 * Find a list of documentModels from the Nuxeo repository
624 * @param docTypes a list of DocType names to match
625 * @param whereClause where the clause to qualify on
626 * @throws DocumentNotFoundException
627 * @throws TransactionException
628 * @throws DocumentException
629 * @return a list of documentModels
632 public DocumentWrapper<DocumentModelList> findDocs(
633 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
634 List<String> docTypes,
636 int pageSize, int pageNum, boolean computeTotal)
637 throws DocumentNotFoundException, TransactionException, DocumentException {
638 RepositoryInstance repoSession = null;
639 DocumentWrapper<DocumentModelList> wrapDoc = null;
642 repoSession = getRepositorySession(ctx);
643 wrapDoc = findDocs(ctx, repoSession, docTypes, whereClause, null,
644 pageSize, pageNum, computeTotal);
645 } catch (IllegalArgumentException iae) {
647 } catch (Exception e) {
648 if (logger.isDebugEnabled()) {
649 logger.debug("Caught exception ", e);
651 throw new DocumentException(e);
653 if (repoSession != null) {
654 releaseRepositorySession(ctx, repoSession);
658 if (logger.isWarnEnabled() == true) {
659 logger.warn("Returned DocumentModelList instance was created with a repository session that is now closed.");
666 * @see org.collectionspace.services.common.storage.StorageClient#get(org.collectionspace.services.common.context.ServiceContext, java.util.List, org.collectionspace.services.common.document.DocumentHandler)
669 public void get(ServiceContext ctx, List<String> csidList, DocumentHandler handler)
670 throws DocumentNotFoundException, TransactionException, DocumentException {
671 if (handler == null) {
672 throw new IllegalArgumentException(
673 "RepositoryJavaClient.getAll: handler is missing");
676 RepositoryInstance repoSession = null;
678 handler.prepare(Action.GET_ALL);
679 repoSession = getRepositorySession(ctx);
680 DocumentModelList docModelList = new DocumentModelListImpl();
681 //FIXME: Should be using NuxeoUtils.createPathRef for security reasons
682 for (String csid : csidList) {
683 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
684 DocumentModel docModel = repoSession.getDocument(docRef);
685 docModelList.add(docModel);
688 //set reposession to handle the document
689 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
690 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docModelList);
691 handler.handle(Action.GET_ALL, wrapDoc);
692 handler.complete(Action.GET_ALL, wrapDoc);
693 } catch (DocumentException de) {
695 } catch (Exception e) {
696 if (logger.isDebugEnabled()) {
697 logger.debug("Caught exception ", e);
699 throw new DocumentException(e);
701 if (repoSession != null) {
702 releaseRepositorySession(ctx, repoSession);
708 * getAll get all documents for an entity entity service from the Nuxeo
711 * @param ctx service context under which this method is invoked
712 * @param handler should be used by the caller to provide and transform the
714 * @throws DocumentNotFoundException
715 * @throws TransactionException
716 * @throws DocumentException
719 public void getAll(ServiceContext ctx, DocumentHandler handler)
720 throws DocumentNotFoundException, TransactionException, DocumentException {
721 if (handler == null) {
722 throw new IllegalArgumentException(
723 "RepositoryJavaClient.getAll: handler is missing");
725 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
726 if (nuxeoWspaceId == null) {
727 throw new DocumentNotFoundException(
728 "Unable to find workspace for service "
729 + ctx.getServiceName()
730 + " check if the workspace exists in the Nuxeo repository.");
733 RepositoryInstance repoSession = null;
735 handler.prepare(Action.GET_ALL);
736 repoSession = getRepositorySession(ctx);
737 DocumentRef wsDocRef = new IdRef(nuxeoWspaceId);
738 DocumentModelList docList = repoSession.getChildren(wsDocRef);
739 //set reposession to handle the document
740 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
741 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
742 handler.handle(Action.GET_ALL, wrapDoc);
743 handler.complete(Action.GET_ALL, wrapDoc);
744 } catch (DocumentException de) {
746 } catch (Exception e) {
747 if (logger.isDebugEnabled()) {
748 logger.debug("Caught exception ", e);
750 throw new DocumentException(e);
752 if (repoSession != null) {
753 releaseRepositorySession(ctx, repoSession);
758 private boolean isClauseEmpty(String theString) {
759 boolean result = true;
760 if (theString != null && !theString.isEmpty()) {
766 public DocumentWrapper<DocumentModel> getDocFromCsid(
767 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
768 RepositoryInstance repoSession,
771 DocumentWrapper<DocumentModel> result = null;
773 result = new DocumentWrapperImpl(NuxeoUtils.getDocFromCsid(ctx, repoSession, csid));
779 * A method to find a CollectionSpace document (of any type) given just a service context and
780 * its CSID. A search across *all* service workspaces (within a given tenant context) is performed to find
783 * This query searches Nuxeo's Hierarchy table where our CSIDs are stored in the "name" column.
786 public DocumentWrapper<DocumentModel> getDocFromCsid(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
789 DocumentWrapper<DocumentModel> result = null;
790 RepositoryInstance repoSession = null;
792 repoSession = getRepositorySession(ctx);
793 result = getDocFromCsid(ctx, repoSession, csid);
795 if (repoSession != null) {
796 releaseRepositorySession(ctx, repoSession);
800 if (logger.isWarnEnabled() == true) {
801 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
808 * Returns a URI value for a document in the Nuxeo repository
810 * @param wrappedDoc a wrapped documentModel
811 * @throws ClientException
812 * @return a document URI
815 public String getDocURI(DocumentWrapper<DocumentModel> wrappedDoc) throws ClientException {
816 DocumentModel docModel = wrappedDoc.getWrappedObject();
817 String uri = (String) docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
818 CollectionSpaceClient.COLLECTIONSPACE_CORE_URI);
823 * See CSPACE-5036 - How to make CMISQL queries from Nuxeo
825 private IterableQueryResult makeCMISQLQuery(RepositoryInstance repoSession, String query, QueryContext queryContext) {
826 IterableQueryResult result = null;
828 // the NuxeoRepository should be constructed only once, then cached
829 // (its construction is expensive)
831 NuxeoRepository repo = new NuxeoRepository(
832 repoSession.getRepositoryName(), repoSession
833 .getRootDocument().getId());
834 logger.debug("Repository ID:" + repo.getId() + " Root folder:"
835 + repo.getRootFolderId());
837 CallContextImpl callContext = new CallContextImpl(
838 CallContext.BINDING_LOCAL, repo.getId(), false);
839 callContext.put(CallContext.USERNAME, repoSession.getPrincipal()
841 NuxeoCmisService cmisService = new NuxeoCmisService(repo,
842 callContext, repoSession);
844 result = repoSession.queryAndFetch(query, "CMISQL", cmisService);
845 } catch (ClientException e) {
846 // TODO Auto-generated catch block
847 logger.error("Encounter trouble making the following CMIS query: " + query, e);
854 * getFiltered get all documents for an entity service from the Document
855 * repository, given filter parameters specified by the handler.
857 * @param ctx service context under which this method is invoked
858 * @param handler should be used by the caller to provide and transform the
860 * @throws DocumentNotFoundException if workspace not found
861 * @throws TransactionException
862 * @throws DocumentException
865 public void getFiltered(ServiceContext ctx, DocumentHandler handler)
866 throws DocumentNotFoundException, TransactionException, DocumentException {
868 DocumentFilter filter = handler.getDocumentFilter();
869 String oldOrderBy = filter.getOrderByClause();
870 if (isClauseEmpty(oldOrderBy) == true) {
871 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
873 QueryContext queryContext = new QueryContext(ctx, handler);
875 RepositoryInstance repoSession = null;
877 handler.prepare(Action.GET_ALL);
878 repoSession = getRepositorySession(ctx); //Keeps a refcount here for the repository session so you need to release this when finished
880 DocumentModelList docList = null;
881 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
883 if (logger.isDebugEnabled()) {
884 logger.debug("Executing NXQL query: " + query.toString());
887 // If we have limit and/or offset, then pass true to get totalSize
888 // in returned DocumentModelList.
889 Profiler profiler = new Profiler(this, 2);
890 profiler.log("Executing NXQL query: " + query.toString());
892 if (handler.isJDBCQuery() == true) {
893 docList = getFilteredJDBC(repoSession, ctx, handler);
894 } else if (handler.isCMISQuery() == true) {
895 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext); //FIXME: REM - Need to deal with paging info in CMIS query
896 } else if ((queryContext.getDocFilter().getOffset() > 0) || (queryContext.getDocFilter().getPageSize() > 0)) {
897 docList = repoSession.query(query, null,
898 queryContext.getDocFilter().getPageSize(), queryContext.getDocFilter().getOffset(), true);
900 docList = repoSession.query(query);
904 //set repoSession to handle the document
905 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
906 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
907 handler.handle(Action.GET_ALL, wrapDoc);
908 handler.complete(Action.GET_ALL, wrapDoc);
909 } catch (DocumentException de) {
911 } catch (Exception e) {
912 if (logger.isDebugEnabled()) {
913 logger.debug("Caught exception ", e);
915 throw new DocumentException(e);
917 if (repoSession != null) {
918 releaseRepositorySession(ctx, repoSession);
924 * Perform a database query, via JDBC and SQL, to retrieve matching records
925 * based on filter criteria.
927 * Although this method currently has a general-purpose name, it is
928 * currently dedicated to a specific task: improving performance for
929 * partial term matching queries on authority items / terms, via
930 * the use of a hand-tuned SQL query, rather than the generated SQL
931 * produced by Nuxeo from an NXQL query.
933 * @param repoSession a repository session.
934 * @param ctx the service context.
935 * @param handler a relevant document handler.
936 * @return a list of document models matching the search criteria.
939 private DocumentModelList getFilteredJDBC(RepositoryInstance repoSession, ServiceContext ctx,
940 DocumentHandler handler) throws Exception {
941 DocumentModelList result = new DocumentModelListImpl();
943 // FIXME: Get all of the following values from appropriate external constants.
945 // At present, the two constants below are duplicated in both RepositoryJavaClientImpl
946 // and in AuthorityItemDocumentModelHandler.
947 final String TERM_GROUP_LIST_NAME = "TERM_GROUP_LIST_NAME";
948 final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
949 final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
950 // Get this from a constant in AuthorityResource or equivalent
951 final String PARENT_WILDCARD = "_ALL_";
953 // Build two SQL statements, to be executed within a single transaction:
954 // the first statement to control join order, and the second statement
955 // representing the actual 'get filtered' query
957 // Build the join control statement
959 // Per http://www.postgresql.org/docs/9.2/static/runtime-config-query.html#GUC-JOIN-COLLAPSE-LIMIT
960 // "Setting [this value] to 1 prevents any reordering of explicit JOINs.
961 // Thus, the explicit join order specified in the query will be the
962 // actual order in which the relations are joined."
963 // See CSPACE-5945 for further discussion of why this setting is needed.
965 // Adding this statement is commented out here for now. It significantly
966 // improved query performance for authority item / term queries where
967 // large numbers of rows were retrieved, but appears to have resulted
968 // in consistently slower-than-desired query performance where zero or
969 // very few records were retrieved. See notes on CSPACE-5945. - ADR 2013-04-09
970 // String joinControlSql = "SET LOCAL join_collapse_limit TO 1;";
972 // Build the query statement
974 // Start with the default query
975 String selectStatement =
976 "SELECT DISTINCT commonschema.id"
977 + " FROM " + handler.getServiceContext().getCommonPartLabel() + " commonschema";
981 + " ON misc.id = commonschema.id"
982 + " INNER JOIN hierarchy hierarchy_termgroup"
983 + " ON hierarchy_termgroup.parentid = misc.id"
984 + " INNER JOIN " + handler.getJDBCQueryParams().get(TERM_GROUP_TABLE_NAME_PARAM) + " termgroup"
985 + " ON termgroup.id = hierarchy_termgroup.id ";
988 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
989 // Value for replaceable parameter 1 in the query
990 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
991 // If the value of the partial term query parameter is blank ('pt='),
992 // return all records, subject to restriction by any limit clause
993 if (Tools.isBlank(partialTerm)) {
996 // Otherwise, return records that match the supplied partial term
998 " WHERE (termgroup.termdisplayname ILIKE ?)";
1001 // At present, results are ordered in code, below, rather than in SQL,
1002 // and the orderByClause below is thus intentionally blank.
1004 // To implement the orderByClause below in SQL; e.g. via
1005 // 'ORDER BY termgroup.termdisplayname', the relevant column
1006 // must be returned by the SELECT statement.
1007 String orderByClause = "";
1010 TenantBindingConfigReaderImpl tReader =
1011 ServiceMain.getInstance().getTenantBindingConfigReader();
1012 TenantBindingType tenantBinding = tReader.getTenantBinding(ctx.getTenantId());
1013 String maxListItemsLimit = TenantBindingUtils.getPropertyValue(tenantBinding,
1014 IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES);
1016 " LIMIT " + getMaxItemsLimitOnJdbcQueries(maxListItemsLimit); // implicit int-to-String conversion
1018 // After building the individual parts of the query, set the values
1019 // of replaceable parameters that will be inserted into that query
1020 // and optionally add restrictions
1022 List<String> params = new ArrayList<>();
1024 if (Tools.notBlank(whereClause)) {
1026 // Read tenant bindings configuration to determine whether
1027 // to automatically insert leading, as well as trailing, wildcards
1028 // into the term matching string.
1029 String usesStartingWildcard = TenantBindingUtils.getPropertyValue(tenantBinding,
1030 IQueryManager.TENANT_USES_STARTING_WILDCARD_FOR_PARTIAL_TERM);
1031 // Handle user-provided leading wildcard characters, in the
1032 // configuration where a leading wildcard is not automatically inserted.
1033 // (The user-provided wildcard must be in the first, or "starting"
1034 // character position in the partial term value.)
1035 if (Tools.notBlank(usesStartingWildcard)) {
1036 if (usesStartingWildcard.equalsIgnoreCase(Boolean.FALSE.toString())) {
1037 partialTerm = handleProvidedStartingWildcard(partialTerm);
1038 // Otherwise, in the configuration where a leading wildcard
1039 // is usually automatically inserted, handle the cases where
1040 // a user has entered an anchor character in the first position
1041 // in the starting term value. In those cases, strip that
1042 // anchor character and don't add a leading wildcard
1044 if (partialTerm.startsWith(USER_SUPPLIED_ANCHOR_CHAR)) {
1045 partialTerm = partialTerm.substring(1, partialTerm.length());
1046 // Otherwise, automatically add a leading wildcard
1048 partialTerm = JDBCTools.SQL_WILDCARD + partialTerm;
1052 // Add SQL wildcards in the midst of the partial term match search
1053 // expression, whever user-supplied wildcards appear, except in the
1054 // first or last character positions of the search expression.
1055 partialTerm = subtituteWildcardsInPartialTerm(partialTerm);
1057 // If a designated 'anchor character' is present as the last character
1058 // in the search expression, strip that character and don't add
1059 // a trailing wildcard
1060 int lastCharPos = partialTerm.length() - 1;
1061 if (partialTerm.endsWith(USER_SUPPLIED_ANCHOR_CHAR) && lastCharPos > 0) {
1062 partialTerm = partialTerm.substring(0, lastCharPos);
1064 // Otherwise, automatically add a trailing wildcard
1065 partialTerm = partialTerm + JDBCTools.SQL_WILDCARD;
1067 params.add(partialTerm);
1070 // Optionally add restrictions to the default query, based on variables
1071 // in the current request
1073 // Restrict the query to filter out deleted records, if requested
1074 String includeDeleted = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_NONDELETED);
1075 if (includeDeleted != null && includeDeleted.equalsIgnoreCase(Boolean.FALSE.toString())) {
1076 whereClause = whereClause
1077 + " AND (misc.lifecyclestate <> '" + WorkflowClient.WORKFLOWSTATE_DELETED + "')";
1080 // If a particular authority is specified, restrict the query further
1081 // to return only records within that authority
1082 String inAuthorityValue = (String) handler.getJDBCQueryParams().get(IN_AUTHORITY_PARAM);
1083 if (Tools.notBlank(inAuthorityValue)) {
1084 // Handle the '_ALL_' case for inAuthority
1085 if (inAuthorityValue.equals(PARENT_WILDCARD)) {
1086 // Add nothing to the query here if it should match within all authorities
1088 whereClause = whereClause
1089 + " AND (commonschema.inauthority = ?)";
1090 params.add(inAuthorityValue); // Value for replaceable parameter 2 in the query
1094 // Restrict the query further to return only records pertaining to
1095 // the current tenant, unless:
1096 // * Data for this service, in this tenant, is stored in its own,
1097 // separate repository, rather than being intermingled with other
1098 // tenants' data in the default repository; or
1099 // * Restriction by tenant ID in JDBC queries has been disabled,
1100 // via configuration for this tenant,
1101 if (restrictJDBCQueryByTenantID(tenantBinding, ctx)) {
1102 joinClauses = joinClauses
1103 + " INNER JOIN collectionspace_core core"
1104 + " ON core.id = hierarchy_termgroup.parentid";
1105 whereClause = whereClause
1106 + " AND (core.tenantid = ?)";
1107 params.add(ctx.getTenantId()); // Value for replaceable parameter 3 in the query
1110 // Piece together the SQL query from its parts
1111 String querySql = selectStatement + joinClauses + whereClause + orderByClause + limitClause;
1113 // Note: PostgreSQL 9.2 introduced a change that may improve performance
1114 // of certain queries using JDBC PreparedStatements. See comments on
1115 // CSPACE-5943 for details.
1117 // See a comment above for the reason that the joinControl SQL statement,
1118 // along with its corresponding prepared statement builder, is commented out for now.
1119 // PreparedStatementBuilder joinControlBuilder = new PreparedStatementBuilder(joinControlSql);
1120 PreparedStatementSimpleBuilder queryBuilder = new PreparedStatementSimpleBuilder(querySql, params);
1121 List<PreparedStatementBuilder> builders = new ArrayList<>();
1122 // builders.add(joinControlBuilder);
1123 builders.add(queryBuilder);
1124 String dataSourceName = JDBCTools.NUXEO_DATASOURCE_NAME;
1125 String repositoryName = ctx.getRepositoryName();
1126 final Boolean EXECUTE_WITHIN_TRANSACTION = true;
1127 Set<String> docIds = new HashSet<>();
1129 List<CachedRowSet> resultsList = JDBCTools.executePreparedQueries(builders,
1130 dataSourceName, repositoryName, EXECUTE_WITHIN_TRANSACTION);
1132 // At least one set of results is expected, from the second prepared
1133 // statement to be executed.
1134 // If fewer results are returned, return an empty list of document models
1135 if (resultsList == null || resultsList.size() < 1) {
1136 return result; // return an empty list of document models
1138 // The join control query (if enabled - it is currently commented
1139 // out as per comments above) will not return results, so query results
1140 // will be the first set of results (rowSet) returned in the list
1141 CachedRowSet queryResults = resultsList.get(0);
1143 // If the result from executing the query is null or contains zero rows,
1144 // return an empty list of document models
1145 if (queryResults == null) {
1146 return result; // return an empty list of document models
1148 queryResults.last();
1149 if (queryResults.getRow() == 0) {
1150 return result; // return an empty list of document models
1153 // Otherwise, get the document IDs from the results of the query
1155 queryResults.beforeFirst();
1156 while (queryResults.next()) {
1157 id = queryResults.getString(1);
1158 if (Tools.notBlank(id)) {
1162 } catch (SQLException sqle) {
1163 logger.warn("Could not obtain document IDs via SQL query '" + querySql + "': " + sqle.getMessage());
1164 return result; // return an empty list of document models
1167 // Get a list of document models, using the list of IDs obtained from the query
1169 // FIXME: Check whether we have a 'get document models from list of CSIDs'
1170 // utility method like this, and if not, add this to the appropriate
1172 DocumentModel docModel;
1173 for (String docId : docIds) {
1174 docModel = NuxeoUtils.getDocumentModel(repoSession, docId);
1175 if (docModel == null) {
1176 logger.warn("Could not obtain document model for document with ID " + docId);
1178 result.add(NuxeoUtils.getDocumentModel(repoSession, docId));
1182 // Order the results
1183 final String COMMON_PART_SCHEMA = handler.getServiceContext().getCommonPartLabel();
1184 final String DISPLAY_NAME_XPATH =
1185 "//" + handler.getJDBCQueryParams().get(TERM_GROUP_LIST_NAME) + "/[0]/termDisplayName";
1186 Collections.sort(result, new Comparator<DocumentModel>() {
1188 public int compare(DocumentModel doc1, DocumentModel doc2) {
1189 String termDisplayName1 = (String) NuxeoUtils.getXPathValue(doc1, COMMON_PART_SCHEMA, DISPLAY_NAME_XPATH);
1190 String termDisplayName2 = (String) NuxeoUtils.getXPathValue(doc2, COMMON_PART_SCHEMA, DISPLAY_NAME_XPATH);
1191 return termDisplayName1.compareToIgnoreCase(termDisplayName2);
1199 private DocumentModelList getFilteredCMIS(RepositoryInstance repoSession, ServiceContext ctx, DocumentHandler handler, QueryContext queryContext)
1200 throws DocumentNotFoundException, DocumentException {
1202 DocumentModelList result = new DocumentModelListImpl();
1204 String query = handler.getCMISQuery(queryContext);
1206 DocumentFilter docFilter = handler.getDocumentFilter();
1207 int pageSize = docFilter.getPageSize();
1208 int offset = docFilter.getOffset();
1209 if (logger.isDebugEnabled()) {
1210 logger.debug("Executing CMIS query: " + query.toString()
1211 + "with pageSize: " + pageSize + " at offset: " + offset);
1214 // If we have limit and/or offset, then pass true to get totalSize
1215 // in returned DocumentModelList.
1216 Profiler profiler = new Profiler(this, 2);
1217 profiler.log("Executing CMIS query: " + query.toString());
1220 IterableQueryResult queryResult = makeCMISQLQuery(repoSession, query, queryContext);
1222 int totalSize = (int) queryResult.size();
1223 ((DocumentModelListImpl) result).setTotalSize(totalSize);
1224 // Skip the rows before our offset
1226 queryResult.skipTo(offset);
1229 for (Map<String, Serializable> row : queryResult) {
1230 if (logger.isTraceEnabled()) {
1231 logger.trace(" Hierarchy Table ID is:" + row.get(IQueryManager.CMIS_TARGET_NUXEO_ID)
1232 + " nuxeo:pathSegment is: " + row.get(IQueryManager.CMIS_TARGET_NAME));
1234 String nuxeoId = (String) row.get(IQueryManager.CMIS_TARGET_NUXEO_ID);
1235 DocumentModel docModel = NuxeoUtils.getDocumentModel(repoSession, nuxeoId);
1236 result.add(docModel);
1238 if (nRows >= pageSize && pageSize != 0) { // A page size of zero means that they want all of them
1239 logger.debug("Got page full of items - quitting");
1244 queryResult.close();
1249 } catch (Exception e) {
1250 if (logger.isDebugEnabled()) {
1251 logger.debug("Caught exception ", e);
1253 throw new DocumentException(e);
1257 // Since we're not supporting paging yet for CMIS queries, we need to perform
1258 // a workaround for the paging information we return in our list of results
1261 if (result != null) {
1262 docFilter.setStartPage(0);
1263 if (totalSize > docFilter.getPageSize()) {
1264 docFilter.setPageSize(totalSize);
1265 ((DocumentModelListImpl)result).setTotalSize(totalSize);
1273 private String logException(Exception e, String msg) {
1274 String result = null;
1276 String exceptionMessage = e.getMessage();
1277 exceptionMessage = exceptionMessage != null ? exceptionMessage : "<No details provided>";
1278 result = msg = msg + ". Caught exception:" + exceptionMessage;
1280 if (logger.isTraceEnabled() == true) {
1281 logger.error(msg, e);
1290 * update given document in the Nuxeo repository
1292 * @param ctx service context under which this method is invoked
1293 * @param csid of the document
1294 * @param handler should be used by the caller to provide and transform the
1296 * @throws BadRequestException
1297 * @throws DocumentNotFoundException
1298 * @throws TransactionException if the transaction times out or otherwise
1299 * cannot be successfully completed
1300 * @throws DocumentException
1303 public void update(ServiceContext ctx, String csid, DocumentHandler handler)
1304 throws BadRequestException, DocumentNotFoundException, TransactionException,
1306 if (handler == null) {
1307 throw new IllegalArgumentException(
1308 "RepositoryJavaClient.update: document handler is missing.");
1311 RepositoryInstance repoSession = null;
1313 handler.prepare(Action.UPDATE);
1314 repoSession = getRepositorySession(ctx);
1315 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
1316 DocumentModel doc = null;
1318 doc = repoSession.getDocument(docRef);
1319 } catch (ClientException ce) {
1320 String msg = logException(ce, "Could not find document to update with CSID=" + csid);
1321 throw new DocumentNotFoundException(msg, ce);
1323 // Check for a versioned document, and check In and Out before we proceed.
1324 if (((DocumentModelHandler) handler).supportsVersioning()) {
1325 /* Once we advance to 5.5 or later, we can add this.
1326 * See also https://jira.nuxeo.com/browse/NXP-8506
1327 if(!doc.isVersionable()) {
1328 throw new DocumentException("Configuration for: "
1329 +handler.getServiceContextPath()+" supports versioning, but Nuxeo config does not!");
1332 /* Force a version number - Not working. Apparently we need to configure the uid schema??
1333 if(doc.getProperty("uid","major_version") == null) {
1334 doc.setProperty("uid","major_version",1);
1336 if(doc.getProperty("uid","minor_version") == null) {
1337 doc.setProperty("uid","minor_version",0);
1340 doc.checkIn(VersioningOption.MINOR, null);
1345 // Set reposession to handle the document
1347 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1348 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
1349 handler.handle(Action.UPDATE, wrapDoc);
1350 repoSession.saveDocument(doc);
1352 handler.complete(Action.UPDATE, wrapDoc);
1353 } catch (BadRequestException bre) {
1355 } catch (DocumentException de) {
1357 } catch (WebApplicationException wae) {
1359 } catch (Exception e) {
1360 if (logger.isDebugEnabled()) {
1361 logger.debug("Caught exception ", e);
1363 throw new DocumentException(e);
1365 if (repoSession != null) {
1366 releaseRepositorySession(ctx, repoSession);
1372 * Save a documentModel to the Nuxeo repository.
1374 * @param ctx service context under which this method is invoked
1375 * @param repoSession
1376 * @param docModel the document to save
1377 * @param fSaveSession if TRUE, will call CoreSession.save() to save
1378 * accumulated changes.
1379 * @throws ClientException
1380 * @throws DocumentException
1382 public void saveDocWithoutHandlerProcessing(
1383 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1384 RepositoryInstance repoSession,
1385 DocumentModel docModel,
1386 boolean fSaveSession)
1387 throws ClientException, DocumentException {
1390 repoSession.saveDocument(docModel);
1394 } catch (ClientException ce) {
1396 } catch (Exception e) {
1397 if (logger.isDebugEnabled()) {
1398 logger.debug("Caught exception ", e);
1400 throw new DocumentException(e);
1405 * Save a list of documentModels to the Nuxeo repository.
1407 * @param ctx service context under which this method is invoked
1408 * @param repoSession a repository session
1409 * @param docModelList a list of document models
1410 * @param fSaveSession if TRUE, will call CoreSession.save() to save
1411 * accumulated changes.
1412 * @throws ClientException
1413 * @throws DocumentException
1415 public void saveDocListWithoutHandlerProcessing(
1416 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1417 RepositoryInstance repoSession,
1418 DocumentModelList docList,
1419 boolean fSaveSession)
1420 throws ClientException, DocumentException {
1422 DocumentModel[] docModelArray = new DocumentModel[docList.size()];
1423 repoSession.saveDocuments(docList.toArray(docModelArray));
1427 } catch (ClientException ce) {
1429 } catch (Exception e) {
1430 logger.error("Caught exception ", e);
1431 throw new DocumentException(e);
1436 * delete a document from the Nuxeo repository
1438 * @param ctx service context under which this method is invoked
1439 * @param id of the document
1440 * @throws DocumentException
1443 public void delete(ServiceContext ctx, String id, DocumentHandler handler) throws DocumentNotFoundException,
1444 DocumentException, TransactionException {
1446 throw new IllegalArgumentException(
1447 "delete(ctx, ix, handler): ctx is missing");
1449 if (handler == null) {
1450 throw new IllegalArgumentException(
1451 "delete(ctx, ix, handler): handler is missing");
1453 if (logger.isDebugEnabled()) {
1454 logger.debug("Deleting document with CSID=" + id);
1456 RepositoryInstance repoSession = null;
1458 handler.prepare(Action.DELETE);
1459 repoSession = getRepositorySession(ctx);
1460 DocumentWrapper<DocumentModel> wrapDoc = null;
1462 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
1463 wrapDoc = new DocumentWrapperImpl<DocumentModel>(repoSession.getDocument(docRef));
1464 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1465 handler.handle(Action.DELETE, wrapDoc);
1466 repoSession.removeDocument(docRef);
1467 } catch (ClientException ce) {
1468 String msg = logException(ce, "Could not find document to delete with CSID=" + id);
1469 throw new DocumentNotFoundException(msg, ce);
1472 handler.complete(Action.DELETE, wrapDoc);
1473 } catch (DocumentException de) {
1475 } catch (Exception e) {
1476 if (logger.isDebugEnabled()) {
1477 logger.debug("Caught exception ", e);
1479 throw new DocumentException(e);
1481 if (repoSession != null) {
1482 releaseRepositorySession(ctx, repoSession);
1488 * @see org.collectionspace.services.common.storage.StorageClient#delete(org.collectionspace.services.common.context.ServiceContext, java.lang.String, org.collectionspace.services.common.document.DocumentHandler)
1492 public void delete(@SuppressWarnings("rawtypes") ServiceContext ctx, String id)
1493 throws DocumentNotFoundException, DocumentException {
1494 throw new UnsupportedOperationException();
1495 // Use the other delete instead
1499 public Hashtable<String, String> retrieveWorkspaceIds(RepositoryDomainType repoDomain) throws Exception {
1500 return NuxeoConnectorEmbedded.getInstance().retrieveWorkspaceIds(repoDomain);
1504 public String createDomain(RepositoryDomainType repositoryDomain) throws Exception {
1505 RepositoryInstance repoSession = null;
1506 String domainId = null;
1509 // Open a connection to the domain's repo/db
1511 String repoName = repositoryDomain.getRepositoryName();
1512 repoSession = getRepositorySession(repoName); // domainName=storageName=repoName=databaseName
1514 // First create the top-level domain directory
1516 String domainName = repositoryDomain.getStorageName();
1517 DocumentRef parentDocRef = new PathRef("/");
1518 DocumentModel parentDoc = repoSession.getDocument(parentDocRef);
1519 DocumentModel domainDoc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1520 domainName, NUXEO_CORE_TYPE_DOMAIN);
1521 domainDoc.setPropertyValue("dc:title", domainName);
1522 domainDoc.setPropertyValue("dc:description", "A CollectionSpace domain "
1524 domainDoc = repoSession.createDocument(domainDoc);
1525 domainId = domainDoc.getId();
1528 // Next, create a "Workspaces" root directory to contain the workspace folders for the individual service documents
1530 DocumentModel workspacesRoot = repoSession.createDocumentModel(domainDoc.getPathAsString(),
1531 NuxeoUtils.Workspaces, NUXEO_CORE_TYPE_WORKSPACEROOT);
1532 workspacesRoot.setPropertyValue("dc:title", NuxeoUtils.Workspaces);
1533 workspacesRoot.setPropertyValue("dc:description", "A CollectionSpace workspaces directory for "
1534 + domainDoc.getPathAsString());
1535 workspacesRoot = repoSession.createDocument(workspacesRoot);
1536 String workspacesRootId = workspacesRoot.getId();
1539 if (logger.isDebugEnabled()) {
1540 logger.debug("Created tenant domain name=" + domainName
1541 + " id=" + domainId + " "
1542 + NuxeoUtils.Workspaces + " id=" + workspacesRootId);
1543 logger.debug("Path to Domain: " + domainDoc.getPathAsString());
1544 logger.debug("Path to Workspaces root: " + workspacesRoot.getPathAsString());
1546 } catch (Exception e) {
1547 if (logger.isDebugEnabled()) {
1548 logger.debug("Could not create tenant domain name=" + repositoryDomain.getStorageName() + " caught exception ", e);
1552 if (repoSession != null) {
1553 releaseRepositorySession(null, repoSession);
1561 public String getDomainId(RepositoryDomainType repositoryDomain) throws Exception {
1562 String domainId = null;
1563 RepositoryInstance repoSession = null;
1565 String repoName = repositoryDomain.getRepositoryName();
1566 String domainStorageName = repositoryDomain.getStorageName();
1567 if (domainStorageName != null && !domainStorageName.isEmpty()) {
1569 repoSession = getRepositorySession(repoName);
1570 DocumentRef docRef = new PathRef("/" + domainStorageName);
1571 DocumentModel domain = repoSession.getDocument(docRef);
1572 domainId = domain.getId();
1573 } catch (Exception e) {
1574 if (logger.isTraceEnabled()) {
1575 logger.trace("Caught exception ", e); // The document doesn't exist, this let's us know we need to create it
1577 //there is no way to identify if document does not exist due to
1578 //lack of typed exception for getDocument method
1581 if (repoSession != null) {
1582 releaseRepositorySession(null, repoSession);
1591 * Returns the workspaces root directory for a given domain.
1593 private DocumentModel getWorkspacesRoot(RepositoryInstance repoSession,
1594 String domainName) throws Exception {
1595 DocumentModel result = null;
1597 String domainPath = "/" + domainName;
1598 DocumentRef parentDocRef = new PathRef(domainPath);
1599 DocumentModelList domainChildrenList = repoSession.getChildren(
1601 Iterator<DocumentModel> witer = domainChildrenList.iterator();
1602 while (witer.hasNext()) {
1603 DocumentModel childNode = witer.next();
1604 if (NuxeoUtils.Workspaces.equalsIgnoreCase(childNode.getName())) {
1606 logger.trace("Found workspaces directory at: " + result.getPathAsString());
1611 if (result == null) {
1612 throw new ClientException("Could not find workspace root directory in: "
1620 * @see org.collectionspace.services.common.repository.RepositoryClient#createWorkspace(java.lang.String, java.lang.String)
1623 public String createWorkspace(RepositoryDomainType repositoryDomain, String workspaceName) throws Exception {
1624 RepositoryInstance repoSession = null;
1625 String workspaceId = null;
1627 String repoName = repositoryDomain.getRepositoryName();
1628 repoSession = getRepositorySession(repoName);
1630 String domainStorageName = repositoryDomain.getStorageName();
1631 DocumentModel parentDoc = getWorkspacesRoot(repoSession, domainStorageName);
1632 if (logger.isTraceEnabled()) {
1633 for (String facet : parentDoc.getFacets()) {
1634 logger.trace("Facet: " + facet);
1638 DocumentModel doc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1639 workspaceName, NuxeoUtils.WORKSPACE_DOCUMENT_TYPE);
1640 doc.setPropertyValue("dc:title", workspaceName);
1641 doc.setPropertyValue("dc:description", "A CollectionSpace workspace for "
1643 doc = repoSession.createDocument(doc);
1644 workspaceId = doc.getId();
1646 if (logger.isDebugEnabled()) {
1647 logger.debug("Created workspace name=" + workspaceName
1648 + " id=" + workspaceId);
1650 } catch (Exception e) {
1651 if (logger.isDebugEnabled()) {
1652 logger.debug("createWorkspace caught exception ", e);
1656 if (repoSession != null) {
1657 releaseRepositorySession(null, repoSession);
1664 * @see org.collectionspace.services.common.repository.RepositoryClient#getWorkspaceId(java.lang.String, java.lang.String)
1668 public String getWorkspaceId(String tenantDomain, String workspaceName) throws Exception {
1669 String workspaceId = null;
1671 RepositoryInstance repoSession = null;
1673 repoSession = getRepositorySession((ServiceContext) null);
1674 DocumentRef docRef = new PathRef(
1676 + "/" + NuxeoUtils.Workspaces
1677 + "/" + workspaceName);
1678 DocumentModel workspace = repoSession.getDocument(docRef);
1679 workspaceId = workspace.getId();
1680 } catch (DocumentException de) {
1682 } catch (Exception e) {
1683 if (logger.isDebugEnabled()) {
1684 logger.debug("Caught exception ", e);
1686 throw new DocumentException(e);
1688 if (repoSession != null) {
1689 releaseRepositorySession(null, repoSession);
1696 public RepositoryInstance getRepositorySession(ServiceContext ctx) throws Exception {
1697 return getRepositorySession(ctx, ctx.getRepositoryName());
1700 public RepositoryInstance getRepositorySession(String repoName) throws Exception {
1701 return getRepositorySession(null, repoName);
1705 * Gets the repository session. - Package access only. If the 'ctx' param is
1706 * null then the repo name must be non-mull and vice-versa
1708 * @return the repository session
1709 * @throws Exception the exception
1711 public RepositoryInstance getRepositorySession(ServiceContext ctx, String repoName) throws Exception {
1712 RepositoryInstance repoSession = null;
1714 Profiler profiler = new Profiler("getRepositorySession():", 2);
1717 // To get a connection to the Nuxeo repo, we need either a valid ServiceContext instance or a repository name
1720 repoName = ctx.getRepositoryName(); // Notice we are overriding the passed in 'repoName' since we have a valid service context passed in to us
1721 repoSession = (RepositoryInstance) ctx.getCurrentRepositorySession(); // Look to see if one exists in the context before creating one
1722 } else if (repoName == null || repoName.trim().isEmpty()) {
1723 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.");
1724 logger.error(errMsg);
1725 throw new Exception(errMsg);
1728 // 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
1729 // just the repo name
1731 if (repoSession == null) {
1732 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1733 repoSession = client.openRepository(repoName);
1735 if (logger.isDebugEnabled() == true) {
1736 logger.warn("Reusing the current context's repository session.");
1741 if (logger.isTraceEnabled()) {
1742 logger.trace("Testing call to getRepository() repository root: " + repoSession.getRootDocument());
1744 } catch (Throwable e) {
1745 logger.trace("Test call to Nuxeo's getRepository() repository root failed", e);
1751 ctx.setCurrentRepositorySession(repoSession); // For reusing, save the repository session in the current service context
1758 * Release repository session. - Package access only.
1760 * @param repoSession the repo session
1762 public void releaseRepositorySession(ServiceContext ctx, RepositoryInstance repoSession) throws TransactionException {
1764 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1767 ctx.clearCurrentRepositorySession(); //clear the current context of the now closed repo session
1768 if (ctx.getCurrentRepositorySession() == null) {
1769 client.releaseRepository(repoSession); //release the repo session if the service context's ref count is zeo.
1772 client.releaseRepository(repoSession); //repo session was acquired without a service context
1774 } catch (TransactionRuntimeException tre) {
1775 TransactionException te = new TransactionException(tre);
1776 logger.error(te.getMessage(), tre); // Log the standard transaction exception message, plus an exception-specific stack trace
1778 } catch (Exception e) {
1779 logger.error("Could not close the repository session", e);
1780 // no need to throw this service specific exception
1785 public void doWorkflowTransition(ServiceContext ctx, String id,
1786 DocumentHandler handler, TransitionDef transitionDef)
1787 throws BadRequestException, DocumentNotFoundException,
1789 // 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
1792 private String handleProvidedStartingWildcard(String partialTerm) {
1793 if (Tools.notBlank(partialTerm)) {
1794 if (partialTerm.substring(0, 1).equals(USER_SUPPLIED_WILDCARD)) {
1795 StringBuffer buffer = new StringBuffer(partialTerm);
1796 buffer.setCharAt(0, JDBCTools.SQL_WILDCARD.charAt(0));
1797 partialTerm = buffer.toString();
1804 * Replaces user-supplied wildcards with SQL wildcards, in a partial term
1805 * matching search expression.
1807 * The scope of this replacement excludes the beginning character
1808 * in that search expression, as that character is treated specially.
1810 * @param partialTerm
1811 * @return the partial term, with any user-supplied wildcards replaced
1814 private String subtituteWildcardsInPartialTerm(String partialTerm) {
1815 if (Tools.isBlank(partialTerm)) {
1818 if (! partialTerm.contains(USER_SUPPLIED_WILDCARD)) {
1821 int len = partialTerm.length();
1822 // Partial term search expressions of 2 or fewer characters
1823 // currently aren't amenable to the use of wildcards
1825 logger.warn("Partial term match search expression of just 1-2 characters in length contains a user-supplied wildcard: " + partialTerm);
1826 logger.warn("Will handle that character as a literal value, rather than as a wildcard ...");
1829 return partialTerm.substring(0, 1) // first char
1830 + partialTerm.substring(1, len).replaceAll(USER_SUPPLIED_WILDCARD_REGEX, JDBCTools.SQL_WILDCARD);
1834 private int getMaxItemsLimitOnJdbcQueries(String maxListItemsLimit) {
1835 final int DEFAULT_ITEMS_LIMIT = 40;
1836 if (maxListItemsLimit == null) {
1837 return DEFAULT_ITEMS_LIMIT;
1841 itemsLimit = Integer.parseInt(maxListItemsLimit);
1842 if (itemsLimit < 1) {
1843 logger.warn("Value of configuration setting "
1844 + IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES
1845 + " must be a positive integer; invalid current value is " + maxListItemsLimit);
1846 logger.warn("Reverting to default value of " + DEFAULT_ITEMS_LIMIT);
1847 itemsLimit = DEFAULT_ITEMS_LIMIT;
1849 } catch (NumberFormatException nfe) {
1850 logger.warn("Value of configuration setting "
1851 + IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES
1852 + " must be a positive integer; invalid current value is " + maxListItemsLimit);
1853 logger.warn("Reverting to default value of " + DEFAULT_ITEMS_LIMIT);
1854 itemsLimit = DEFAULT_ITEMS_LIMIT;
1860 * Identifies whether a restriction on tenant ID - to return only records
1861 * pertaining to the current tenant - is required in a JDBC query.
1863 * @param tenantBinding a tenant binding configuration.
1864 * @param ctx a service context.
1865 * @return true if a restriction on tenant ID is required in the query;
1866 * false if a restriction is not required.
1868 private boolean restrictJDBCQueryByTenantID(TenantBindingType tenantBinding, ServiceContext ctx) {
1869 boolean restrict = true;
1870 // If data for the current service, in the current tenant, is isolated
1871 // within its own separate, per-tenant repository, as contrasted with
1872 // being intermingled with other tenants' data in the default repository,
1873 // no restriction on Tenant ID is required in the query.
1874 String repositoryDomainName = ConfigUtils.getRepositoryName(tenantBinding, ctx.getRepositoryDomainName());
1875 if (!(repositoryDomainName.equals(ConfigUtils.DEFAULT_NUXEO_REPOSITORY_NAME))) {
1878 // If a configuration setting for this tenant identifies that JDBC
1879 // queries should not be restricted by tenant ID (perhaps because
1880 // there is always expected to be only one tenant's data present in
1881 // the system), no restriction on Tenant ID is required in the query.
1882 String queriesRestrictedByTenantId = TenantBindingUtils.getPropertyValue(tenantBinding,
1883 IQueryManager.JDBC_QUERIES_ARE_TENANT_ID_RESTRICTED);
1884 if (Tools.notBlank(queriesRestrictedByTenantId) &&
1885 queriesRestrictedByTenantId.equalsIgnoreCase(Boolean.FALSE.toString())) {