2 * This document is a part of the source code and related artifacts for
3 * CollectionSpace, an open source collections management system for museums and
4 * related institutions:
6 * http://www.collectionspace.org http://wiki.collectionspace.org
8 * Copyright 2009 University of California at Berkeley
10 * Licensed under the Educational Community License (ECL), Version 2.0. You may
11 * not use this file except in compliance with this License.
13 * You may obtain a copy of the ECL 2.0 License at
15 * https://source.collectionspace.org/collection-space/LICENSE.txt
17 package org.collectionspace.services.nuxeo.client.java;
19 import java.io.Serializable;
20 import java.sql.SQLException;
21 import java.util.ArrayList;
22 import java.util.Collections;
23 import java.util.Comparator;
24 import java.util.HashSet;
25 import java.util.Hashtable;
26 import java.util.Iterator;
27 import java.util.List;
30 import java.util.UUID;
32 import javax.sql.rowset.CachedRowSet;
33 import javax.ws.rs.core.MultivaluedMap;
35 import org.collectionspace.services.lifecycle.TransitionDef;
36 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
37 import org.collectionspace.services.client.CollectionSpaceClient;
38 import org.collectionspace.services.client.IQueryManager;
39 import org.collectionspace.services.client.PoxPayloadIn;
40 import org.collectionspace.services.client.PoxPayloadOut;
41 import org.collectionspace.services.client.Profiler;
42 import org.collectionspace.services.client.workflow.WorkflowClient;
43 import org.collectionspace.services.common.context.ServiceContext;
44 import org.collectionspace.services.common.query.QueryContext;
45 import org.collectionspace.services.common.repository.RepositoryClient;
46 import org.collectionspace.services.common.storage.JDBCTools;
47 import org.collectionspace.services.common.storage.PreparedStatementSimpleBuilder;
48 import org.collectionspace.services.common.document.BadRequestException;
49 import org.collectionspace.services.common.document.DocumentException;
50 import org.collectionspace.services.common.document.DocumentFilter;
51 import org.collectionspace.services.common.document.DocumentHandler;
52 import org.collectionspace.services.common.document.DocumentNotFoundException;
53 import org.collectionspace.services.common.document.DocumentHandler.Action;
54 import org.collectionspace.services.common.document.DocumentWrapper;
55 import org.collectionspace.services.common.document.DocumentWrapperImpl;
56 import org.collectionspace.services.common.document.TransactionException;
57 import org.collectionspace.services.common.CSWebApplicationException;
58 import org.collectionspace.services.common.ServiceMain;
59 import org.collectionspace.services.common.api.Tools;
60 import org.collectionspace.services.common.config.ConfigUtils;
61 import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl;
62 import org.collectionspace.services.common.config.TenantBindingUtils;
63 import org.collectionspace.services.common.storage.PreparedStatementBuilder;
64 import org.collectionspace.services.config.tenant.TenantBindingType;
65 import org.collectionspace.services.config.tenant.RepositoryDomainType;
68 // CSPACE-5036 - How to make CMISQL queries from Nuxeo
70 import org.apache.chemistry.opencmis.commons.enums.CmisVersion;
71 import org.apache.chemistry.opencmis.commons.server.CallContext;
72 import org.apache.chemistry.opencmis.server.impl.CallContextImpl;
73 import org.apache.chemistry.opencmis.server.shared.ThresholdOutputStreamFactory;
75 import org.nuxeo.common.utils.IdUtils;
76 import org.nuxeo.ecm.core.api.ClientException;
77 import org.nuxeo.ecm.core.api.DocumentModel;
78 import org.nuxeo.ecm.core.api.DocumentModelList;
79 import org.nuxeo.ecm.core.api.IterableQueryResult;
80 import org.nuxeo.ecm.core.api.VersioningOption;
81 import org.nuxeo.ecm.core.api.impl.DocumentModelListImpl;
82 import org.nuxeo.ecm.core.api.DocumentRef;
83 import org.nuxeo.ecm.core.api.IdRef;
84 import org.nuxeo.ecm.core.api.PathRef;
85 import org.nuxeo.runtime.transaction.TransactionRuntimeException;
86 import org.nuxeo.ecm.core.opencmis.bindings.NuxeoCmisServiceFactory;
87 import org.nuxeo.ecm.core.opencmis.impl.server.NuxeoCmisService;
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 public static final String BACKSLASH = "\\";
112 public static final String USER_SUPPLIED_WILDCARD = "*";
113 public static final String USER_SUPPLIED_WILDCARD_REGEX = BACKSLASH + USER_SUPPLIED_WILDCARD;
114 public static final String USER_SUPPLIED_ANCHOR_CHAR = "^";
115 public static final String USER_SUPPLIED_ANCHOR_CHAR_REGEX = BACKSLASH + USER_SUPPLIED_ANCHOR_CHAR;
116 public static final String ENDING_ANCHOR_CHAR = "$";
117 public static final String ENDING_ANCHOR_CHAR_REGEX = BACKSLASH + ENDING_ANCHOR_CHAR;
121 * Instantiates a new repository java client impl.
123 public RepositoryJavaClientImpl() {
127 public void assertWorkflowState(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
128 DocumentModel docModel) throws DocumentNotFoundException, ClientException {
129 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
130 if (queryParams != null) {
132 // Look for the workflow "delete" query param and see if we need to assert that the
133 // docModel is in a non-deleted workflow state.
135 String currentState = docModel.getCurrentLifeCycleState();
136 String includeDeletedStr = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_NONDELETED);
137 boolean includeDeleted = includeDeletedStr == null ? true : Boolean.parseBoolean(includeDeletedStr);
138 if (includeDeleted == false) {
140 // We don't wanted soft-deleted object, so throw an exception if this one is soft-deleted.
142 if (currentState.equalsIgnoreCase(WorkflowClient.WORKFLOWSTATE_DELETED)) {
143 String msg = "The GET assertion that docModel not be in 'deleted' workflow state failed.";
145 throw new DocumentNotFoundException(msg);
152 * create document in the Nuxeo repository
154 * @param ctx service context under which this method is invoked
155 * @param handler should be used by the caller to provide and transform the
157 * @return id in repository of the newly created document
158 * @throws BadRequestException
159 * @throws TransactionException
160 * @throws DocumentException
163 public String create(ServiceContext ctx,
164 DocumentHandler handler) throws BadRequestException,
165 TransactionException, DocumentException {
167 String docType = NuxeoUtils.getTenantQualifiedDocType(ctx); //ctx.getDocumentType();
168 if (docType == null) {
169 throw new IllegalArgumentException(
170 "RepositoryJavaClient.create: docType is missing");
173 if (handler == null) {
174 throw new IllegalArgumentException(
175 "RepositoryJavaClient.create: handler is missing");
177 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
178 if (nuxeoWspaceId == null) {
179 throw new DocumentNotFoundException(
180 "Unable to find workspace for service " + ctx.getServiceName()
181 + " check if the workspace exists in the Nuxeo repository");
184 CoreSessionInterface repoSession = null;
186 handler.prepare(Action.CREATE);
187 repoSession = getRepositorySession(ctx);
188 DocumentRef nuxeoWspace = new IdRef(nuxeoWspaceId);
189 DocumentModel wspaceDoc = repoSession.getDocument(nuxeoWspace);
190 String wspacePath = wspaceDoc.getPathAsString();
191 //give our own ID so PathRef could be constructed later on
192 String id = IdUtils.generateId(UUID.randomUUID().toString());
193 // create document model
194 DocumentModel doc = repoSession.createDocumentModel(wspacePath, id, docType);
195 /* Check for a versioned document, and check In and Out before we proceed.
196 * This does not work as we do not have the uid schema on our docs.
197 if(((DocumentModelHandler) handler).supportsVersioning()) {
198 doc.setProperty("uid","major_version",1);
199 doc.setProperty("uid","minor_version",0);
202 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
203 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
204 handler.handle(Action.CREATE, wrapDoc);
205 // create document with documentmodel
206 doc = repoSession.createDocument(doc);
208 // TODO for sub-docs need to call into the handler to let it deal with subitems. Pass in the id,
209 // and assume the handler has the state it needs (doc fragments).
210 handler.complete(Action.CREATE, wrapDoc);
212 } catch (BadRequestException bre) {
214 } catch (Exception e) {
215 throw new NuxeoDocumentException(e);
217 if (repoSession != null) {
218 releaseRepositorySession(ctx, repoSession);
225 * get document from the Nuxeo repository
227 * @param ctx service context under which this method is invoked
228 * @param id of the document to retrieve
229 * @param handler should be used by the caller to provide and transform the
231 * @throws DocumentNotFoundException if the document cannot be found in the
233 * @throws TransactionException
234 * @throws DocumentException
237 public void get(ServiceContext ctx, String id, DocumentHandler handler)
238 throws DocumentNotFoundException, TransactionException, DocumentException {
240 if (handler == null) {
241 throw new IllegalArgumentException(
242 "RepositoryJavaClient.get: handler is missing");
245 CoreSessionInterface repoSession = null;
247 handler.prepare(Action.GET);
248 repoSession = getRepositorySession(ctx);
249 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
250 DocumentModel docModel = null;
252 docModel = repoSession.getDocument(docRef);
253 assertWorkflowState(ctx, docModel);
254 } catch (ClientException ce) {
255 String msg = logException(ce, "Could not find document with CSID=" + id);
256 throw new DocumentNotFoundException(msg, ce);
259 // Set repository session to handle the document
261 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
262 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(docModel);
263 handler.handle(Action.GET, wrapDoc);
264 handler.complete(Action.GET, wrapDoc);
265 } catch (IllegalArgumentException iae) {
267 } catch (DocumentException de) {
269 } catch (Exception e) {
270 if (logger.isDebugEnabled()) {
271 logger.debug("Caught exception ", e);
273 throw new NuxeoDocumentException(e);
275 if (repoSession != null) {
276 releaseRepositorySession(ctx, repoSession);
282 * get a document from the Nuxeo repository, using the docFilter params.
284 * @param ctx service context under which this method is invoked
285 * @param handler should be used by the caller to provide and transform the
286 * document. Handler must have a docFilter set to return a single item.
287 * @throws DocumentNotFoundException if the document cannot be found in the
289 * @throws TransactionException
290 * @throws DocumentException
293 public void get(ServiceContext ctx, DocumentHandler handler)
294 throws DocumentNotFoundException, TransactionException, DocumentException {
295 QueryContext queryContext = new QueryContext(ctx, handler);
296 CoreSessionInterface repoSession = null;
299 handler.prepare(Action.GET);
300 repoSession = getRepositorySession(ctx);
302 DocumentModelList docList = null;
303 // force limit to 1, and ignore totalSize
304 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
305 docList = repoSession.query(query, null, 1, 0, false);
306 if (docList.size() != 1) {
307 throw new DocumentNotFoundException("No document found matching filter params: " + query);
309 DocumentModel doc = docList.get(0);
311 if (logger.isDebugEnabled()) {
312 logger.debug("Executed NXQL query: " + query);
315 //set reposession to handle the document
316 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
317 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
318 handler.handle(Action.GET, wrapDoc);
319 handler.complete(Action.GET, wrapDoc);
320 } catch (IllegalArgumentException iae) {
322 } catch (DocumentException de) {
324 } catch (Exception e) {
325 if (logger.isDebugEnabled()) {
326 logger.debug("Caught exception ", e);
328 throw new NuxeoDocumentException(e);
330 if (repoSession != null) {
331 releaseRepositorySession(ctx, repoSession);
336 public DocumentWrapper<DocumentModel> getDoc(
337 CoreSessionInterface repoSession,
338 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
339 String csid) throws DocumentNotFoundException, DocumentException {
340 DocumentWrapper<DocumentModel> wrapDoc = null;
343 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
344 DocumentModel doc = null;
346 doc = repoSession.getDocument(docRef);
347 } catch (ClientException ce) {
348 String msg = logException(ce, "Could not find document with CSID=" + csid);
349 throw new DocumentNotFoundException(msg, ce);
351 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
352 } catch (IllegalArgumentException iae) {
354 } catch (DocumentException de) {
362 * Get wrapped documentModel from the Nuxeo repository. The search is
363 * restricted to the workspace of the current context.
365 * @param ctx service context under which this method is invoked
366 * @param csid of the document to retrieve
367 * @throws DocumentNotFoundException
368 * @throws TransactionException
369 * @throws DocumentException
370 * @return a wrapped documentModel
373 public DocumentWrapper<DocumentModel> getDoc(
374 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
375 String csid) throws DocumentNotFoundException, TransactionException, DocumentException {
376 CoreSessionInterface repoSession = null;
377 DocumentWrapper<DocumentModel> wrapDoc = null;
380 // Open a new repository session
381 repoSession = getRepositorySession(ctx);
382 wrapDoc = getDoc(repoSession, ctx, csid);
383 } catch (IllegalArgumentException iae) {
385 } catch (DocumentException de) {
387 } catch (Exception e) {
388 if (logger.isDebugEnabled()) {
389 logger.debug("Caught exception ", e);
391 throw new NuxeoDocumentException(e);
393 if (repoSession != null) {
394 releaseRepositorySession(ctx, repoSession);
398 if (logger.isWarnEnabled() == true) {
399 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
404 public DocumentWrapper<DocumentModel> findDoc(
405 CoreSessionInterface repoSession,
406 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
408 throws DocumentNotFoundException, DocumentException {
409 DocumentWrapper<DocumentModel> wrapDoc = null;
412 QueryContext queryContext = new QueryContext(ctx, whereClause);
413 DocumentModelList docList = null;
414 // force limit to 1, and ignore totalSize
415 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
416 docList = repoSession.query(query,
421 if (docList.size() != 1) {
422 if (logger.isDebugEnabled()) {
423 logger.debug("findDoc: Query found: " + docList.size() + " items.");
424 logger.debug(" Query: " + query);
426 throw new DocumentNotFoundException("No document found matching filter params: " + query);
428 DocumentModel doc = docList.get(0);
429 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
430 } catch (IllegalArgumentException iae) {
432 } catch (DocumentException de) {
434 } catch (Exception e) {
435 if (logger.isDebugEnabled()) {
436 logger.debug("Caught exception ", e);
438 throw new NuxeoDocumentException(e);
445 * find wrapped documentModel from the Nuxeo repository
447 * @param ctx service context under which this method is invoked
448 * @param whereClause where NXQL where clause to get the document
449 * @throws DocumentNotFoundException
450 * @throws TransactionException
451 * @throws DocumentException
452 * @return a wrapped documentModel retrieved by the repository query
455 public DocumentWrapper<DocumentModel> findDoc(
456 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
458 throws DocumentNotFoundException, TransactionException, DocumentException {
459 CoreSessionInterface repoSession = null;
460 DocumentWrapper<DocumentModel> wrapDoc = null;
463 repoSession = getRepositorySession(ctx);
464 wrapDoc = findDoc(repoSession, ctx, whereClause);
465 } catch (DocumentNotFoundException dnfe) {
467 } catch (DocumentException de) {
469 } catch (Exception e) {
470 if (repoSession == null) {
471 throw new NuxeoDocumentException("Unable to create a Nuxeo repository session.", e);
473 throw new NuxeoDocumentException("Unexpected Nuxeo exception.", e);
476 if (repoSession != null) {
477 releaseRepositorySession(ctx, repoSession);
481 if (logger.isWarnEnabled() == true) {
482 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
489 * find doc and return CSID from the Nuxeo repository
492 * @param ctx service context under which this method is invoked
493 * @param whereClause where NXQL where clause to get the document
494 * @throws DocumentNotFoundException
495 * @throws TransactionException
496 * @throws DocumentException
497 * @return the CollectionSpace ID (CSID) of the requested document
500 public String findDocCSID(CoreSessionInterface repoSession,
501 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String whereClause)
502 throws DocumentNotFoundException, TransactionException, DocumentException {
504 boolean releaseSession = false;
506 if (repoSession == null) {
507 repoSession = this.getRepositorySession(ctx);
508 releaseSession = true;
510 DocumentWrapper<DocumentModel> wrapDoc = findDoc(repoSession, ctx, whereClause);
511 DocumentModel docModel = wrapDoc.getWrappedObject();
512 csid = NuxeoUtils.getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
513 } catch (DocumentNotFoundException dnfe) {
515 } catch (IllegalArgumentException iae) {
517 } catch (DocumentException de) {
519 } catch (Exception e) {
520 if (logger.isDebugEnabled()) {
521 logger.debug("Caught exception ", e);
523 throw new NuxeoDocumentException(e);
525 if (releaseSession && (repoSession != null)) {
526 this.releaseRepositorySession(ctx, repoSession);
532 public DocumentWrapper<DocumentModelList> findDocs(
533 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
534 CoreSessionInterface repoSession,
535 List<String> docTypes,
537 String orderByClause,
540 boolean computeTotal)
541 throws DocumentNotFoundException, DocumentException {
542 DocumentWrapper<DocumentModelList> wrapDoc = null;
545 if (docTypes == null || docTypes.size() < 1) {
546 throw new DocumentNotFoundException(
547 "The findDocs() method must specify at least one DocumentType.");
549 DocumentModelList docList = null;
550 QueryContext queryContext = new QueryContext(ctx, whereClause, orderByClause);
551 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
552 if (logger.isDebugEnabled()) {
553 logger.debug("findDocs() NXQL: " + query);
555 docList = repoSession.query(query, null, pageSize, pageSize * pageNum, computeTotal);
556 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
557 } catch (IllegalArgumentException iae) {
559 } catch (Exception e) {
560 if (logger.isDebugEnabled()) {
561 logger.debug("Caught exception ", e);
563 throw new NuxeoDocumentException(e);
569 protected static String buildInListForDocTypes(List<String> docTypes) {
570 StringBuilder sb = new StringBuilder();
572 boolean first = true;
573 for (String docType : docTypes) {
584 return sb.toString();
587 public DocumentWrapper<DocumentModelList> findDocs(
588 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
589 DocumentHandler handler,
590 CoreSessionInterface repoSession,
591 List<String> docTypes)
592 throws DocumentNotFoundException, DocumentException {
593 DocumentWrapper<DocumentModelList> wrapDoc = null;
595 DocumentFilter filter = handler.getDocumentFilter();
596 String oldOrderBy = filter.getOrderByClause();
597 if (isClauseEmpty(oldOrderBy) == true) {
598 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
600 QueryContext queryContext = new QueryContext(ctx, handler);
603 if (docTypes == null || docTypes.size() < 1) {
604 throw new DocumentNotFoundException(
605 "The findDocs() method must specify at least one DocumentType.");
607 DocumentModelList docList = null;
608 if (handler.isCMISQuery() == true) {
609 String inList = buildInListForDocTypes(docTypes);
610 ctx.getQueryParams().add(IQueryManager.SEARCH_RELATED_MATCH_OBJ_DOCTYPES, inList);
611 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
613 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
614 if (logger.isDebugEnabled()) {
615 logger.debug("findDocs() NXQL: " + query);
617 docList = repoSession.query(query, null, filter.getPageSize(), filter.getOffset(), true);
619 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
620 } catch (IllegalArgumentException iae) {
622 } catch (Exception e) {
623 if (logger.isDebugEnabled()) {
624 logger.debug("Caught exception ", e);
626 throw new NuxeoDocumentException(e);
633 * Find a list of documentModels from the Nuxeo repository
635 * @param docTypes a list of DocType names to match
636 * @param whereClause where the clause to qualify on
637 * @throws DocumentNotFoundException
638 * @throws TransactionException
639 * @throws DocumentException
640 * @return a list of documentModels
643 public DocumentWrapper<DocumentModelList> findDocs(
644 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
645 List<String> docTypes,
647 int pageSize, int pageNum, boolean computeTotal)
648 throws DocumentNotFoundException, TransactionException, DocumentException {
649 CoreSessionInterface repoSession = null;
650 DocumentWrapper<DocumentModelList> wrapDoc = null;
653 repoSession = getRepositorySession(ctx);
654 wrapDoc = findDocs(ctx, repoSession, docTypes, whereClause, null,
655 pageSize, pageNum, computeTotal);
656 } catch (IllegalArgumentException iae) {
658 } catch (Exception e) {
659 if (logger.isDebugEnabled()) {
660 logger.debug("Caught exception ", e);
662 throw new NuxeoDocumentException(e);
664 if (repoSession != null) {
665 releaseRepositorySession(ctx, repoSession);
669 if (logger.isWarnEnabled() == true) {
670 logger.warn("Returned DocumentModelList instance was created with a repository session that is now closed.");
677 * @see org.collectionspace.services.common.storage.StorageClient#get(org.collectionspace.services.common.context.ServiceContext, java.util.List, org.collectionspace.services.common.document.DocumentHandler)
680 public void get(ServiceContext ctx, List<String> csidList, DocumentHandler handler)
681 throws DocumentNotFoundException, TransactionException, DocumentException {
682 if (handler == null) {
683 throw new IllegalArgumentException(
684 "RepositoryJavaClient.getAll: handler is missing");
687 CoreSessionInterface repoSession = null;
689 handler.prepare(Action.GET_ALL);
690 repoSession = getRepositorySession(ctx);
691 DocumentModelList docModelList = new DocumentModelListImpl();
692 //FIXME: Should be using NuxeoUtils.createPathRef for security reasons
693 for (String csid : csidList) {
694 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
695 DocumentModel docModel = repoSession.getDocument(docRef);
696 docModelList.add(docModel);
699 //set reposession to handle the document
700 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
701 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docModelList);
702 handler.handle(Action.GET_ALL, wrapDoc);
703 handler.complete(Action.GET_ALL, wrapDoc);
704 } catch (DocumentException de) {
706 } catch (Exception e) {
707 if (logger.isDebugEnabled()) {
708 logger.debug("Caught exception ", e);
710 throw new NuxeoDocumentException(e);
712 if (repoSession != null) {
713 releaseRepositorySession(ctx, repoSession);
719 * getAll get all documents for an entity entity service from the Nuxeo
722 * @param ctx service context under which this method is invoked
723 * @param handler should be used by the caller to provide and transform the
725 * @throws DocumentNotFoundException
726 * @throws TransactionException
727 * @throws DocumentException
730 public void getAll(ServiceContext ctx, DocumentHandler handler)
731 throws DocumentNotFoundException, TransactionException, DocumentException {
732 if (handler == null) {
733 throw new IllegalArgumentException(
734 "RepositoryJavaClient.getAll: handler is missing");
736 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
737 if (nuxeoWspaceId == null) {
738 throw new DocumentNotFoundException(
739 "Unable to find workspace for service "
740 + ctx.getServiceName()
741 + " check if the workspace exists in the Nuxeo repository.");
744 CoreSessionInterface repoSession = null;
746 handler.prepare(Action.GET_ALL);
747 repoSession = getRepositorySession(ctx);
748 DocumentRef wsDocRef = new IdRef(nuxeoWspaceId);
749 DocumentModelList docList = repoSession.getChildren(wsDocRef);
750 //set reposession to handle the document
751 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
752 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
753 handler.handle(Action.GET_ALL, wrapDoc);
754 handler.complete(Action.GET_ALL, wrapDoc);
755 } catch (DocumentException de) {
757 } catch (Exception e) {
758 if (logger.isDebugEnabled()) {
759 logger.debug("Caught exception ", e);
761 throw new NuxeoDocumentException(e);
763 if (repoSession != null) {
764 releaseRepositorySession(ctx, repoSession);
769 private boolean isClauseEmpty(String theString) {
770 boolean result = true;
771 if (theString != null && !theString.isEmpty()) {
777 public DocumentWrapper<DocumentModel> getDocFromCsid(
778 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
779 CoreSessionInterface repoSession,
782 DocumentWrapper<DocumentModel> result = null;
784 result = new DocumentWrapperImpl<DocumentModel>(NuxeoUtils.getDocFromCsid(ctx, repoSession, csid));
790 * A method to find a CollectionSpace document (of any type) given just a service context and
791 * its CSID. A search across *all* service workspaces (within a given tenant context) is performed to find
794 * This query searches Nuxeo's Hierarchy table where our CSIDs are stored in the "name" column.
797 public DocumentWrapper<DocumentModel> getDocFromCsid(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
800 DocumentWrapper<DocumentModel> result = null;
801 CoreSessionInterface repoSession = null;
803 repoSession = getRepositorySession(ctx);
804 result = getDocFromCsid(ctx, repoSession, csid);
806 if (repoSession != null) {
807 releaseRepositorySession(ctx, repoSession);
811 if (logger.isWarnEnabled() == true) {
812 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
819 * Returns a URI value for a document in the Nuxeo repository
821 * @param wrappedDoc a wrapped documentModel
822 * @throws ClientException
823 * @return a document URI
826 public String getDocURI(DocumentWrapper<DocumentModel> wrappedDoc) throws ClientException {
827 DocumentModel docModel = wrappedDoc.getWrappedObject();
828 String uri = (String) docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
829 CollectionSpaceClient.COLLECTIONSPACE_CORE_URI);
834 * See CSPACE-5036 - How to make CMISQL queries from Nuxeo
836 private IterableQueryResult makeCMISQLQuery(CoreSessionInterface repoSession, String query, QueryContext queryContext) throws DocumentException {
837 IterableQueryResult result = null;
838 /** Threshold over which temporary files are not kept in memory. */
839 final int THRESHOLD = 1024 * 1024;
842 logger.debug(String.format("Performing a CMIS query on Nuxeo repository named %s",
843 repoSession.getRepositoryName()));
845 ThresholdOutputStreamFactory streamFactory = ThresholdOutputStreamFactory.newInstance(
846 null, THRESHOLD, -1, false);
847 CallContextImpl callContext = new CallContextImpl(
848 CallContext.BINDING_LOCAL,
849 CmisVersion.CMIS_1_1,
850 repoSession.getRepositoryName(),
851 null, // ServletContext
852 null, // HttpServletRequest
853 null, // HttpServletResponse
854 new NuxeoCmisServiceFactory(),
856 callContext.put(CallContext.USERNAME, repoSession.getPrincipal().getName());
858 NuxeoCmisService cmisService = new NuxeoCmisService(repoSession.getCoreSession());
859 result = repoSession.queryAndFetch(query, "CMISQL", cmisService);
860 } catch (ClientException e) {
861 // TODO Auto-generated catch block
862 logger.error("Encounter trouble making the following CMIS query: " + query, e);
863 throw new NuxeoDocumentException(e);
870 * getFiltered get all documents for an entity service from the Document
871 * repository, given filter parameters specified by the handler.
873 * @param ctx service context under which this method is invoked
874 * @param handler should be used by the caller to provide and transform the
876 * @throws DocumentNotFoundException if workspace not found
877 * @throws TransactionException
878 * @throws DocumentException
881 public void getFiltered(ServiceContext ctx, DocumentHandler handler)
882 throws DocumentNotFoundException, TransactionException, DocumentException {
884 DocumentFilter filter = handler.getDocumentFilter();
885 String oldOrderBy = filter.getOrderByClause();
886 if (isClauseEmpty(oldOrderBy) == true) {
887 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
889 QueryContext queryContext = new QueryContext(ctx, handler);
891 CoreSessionInterface repoSession = null;
893 handler.prepare(Action.GET_ALL);
894 repoSession = getRepositorySession(ctx); //Keeps a refcount here for the repository session so you need to release this when finished
896 DocumentModelList docList = null;
898 if (handler.isJDBCQuery() == true) {
899 docList = getFilteredJDBC(repoSession, ctx, handler);
901 } else if (handler.isCMISQuery() == true) {
902 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext); //FIXME: REM - Need to deal with paging info in CMIS query
905 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
906 if (logger.isDebugEnabled()) {
907 logger.debug("Executing NXQL query: " + query.toString());
909 Profiler profiler = new Profiler(this, 2);
910 profiler.log("Executing NXQL query: " + query.toString());
912 // If we have a page size and/or offset, then reflect those values
913 // when constructing the query, and also pass 'true' to get totalSize
914 // in the returned DocumentModelList.
915 if ((queryContext.getDocFilter().getOffset() > 0) || (queryContext.getDocFilter().getPageSize() > 0)) {
916 docList = repoSession.query(query, null,
917 queryContext.getDocFilter().getPageSize(), queryContext.getDocFilter().getOffset(), true);
919 docList = repoSession.query(query);
924 //set repoSession to handle the document
925 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
926 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
927 handler.handle(Action.GET_ALL, wrapDoc);
928 handler.complete(Action.GET_ALL, wrapDoc);
929 } catch (DocumentException de) {
931 } catch (Exception e) {
932 if (logger.isDebugEnabled()) {
933 logger.debug("Caught exception ", e); // REM - 1/17/2014: Check for org.nuxeo.ecm.core.api.ClientException and re-attempt
935 throw new NuxeoDocumentException(e);
937 if (repoSession != null) {
938 releaseRepositorySession(ctx, repoSession);
944 * Perform a database query, via JDBC and SQL, to retrieve matching records
945 * based on filter criteria.
947 * Although this method currently has a general-purpose name, it is
948 * currently dedicated to a specific task: that of improving performance
949 * for partial term matching queries on authority items / terms, via
950 * the use of a hand-tuned SQL query, rather than via the generated SQL
951 * produced by Nuxeo from an NXQL query. (See CSPACE-6361 for a task
952 * to generalize this method.)
954 * @param repoSession a repository session.
955 * @param ctx the service context.
956 * @param handler a relevant document handler.
957 * @return a list of document models matching the search criteria.
960 private DocumentModelList getFilteredJDBC(CoreSessionInterface repoSession, ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
961 DocumentHandler handler) throws Exception {
962 DocumentModelList result = new DocumentModelListImpl();
964 // FIXME: Get all of the following values from appropriate external constants.
966 // At present, the two constants below are duplicated in both RepositoryJavaClientImpl
967 // and in AuthorityItemDocumentModelHandler.
968 final String TERM_GROUP_LIST_NAME = "TERM_GROUP_LIST_NAME";
969 final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
970 final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
971 // Get this from a constant in AuthorityResource or equivalent
972 final String PARENT_WILDCARD = "_ALL_";
974 // Build two SQL statements, to be executed within a single transaction:
975 // the first statement to control join order, and the second statement
976 // representing the actual 'get filtered' query
978 // Build the join control statement
980 // Per http://www.postgresql.org/docs/9.2/static/runtime-config-query.html#GUC-JOIN-COLLAPSE-LIMIT
981 // "Setting [this value] to 1 prevents any reordering of explicit JOINs.
982 // Thus, the explicit join order specified in the query will be the
983 // actual order in which the relations are joined."
984 // See CSPACE-5945 for further discussion of why this setting is needed.
986 // Adding this statement is commented out here for now. It significantly
987 // improved query performance for authority item / term queries where
988 // large numbers of rows were retrieved, but appears to have resulted
989 // in consistently slower-than-desired query performance where zero or
990 // very few records were retrieved. See notes on CSPACE-5945. - ADR 2013-04-09
991 // String joinControlSql = "SET LOCAL join_collapse_limit TO 1;";
993 // Build the query statement
995 // Start with the default query
996 String selectStatement =
997 "SELECT DISTINCT commonschema.id"
998 + " FROM " + handler.getServiceContext().getCommonPartLabel() + " commonschema";
1000 String joinClauses =
1002 + " ON misc.id = commonschema.id"
1003 + " INNER JOIN hierarchy hierarchy_termgroup"
1004 + " ON hierarchy_termgroup.parentid = misc.id"
1005 + " INNER JOIN " + handler.getJDBCQueryParams().get(TERM_GROUP_TABLE_NAME_PARAM) + " termgroup"
1006 + " ON termgroup.id = hierarchy_termgroup.id ";
1009 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
1010 // Value for replaceable parameter 1 in the query
1011 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
1012 // If the value of the partial term query parameter is blank ('pt='),
1013 // return all records, subject to restriction by any limit clause
1014 if (Tools.isBlank(partialTerm)) {
1017 // Otherwise, return records that match the supplied partial term
1019 " WHERE (termgroup.termdisplayname ILIKE ?)";
1022 // At present, results are ordered in code, below, rather than in SQL,
1023 // and the orderByClause below is thus intentionally blank.
1025 // To implement the orderByClause below in SQL; e.g. via
1026 // 'ORDER BY termgroup.termdisplayname', the relevant column
1027 // must be returned by the SELECT statement.
1028 String orderByClause = "";
1031 TenantBindingConfigReaderImpl tReader =
1032 ServiceMain.getInstance().getTenantBindingConfigReader();
1033 TenantBindingType tenantBinding = tReader.getTenantBinding(ctx.getTenantId());
1034 String maxListItemsLimit = TenantBindingUtils.getPropertyValue(tenantBinding,
1035 IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES);
1037 " LIMIT " + getMaxItemsLimitOnJdbcQueries(maxListItemsLimit); // implicit int-to-String conversion
1039 // After building the individual parts of the query, set the values
1040 // of replaceable parameters that will be inserted into that query
1041 // and optionally add restrictions
1043 List<String> params = new ArrayList<>();
1045 if (Tools.notBlank(whereClause)) {
1047 // Read tenant bindings configuration to determine whether
1048 // to automatically insert leading, as well as trailing, wildcards
1049 // into the term matching string.
1050 String usesStartingWildcard = TenantBindingUtils.getPropertyValue(tenantBinding,
1051 IQueryManager.TENANT_USES_STARTING_WILDCARD_FOR_PARTIAL_TERM);
1052 // Handle user-provided leading wildcard characters, in the
1053 // configuration where a leading wildcard is not automatically inserted.
1054 // (The user-provided wildcard must be in the first, or "starting"
1055 // character position in the partial term value.)
1056 if (Tools.notBlank(usesStartingWildcard)) {
1057 if (usesStartingWildcard.equalsIgnoreCase(Boolean.FALSE.toString())) {
1058 partialTerm = handleProvidedStartingWildcard(partialTerm);
1059 // Otherwise, in the configuration where a leading wildcard
1060 // is usually automatically inserted, handle the cases where
1061 // a user has entered an anchor character in the first position
1062 // in the starting term value. In those cases, strip that
1063 // anchor character and don't add a leading wildcard
1065 if (partialTerm.startsWith(USER_SUPPLIED_ANCHOR_CHAR)) {
1066 partialTerm = partialTerm.substring(1, partialTerm.length());
1067 // Otherwise, automatically add a leading wildcard
1069 partialTerm = JDBCTools.SQL_WILDCARD + partialTerm;
1073 // Add SQL wildcards in the midst of the partial term match search
1074 // expression, whever user-supplied wildcards appear, except in the
1075 // first or last character positions of the search expression.
1076 partialTerm = subtituteWildcardsInPartialTerm(partialTerm);
1078 // If a designated 'anchor character' is present as the last character
1079 // in the search expression, strip that character and don't add
1080 // a trailing wildcard
1081 int lastCharPos = partialTerm.length() - 1;
1082 if (partialTerm.endsWith(USER_SUPPLIED_ANCHOR_CHAR) && lastCharPos > 0) {
1083 partialTerm = partialTerm.substring(0, lastCharPos);
1085 // Otherwise, automatically add a trailing wildcard
1086 partialTerm = partialTerm + JDBCTools.SQL_WILDCARD;
1088 params.add(partialTerm);
1091 // Optionally add restrictions to the default query, based on variables
1092 // in the current request
1094 // Restrict the query to filter out deleted records, if requested
1095 String includeDeleted = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_NONDELETED);
1096 if (includeDeleted != null && includeDeleted.equalsIgnoreCase(Boolean.FALSE.toString())) {
1097 whereClause = whereClause
1098 + " AND (misc.lifecyclestate <> '" + WorkflowClient.WORKFLOWSTATE_DELETED + "')";
1101 // If a particular authority is specified, restrict the query further
1102 // to return only records within that authority
1103 String inAuthorityValue = (String) handler.getJDBCQueryParams().get(IN_AUTHORITY_PARAM);
1104 if (Tools.notBlank(inAuthorityValue)) {
1105 // Handle the '_ALL_' case for inAuthority
1106 if (inAuthorityValue.equals(PARENT_WILDCARD)) {
1107 // Add nothing to the query here if it should match within all authorities
1109 whereClause = whereClause
1110 + " AND (commonschema.inauthority = ?)";
1111 params.add(inAuthorityValue); // Value for replaceable parameter 2 in the query
1115 // Restrict the query further to return only records pertaining to
1116 // the current tenant, unless:
1117 // * Data for this service, in this tenant, is stored in its own,
1118 // separate repository, rather than being intermingled with other
1119 // tenants' data in the default repository; or
1120 // * Restriction by tenant ID in JDBC queries has been disabled,
1121 // via configuration for this tenant,
1122 if (restrictJDBCQueryByTenantID(tenantBinding, ctx)) {
1123 joinClauses = joinClauses
1124 + " INNER JOIN collectionspace_core core"
1125 + " ON core.id = hierarchy_termgroup.parentid";
1126 whereClause = whereClause
1127 + " AND (core.tenantid = ?)";
1128 params.add(ctx.getTenantId()); // Value for replaceable parameter 3 in the query
1131 // Piece together the SQL query from its parts
1132 String querySql = selectStatement + joinClauses + whereClause + orderByClause + limitClause;
1134 // Note: PostgreSQL 9.2 introduced a change that may improve performance
1135 // of certain queries using JDBC PreparedStatements. See comments on
1136 // CSPACE-5943 for details.
1138 // See a comment above for the reason that the joinControl SQL statement,
1139 // along with its corresponding prepared statement builder, is commented out for now.
1140 // PreparedStatementBuilder joinControlBuilder = new PreparedStatementBuilder(joinControlSql);
1141 PreparedStatementSimpleBuilder queryBuilder = new PreparedStatementSimpleBuilder(querySql, params);
1142 List<PreparedStatementBuilder> builders = new ArrayList<>();
1143 // builders.add(joinControlBuilder);
1144 builders.add(queryBuilder);
1145 String dataSourceName = JDBCTools.NUXEO_DATASOURCE_NAME;
1146 String repositoryName = ctx.getRepositoryName();
1147 final Boolean EXECUTE_WITHIN_TRANSACTION = true;
1148 Set<String> docIds = new HashSet<>();
1150 String cspaceInstanceId = ServiceMain.getInstance().getCspaceInstanceId();
1151 List<CachedRowSet> resultsList = JDBCTools.executePreparedQueries(builders,
1152 dataSourceName, repositoryName, cspaceInstanceId, EXECUTE_WITHIN_TRANSACTION);
1154 // At least one set of results is expected, from the second prepared
1155 // statement to be executed.
1156 // If fewer results are returned, return an empty list of document models
1157 if (resultsList == null || resultsList.size() < 1) {
1158 return result; // return an empty list of document models
1160 // The join control query (if enabled - it is currently commented
1161 // out as per comments above) will not return results, so query results
1162 // will be the first set of results (rowSet) returned in the list
1163 CachedRowSet queryResults = resultsList.get(0);
1165 // If the result from executing the query is null or contains zero rows,
1166 // return an empty list of document models
1167 if (queryResults == null) {
1168 return result; // return an empty list of document models
1170 queryResults.last();
1171 if (queryResults.getRow() == 0) {
1172 return result; // return an empty list of document models
1175 // Otherwise, get the document IDs from the results of the query
1177 queryResults.beforeFirst();
1178 while (queryResults.next()) {
1179 id = queryResults.getString(1);
1180 if (Tools.notBlank(id)) {
1184 } catch (SQLException sqle) {
1185 logger.warn("Could not obtain document IDs via SQL query '" + querySql + "': " + sqle.getMessage());
1186 return result; // return an empty list of document models
1189 // Get a list of document models, using the list of IDs obtained from the query
1191 // FIXME: Check whether we have a 'get document models from list of CSIDs'
1192 // utility method like this, and if not, add this to the appropriate
1194 DocumentModel docModel;
1195 for (String docId : docIds) {
1196 docModel = NuxeoUtils.getDocumentModel(repoSession, docId);
1197 if (docModel == null) {
1198 logger.warn("Could not obtain document model for document with ID " + docId);
1200 result.add(docModel);
1204 // Order the results
1205 final String COMMON_PART_SCHEMA = handler.getServiceContext().getCommonPartLabel();
1206 final String DISPLAY_NAME_XPATH =
1207 "//" + handler.getJDBCQueryParams().get(TERM_GROUP_LIST_NAME) + "/[0]/termDisplayName";
1208 Collections.sort(result, new Comparator<DocumentModel>() {
1210 public int compare(DocumentModel doc1, DocumentModel doc2) {
1211 String termDisplayName1 = null;
1212 String termDisplayName2 = null;
1214 termDisplayName1 = (String) NuxeoUtils.getXPathValue(doc1, COMMON_PART_SCHEMA, DISPLAY_NAME_XPATH);
1215 termDisplayName2 = (String) NuxeoUtils.getXPathValue(doc2, COMMON_PART_SCHEMA, DISPLAY_NAME_XPATH);
1216 } catch (NuxeoDocumentException e) {
1217 throw new RuntimeException(e); // We need to throw a RuntimeException because the compare() method of the Comparator interface does not support throwing an Exception
1219 return termDisplayName1.compareToIgnoreCase(termDisplayName2);
1227 private DocumentModelList getFilteredCMIS(CoreSessionInterface repoSession,
1228 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, DocumentHandler handler, QueryContext queryContext)
1229 throws DocumentNotFoundException, DocumentException {
1231 DocumentModelList result = new DocumentModelListImpl();
1233 String query = handler.getCMISQuery(queryContext);
1235 DocumentFilter docFilter = handler.getDocumentFilter();
1236 int pageSize = docFilter.getPageSize();
1237 int offset = docFilter.getOffset();
1238 if (logger.isDebugEnabled()) {
1239 logger.debug("Executing CMIS query: " + query.toString()
1240 + "with pageSize: " + pageSize + " at offset: " + offset);
1243 // If we have limit and/or offset, then pass true to get totalSize
1244 // in returned DocumentModelList.
1245 Profiler profiler = new Profiler(this, 2);
1246 profiler.log("Executing CMIS query: " + query.toString());
1249 IterableQueryResult queryResult = makeCMISQLQuery(repoSession, query, queryContext);
1251 int totalSize = (int) queryResult.size();
1252 ((DocumentModelListImpl) result).setTotalSize(totalSize);
1253 // Skip the rows before our offset
1255 queryResult.skipTo(offset);
1258 for (Map<String, Serializable> row : queryResult) {
1259 if (logger.isTraceEnabled()) {
1260 logger.trace(" Hierarchy Table ID is:" + row.get(IQueryManager.CMIS_TARGET_NUXEO_ID)
1261 + " nuxeo:pathSegment is: " + row.get(IQueryManager.CMIS_TARGET_NAME));
1263 String nuxeoId = (String) row.get(IQueryManager.CMIS_TARGET_NUXEO_ID);
1264 DocumentModel docModel = NuxeoUtils.getDocumentModel(repoSession, nuxeoId);
1265 result.add(docModel);
1267 if (nRows >= pageSize && pageSize != 0) { // A page size of zero means that they want all of them
1268 logger.debug("Got page full of items - quitting");
1273 queryResult.close();
1278 } catch (Exception e) {
1279 if (logger.isDebugEnabled()) {
1280 logger.debug("Caught exception ", e);
1282 throw new NuxeoDocumentException(e);
1286 // Since we're not supporting paging yet for CMIS queries, we need to perform
1287 // a workaround for the paging information we return in our list of results
1290 if (result != null) {
1291 docFilter.setStartPage(0);
1292 if (totalSize > docFilter.getPageSize()) {
1293 docFilter.setPageSize(totalSize);
1294 ((DocumentModelListImpl)result).setTotalSize(totalSize);
1302 private String logException(Exception e, String msg) {
1303 String result = null;
1305 String exceptionMessage = e.getMessage();
1306 exceptionMessage = exceptionMessage != null ? exceptionMessage : "<No details provided>";
1307 result = msg = msg + ". Caught exception:" + exceptionMessage;
1309 if (logger.isTraceEnabled() == true) {
1310 logger.error(msg, e);
1319 * update given document in the Nuxeo repository
1321 * @param ctx service context under which this method is invoked
1322 * @param csid of the document
1323 * @param handler should be used by the caller to provide and transform the
1325 * @throws BadRequestException
1326 * @throws DocumentNotFoundException
1327 * @throws TransactionException if the transaction times out or otherwise
1328 * cannot be successfully completed
1329 * @throws DocumentException
1332 public void update(ServiceContext ctx, String csid, DocumentHandler handler)
1333 throws BadRequestException, DocumentNotFoundException, TransactionException,
1335 if (handler == null) {
1336 throw new IllegalArgumentException(
1337 "RepositoryJavaClient.update: document handler is missing.");
1340 CoreSessionInterface repoSession = null;
1342 handler.prepare(Action.UPDATE);
1343 repoSession = getRepositorySession(ctx);
1344 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
1345 DocumentModel doc = null;
1347 doc = repoSession.getDocument(docRef);
1348 } catch (ClientException ce) {
1349 String msg = logException(ce, "Could not find document to update with CSID=" + csid);
1350 throw new DocumentNotFoundException(msg, ce);
1352 // Check for a versioned document, and check In and Out before we proceed.
1353 if (((DocumentModelHandler) handler).supportsVersioning()) {
1354 /* Once we advance to 5.5 or later, we can add this.
1355 * See also https://jira.nuxeo.com/browse/NXP-8506
1356 if(!doc.isVersionable()) {
1357 throw new NuxeoDocumentException("Configuration for: "
1358 +handler.getServiceContextPath()+" supports versioning, but Nuxeo config does not!");
1361 /* Force a version number - Not working. Apparently we need to configure the uid schema??
1362 if(doc.getProperty("uid","major_version") == null) {
1363 doc.setProperty("uid","major_version",1);
1365 if(doc.getProperty("uid","minor_version") == null) {
1366 doc.setProperty("uid","minor_version",0);
1369 doc.checkIn(VersioningOption.MINOR, null);
1374 // Set reposession to handle the document
1376 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1377 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
1378 handler.handle(Action.UPDATE, wrapDoc);
1379 repoSession.saveDocument(doc);
1381 handler.complete(Action.UPDATE, wrapDoc);
1382 } catch (BadRequestException bre) {
1384 } catch (DocumentException de) {
1386 } catch (CSWebApplicationException wae) {
1388 } catch (Exception e) {
1389 throw new NuxeoDocumentException(e);
1391 if (repoSession != null) {
1392 releaseRepositorySession(ctx, repoSession);
1398 * Save a documentModel to the Nuxeo repository.
1400 * @param ctx service context under which this method is invoked
1401 * @param repoSession
1402 * @param docModel the document to save
1403 * @param fSaveSession if TRUE, will call CoreSessionInterface.save() to save
1404 * accumulated changes.
1405 * @throws ClientException
1406 * @throws DocumentException
1408 public void saveDocWithoutHandlerProcessing(
1409 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1410 CoreSessionInterface repoSession,
1411 DocumentModel docModel,
1412 boolean fSaveSession)
1413 throws ClientException, DocumentException {
1416 repoSession.saveDocument(docModel);
1420 } catch (ClientException ce) {
1422 } catch (Exception e) {
1423 if (logger.isDebugEnabled()) {
1424 logger.debug("Caught exception ", e);
1426 throw new NuxeoDocumentException(e);
1431 * Save a list of documentModels to the Nuxeo repository.
1433 * @param ctx service context under which this method is invoked
1434 * @param repoSession a repository session
1435 * @param docModelList a list of document models
1436 * @param fSaveSession if TRUE, will call CoreSessionInterface.save() to save
1437 * accumulated changes.
1438 * @throws ClientException
1439 * @throws DocumentException
1441 public void saveDocListWithoutHandlerProcessing(
1442 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1443 CoreSessionInterface repoSession,
1444 DocumentModelList docList,
1445 boolean fSaveSession)
1446 throws ClientException, DocumentException {
1448 DocumentModel[] docModelArray = new DocumentModel[docList.size()];
1449 repoSession.saveDocuments(docList.toArray(docModelArray));
1453 } catch (ClientException ce) {
1455 } catch (Exception e) {
1456 logger.error("Caught exception ", e);
1457 throw new NuxeoDocumentException(e);
1462 public void deleteWithWhereClause(@SuppressWarnings("rawtypes") ServiceContext ctx, String whereClause,
1463 @SuppressWarnings("rawtypes") DocumentHandler handler) throws
1464 DocumentNotFoundException, DocumentException {
1466 throw new IllegalArgumentException(
1467 "delete(ctx, specifier): ctx is missing");
1469 if (logger.isDebugEnabled()) {
1470 logger.debug("Deleting document with whereClause=" + whereClause);
1473 DocumentWrapper<DocumentModel> foundDocWrapper = this.findDoc(ctx, whereClause);
1474 if (foundDocWrapper != null) {
1475 DocumentModel docModel = foundDocWrapper.getWrappedObject();
1476 String csid = docModel.getName();
1477 this.delete(ctx, csid, handler);
1482 * delete a document from the Nuxeo repository
1484 * @param ctx service context under which this method is invoked
1485 * @param id of the document
1486 * @throws DocumentException
1489 public void delete(ServiceContext ctx, String id, DocumentHandler handler) throws DocumentNotFoundException,
1490 DocumentException, TransactionException {
1492 throw new IllegalArgumentException(
1493 "delete(ctx, ix, handler): ctx is missing");
1495 if (handler == null) {
1496 throw new IllegalArgumentException(
1497 "delete(ctx, ix, handler): handler is missing");
1499 if (logger.isDebugEnabled()) {
1500 logger.debug("Deleting document with CSID=" + id);
1502 CoreSessionInterface repoSession = null;
1504 handler.prepare(Action.DELETE);
1505 repoSession = getRepositorySession(ctx);
1506 DocumentWrapper<DocumentModel> wrapDoc = null;
1508 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
1509 wrapDoc = new DocumentWrapperImpl<DocumentModel>(repoSession.getDocument(docRef));
1510 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1511 handler.handle(Action.DELETE, wrapDoc);
1512 repoSession.removeDocument(docRef);
1513 } catch (ClientException ce) {
1514 String msg = logException(ce, "Could not find document to delete with CSID=" + id);
1515 throw new DocumentNotFoundException(msg, ce);
1518 handler.complete(Action.DELETE, wrapDoc);
1519 } catch (DocumentException de) {
1521 } catch (Exception e) {
1522 if (logger.isDebugEnabled()) {
1523 logger.debug("Caught exception ", e);
1525 throw new NuxeoDocumentException(e);
1527 if (repoSession != null) {
1528 releaseRepositorySession(ctx, repoSession);
1534 * @see org.collectionspace.services.common.storage.StorageClient#delete(org.collectionspace.services.common.context.ServiceContext, java.lang.String, org.collectionspace.services.common.document.DocumentHandler)
1538 public void delete(@SuppressWarnings("rawtypes") ServiceContext ctx, String id)
1539 throws DocumentNotFoundException, DocumentException {
1540 throw new UnsupportedOperationException();
1541 // Use the other delete instead
1545 public Hashtable<String, String> retrieveWorkspaceIds(RepositoryDomainType repoDomain) throws Exception {
1546 return NuxeoConnectorEmbedded.getInstance().retrieveWorkspaceIds(repoDomain);
1550 public String createDomain(RepositoryDomainType repositoryDomain) throws Exception {
1551 CoreSessionInterface repoSession = null;
1552 String domainId = null;
1555 // Open a connection to the domain's repo/db
1557 String repoName = repositoryDomain.getRepositoryName();
1558 repoSession = getRepositorySession(repoName); // domainName=storageName=repoName=databaseName
1560 // First create the top-level domain directory
1562 String domainName = repositoryDomain.getStorageName();
1563 DocumentRef parentDocRef = new PathRef("/");
1564 DocumentModel parentDoc = repoSession.getDocument(parentDocRef);
1565 DocumentModel domainDoc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1566 domainName, NUXEO_CORE_TYPE_DOMAIN);
1567 domainDoc.setPropertyValue("dc:title", domainName);
1568 domainDoc.setPropertyValue("dc:description", "A CollectionSpace domain "
1570 domainDoc = repoSession.createDocument(domainDoc);
1571 domainId = domainDoc.getId();
1574 // Next, create a "Workspaces" root directory to contain the workspace folders for the individual service documents
1576 DocumentModel workspacesRoot = repoSession.createDocumentModel(domainDoc.getPathAsString(),
1577 NuxeoUtils.Workspaces, NUXEO_CORE_TYPE_WORKSPACEROOT);
1578 workspacesRoot.setPropertyValue("dc:title", NuxeoUtils.Workspaces);
1579 workspacesRoot.setPropertyValue("dc:description", "A CollectionSpace workspaces directory for "
1580 + domainDoc.getPathAsString());
1581 workspacesRoot = repoSession.createDocument(workspacesRoot);
1582 String workspacesRootId = workspacesRoot.getId();
1585 if (logger.isDebugEnabled()) {
1586 logger.debug("Created tenant domain name=" + domainName
1587 + " id=" + domainId + " "
1588 + NuxeoUtils.Workspaces + " id=" + workspacesRootId);
1589 logger.debug("Path to Domain: " + domainDoc.getPathAsString());
1590 logger.debug("Path to Workspaces root: " + workspacesRoot.getPathAsString());
1592 } catch (Exception e) {
1593 if (logger.isDebugEnabled()) {
1594 logger.debug("Could not create tenant domain name=" + repositoryDomain.getStorageName() + " caught exception ", e);
1598 if (repoSession != null) {
1599 releaseRepositorySession(null, repoSession);
1607 public String getDomainId(RepositoryDomainType repositoryDomain) throws Exception {
1608 String domainId = null;
1609 CoreSessionInterface repoSession = null;
1611 String repoName = repositoryDomain.getRepositoryName();
1612 String domainStorageName = repositoryDomain.getStorageName();
1613 if (domainStorageName != null && !domainStorageName.isEmpty()) {
1615 repoSession = getRepositorySession(repoName);
1616 DocumentRef docRef = new PathRef("/" + domainStorageName);
1617 DocumentModel domain = repoSession.getDocument(docRef);
1618 domainId = domain.getId();
1619 } catch (Exception e) {
1620 if (logger.isTraceEnabled()) {
1621 logger.trace("Caught exception ", e); // The document doesn't exist, this let's us know we need to create it
1623 //there is no way to identify if document does not exist due to
1624 //lack of typed exception for getDocument method
1627 if (repoSession != null) {
1628 releaseRepositorySession(null, repoSession);
1637 * Returns the workspaces root directory for a given domain.
1639 private DocumentModel getWorkspacesRoot(CoreSessionInterface repoSession,
1640 String domainName) throws Exception {
1641 DocumentModel result = null;
1643 String domainPath = "/" + domainName;
1644 DocumentRef parentDocRef = new PathRef(domainPath);
1645 DocumentModelList domainChildrenList = repoSession.getChildren(
1647 Iterator<DocumentModel> witer = domainChildrenList.iterator();
1648 while (witer.hasNext()) {
1649 DocumentModel childNode = witer.next();
1650 if (NuxeoUtils.Workspaces.equalsIgnoreCase(childNode.getName())) {
1652 logger.trace("Found workspaces directory at: " + result.getPathAsString());
1657 if (result == null) {
1658 throw new ClientException("Could not find workspace root directory in: "
1666 * @see org.collectionspace.services.common.repository.RepositoryClient#createWorkspace(java.lang.String, java.lang.String)
1669 public String createWorkspace(RepositoryDomainType repositoryDomain, String workspaceName) throws Exception {
1670 CoreSessionInterface repoSession = null;
1671 String workspaceId = null;
1673 String repoName = repositoryDomain.getRepositoryName();
1674 repoSession = getRepositorySession(repoName);
1676 String domainStorageName = repositoryDomain.getStorageName();
1677 DocumentModel parentDoc = getWorkspacesRoot(repoSession, domainStorageName);
1678 if (logger.isTraceEnabled()) {
1679 for (String facet : parentDoc.getFacets()) {
1680 logger.trace("Facet: " + facet);
1684 DocumentModel doc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1685 workspaceName, NuxeoUtils.WORKSPACE_DOCUMENT_TYPE);
1686 doc.setPropertyValue("dc:title", workspaceName);
1687 doc.setPropertyValue("dc:description", "A CollectionSpace workspace for "
1689 doc = repoSession.createDocument(doc);
1690 workspaceId = doc.getId();
1692 if (logger.isDebugEnabled()) {
1693 logger.debug("Created workspace name=" + workspaceName
1694 + " id=" + workspaceId);
1696 } catch (Exception e) {
1697 if (logger.isDebugEnabled()) {
1698 logger.debug("createWorkspace caught exception ", e);
1702 if (repoSession != null) {
1703 releaseRepositorySession(null, repoSession);
1710 * @see org.collectionspace.services.common.repository.RepositoryClient#getWorkspaceId(java.lang.String, java.lang.String)
1714 public String getWorkspaceId(String tenantDomain, String workspaceName) throws Exception {
1715 String workspaceId = null;
1717 CoreSessionInterface repoSession = null;
1719 repoSession = getRepositorySession((ServiceContext<PoxPayloadIn, PoxPayloadOut>) null);
1720 DocumentRef docRef = new PathRef(
1722 + "/" + NuxeoUtils.Workspaces
1723 + "/" + workspaceName);
1724 DocumentModel workspace = repoSession.getDocument(docRef);
1725 workspaceId = workspace.getId();
1726 } catch (DocumentException de) {
1728 } catch (Exception e) {
1729 if (logger.isDebugEnabled()) {
1730 logger.debug("Caught exception ", e);
1732 throw new NuxeoDocumentException(e);
1734 if (repoSession != null) {
1735 releaseRepositorySession(null, repoSession);
1742 public CoreSessionInterface getRepositorySession(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) throws Exception {
1743 return getRepositorySession(ctx, ctx.getRepositoryName(), ctx.getTimeoutSecs());
1746 public CoreSessionInterface getRepositorySession(String repoName) throws Exception {
1747 return getRepositorySession(null, repoName, ServiceContext.DEFAULT_TX_TIMEOUT);
1751 * Gets the repository session. - Package access only. If the 'ctx' param is
1752 * null then the repo name must be non-mull and vice-versa
1754 * @return the repository session
1755 * @throws Exception the exception
1757 public CoreSessionInterface getRepositorySession(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1759 int timeoutSeconds) throws Exception {
1760 CoreSessionInterface repoSession = null;
1762 Profiler profiler = new Profiler("getRepositorySession():", 2);
1765 // To get a connection to the Nuxeo repo, we need either a valid ServiceContext instance or a repository name
1768 repoName = ctx.getRepositoryName(); // Notice we are overriding the passed in 'repoName' since we have a valid service context passed in to us
1769 repoSession = (CoreSessionInterface) ctx.getCurrentRepositorySession(); // Look to see if one exists in the context before creating one
1770 } else if (repoName == null || repoName.trim().isEmpty()) {
1771 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.");
1772 logger.error(errMsg);
1773 throw new Exception(errMsg);
1776 // 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
1777 // just the repo name
1779 if (repoSession == null) {
1780 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1781 repoSession = client.openRepository(repoName, timeoutSeconds);
1783 if (logger.isDebugEnabled() == true) {
1784 logger.warn("Reusing the current context's repository session.");
1789 if (logger.isTraceEnabled()) {
1790 logger.trace("Testing call to getRepository() repository root: " + repoSession.getRootDocument());
1792 } catch (Throwable e) {
1793 logger.trace("Test call to Nuxeo's getRepository() repository root failed", e);
1799 ctx.setCurrentRepositorySession(repoSession); // For reusing, save the repository session in the current service context
1806 * Release repository session. - Package access only.
1808 * @param repoSession the repo session
1810 public void releaseRepositorySession(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, CoreSessionInterface repoSession) throws TransactionException {
1812 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1815 ctx.clearCurrentRepositorySession(); //clear the current context of the now closed repo session
1816 if (ctx.getCurrentRepositorySession() == null) {
1817 client.releaseRepository(repoSession); //release the repo session if the service context's ref count is zeo.
1820 client.releaseRepository(repoSession); //repo session was acquired without a service context
1822 } catch (TransactionRuntimeException tre) {
1823 String causeMsg = null;
1824 Throwable cause = tre.getCause();
1825 if (cause != null) {
1826 causeMsg = cause.getMessage();
1829 TransactionException te; // a CollectionSpace specific tx exception
1830 if (causeMsg != null) {
1831 te = new TransactionException(causeMsg, tre);
1833 te = new TransactionException(tre);
1836 logger.error(te.getMessage(), tre); // Log the standard transaction exception message, plus an exception-specific stack trace
1838 } catch (Exception e) {
1839 logger.error("Could not close the repository session.", e);
1840 // no need to throw this service specific exception
1845 public void doWorkflowTransition(ServiceContext ctx, String id,
1846 DocumentHandler handler, TransitionDef transitionDef)
1847 throws BadRequestException, DocumentNotFoundException,
1849 // 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
1852 private String handleProvidedStartingWildcard(String partialTerm) {
1853 if (Tools.notBlank(partialTerm)) {
1854 if (partialTerm.substring(0, 1).equals(USER_SUPPLIED_WILDCARD)) {
1855 StringBuffer buffer = new StringBuffer(partialTerm);
1856 buffer.setCharAt(0, JDBCTools.SQL_WILDCARD.charAt(0));
1857 partialTerm = buffer.toString();
1864 * Replaces user-supplied wildcards with SQL wildcards, in a partial term
1865 * matching search expression.
1867 * The scope of this replacement excludes the beginning character
1868 * in that search expression, as that character is treated specially.
1870 * @param partialTerm
1871 * @return the partial term, with any user-supplied wildcards replaced
1874 private String subtituteWildcardsInPartialTerm(String partialTerm) {
1875 if (Tools.isBlank(partialTerm)) {
1878 if (! partialTerm.contains(USER_SUPPLIED_WILDCARD)) {
1881 int len = partialTerm.length();
1882 // Partial term search expressions of 2 or fewer characters
1883 // currently aren't amenable to the use of wildcards
1885 logger.warn("Partial term match search expression of just 1-2 characters in length contains a user-supplied wildcard: " + partialTerm);
1886 logger.warn("Will handle that character as a literal value, rather than as a wildcard ...");
1889 return partialTerm.substring(0, 1) // first char
1890 + partialTerm.substring(1, len).replaceAll(USER_SUPPLIED_WILDCARD_REGEX, JDBCTools.SQL_WILDCARD);
1894 private int getMaxItemsLimitOnJdbcQueries(String maxListItemsLimit) {
1895 final int DEFAULT_ITEMS_LIMIT = 40;
1896 if (maxListItemsLimit == null) {
1897 return DEFAULT_ITEMS_LIMIT;
1901 itemsLimit = Integer.parseInt(maxListItemsLimit);
1902 if (itemsLimit < 1) {
1903 logger.warn("Value of configuration setting "
1904 + IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES
1905 + " must be a positive integer; invalid current value is " + maxListItemsLimit);
1906 logger.warn("Reverting to default value of " + DEFAULT_ITEMS_LIMIT);
1907 itemsLimit = DEFAULT_ITEMS_LIMIT;
1909 } catch (NumberFormatException nfe) {
1910 logger.warn("Value of configuration setting "
1911 + IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES
1912 + " must be a positive integer; invalid current value is " + maxListItemsLimit);
1913 logger.warn("Reverting to default value of " + DEFAULT_ITEMS_LIMIT);
1914 itemsLimit = DEFAULT_ITEMS_LIMIT;
1920 * Identifies whether a restriction on tenant ID - to return only records
1921 * pertaining to the current tenant - is required in a JDBC query.
1923 * @param tenantBinding a tenant binding configuration.
1924 * @param ctx a service context.
1925 * @return true if a restriction on tenant ID is required in the query;
1926 * false if a restriction is not required.
1928 private boolean restrictJDBCQueryByTenantID(TenantBindingType tenantBinding, ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
1929 boolean restrict = true;
1930 // If data for the current service, in the current tenant, is isolated
1931 // within its own separate, per-tenant repository, as contrasted with
1932 // being intermingled with other tenants' data in the default repository,
1933 // no restriction on Tenant ID is required in the query.
1934 String repositoryDomainName = ConfigUtils.getRepositoryName(tenantBinding, ctx.getRepositoryDomainName());
1935 if (!(repositoryDomainName.equals(ConfigUtils.DEFAULT_NUXEO_REPOSITORY_NAME))) {
1938 // If a configuration setting for this tenant identifies that JDBC
1939 // queries should not be restricted by tenant ID (perhaps because
1940 // there is always expected to be only one tenant's data present in
1941 // the system), no restriction on Tenant ID is required in the query.
1942 String queriesRestrictedByTenantId = TenantBindingUtils.getPropertyValue(tenantBinding,
1943 IQueryManager.JDBC_QUERIES_ARE_TENANT_ID_RESTRICTED);
1944 if (Tools.notBlank(queriesRestrictedByTenantId) &&
1945 queriesRestrictedByTenantId.equalsIgnoreCase(Boolean.FALSE.toString())) {