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 = "*";
118 * Instantiates a new repository java client impl.
120 public RepositoryJavaClientImpl() {
124 public void assertWorkflowState(ServiceContext ctx,
125 DocumentModel docModel) throws DocumentNotFoundException, ClientException {
126 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
127 if (queryParams != null) {
129 // Look for the workflow "delete" query param and see if we need to assert that the
130 // docModel is in a non-deleted workflow state.
132 String currentState = docModel.getCurrentLifeCycleState();
133 String includeDeletedStr = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_NONDELETED);
134 boolean includeDeleted = includeDeletedStr == null ? true : Boolean.parseBoolean(includeDeletedStr);
135 if (includeDeleted == false) {
137 // We don't wanted soft-deleted object, so throw an exception if this one is soft-deleted.
139 if (currentState.equalsIgnoreCase(WorkflowClient.WORKFLOWSTATE_DELETED)) {
140 String msg = "The GET assertion that docModel not be in 'deleted' workflow state failed.";
142 throw new DocumentNotFoundException(msg);
149 * create document in the Nuxeo repository
151 * @param ctx service context under which this method is invoked
152 * @param handler should be used by the caller to provide and transform the
154 * @return id in repository of the newly created document
155 * @throws BadRequestException
156 * @throws TransactionException
157 * @throws DocumentException
160 public String create(ServiceContext ctx,
161 DocumentHandler handler) throws BadRequestException,
162 TransactionException, DocumentException {
164 String docType = NuxeoUtils.getTenantQualifiedDocType(ctx); //ctx.getDocumentType();
165 if (docType == null) {
166 throw new IllegalArgumentException(
167 "RepositoryJavaClient.create: docType is missing");
170 if (handler == null) {
171 throw new IllegalArgumentException(
172 "RepositoryJavaClient.create: handler is missing");
174 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
175 if (nuxeoWspaceId == null) {
176 throw new DocumentNotFoundException(
177 "Unable to find workspace for service " + ctx.getServiceName()
178 + " check if the workspace exists in the Nuxeo repository");
181 RepositoryInstance repoSession = null;
183 handler.prepare(Action.CREATE);
184 repoSession = getRepositorySession(ctx);
185 DocumentRef nuxeoWspace = new IdRef(nuxeoWspaceId);
186 DocumentModel wspaceDoc = repoSession.getDocument(nuxeoWspace);
187 String wspacePath = wspaceDoc.getPathAsString();
188 //give our own ID so PathRef could be constructed later on
189 String id = IdUtils.generateId(UUID.randomUUID().toString());
190 // create document model
191 DocumentModel doc = repoSession.createDocumentModel(wspacePath, id, docType);
192 /* Check for a versioned document, and check In and Out before we proceed.
193 * This does not work as we do not have the uid schema on our docs.
194 if(((DocumentModelHandler) handler).supportsVersioning()) {
195 doc.setProperty("uid","major_version",1);
196 doc.setProperty("uid","minor_version",0);
199 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
200 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
201 handler.handle(Action.CREATE, wrapDoc);
202 // create document with documentmodel
203 doc = repoSession.createDocument(doc);
205 // TODO for sub-docs need to call into the handler to let it deal with subitems. Pass in the id,
206 // and assume the handler has the state it needs (doc fragments).
207 handler.complete(Action.CREATE, wrapDoc);
209 } catch (BadRequestException bre) {
211 } catch (Exception e) {
212 logger.error("Caught exception ", e);
213 throw new DocumentException(e);
215 if (repoSession != null) {
216 releaseRepositorySession(ctx, repoSession);
223 * get document from the Nuxeo repository
225 * @param ctx service context under which this method is invoked
226 * @param id of the document to retrieve
227 * @param handler should be used by the caller to provide and transform the
229 * @throws DocumentNotFoundException if the document cannot be found in the
231 * @throws TransactionException
232 * @throws DocumentException
235 public void get(ServiceContext ctx, String id, DocumentHandler handler)
236 throws DocumentNotFoundException, TransactionException, DocumentException {
238 if (handler == null) {
239 throw new IllegalArgumentException(
240 "RepositoryJavaClient.get: handler is missing");
243 RepositoryInstance repoSession = null;
245 handler.prepare(Action.GET);
246 repoSession = getRepositorySession(ctx);
247 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
248 DocumentModel docModel = null;
250 docModel = repoSession.getDocument(docRef);
251 assertWorkflowState(ctx, docModel);
252 } catch (ClientException ce) {
253 String msg = logException(ce, "Could not find document with CSID=" + id);
254 throw new DocumentNotFoundException(msg, ce);
257 // Set repository session to handle the document
259 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
260 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(docModel);
261 handler.handle(Action.GET, wrapDoc);
262 handler.complete(Action.GET, wrapDoc);
263 } catch (IllegalArgumentException iae) {
265 } catch (DocumentException de) {
267 } catch (Exception e) {
268 if (logger.isDebugEnabled()) {
269 logger.debug("Caught exception ", e);
271 throw new DocumentException(e);
273 if (repoSession != null) {
274 releaseRepositorySession(ctx, repoSession);
280 * get a document from the Nuxeo repository, using the docFilter params.
282 * @param ctx service context under which this method is invoked
283 * @param handler should be used by the caller to provide and transform the
284 * document. Handler must have a docFilter set to return a single item.
285 * @throws DocumentNotFoundException if the document cannot be found in the
287 * @throws TransactionException
288 * @throws DocumentException
291 public void get(ServiceContext ctx, DocumentHandler handler)
292 throws DocumentNotFoundException, TransactionException, DocumentException {
293 QueryContext queryContext = new QueryContext(ctx, handler);
294 RepositoryInstance repoSession = null;
297 handler.prepare(Action.GET);
298 repoSession = getRepositorySession(ctx);
300 DocumentModelList docList = null;
301 // force limit to 1, and ignore totalSize
302 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
303 docList = repoSession.query(query, null, 1, 0, false);
304 if (docList.size() != 1) {
305 throw new DocumentNotFoundException("No document found matching filter params: " + query);
307 DocumentModel doc = docList.get(0);
309 if (logger.isDebugEnabled()) {
310 logger.debug("Executed NXQL query: " + query);
313 //set reposession to handle the document
314 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
315 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
316 handler.handle(Action.GET, wrapDoc);
317 handler.complete(Action.GET, wrapDoc);
318 } catch (IllegalArgumentException iae) {
320 } catch (DocumentException de) {
322 } catch (Exception e) {
323 if (logger.isDebugEnabled()) {
324 logger.debug("Caught exception ", e);
326 throw new DocumentException(e);
328 if (repoSession != null) {
329 releaseRepositorySession(ctx, repoSession);
334 public DocumentWrapper<DocumentModel> getDoc(
335 RepositoryInstance repoSession,
336 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
337 String csid) throws DocumentNotFoundException, DocumentException {
338 DocumentWrapper<DocumentModel> wrapDoc = null;
341 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
342 DocumentModel doc = null;
344 doc = repoSession.getDocument(docRef);
345 } catch (ClientException ce) {
346 String msg = logException(ce, "Could not find document with CSID=" + csid);
347 throw new DocumentNotFoundException(msg, ce);
349 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
350 } catch (IllegalArgumentException iae) {
352 } catch (DocumentException de) {
360 * Get wrapped documentModel from the Nuxeo repository. The search is
361 * restricted to the workspace of the current context.
363 * @param ctx service context under which this method is invoked
364 * @param csid of the document to retrieve
365 * @throws DocumentNotFoundException
366 * @throws TransactionException
367 * @throws DocumentException
368 * @return a wrapped documentModel
371 public DocumentWrapper<DocumentModel> getDoc(
372 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
373 String csid) throws DocumentNotFoundException, TransactionException, DocumentException {
374 RepositoryInstance repoSession = null;
375 DocumentWrapper<DocumentModel> wrapDoc = null;
378 // Open a new repository session
379 repoSession = getRepositorySession(ctx);
380 wrapDoc = getDoc(repoSession, ctx, csid);
381 } catch (IllegalArgumentException iae) {
383 } catch (DocumentException de) {
385 } catch (Exception e) {
386 if (logger.isDebugEnabled()) {
387 logger.debug("Caught exception ", e);
389 throw new DocumentException(e);
391 if (repoSession != null) {
392 releaseRepositorySession(ctx, repoSession);
396 if (logger.isWarnEnabled() == true) {
397 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
402 public DocumentWrapper<DocumentModel> findDoc(
403 RepositoryInstance repoSession,
404 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
406 throws DocumentNotFoundException, DocumentException {
407 DocumentWrapper<DocumentModel> wrapDoc = null;
410 QueryContext queryContext = new QueryContext(ctx, whereClause);
411 DocumentModelList docList = null;
412 // force limit to 1, and ignore totalSize
413 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
414 docList = repoSession.query(query,
419 if (docList.size() != 1) {
420 if (logger.isDebugEnabled()) {
421 logger.debug("findDoc: Query found: " + docList.size() + " items.");
422 logger.debug(" Query: " + query);
424 throw new DocumentNotFoundException("No document found matching filter params: " + query);
426 DocumentModel doc = docList.get(0);
427 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
428 } catch (IllegalArgumentException iae) {
430 } catch (DocumentException de) {
432 } catch (Exception e) {
433 if (logger.isDebugEnabled()) {
434 logger.debug("Caught exception ", e);
436 throw new DocumentException(e);
443 * find wrapped documentModel from the Nuxeo repository
445 * @param ctx service context under which this method is invoked
446 * @param whereClause where NXQL where clause to get the document
447 * @throws DocumentNotFoundException
448 * @throws TransactionException
449 * @throws DocumentException
450 * @return a wrapped documentModel retrieved by the repository query
453 public DocumentWrapper<DocumentModel> findDoc(
454 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
456 throws DocumentNotFoundException, TransactionException, DocumentException {
457 RepositoryInstance repoSession = null;
458 DocumentWrapper<DocumentModel> wrapDoc = null;
461 repoSession = getRepositorySession(ctx);
462 wrapDoc = findDoc(repoSession, ctx, whereClause);
463 } catch (Exception e) {
464 throw new DocumentException("Unable to create a Nuxeo repository session.", e);
466 if (repoSession != null) {
467 releaseRepositorySession(ctx, repoSession);
471 if (logger.isWarnEnabled() == true) {
472 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
479 * find doc and return CSID from the Nuxeo repository
482 * @param ctx service context under which this method is invoked
483 * @param whereClause where NXQL where clause to get the document
484 * @throws DocumentNotFoundException
485 * @throws TransactionException
486 * @throws DocumentException
487 * @return the CollectionSpace ID (CSID) of the requested document
490 public String findDocCSID(RepositoryInstance repoSession,
491 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String whereClause)
492 throws DocumentNotFoundException, TransactionException, DocumentException {
494 boolean releaseSession = false;
496 if (repoSession == null) {
497 repoSession = this.getRepositorySession(ctx);
498 releaseSession = true;
500 DocumentWrapper<DocumentModel> wrapDoc = findDoc(repoSession, ctx, whereClause);
501 DocumentModel docModel = wrapDoc.getWrappedObject();
502 csid = NuxeoUtils.getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
503 } catch (DocumentNotFoundException dnfe) {
505 } catch (IllegalArgumentException iae) {
507 } catch (DocumentException de) {
509 } catch (Exception e) {
510 if (logger.isDebugEnabled()) {
511 logger.debug("Caught exception ", e);
513 throw new DocumentException(e);
515 if (releaseSession && (repoSession != null)) {
516 this.releaseRepositorySession(ctx, repoSession);
522 public DocumentWrapper<DocumentModelList> findDocs(
523 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
524 RepositoryInstance repoSession,
525 List<String> docTypes,
527 String orderByClause,
530 boolean computeTotal)
531 throws DocumentNotFoundException, DocumentException {
532 DocumentWrapper<DocumentModelList> wrapDoc = null;
535 if (docTypes == null || docTypes.size() < 1) {
536 throw new DocumentNotFoundException(
537 "The findDocs() method must specify at least one DocumentType.");
539 DocumentModelList docList = null;
540 QueryContext queryContext = new QueryContext(ctx, whereClause, orderByClause);
541 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
542 if (logger.isDebugEnabled()) {
543 logger.debug("findDocs() NXQL: " + query);
545 docList = repoSession.query(query, null, pageSize, pageSize * pageNum, computeTotal);
546 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
547 } catch (IllegalArgumentException iae) {
549 } catch (Exception e) {
550 if (logger.isDebugEnabled()) {
551 logger.debug("Caught exception ", e);
553 throw new DocumentException(e);
559 protected static String buildInListForDocTypes(List<String> docTypes) {
560 StringBuilder sb = new StringBuilder();
562 boolean first = true;
563 for (String docType : docTypes) {
574 return sb.toString();
577 public DocumentWrapper<DocumentModelList> findDocs(
578 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
579 DocumentHandler handler,
580 RepositoryInstance repoSession,
581 List<String> docTypes)
582 throws DocumentNotFoundException, DocumentException {
583 DocumentWrapper<DocumentModelList> wrapDoc = null;
585 DocumentFilter filter = handler.getDocumentFilter();
586 String oldOrderBy = filter.getOrderByClause();
587 if (isClauseEmpty(oldOrderBy) == true) {
588 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
590 QueryContext queryContext = new QueryContext(ctx, handler);
593 if (docTypes == null || docTypes.size() < 1) {
594 throw new DocumentNotFoundException(
595 "The findDocs() method must specify at least one DocumentType.");
597 DocumentModelList docList = null;
598 if (handler.isCMISQuery() == true) {
599 String inList = buildInListForDocTypes(docTypes);
600 ctx.getQueryParams().add(IQueryManager.SEARCH_RELATED_MATCH_OBJ_DOCTYPES, inList);
601 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
603 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
604 if (logger.isDebugEnabled()) {
605 logger.debug("findDocs() NXQL: " + query);
607 docList = repoSession.query(query, null, filter.getPageSize(), filter.getOffset(), true);
609 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
610 } catch (IllegalArgumentException iae) {
612 } catch (Exception e) {
613 if (logger.isDebugEnabled()) {
614 logger.debug("Caught exception ", e);
616 throw new DocumentException(e);
623 * Find a list of documentModels from the Nuxeo repository
625 * @param docTypes a list of DocType names to match
626 * @param whereClause where the clause to qualify on
627 * @throws DocumentNotFoundException
628 * @throws TransactionException
629 * @throws DocumentException
630 * @return a list of documentModels
633 public DocumentWrapper<DocumentModelList> findDocs(
634 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
635 List<String> docTypes,
637 int pageSize, int pageNum, boolean computeTotal)
638 throws DocumentNotFoundException, TransactionException, DocumentException {
639 RepositoryInstance repoSession = null;
640 DocumentWrapper<DocumentModelList> wrapDoc = null;
643 repoSession = getRepositorySession(ctx);
644 wrapDoc = findDocs(ctx, repoSession, docTypes, whereClause, null,
645 pageSize, pageNum, computeTotal);
646 } catch (IllegalArgumentException iae) {
648 } catch (Exception e) {
649 if (logger.isDebugEnabled()) {
650 logger.debug("Caught exception ", e);
652 throw new DocumentException(e);
654 if (repoSession != null) {
655 releaseRepositorySession(ctx, repoSession);
659 if (logger.isWarnEnabled() == true) {
660 logger.warn("Returned DocumentModelList instance was created with a repository session that is now closed.");
667 * @see org.collectionspace.services.common.storage.StorageClient#get(org.collectionspace.services.common.context.ServiceContext, java.util.List, org.collectionspace.services.common.document.DocumentHandler)
670 public void get(ServiceContext ctx, List<String> csidList, DocumentHandler handler)
671 throws DocumentNotFoundException, TransactionException, DocumentException {
672 if (handler == null) {
673 throw new IllegalArgumentException(
674 "RepositoryJavaClient.getAll: handler is missing");
677 RepositoryInstance repoSession = null;
679 handler.prepare(Action.GET_ALL);
680 repoSession = getRepositorySession(ctx);
681 DocumentModelList docModelList = new DocumentModelListImpl();
682 //FIXME: Should be using NuxeoUtils.createPathRef for security reasons
683 for (String csid : csidList) {
684 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
685 DocumentModel docModel = repoSession.getDocument(docRef);
686 docModelList.add(docModel);
689 //set reposession to handle the document
690 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
691 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docModelList);
692 handler.handle(Action.GET_ALL, wrapDoc);
693 handler.complete(Action.GET_ALL, wrapDoc);
694 } catch (DocumentException de) {
696 } catch (Exception e) {
697 if (logger.isDebugEnabled()) {
698 logger.debug("Caught exception ", e);
700 throw new DocumentException(e);
702 if (repoSession != null) {
703 releaseRepositorySession(ctx, repoSession);
709 * getAll get all documents for an entity entity service from the Nuxeo
712 * @param ctx service context under which this method is invoked
713 * @param handler should be used by the caller to provide and transform the
715 * @throws DocumentNotFoundException
716 * @throws TransactionException
717 * @throws DocumentException
720 public void getAll(ServiceContext ctx, DocumentHandler handler)
721 throws DocumentNotFoundException, TransactionException, DocumentException {
722 if (handler == null) {
723 throw new IllegalArgumentException(
724 "RepositoryJavaClient.getAll: handler is missing");
726 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
727 if (nuxeoWspaceId == null) {
728 throw new DocumentNotFoundException(
729 "Unable to find workspace for service "
730 + ctx.getServiceName()
731 + " check if the workspace exists in the Nuxeo repository.");
734 RepositoryInstance repoSession = null;
736 handler.prepare(Action.GET_ALL);
737 repoSession = getRepositorySession(ctx);
738 DocumentRef wsDocRef = new IdRef(nuxeoWspaceId);
739 DocumentModelList docList = repoSession.getChildren(wsDocRef);
740 //set reposession to handle the document
741 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
742 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
743 handler.handle(Action.GET_ALL, wrapDoc);
744 handler.complete(Action.GET_ALL, wrapDoc);
745 } catch (DocumentException de) {
747 } catch (Exception e) {
748 if (logger.isDebugEnabled()) {
749 logger.debug("Caught exception ", e);
751 throw new DocumentException(e);
753 if (repoSession != null) {
754 releaseRepositorySession(ctx, repoSession);
759 private boolean isClauseEmpty(String theString) {
760 boolean result = true;
761 if (theString != null && !theString.isEmpty()) {
767 public DocumentWrapper<DocumentModel> getDocFromCsid(
768 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
769 RepositoryInstance repoSession,
772 DocumentWrapper<DocumentModel> result = null;
774 result = new DocumentWrapperImpl(NuxeoUtils.getDocFromCsid(ctx, repoSession, csid));
780 * A method to find a CollectionSpace document (of any type) given just a service context and
781 * its CSID. A search across *all* service workspaces (within a given tenant context) is performed to find
784 * This query searches Nuxeo's Hierarchy table where our CSIDs are stored in the "name" column.
787 public DocumentWrapper<DocumentModel> getDocFromCsid(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
790 DocumentWrapper<DocumentModel> result = null;
791 RepositoryInstance repoSession = null;
793 repoSession = getRepositorySession(ctx);
794 result = getDocFromCsid(ctx, repoSession, csid);
796 if (repoSession != null) {
797 releaseRepositorySession(ctx, repoSession);
801 if (logger.isWarnEnabled() == true) {
802 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
809 * Returns a URI value for a document in the Nuxeo repository
811 * @param wrappedDoc a wrapped documentModel
812 * @throws ClientException
813 * @return a document URI
816 public String getDocURI(DocumentWrapper<DocumentModel> wrappedDoc) throws ClientException {
817 DocumentModel docModel = wrappedDoc.getWrappedObject();
818 String uri = (String) docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
819 CollectionSpaceClient.COLLECTIONSPACE_CORE_URI);
824 * See CSPACE-5036 - How to make CMISQL queries from Nuxeo
826 private IterableQueryResult makeCMISQLQuery(RepositoryInstance repoSession, String query, QueryContext queryContext) {
827 IterableQueryResult result = null;
829 // the NuxeoRepository should be constructed only once, then cached
830 // (its construction is expensive)
832 NuxeoRepository repo = new NuxeoRepository(
833 repoSession.getRepositoryName(), repoSession
834 .getRootDocument().getId());
835 logger.debug("Repository ID:" + repo.getId() + " Root folder:"
836 + repo.getRootFolderId());
838 CallContextImpl callContext = new CallContextImpl(
839 CallContext.BINDING_LOCAL, repo.getId(), false);
840 callContext.put(CallContext.USERNAME, repoSession.getPrincipal()
842 NuxeoCmisService cmisService = new NuxeoCmisService(repo,
843 callContext, repoSession);
845 result = repoSession.queryAndFetch(query, "CMISQL", cmisService);
846 } catch (ClientException e) {
847 // TODO Auto-generated catch block
848 logger.error("Encounter trouble making the following CMIS query: " + query, e);
855 * getFiltered get all documents for an entity service from the Document
856 * repository, given filter parameters specified by the handler.
858 * @param ctx service context under which this method is invoked
859 * @param handler should be used by the caller to provide and transform the
861 * @throws DocumentNotFoundException if workspace not found
862 * @throws TransactionException
863 * @throws DocumentException
866 public void getFiltered(ServiceContext ctx, DocumentHandler handler)
867 throws DocumentNotFoundException, TransactionException, DocumentException {
869 DocumentFilter filter = handler.getDocumentFilter();
870 String oldOrderBy = filter.getOrderByClause();
871 if (isClauseEmpty(oldOrderBy) == true) {
872 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
874 QueryContext queryContext = new QueryContext(ctx, handler);
876 RepositoryInstance repoSession = null;
878 handler.prepare(Action.GET_ALL);
879 repoSession = getRepositorySession(ctx); //Keeps a refcount here for the repository session so you need to release this when finished
881 DocumentModelList docList = null;
882 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
884 if (logger.isDebugEnabled()) {
885 logger.debug("Executing NXQL query: " + query.toString());
888 // If we have limit and/or offset, then pass true to get totalSize
889 // in returned DocumentModelList.
890 Profiler profiler = new Profiler(this, 2);
891 profiler.log("Executing NXQL query: " + query.toString());
893 if (handler.isJDBCQuery() == true) {
894 docList = getFilteredJDBC(repoSession, ctx, handler);
895 } else if (handler.isCMISQuery() == true) {
896 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext); //FIXME: REM - Need to deal with paging info in CMIS query
897 } else if ((queryContext.getDocFilter().getOffset() > 0) || (queryContext.getDocFilter().getPageSize() > 0)) {
898 docList = repoSession.query(query, null,
899 queryContext.getDocFilter().getPageSize(), queryContext.getDocFilter().getOffset(), true);
901 docList = repoSession.query(query);
905 //set repoSession to handle the document
906 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
907 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
908 handler.handle(Action.GET_ALL, wrapDoc);
909 handler.complete(Action.GET_ALL, wrapDoc);
910 } catch (DocumentException de) {
912 } catch (Exception e) {
913 if (logger.isDebugEnabled()) {
914 logger.debug("Caught exception ", e);
916 throw new DocumentException(e);
918 if (repoSession != null) {
919 releaseRepositorySession(ctx, repoSession);
925 * Perform a database query, via JDBC and SQL, to retrieve matching records
926 * based on filter criteria.
928 * Although this method currently has a general-purpose name, it is
929 * currently dedicated to a specific task: improving performance for
930 * partial term matching queries on authority items / terms, via
931 * the use of a hand-tuned SQL query, rather than the generated SQL
932 * produced by Nuxeo from an NXQL query.
934 * @param repoSession a repository session.
935 * @param ctx the service context.
936 * @param handler a relevant document handler.
937 * @return a list of document models matching the search criteria.
940 private DocumentModelList getFilteredJDBC(RepositoryInstance repoSession, ServiceContext ctx,
941 DocumentHandler handler) throws Exception {
942 DocumentModelList result = new DocumentModelListImpl();
944 // FIXME: Get all of the following values from appropriate external constants.
946 // At present, the two constants below are duplicated in both RepositoryJavaClientImpl
947 // and in AuthorityItemDocumentModelHandler.
948 final String TERM_GROUP_LIST_NAME = "TERM_GROUP_LIST_NAME";
949 final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
950 final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
951 // Get this from a constant in AuthorityResource or equivalent
952 final String PARENT_WILDCARD = "_ALL_";
954 // Build two SQL statements, to be executed within a single transaction:
955 // the first statement to control join order, and the second statement
956 // representing the actual 'get filtered' query
958 // Build the join control statement
960 // Per http://www.postgresql.org/docs/9.2/static/runtime-config-query.html#GUC-JOIN-COLLAPSE-LIMIT
961 // "Setting [this value] to 1 prevents any reordering of explicit JOINs.
962 // Thus, the explicit join order specified in the query will be the
963 // actual order in which the relations are joined."
964 // See CSPACE-5945 for further discussion of why this setting is needed.
966 // Adding this statement is commented out here for now. It significantly
967 // improved query performance for authority item / term queries where
968 // large numbers of rows were retrieved, but appears to have resulted
969 // in consistently slower-than-desired query performance where zero or
970 // very few records were retrieved. See notes on CSPACE-5945. - ADR 2013-04-09
971 // String joinControlSql = "SET LOCAL join_collapse_limit TO 1;";
973 // Build the query statement
975 // Start with the default query
976 String selectStatement =
977 "SELECT DISTINCT commonschema.id"
978 + " FROM " + handler.getServiceContext().getCommonPartLabel() + " commonschema";
982 + " ON misc.id = commonschema.id"
983 + " INNER JOIN hierarchy hierarchy_termgroup"
984 + " ON hierarchy_termgroup.parentid = misc.id"
985 + " INNER JOIN " + handler.getJDBCQueryParams().get(TERM_GROUP_TABLE_NAME_PARAM) + " termgroup"
986 + " ON termgroup.id = hierarchy_termgroup.id ";
989 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
990 // Value for replaceable parameter 1 in the query
991 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
992 // If the value of the partial term query parameter is blank ('pt='),
993 // return all records, subject to restriction by any limit clause
994 if (Tools.isBlank(partialTerm)) {
997 // Otherwise, return records that match the supplied partial term
999 " WHERE (termgroup.termdisplayname ILIKE ?)";
1002 // At present, results are ordered in code, below, rather than in SQL,
1003 // and the orderByClause below is thus intentionally blank.
1005 // To implement the orderByClause below in SQL; e.g. via
1006 // 'ORDER BY termgroup.termdisplayname', the relevant column
1007 // must be returned by the SELECT statement.
1008 String orderByClause = "";
1011 TenantBindingConfigReaderImpl tReader =
1012 ServiceMain.getInstance().getTenantBindingConfigReader();
1013 TenantBindingType tenantBinding = tReader.getTenantBinding(ctx.getTenantId());
1014 String maxListItemsLimit = TenantBindingUtils.getPropertyValue(tenantBinding,
1015 IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES);
1017 " LIMIT " + getMaxItemsLimitOnJdbcQueries(maxListItemsLimit); // implicit int-to-String conversion
1019 List<String> params = new ArrayList<>();
1021 // Read tenant bindings configuration to determine whether
1022 // to automatically insert leading, as well as trailing, wildcards
1023 // into the term matching string.
1024 String usesStartingWildcard = TenantBindingUtils.getPropertyValue(tenantBinding,
1025 IQueryManager.TENANT_USES_STARTING_WILDCARD_FOR_PARTIAL_TERM);
1026 // Handle user-provided leading wildcard characters, in the
1027 // configuration where a leading wildcard is not automatically inserted.
1028 // (The user-provided wildcard must be in the first, or "starting"
1029 // character position in the partial term value.)
1030 if (Tools.notBlank(usesStartingWildcard) && usesStartingWildcard.equalsIgnoreCase(Boolean.FALSE.toString())) {
1031 partialTerm = handleProvidedStartingWildcard(partialTerm);
1032 // Otherwise, automatically insert a leading wildcard
1034 partialTerm = JDBCTools.SQL_WILDCARD + partialTerm;
1036 // Add SQL wildcards in the midst of the partial term match search
1037 // expression, whever user-supplied wildcards appear, except in the
1038 // first or last character positions of the search expression.
1039 partialTerm = subtituteWildcardsInPartialTerm(partialTerm);
1041 // FIXME: We may wish to handle instances where a designated 'stop
1042 // character' has been inserted by the user as the last character in
1043 // the search expression, whereupon we would strip that stop character
1044 // and skip the automatic adding of a trailing wildcard, below.
1046 // Automatically add a trailing wildcard
1047 params.add(partialTerm + JDBCTools.SQL_WILDCARD);
1049 // Optionally add restrictions to the default query, based on variables
1050 // in the current request
1052 // Restrict the query to filter out deleted records, if requested
1053 String includeDeleted = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_NONDELETED);
1054 if (includeDeleted != null && includeDeleted.equalsIgnoreCase(Boolean.FALSE.toString())) {
1055 whereClause = whereClause
1056 + " AND (misc.lifecyclestate <> '" + WorkflowClient.WORKFLOWSTATE_DELETED + "')";
1059 // If a particular authority is specified, restrict the query further
1060 // to return only records within that authority
1061 String inAuthorityValue = (String) handler.getJDBCQueryParams().get(IN_AUTHORITY_PARAM);
1062 if (Tools.notBlank(inAuthorityValue)) {
1063 // Handle the '_ALL_' case for inAuthority
1064 if (inAuthorityValue.equals(PARENT_WILDCARD)) {
1065 // Add nothing to the query here if it should match within all authorities
1067 whereClause = whereClause
1068 + " AND (commonschema.inauthority = ?)";
1069 params.add(inAuthorityValue); // Value for replaceable parameter 2 in the query
1073 // Restrict the query further to return only records pertaining to
1074 // the current tenant, unless:
1075 // * Data for this service, in this tenant, is stored in its own,
1076 // separate repository, rather than being intermingled with other
1077 // tenants' data in the default repository; or
1078 // * Restriction by tenant ID in JDBC queries has been disabled,
1079 // via configuration for this tenant,
1080 if (restrictJDBCQueryByTenantID(tenantBinding, ctx)) {
1081 joinClauses = joinClauses
1082 + " INNER JOIN collectionspace_core core"
1083 + " ON core.id = hierarchy_termgroup.parentid";
1084 whereClause = whereClause
1085 + " AND (core.tenantid = ?)";
1086 params.add(ctx.getTenantId()); // Value for replaceable parameter 3 in the query
1089 // Piece together the SQL query from its parts
1090 String querySql = selectStatement + joinClauses + whereClause + orderByClause + limitClause;
1092 // Note: PostgreSQL 9.2 introduced a change that may improve performance
1093 // of certain queries using JDBC PreparedStatements. See comments on
1094 // CSPACE-5943 for details.
1096 // See a comment above for the reason that the joinControl SQL statement,
1097 // along with its corresponding prepared statement builder, is commented out for now.
1098 // PreparedStatementBuilder joinControlBuilder = new PreparedStatementBuilder(joinControlSql);
1099 PreparedStatementSimpleBuilder queryBuilder = new PreparedStatementSimpleBuilder(querySql, params);
1100 List<PreparedStatementBuilder> builders = new ArrayList<>();
1101 // builders.add(joinControlBuilder);
1102 builders.add(queryBuilder);
1103 String dataSourceName = JDBCTools.NUXEO_DATASOURCE_NAME;
1104 String repositoryName = ctx.getRepositoryName();
1105 final Boolean EXECUTE_WITHIN_TRANSACTION = true;
1106 Set<String> docIds = new HashSet<>();
1108 List<CachedRowSet> resultsList = JDBCTools.executePreparedQueries(builders,
1109 dataSourceName, repositoryName, EXECUTE_WITHIN_TRANSACTION);
1111 // At least one set of results is expected, from the second prepared
1112 // statement to be executed.
1113 // If fewer results are returned, return an empty list of document models
1114 if (resultsList == null || resultsList.size() < 1) {
1115 return result; // return an empty list of document models
1117 // The join control query (if enabled - it is currently commented
1118 // out as per comments above) will not return results, so query results
1119 // will be the first set of results (rowSet) returned in the list
1120 CachedRowSet queryResults = resultsList.get(0);
1122 // If the result from executing the query is null or contains zero rows,
1123 // return an empty list of document models
1124 if (queryResults == null) {
1125 return result; // return an empty list of document models
1127 queryResults.last();
1128 if (queryResults.getRow() == 0) {
1129 return result; // return an empty list of document models
1132 // Otherwise, get the document IDs from the results of the query
1134 queryResults.beforeFirst();
1135 while (queryResults.next()) {
1136 id = queryResults.getString(1);
1137 if (Tools.notBlank(id)) {
1141 } catch (SQLException sqle) {
1142 logger.warn("Could not obtain document IDs via SQL query '" + querySql + "': " + sqle.getMessage());
1143 return result; // return an empty list of document models
1146 // Get a list of document models, using the IDs obtained from the query
1147 DocumentModel docModel;
1148 for (String docId : docIds) {
1149 docModel = NuxeoUtils.getDocumentModel(repoSession, docId);
1150 if (docModel == null) {
1151 logger.warn("Could not obtain document model for document with ID " + docId);
1153 result.add(NuxeoUtils.getDocumentModel(repoSession, docId));
1157 // Order the results
1158 final String COMMON_PART_SCHEMA = handler.getServiceContext().getCommonPartLabel();
1159 final String DISPLAY_NAME_XPATH =
1160 "//" + handler.getJDBCQueryParams().get(TERM_GROUP_LIST_NAME) + "/[0]/termDisplayName";
1161 Collections.sort(result, new Comparator<DocumentModel>() {
1163 public int compare(DocumentModel doc1, DocumentModel doc2) {
1164 String termDisplayName1 = (String) NuxeoUtils.getXPathValue(doc1, COMMON_PART_SCHEMA, DISPLAY_NAME_XPATH);
1165 String termDisplayName2 = (String) NuxeoUtils.getXPathValue(doc2, COMMON_PART_SCHEMA, DISPLAY_NAME_XPATH);
1166 return termDisplayName1.compareToIgnoreCase(termDisplayName2);
1174 private DocumentModelList getFilteredCMIS(RepositoryInstance repoSession, ServiceContext ctx, DocumentHandler handler, QueryContext queryContext)
1175 throws DocumentNotFoundException, DocumentException {
1177 DocumentModelList result = new DocumentModelListImpl();
1179 String query = handler.getCMISQuery(queryContext);
1181 DocumentFilter docFilter = handler.getDocumentFilter();
1182 int pageSize = docFilter.getPageSize();
1183 int offset = docFilter.getOffset();
1184 if (logger.isDebugEnabled()) {
1185 logger.debug("Executing CMIS query: " + query.toString()
1186 + "with pageSize: " + pageSize + " at offset: " + offset);
1189 // If we have limit and/or offset, then pass true to get totalSize
1190 // in returned DocumentModelList.
1191 Profiler profiler = new Profiler(this, 2);
1192 profiler.log("Executing CMIS query: " + query.toString());
1195 IterableQueryResult queryResult = makeCMISQLQuery(repoSession, query, queryContext);
1197 int totalSize = (int) queryResult.size();
1198 ((DocumentModelListImpl) result).setTotalSize(totalSize);
1199 // Skip the rows before our offset
1201 queryResult.skipTo(offset);
1204 for (Map<String, Serializable> row : queryResult) {
1205 if (logger.isTraceEnabled()) {
1206 logger.trace(" Hierarchy Table ID is:" + row.get(IQueryManager.CMIS_TARGET_NUXEO_ID)
1207 + " nuxeo:pathSegment is: " + row.get(IQueryManager.CMIS_TARGET_NAME));
1209 String nuxeoId = (String) row.get(IQueryManager.CMIS_TARGET_NUXEO_ID);
1210 DocumentModel docModel = NuxeoUtils.getDocumentModel(repoSession, nuxeoId);
1211 result.add(docModel);
1213 if (nRows >= pageSize && pageSize != 0) { // A page size of zero means that they want all of them
1214 logger.debug("Got page full of items - quitting");
1219 queryResult.close();
1224 } catch (Exception e) {
1225 if (logger.isDebugEnabled()) {
1226 logger.debug("Caught exception ", e);
1228 throw new DocumentException(e);
1232 // Since we're not supporting paging yet for CMIS queries, we need to perform
1233 // a workaround for the paging information we return in our list of results
1236 if (result != null) {
1237 docFilter.setStartPage(0);
1238 if (totalSize > docFilter.getPageSize()) {
1239 docFilter.setPageSize(totalSize);
1240 ((DocumentModelListImpl)result).setTotalSize(totalSize);
1248 private String logException(Exception e, String msg) {
1249 String result = null;
1251 String exceptionMessage = e.getMessage();
1252 exceptionMessage = exceptionMessage != null ? exceptionMessage : "<No details provided>";
1253 result = msg = msg + ". Caught exception:" + exceptionMessage;
1255 if (logger.isTraceEnabled() == true) {
1256 logger.error(msg, e);
1265 * update given document in the Nuxeo repository
1267 * @param ctx service context under which this method is invoked
1268 * @param csid of the document
1269 * @param handler should be used by the caller to provide and transform the
1271 * @throws BadRequestException
1272 * @throws DocumentNotFoundException
1273 * @throws TransactionException if the transaction times out or otherwise
1274 * cannot be successfully completed
1275 * @throws DocumentException
1278 public void update(ServiceContext ctx, String csid, DocumentHandler handler)
1279 throws BadRequestException, DocumentNotFoundException, TransactionException,
1281 if (handler == null) {
1282 throw new IllegalArgumentException(
1283 "RepositoryJavaClient.update: document handler is missing.");
1286 RepositoryInstance repoSession = null;
1288 handler.prepare(Action.UPDATE);
1289 repoSession = getRepositorySession(ctx);
1290 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
1291 DocumentModel doc = null;
1293 doc = repoSession.getDocument(docRef);
1294 } catch (ClientException ce) {
1295 String msg = logException(ce, "Could not find document to update with CSID=" + csid);
1296 throw new DocumentNotFoundException(msg, ce);
1298 // Check for a versioned document, and check In and Out before we proceed.
1299 if (((DocumentModelHandler) handler).supportsVersioning()) {
1300 /* Once we advance to 5.5 or later, we can add this.
1301 * See also https://jira.nuxeo.com/browse/NXP-8506
1302 if(!doc.isVersionable()) {
1303 throw new DocumentException("Configuration for: "
1304 +handler.getServiceContextPath()+" supports versioning, but Nuxeo config does not!");
1307 /* Force a version number - Not working. Apparently we need to configure the uid schema??
1308 if(doc.getProperty("uid","major_version") == null) {
1309 doc.setProperty("uid","major_version",1);
1311 if(doc.getProperty("uid","minor_version") == null) {
1312 doc.setProperty("uid","minor_version",0);
1315 doc.checkIn(VersioningOption.MINOR, null);
1320 // Set reposession to handle the document
1322 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1323 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
1324 handler.handle(Action.UPDATE, wrapDoc);
1325 repoSession.saveDocument(doc);
1327 handler.complete(Action.UPDATE, wrapDoc);
1328 } catch (BadRequestException bre) {
1330 } catch (DocumentException de) {
1332 } catch (WebApplicationException wae) {
1334 } catch (Exception e) {
1335 if (logger.isDebugEnabled()) {
1336 logger.debug("Caught exception ", e);
1338 throw new DocumentException(e);
1340 if (repoSession != null) {
1341 releaseRepositorySession(ctx, repoSession);
1347 * Save a documentModel to the Nuxeo repository.
1349 * @param ctx service context under which this method is invoked
1350 * @param repoSession
1351 * @param docModel the document to save
1352 * @param fSaveSession if TRUE, will call CoreSession.save() to save
1353 * accumulated changes.
1354 * @throws ClientException
1355 * @throws DocumentException
1357 public void saveDocWithoutHandlerProcessing(
1358 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1359 RepositoryInstance repoSession,
1360 DocumentModel docModel,
1361 boolean fSaveSession)
1362 throws ClientException, DocumentException {
1365 repoSession.saveDocument(docModel);
1369 } catch (ClientException ce) {
1371 } catch (Exception e) {
1372 if (logger.isDebugEnabled()) {
1373 logger.debug("Caught exception ", e);
1375 throw new DocumentException(e);
1380 * Save a list of documentModels to the Nuxeo repository.
1382 * @param ctx service context under which this method is invoked
1383 * @param repoSession a repository session
1384 * @param docModelList a list of document models
1385 * @param fSaveSession if TRUE, will call CoreSession.save() to save
1386 * accumulated changes.
1387 * @throws ClientException
1388 * @throws DocumentException
1390 public void saveDocListWithoutHandlerProcessing(
1391 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1392 RepositoryInstance repoSession,
1393 DocumentModelList docList,
1394 boolean fSaveSession)
1395 throws ClientException, DocumentException {
1397 DocumentModel[] docModelArray = new DocumentModel[docList.size()];
1398 repoSession.saveDocuments(docList.toArray(docModelArray));
1402 } catch (ClientException ce) {
1404 } catch (Exception e) {
1405 logger.error("Caught exception ", e);
1406 throw new DocumentException(e);
1411 * delete a document from the Nuxeo repository
1413 * @param ctx service context under which this method is invoked
1414 * @param id of the document
1415 * @throws DocumentException
1418 public void delete(ServiceContext ctx, String id, DocumentHandler handler) throws DocumentNotFoundException,
1419 DocumentException, TransactionException {
1421 throw new IllegalArgumentException(
1422 "delete(ctx, ix, handler): ctx is missing");
1424 if (handler == null) {
1425 throw new IllegalArgumentException(
1426 "delete(ctx, ix, handler): handler is missing");
1428 if (logger.isDebugEnabled()) {
1429 logger.debug("Deleting document with CSID=" + id);
1431 RepositoryInstance repoSession = null;
1433 handler.prepare(Action.DELETE);
1434 repoSession = getRepositorySession(ctx);
1435 DocumentWrapper<DocumentModel> wrapDoc = null;
1437 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
1438 wrapDoc = new DocumentWrapperImpl<DocumentModel>(repoSession.getDocument(docRef));
1439 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1440 handler.handle(Action.DELETE, wrapDoc);
1441 repoSession.removeDocument(docRef);
1442 } catch (ClientException ce) {
1443 String msg = logException(ce, "Could not find document to delete with CSID=" + id);
1444 throw new DocumentNotFoundException(msg, ce);
1447 handler.complete(Action.DELETE, wrapDoc);
1448 } catch (DocumentException de) {
1450 } catch (Exception e) {
1451 if (logger.isDebugEnabled()) {
1452 logger.debug("Caught exception ", e);
1454 throw new DocumentException(e);
1456 if (repoSession != null) {
1457 releaseRepositorySession(ctx, repoSession);
1463 * @see org.collectionspace.services.common.storage.StorageClient#delete(org.collectionspace.services.common.context.ServiceContext, java.lang.String, org.collectionspace.services.common.document.DocumentHandler)
1467 public void delete(@SuppressWarnings("rawtypes") ServiceContext ctx, String id)
1468 throws DocumentNotFoundException, DocumentException {
1469 throw new UnsupportedOperationException();
1470 // Use the other delete instead
1474 public Hashtable<String, String> retrieveWorkspaceIds(RepositoryDomainType repoDomain) throws Exception {
1475 return NuxeoConnectorEmbedded.getInstance().retrieveWorkspaceIds(repoDomain);
1479 public String createDomain(RepositoryDomainType repositoryDomain) throws Exception {
1480 RepositoryInstance repoSession = null;
1481 String domainId = null;
1484 // Open a connection to the domain's repo/db
1486 String repoName = repositoryDomain.getRepositoryName();
1487 repoSession = getRepositorySession(repoName); // domainName=storageName=repoName=databaseName
1489 // First create the top-level domain directory
1491 String domainName = repositoryDomain.getStorageName();
1492 DocumentRef parentDocRef = new PathRef("/");
1493 DocumentModel parentDoc = repoSession.getDocument(parentDocRef);
1494 DocumentModel domainDoc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1495 domainName, NUXEO_CORE_TYPE_DOMAIN);
1496 domainDoc.setPropertyValue("dc:title", domainName);
1497 domainDoc.setPropertyValue("dc:description", "A CollectionSpace domain "
1499 domainDoc = repoSession.createDocument(domainDoc);
1500 domainId = domainDoc.getId();
1503 // Next, create a "Workspaces" root directory to contain the workspace folders for the individual service documents
1505 DocumentModel workspacesRoot = repoSession.createDocumentModel(domainDoc.getPathAsString(),
1506 NuxeoUtils.Workspaces, NUXEO_CORE_TYPE_WORKSPACEROOT);
1507 workspacesRoot.setPropertyValue("dc:title", NuxeoUtils.Workspaces);
1508 workspacesRoot.setPropertyValue("dc:description", "A CollectionSpace workspaces directory for "
1509 + domainDoc.getPathAsString());
1510 workspacesRoot = repoSession.createDocument(workspacesRoot);
1511 String workspacesRootId = workspacesRoot.getId();
1514 if (logger.isDebugEnabled()) {
1515 logger.debug("Created tenant domain name=" + domainName
1516 + " id=" + domainId + " "
1517 + NuxeoUtils.Workspaces + " id=" + workspacesRootId);
1518 logger.debug("Path to Domain: " + domainDoc.getPathAsString());
1519 logger.debug("Path to Workspaces root: " + workspacesRoot.getPathAsString());
1521 } catch (Exception e) {
1522 if (logger.isDebugEnabled()) {
1523 logger.debug("Could not create tenant domain name=" + repositoryDomain.getStorageName() + " caught exception ", e);
1527 if (repoSession != null) {
1528 releaseRepositorySession(null, repoSession);
1536 public String getDomainId(RepositoryDomainType repositoryDomain) throws Exception {
1537 String domainId = null;
1538 RepositoryInstance repoSession = null;
1540 String repoName = repositoryDomain.getRepositoryName();
1541 String domainStorageName = repositoryDomain.getStorageName();
1542 if (domainStorageName != null && !domainStorageName.isEmpty()) {
1544 repoSession = getRepositorySession(repoName);
1545 DocumentRef docRef = new PathRef("/" + domainStorageName);
1546 DocumentModel domain = repoSession.getDocument(docRef);
1547 domainId = domain.getId();
1548 } catch (Exception e) {
1549 if (logger.isTraceEnabled()) {
1550 logger.trace("Caught exception ", e); // The document doesn't exist, this let's us know we need to create it
1552 //there is no way to identify if document does not exist due to
1553 //lack of typed exception for getDocument method
1556 if (repoSession != null) {
1557 releaseRepositorySession(null, repoSession);
1566 * Returns the workspaces root directory for a given domain.
1568 private DocumentModel getWorkspacesRoot(RepositoryInstance repoSession,
1569 String domainName) throws Exception {
1570 DocumentModel result = null;
1572 String domainPath = "/" + domainName;
1573 DocumentRef parentDocRef = new PathRef(domainPath);
1574 DocumentModelList domainChildrenList = repoSession.getChildren(
1576 Iterator<DocumentModel> witer = domainChildrenList.iterator();
1577 while (witer.hasNext()) {
1578 DocumentModel childNode = witer.next();
1579 if (NuxeoUtils.Workspaces.equalsIgnoreCase(childNode.getName())) {
1581 logger.trace("Found workspaces directory at: " + result.getPathAsString());
1586 if (result == null) {
1587 throw new ClientException("Could not find workspace root directory in: "
1595 * @see org.collectionspace.services.common.repository.RepositoryClient#createWorkspace(java.lang.String, java.lang.String)
1598 public String createWorkspace(RepositoryDomainType repositoryDomain, String workspaceName) throws Exception {
1599 RepositoryInstance repoSession = null;
1600 String workspaceId = null;
1602 String repoName = repositoryDomain.getRepositoryName();
1603 repoSession = getRepositorySession(repoName);
1605 String domainStorageName = repositoryDomain.getStorageName();
1606 DocumentModel parentDoc = getWorkspacesRoot(repoSession, domainStorageName);
1607 if (logger.isTraceEnabled()) {
1608 for (String facet : parentDoc.getFacets()) {
1609 logger.trace("Facet: " + facet);
1613 DocumentModel doc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1614 workspaceName, NuxeoUtils.WORKSPACE_DOCUMENT_TYPE);
1615 doc.setPropertyValue("dc:title", workspaceName);
1616 doc.setPropertyValue("dc:description", "A CollectionSpace workspace for "
1618 doc = repoSession.createDocument(doc);
1619 workspaceId = doc.getId();
1621 if (logger.isDebugEnabled()) {
1622 logger.debug("Created workspace name=" + workspaceName
1623 + " id=" + workspaceId);
1625 } catch (Exception e) {
1626 if (logger.isDebugEnabled()) {
1627 logger.debug("createWorkspace caught exception ", e);
1631 if (repoSession != null) {
1632 releaseRepositorySession(null, repoSession);
1639 * @see org.collectionspace.services.common.repository.RepositoryClient#getWorkspaceId(java.lang.String, java.lang.String)
1643 public String getWorkspaceId(String tenantDomain, String workspaceName) throws Exception {
1644 String workspaceId = null;
1646 RepositoryInstance repoSession = null;
1648 repoSession = getRepositorySession((ServiceContext) null);
1649 DocumentRef docRef = new PathRef(
1651 + "/" + NuxeoUtils.Workspaces
1652 + "/" + workspaceName);
1653 DocumentModel workspace = repoSession.getDocument(docRef);
1654 workspaceId = workspace.getId();
1655 } catch (DocumentException de) {
1657 } catch (Exception e) {
1658 if (logger.isDebugEnabled()) {
1659 logger.debug("Caught exception ", e);
1661 throw new DocumentException(e);
1663 if (repoSession != null) {
1664 releaseRepositorySession(null, repoSession);
1671 public RepositoryInstance getRepositorySession(ServiceContext ctx) throws Exception {
1672 return getRepositorySession(ctx, ctx.getRepositoryName());
1675 public RepositoryInstance getRepositorySession(String repoName) throws Exception {
1676 return getRepositorySession(null, repoName);
1680 * Gets the repository session. - Package access only. If the 'ctx' param is
1681 * null then the repo name must be non-mull and vice-versa
1683 * @return the repository session
1684 * @throws Exception the exception
1686 public RepositoryInstance getRepositorySession(ServiceContext ctx, String repoName) throws Exception {
1687 RepositoryInstance repoSession = null;
1689 Profiler profiler = new Profiler("getRepositorySession():", 2);
1692 // To get a connection to the Nuxeo repo, we need either a valid ServiceContext instance or a repository name
1695 repoName = ctx.getRepositoryName(); // Notice we are overriding the passed in 'repoName' since we have a valid service context passed in to us
1696 repoSession = (RepositoryInstance) ctx.getCurrentRepositorySession(); // Look to see if one exists in the context before creating one
1697 } else if (repoName == null || repoName.trim().isEmpty()) {
1698 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.");
1699 logger.error(errMsg);
1700 throw new Exception(errMsg);
1703 // 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
1704 // just the repo name
1706 if (repoSession == null) {
1707 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1708 repoSession = client.openRepository(repoName);
1710 if (logger.isDebugEnabled() == true) {
1711 logger.warn("Reusing the current context's repository session.");
1715 if (logger.isTraceEnabled()) {
1716 logger.trace("Testing call to getRepository() repository root: " + repoSession.getRootDocument());
1722 ctx.setCurrentRepositorySession(repoSession); // For reusing, save the repository session in the current service context
1729 * Release repository session. - Package access only.
1731 * @param repoSession the repo session
1733 public void releaseRepositorySession(ServiceContext ctx, RepositoryInstance repoSession) throws TransactionException {
1735 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1738 ctx.clearCurrentRepositorySession(); //clear the current context of the now closed repo session
1739 if (ctx.getCurrentRepositorySession() == null) {
1740 client.releaseRepository(repoSession); //release the repo session if the service context's ref count is zeo.
1743 client.releaseRepository(repoSession); //repo session was acquired without a service context
1745 } catch (TransactionRuntimeException tre) {
1746 TransactionException te = new TransactionException(tre);
1747 logger.error(te.getMessage(), tre); // Log the standard transaction exception message, plus an exception-specific stack trace
1749 } catch (Exception e) {
1750 logger.error("Could not close the repository session", e);
1751 // no need to throw this service specific exception
1756 public void doWorkflowTransition(ServiceContext ctx, String id,
1757 DocumentHandler handler, TransitionDef transitionDef)
1758 throws BadRequestException, DocumentNotFoundException,
1760 // 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
1763 private String handleProvidedStartingWildcard(String partialTerm) {
1764 if (Tools.notBlank(partialTerm)) {
1765 if (partialTerm.substring(0, 1).equals(USER_SUPPLIED_WILDCARD)) {
1766 StringBuffer buffer = new StringBuffer(partialTerm);
1767 buffer.setCharAt(0, JDBCTools.SQL_WILDCARD.charAt(0));
1768 partialTerm = buffer.toString();
1775 * Replaces user-supplied wildcards with SQL wildcards, in a partial term
1776 * matching search expression.
1778 * The scope of this replacement excludes the beginning and ending
1779 * characters in that search expression, as those are treated specially.
1781 * @param partialTerm
1782 * @return the partial term, with any user-supplied wildcards replaced
1785 private String subtituteWildcardsInPartialTerm(String partialTerm) {
1786 if (Tools.isBlank(partialTerm)) {
1789 if (! partialTerm.contains(USER_SUPPLIED_WILDCARD)) {
1792 int len = partialTerm.length();
1793 // Partial term search expressions of 2 or fewer characters
1794 // currently aren't amenable to the use of wildcards
1796 logger.warn("Partial term matching expression of 1 or 2 characters contains user-supplied wildcard:" + partialTerm);
1799 int lastCharPos = len - 1;
1800 return partialTerm.substring(0, 1) // first char
1801 + partialTerm.substring(1, lastCharPos).replaceAll("\\*", "%") // middle of search expression, excluding first and last
1802 + partialTerm.substring(lastCharPos); // last char
1806 private int getMaxItemsLimitOnJdbcQueries(String maxListItemsLimit) {
1807 final int DEFAULT_ITEMS_LIMIT = 40;
1808 if (maxListItemsLimit == null) {
1809 return DEFAULT_ITEMS_LIMIT;
1813 itemsLimit = Integer.parseInt(maxListItemsLimit);
1814 if (itemsLimit < 1) {
1815 logger.warn("Value of configuration setting "
1816 + IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES
1817 + " must be a positive integer; invalid current value is " + maxListItemsLimit);
1818 logger.warn("Reverting to default value of " + DEFAULT_ITEMS_LIMIT);
1819 itemsLimit = DEFAULT_ITEMS_LIMIT;
1821 } catch (NumberFormatException nfe) {
1822 logger.warn("Value of configuration setting "
1823 + IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES
1824 + " must be a positive integer; invalid current value is " + maxListItemsLimit);
1825 logger.warn("Reverting to default value of " + DEFAULT_ITEMS_LIMIT);
1826 itemsLimit = DEFAULT_ITEMS_LIMIT;
1832 * Identifies whether a restriction on tenant ID - to return only records
1833 * pertaining to the current tenant - is required in a JDBC query.
1835 * @param tenantBinding a tenant binding configuration.
1836 * @param ctx a service context.
1837 * @return true if a restriction on tenant ID is required in the query;
1838 * false if a restriction is not required.
1840 private boolean restrictJDBCQueryByTenantID(TenantBindingType tenantBinding, ServiceContext ctx) {
1841 boolean restrict = true;
1842 // If data for the current service, in the current tenant, is isolated
1843 // within its own separate, per-tenant repository, as contrasted with
1844 // being intermingled with other tenants' data in the default repository,
1845 // no restriction on Tenant ID is required in the query.
1846 String repositoryDomainName = ConfigUtils.getRepositoryName(tenantBinding, ctx.getRepositoryDomainName());
1847 if (!(repositoryDomainName.equals(ConfigUtils.DEFAULT_NUXEO_REPOSITORY_NAME))) {
1850 // If a configuration setting for this tenant identifies that JDBC
1851 // queries should not be restricted by tenant ID (perhaps because
1852 // there is always expected to be only one tenant's data present in
1853 // the system), no restriction on Tenant ID is required in the query.
1854 String queriesRestrictedByTenantId = TenantBindingUtils.getPropertyValue(tenantBinding,
1855 IQueryManager.JDBC_QUERIES_ARE_TENANT_ID_RESTRICTED);
1856 if (Tools.notBlank(queriesRestrictedByTenantId) &&
1857 queriesRestrictedByTenantId.equalsIgnoreCase(Boolean.FALSE.toString())) {