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";
116 * Instantiates a new repository java client impl.
118 public RepositoryJavaClientImpl() {
122 public void assertWorkflowState(ServiceContext ctx,
123 DocumentModel docModel) throws DocumentNotFoundException, ClientException {
124 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
125 if (queryParams != null) {
127 // Look for the workflow "delete" query param and see if we need to assert that the
128 // docModel is in a non-deleted workflow state.
130 String currentState = docModel.getCurrentLifeCycleState();
131 String includeDeletedStr = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_NONDELETED);
132 boolean includeDeleted = includeDeletedStr == null ? true : Boolean.parseBoolean(includeDeletedStr);
133 if (includeDeleted == false) {
135 // We don't wanted soft-deleted object, so throw an exception if this one is soft-deleted.
137 if (currentState.equalsIgnoreCase(WorkflowClient.WORKFLOWSTATE_DELETED)) {
138 String msg = "The GET assertion that docModel not be in 'deleted' workflow state failed.";
140 throw new DocumentNotFoundException(msg);
147 * create document in the Nuxeo repository
149 * @param ctx service context under which this method is invoked
150 * @param handler should be used by the caller to provide and transform the
152 * @return id in repository of the newly created document
153 * @throws BadRequestException
154 * @throws TransactionException
155 * @throws DocumentException
158 public String create(ServiceContext ctx,
159 DocumentHandler handler) throws BadRequestException,
160 TransactionException, DocumentException {
162 String docType = NuxeoUtils.getTenantQualifiedDocType(ctx); //ctx.getDocumentType();
163 if (docType == null) {
164 throw new IllegalArgumentException(
165 "RepositoryJavaClient.create: docType is missing");
168 if (handler == null) {
169 throw new IllegalArgumentException(
170 "RepositoryJavaClient.create: handler is missing");
172 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
173 if (nuxeoWspaceId == null) {
174 throw new DocumentNotFoundException(
175 "Unable to find workspace for service " + ctx.getServiceName()
176 + " check if the workspace exists in the Nuxeo repository");
179 RepositoryInstance repoSession = null;
181 handler.prepare(Action.CREATE);
182 repoSession = getRepositorySession(ctx);
183 DocumentRef nuxeoWspace = new IdRef(nuxeoWspaceId);
184 DocumentModel wspaceDoc = repoSession.getDocument(nuxeoWspace);
185 String wspacePath = wspaceDoc.getPathAsString();
186 //give our own ID so PathRef could be constructed later on
187 String id = IdUtils.generateId(UUID.randomUUID().toString());
188 // create document model
189 DocumentModel doc = repoSession.createDocumentModel(wspacePath, id, docType);
190 /* Check for a versioned document, and check In and Out before we proceed.
191 * This does not work as we do not have the uid schema on our docs.
192 if(((DocumentModelHandler) handler).supportsVersioning()) {
193 doc.setProperty("uid","major_version",1);
194 doc.setProperty("uid","minor_version",0);
197 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
198 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
199 handler.handle(Action.CREATE, wrapDoc);
200 // create document with documentmodel
201 doc = repoSession.createDocument(doc);
203 // TODO for sub-docs need to call into the handler to let it deal with subitems. Pass in the id,
204 // and assume the handler has the state it needs (doc fragments).
205 handler.complete(Action.CREATE, wrapDoc);
207 } catch (BadRequestException bre) {
209 } catch (Exception e) {
210 logger.error("Caught exception ", e);
211 throw new DocumentException(e);
213 if (repoSession != null) {
214 releaseRepositorySession(ctx, repoSession);
221 * get document from the Nuxeo repository
223 * @param ctx service context under which this method is invoked
224 * @param id of the document to retrieve
225 * @param handler should be used by the caller to provide and transform the
227 * @throws DocumentNotFoundException if the document cannot be found in the
229 * @throws TransactionException
230 * @throws DocumentException
233 public void get(ServiceContext ctx, String id, DocumentHandler handler)
234 throws DocumentNotFoundException, TransactionException, DocumentException {
236 if (handler == null) {
237 throw new IllegalArgumentException(
238 "RepositoryJavaClient.get: handler is missing");
241 RepositoryInstance repoSession = null;
243 handler.prepare(Action.GET);
244 repoSession = getRepositorySession(ctx);
245 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
246 DocumentModel docModel = null;
248 docModel = repoSession.getDocument(docRef);
249 assertWorkflowState(ctx, docModel);
250 } catch (ClientException ce) {
251 String msg = logException(ce, "Could not find document with CSID=" + id);
252 throw new DocumentNotFoundException(msg, ce);
255 // Set repository session to handle the document
257 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
258 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(docModel);
259 handler.handle(Action.GET, wrapDoc);
260 handler.complete(Action.GET, wrapDoc);
261 } catch (IllegalArgumentException iae) {
263 } catch (DocumentException de) {
265 } catch (Exception e) {
266 if (logger.isDebugEnabled()) {
267 logger.debug("Caught exception ", e);
269 throw new DocumentException(e);
271 if (repoSession != null) {
272 releaseRepositorySession(ctx, repoSession);
278 * get a document from the Nuxeo repository, using the docFilter params.
280 * @param ctx service context under which this method is invoked
281 * @param handler should be used by the caller to provide and transform the
282 * document. Handler must have a docFilter set to return a single item.
283 * @throws DocumentNotFoundException if the document cannot be found in the
285 * @throws TransactionException
286 * @throws DocumentException
289 public void get(ServiceContext ctx, DocumentHandler handler)
290 throws DocumentNotFoundException, TransactionException, DocumentException {
291 QueryContext queryContext = new QueryContext(ctx, handler);
292 RepositoryInstance repoSession = null;
295 handler.prepare(Action.GET);
296 repoSession = getRepositorySession(ctx);
298 DocumentModelList docList = null;
299 // force limit to 1, and ignore totalSize
300 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
301 docList = repoSession.query(query, null, 1, 0, false);
302 if (docList.size() != 1) {
303 throw new DocumentNotFoundException("No document found matching filter params: " + query);
305 DocumentModel doc = docList.get(0);
307 if (logger.isDebugEnabled()) {
308 logger.debug("Executed NXQL query: " + query);
311 //set reposession to handle the document
312 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
313 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
314 handler.handle(Action.GET, wrapDoc);
315 handler.complete(Action.GET, wrapDoc);
316 } catch (IllegalArgumentException iae) {
318 } catch (DocumentException de) {
320 } catch (Exception e) {
321 if (logger.isDebugEnabled()) {
322 logger.debug("Caught exception ", e);
324 throw new DocumentException(e);
326 if (repoSession != null) {
327 releaseRepositorySession(ctx, repoSession);
332 public DocumentWrapper<DocumentModel> getDoc(
333 RepositoryInstance repoSession,
334 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
335 String csid) throws DocumentNotFoundException, DocumentException {
336 DocumentWrapper<DocumentModel> wrapDoc = null;
339 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
340 DocumentModel doc = null;
342 doc = repoSession.getDocument(docRef);
343 } catch (ClientException ce) {
344 String msg = logException(ce, "Could not find document with CSID=" + csid);
345 throw new DocumentNotFoundException(msg, ce);
347 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
348 } catch (IllegalArgumentException iae) {
350 } catch (DocumentException de) {
358 * Get wrapped documentModel from the Nuxeo repository. The search is
359 * restricted to the workspace of the current context.
361 * @param ctx service context under which this method is invoked
362 * @param csid of the document to retrieve
363 * @throws DocumentNotFoundException
364 * @throws TransactionException
365 * @throws DocumentException
366 * @return a wrapped documentModel
369 public DocumentWrapper<DocumentModel> getDoc(
370 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
371 String csid) throws DocumentNotFoundException, TransactionException, DocumentException {
372 RepositoryInstance repoSession = null;
373 DocumentWrapper<DocumentModel> wrapDoc = null;
376 // Open a new repository session
377 repoSession = getRepositorySession(ctx);
378 wrapDoc = getDoc(repoSession, ctx, csid);
379 } catch (IllegalArgumentException iae) {
381 } catch (DocumentException de) {
383 } catch (Exception e) {
384 if (logger.isDebugEnabled()) {
385 logger.debug("Caught exception ", e);
387 throw new DocumentException(e);
389 if (repoSession != null) {
390 releaseRepositorySession(ctx, repoSession);
394 if (logger.isWarnEnabled() == true) {
395 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
400 public DocumentWrapper<DocumentModel> findDoc(
401 RepositoryInstance repoSession,
402 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
404 throws DocumentNotFoundException, DocumentException {
405 DocumentWrapper<DocumentModel> wrapDoc = null;
408 QueryContext queryContext = new QueryContext(ctx, whereClause);
409 DocumentModelList docList = null;
410 // force limit to 1, and ignore totalSize
411 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
412 docList = repoSession.query(query,
417 if (docList.size() != 1) {
418 if (logger.isDebugEnabled()) {
419 logger.debug("findDoc: Query found: " + docList.size() + " items.");
420 logger.debug(" Query: " + query);
422 throw new DocumentNotFoundException("No document found matching filter params: " + query);
424 DocumentModel doc = docList.get(0);
425 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
426 } catch (IllegalArgumentException iae) {
428 } catch (DocumentException de) {
430 } catch (Exception e) {
431 if (logger.isDebugEnabled()) {
432 logger.debug("Caught exception ", e);
434 throw new DocumentException(e);
441 * find wrapped documentModel from the Nuxeo repository
443 * @param ctx service context under which this method is invoked
444 * @param whereClause where NXQL where clause to get the document
445 * @throws DocumentNotFoundException
446 * @throws TransactionException
447 * @throws DocumentException
448 * @return a wrapped documentModel retrieved by the repository query
451 public DocumentWrapper<DocumentModel> findDoc(
452 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
454 throws DocumentNotFoundException, TransactionException, DocumentException {
455 RepositoryInstance repoSession = null;
456 DocumentWrapper<DocumentModel> wrapDoc = null;
459 repoSession = getRepositorySession(ctx);
460 wrapDoc = findDoc(repoSession, ctx, whereClause);
461 } catch (Exception e) {
462 throw new DocumentException("Unable to create a Nuxeo repository session.", e);
464 if (repoSession != null) {
465 releaseRepositorySession(ctx, repoSession);
469 if (logger.isWarnEnabled() == true) {
470 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
477 * find doc and return CSID from the Nuxeo repository
480 * @param ctx service context under which this method is invoked
481 * @param whereClause where NXQL where clause to get the document
482 * @throws DocumentNotFoundException
483 * @throws TransactionException
484 * @throws DocumentException
485 * @return the CollectionSpace ID (CSID) of the requested document
488 public String findDocCSID(RepositoryInstance repoSession,
489 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String whereClause)
490 throws DocumentNotFoundException, TransactionException, DocumentException {
492 boolean releaseSession = false;
494 if (repoSession == null) {
495 repoSession = this.getRepositorySession(ctx);
496 releaseSession = true;
498 DocumentWrapper<DocumentModel> wrapDoc = findDoc(repoSession, ctx, whereClause);
499 DocumentModel docModel = wrapDoc.getWrappedObject();
500 csid = NuxeoUtils.getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
501 } catch (DocumentNotFoundException dnfe) {
503 } catch (IllegalArgumentException iae) {
505 } catch (DocumentException de) {
507 } catch (Exception e) {
508 if (logger.isDebugEnabled()) {
509 logger.debug("Caught exception ", e);
511 throw new DocumentException(e);
513 if (releaseSession && (repoSession != null)) {
514 this.releaseRepositorySession(ctx, repoSession);
520 public DocumentWrapper<DocumentModelList> findDocs(
521 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
522 RepositoryInstance repoSession,
523 List<String> docTypes,
525 String orderByClause,
528 boolean computeTotal)
529 throws DocumentNotFoundException, DocumentException {
530 DocumentWrapper<DocumentModelList> wrapDoc = null;
533 if (docTypes == null || docTypes.size() < 1) {
534 throw new DocumentNotFoundException(
535 "The findDocs() method must specify at least one DocumentType.");
537 DocumentModelList docList = null;
538 QueryContext queryContext = new QueryContext(ctx, whereClause, orderByClause);
539 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
540 if (logger.isDebugEnabled()) {
541 logger.debug("findDocs() NXQL: " + query);
543 docList = repoSession.query(query, null, pageSize, pageSize * pageNum, computeTotal);
544 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
545 } catch (IllegalArgumentException iae) {
547 } catch (Exception e) {
548 if (logger.isDebugEnabled()) {
549 logger.debug("Caught exception ", e);
551 throw new DocumentException(e);
557 protected static String buildInListForDocTypes(List<String> docTypes) {
558 StringBuilder sb = new StringBuilder();
560 boolean first = true;
561 for (String docType : docTypes) {
572 return sb.toString();
575 public DocumentWrapper<DocumentModelList> findDocs(
576 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
577 DocumentHandler handler,
578 RepositoryInstance repoSession,
579 List<String> docTypes)
580 throws DocumentNotFoundException, DocumentException {
581 DocumentWrapper<DocumentModelList> wrapDoc = null;
583 DocumentFilter filter = handler.getDocumentFilter();
584 String oldOrderBy = filter.getOrderByClause();
585 if (isClauseEmpty(oldOrderBy) == true) {
586 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
588 QueryContext queryContext = new QueryContext(ctx, handler);
591 if (docTypes == null || docTypes.size() < 1) {
592 throw new DocumentNotFoundException(
593 "The findDocs() method must specify at least one DocumentType.");
595 DocumentModelList docList = null;
596 if (handler.isCMISQuery() == true) {
597 String inList = buildInListForDocTypes(docTypes);
598 ctx.getQueryParams().add(IQueryManager.SEARCH_RELATED_MATCH_OBJ_DOCTYPES, inList);
599 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
601 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
602 if (logger.isDebugEnabled()) {
603 logger.debug("findDocs() NXQL: " + query);
605 docList = repoSession.query(query, null, filter.getPageSize(), filter.getOffset(), true);
607 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
608 } catch (IllegalArgumentException iae) {
610 } catch (Exception e) {
611 if (logger.isDebugEnabled()) {
612 logger.debug("Caught exception ", e);
614 throw new DocumentException(e);
621 * Find a list of documentModels from the Nuxeo repository
623 * @param docTypes a list of DocType names to match
624 * @param whereClause where the clause to qualify on
625 * @throws DocumentNotFoundException
626 * @throws TransactionException
627 * @throws DocumentException
628 * @return a list of documentModels
631 public DocumentWrapper<DocumentModelList> findDocs(
632 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
633 List<String> docTypes,
635 int pageSize, int pageNum, boolean computeTotal)
636 throws DocumentNotFoundException, TransactionException, DocumentException {
637 RepositoryInstance repoSession = null;
638 DocumentWrapper<DocumentModelList> wrapDoc = null;
641 repoSession = getRepositorySession(ctx);
642 wrapDoc = findDocs(ctx, repoSession, docTypes, whereClause, null,
643 pageSize, pageNum, computeTotal);
644 } catch (IllegalArgumentException iae) {
646 } catch (Exception e) {
647 if (logger.isDebugEnabled()) {
648 logger.debug("Caught exception ", e);
650 throw new DocumentException(e);
652 if (repoSession != null) {
653 releaseRepositorySession(ctx, repoSession);
657 if (logger.isWarnEnabled() == true) {
658 logger.warn("Returned DocumentModelList instance was created with a repository session that is now closed.");
665 * @see org.collectionspace.services.common.storage.StorageClient#get(org.collectionspace.services.common.context.ServiceContext, java.util.List, org.collectionspace.services.common.document.DocumentHandler)
668 public void get(ServiceContext ctx, List<String> csidList, DocumentHandler handler)
669 throws DocumentNotFoundException, TransactionException, DocumentException {
670 if (handler == null) {
671 throw new IllegalArgumentException(
672 "RepositoryJavaClient.getAll: handler is missing");
675 RepositoryInstance repoSession = null;
677 handler.prepare(Action.GET_ALL);
678 repoSession = getRepositorySession(ctx);
679 DocumentModelList docModelList = new DocumentModelListImpl();
680 //FIXME: Should be using NuxeoUtils.createPathRef for security reasons
681 for (String csid : csidList) {
682 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
683 DocumentModel docModel = repoSession.getDocument(docRef);
684 docModelList.add(docModel);
687 //set reposession to handle the document
688 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
689 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docModelList);
690 handler.handle(Action.GET_ALL, wrapDoc);
691 handler.complete(Action.GET_ALL, wrapDoc);
692 } catch (DocumentException de) {
694 } catch (Exception e) {
695 if (logger.isDebugEnabled()) {
696 logger.debug("Caught exception ", e);
698 throw new DocumentException(e);
700 if (repoSession != null) {
701 releaseRepositorySession(ctx, repoSession);
707 * getAll get all documents for an entity entity service from the Nuxeo
710 * @param ctx service context under which this method is invoked
711 * @param handler should be used by the caller to provide and transform the
713 * @throws DocumentNotFoundException
714 * @throws TransactionException
715 * @throws DocumentException
718 public void getAll(ServiceContext ctx, DocumentHandler handler)
719 throws DocumentNotFoundException, TransactionException, DocumentException {
720 if (handler == null) {
721 throw new IllegalArgumentException(
722 "RepositoryJavaClient.getAll: handler is missing");
724 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
725 if (nuxeoWspaceId == null) {
726 throw new DocumentNotFoundException(
727 "Unable to find workspace for service "
728 + ctx.getServiceName()
729 + " check if the workspace exists in the Nuxeo repository.");
732 RepositoryInstance repoSession = null;
734 handler.prepare(Action.GET_ALL);
735 repoSession = getRepositorySession(ctx);
736 DocumentRef wsDocRef = new IdRef(nuxeoWspaceId);
737 DocumentModelList docList = repoSession.getChildren(wsDocRef);
738 //set reposession to handle the document
739 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
740 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
741 handler.handle(Action.GET_ALL, wrapDoc);
742 handler.complete(Action.GET_ALL, wrapDoc);
743 } catch (DocumentException de) {
745 } catch (Exception e) {
746 if (logger.isDebugEnabled()) {
747 logger.debug("Caught exception ", e);
749 throw new DocumentException(e);
751 if (repoSession != null) {
752 releaseRepositorySession(ctx, repoSession);
757 private boolean isClauseEmpty(String theString) {
758 boolean result = true;
759 if (theString != null && !theString.isEmpty()) {
765 public DocumentWrapper<DocumentModel> getDocFromCsid(
766 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
767 RepositoryInstance repoSession,
770 DocumentWrapper<DocumentModel> result = null;
772 result = new DocumentWrapperImpl(NuxeoUtils.getDocFromCsid(ctx, repoSession, csid));
778 * A method to find a CollectionSpace document (of any type) given just a service context and
779 * its CSID. A search across *all* service workspaces (within a given tenant context) is performed to find
782 * This query searches Nuxeo's Hierarchy table where our CSIDs are stored in the "name" column.
785 public DocumentWrapper<DocumentModel> getDocFromCsid(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
788 DocumentWrapper<DocumentModel> result = null;
789 RepositoryInstance repoSession = null;
791 repoSession = getRepositorySession(ctx);
792 result = getDocFromCsid(ctx, repoSession, csid);
794 if (repoSession != null) {
795 releaseRepositorySession(ctx, repoSession);
799 if (logger.isWarnEnabled() == true) {
800 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
807 * Returns a URI value for a document in the Nuxeo repository
809 * @param wrappedDoc a wrapped documentModel
810 * @throws ClientException
811 * @return a document URI
814 public String getDocURI(DocumentWrapper<DocumentModel> wrappedDoc) throws ClientException {
815 DocumentModel docModel = wrappedDoc.getWrappedObject();
816 String uri = (String) docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
817 CollectionSpaceClient.COLLECTIONSPACE_CORE_URI);
822 * See CSPACE-5036 - How to make CMISQL queries from Nuxeo
824 private IterableQueryResult makeCMISQLQuery(RepositoryInstance repoSession, String query, QueryContext queryContext) {
825 IterableQueryResult result = null;
827 // the NuxeoRepository should be constructed only once, then cached
828 // (its construction is expensive)
830 NuxeoRepository repo = new NuxeoRepository(
831 repoSession.getRepositoryName(), repoSession
832 .getRootDocument().getId());
833 logger.debug("Repository ID:" + repo.getId() + " Root folder:"
834 + repo.getRootFolderId());
836 CallContextImpl callContext = new CallContextImpl(
837 CallContext.BINDING_LOCAL, repo.getId(), false);
838 callContext.put(CallContext.USERNAME, repoSession.getPrincipal()
840 NuxeoCmisService cmisService = new NuxeoCmisService(repo,
841 callContext, repoSession);
843 result = repoSession.queryAndFetch(query, "CMISQL", cmisService);
844 } catch (ClientException e) {
845 // TODO Auto-generated catch block
846 logger.error("Encounter trouble making the following CMIS query: " + query, e);
853 * getFiltered get all documents for an entity service from the Document
854 * repository, given filter parameters specified by the handler.
856 * @param ctx service context under which this method is invoked
857 * @param handler should be used by the caller to provide and transform the
859 * @throws DocumentNotFoundException if workspace not found
860 * @throws TransactionException
861 * @throws DocumentException
864 public void getFiltered(ServiceContext ctx, DocumentHandler handler)
865 throws DocumentNotFoundException, TransactionException, DocumentException {
867 DocumentFilter filter = handler.getDocumentFilter();
868 String oldOrderBy = filter.getOrderByClause();
869 if (isClauseEmpty(oldOrderBy) == true) {
870 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
872 QueryContext queryContext = new QueryContext(ctx, handler);
874 RepositoryInstance repoSession = null;
876 handler.prepare(Action.GET_ALL);
877 repoSession = getRepositorySession(ctx); //Keeps a refcount here for the repository session so you need to release this when finished
879 DocumentModelList docList = null;
880 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
882 if (logger.isDebugEnabled()) {
883 logger.debug("Executing NXQL query: " + query.toString());
886 // If we have limit and/or offset, then pass true to get totalSize
887 // in returned DocumentModelList.
888 Profiler profiler = new Profiler(this, 2);
889 profiler.log("Executing NXQL query: " + query.toString());
891 if (handler.isJDBCQuery() == true) {
892 docList = getFilteredJDBC(repoSession, ctx, handler, queryContext);
893 } else if (handler.isCMISQuery() == true) {
894 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext); //FIXME: REM - Need to deal with paging info in CMIS query
895 } else if ((queryContext.getDocFilter().getOffset() > 0) || (queryContext.getDocFilter().getPageSize() > 0)) {
896 docList = repoSession.query(query, null,
897 queryContext.getDocFilter().getPageSize(), queryContext.getDocFilter().getOffset(), true);
899 docList = repoSession.query(query);
903 //set repoSession to handle the document
904 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
905 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
906 handler.handle(Action.GET_ALL, wrapDoc);
907 handler.complete(Action.GET_ALL, wrapDoc);
908 } catch (DocumentException de) {
910 } catch (Exception e) {
911 if (logger.isDebugEnabled()) {
912 logger.debug("Caught exception ", e);
914 throw new DocumentException(e);
916 if (repoSession != null) {
917 releaseRepositorySession(ctx, repoSession);
922 private DocumentModelList getFilteredJDBC(RepositoryInstance repoSession, ServiceContext ctx,
923 DocumentHandler handler, QueryContext queryContext) throws Exception {
924 DocumentModelList result = new DocumentModelListImpl();
926 // FIXME: Get all of the following values from appropriate external constants.
928 // At present, the two constants below are duplicated in both RepositoryJavaClientImpl
929 // and in AuthorityItemDocumentModelHandler.
930 final String TERM_GROUP_LIST_NAME = "TERM_GROUP_LIST_NAME";
931 final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
932 final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
933 // Get this from a constant in AuthorityResource or equivalent
934 final String PARENT_WILDCARD = "_ALL_";
936 // Build two SQL statements, to be executed within a single transaction:
937 // the first statement to control join order, and the second statement
938 // representing the actual 'get filtered' query
940 // Build the join control statement
942 // Per http://www.postgresql.org/docs/9.2/static/runtime-config-query.html#GUC-JOIN-COLLAPSE-LIMIT
943 // "Setting [this value] to 1 prevents any reordering of explicit JOINs.
944 // Thus, the explicit join order specified in the query will be the
945 // actual order in which the relations are joined."
946 // See CSPACE-5945 for further discussion of why this setting is needed.
947 String joinControlSql = "SET LOCAL join_collapse_limit TO 1;";
949 // Build the query statement
951 // Start with the default query
952 String selectStatement =
953 "SELECT DISTINCT hierarchy_termgroup.parentid as id"
954 + " FROM " + handler.getJDBCQueryParams().get(TERM_GROUP_TABLE_NAME_PARAM) + " termgroup";
957 " INNER JOIN hierarchy hierarchy_termgroup"
958 + " ON hierarchy_termgroup.id = termgroup.id";
961 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
962 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
963 // If the value of the partial term query parameter is blank ('pt='),
964 // return all records, subject to restriction by any limit clause
965 if (Tools.isBlank(partialTerm)) {
968 // Otherwise, return records that match the supplied partial term
970 " WHERE (termgroup.termdisplayname ILIKE ?)";
973 // At present, results are ordered in code, below, rather than in SQL,
974 // and the orderByClause below is thus intentionally blank.
976 // To implement the orderByClause below in SQL; e.g. via
977 // 'ORDER BY termgroup.termdisplayname', the relevant column
978 // must be returned by the SELECT statement.
979 String orderByClause = "";
982 TenantBindingConfigReaderImpl tReader =
983 ServiceMain.getInstance().getTenantBindingConfigReader();
984 TenantBindingType tenantBinding = tReader.getTenantBinding(ctx.getTenantId());
985 String maxListItemsLimit = TenantBindingUtils.getPropertyValue(tenantBinding,
986 IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES);
988 " LIMIT " + getMaxItemsLimitOnJdbcQueries(maxListItemsLimit); // implicit int-to-String conversion
990 List<String> params = new ArrayList<>();
992 // Read tenant bindings configuration to determine whether
993 // to automatically insert leading, as well as trailing, wildcards
994 // into the term matching string.
995 String usesStartingWildcard = TenantBindingUtils.getPropertyValue(tenantBinding,
996 IQueryManager.TENANT_USES_STARTING_WILDCARD_FOR_PARTIAL_TERM);
997 // Handle user-provided leading wildcard characters, in the
998 // configuration where a leading wildcard is not automatically inserted.
999 // (The user-provided wildcard must be in the first, or "starting"
1000 // character position in the partial term value.)
1001 if (Tools.notBlank(usesStartingWildcard) && usesStartingWildcard.equalsIgnoreCase(Boolean.FALSE.toString())) {
1002 partialTerm = handleProvidedStartingWildcard(partialTerm);
1003 // Otherwise, automatically insert a leading wildcard
1005 partialTerm = JDBCTools.SQL_WILDCARD + partialTerm;
1007 // Automatically insert a trailing wildcard
1008 params.add(partialTerm + JDBCTools.SQL_WILDCARD); // Value for replaceable parameter 1 in the query
1010 // Restrict the query to filter out deleted records, if requested
1011 String includeDeleted = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_NONDELETED);
1012 if (includeDeleted != null && includeDeleted.equalsIgnoreCase(Boolean.FALSE.toString())) {
1013 joinClauses = joinClauses
1014 + " INNER JOIN misc"
1015 + " ON misc.id = hierarchy_termgroup.parentid";
1016 whereClause = whereClause
1017 + " AND (misc.lifecyclestate <> '" + WorkflowClient.WORKFLOWSTATE_DELETED + "')";
1020 // If a particular authority is specified, restrict the query further
1021 // to return only records within that authority
1022 String inAuthorityValue = (String) handler.getJDBCQueryParams().get(IN_AUTHORITY_PARAM);
1023 if (Tools.notBlank(inAuthorityValue)) {
1024 // Handle the '_ALL_' case for inAuthority
1025 if (inAuthorityValue.equals(PARENT_WILDCARD)) {
1026 // Add nothing to the query here if it should match within all authorities
1028 joinClauses = joinClauses
1029 + " INNER JOIN " + handler.getServiceContext().getCommonPartLabel() + " commonschema"
1030 + " ON commonschema.id = hierarchy_termgroup.parentid";
1031 whereClause = whereClause
1032 + " AND (commonschema.inauthority = ?)";
1033 params.add(inAuthorityValue); // Value for replaceable parameter 2 in the query
1037 // Restrict the query further to return only records pertaining to
1038 // the current tenant, unless:
1039 // * Data for this service, in this tenant, is stored in its own,
1040 // separate repository, rather than being intermingled with other
1041 // tenants' data in the default repository; or
1042 // * Restriction by tenant ID in JDBC queries has been disabled,
1043 // via configuration for this tenant,
1044 if (restrictJDBCQueryByTenantID(tenantBinding, ctx)) {
1045 joinClauses = joinClauses
1046 + " INNER JOIN collectionspace_core core"
1047 + " ON core.id = hierarchy_termgroup.parentid";
1048 whereClause = whereClause
1049 + " AND (core.tenantid = ?)";
1050 params.add(ctx.getTenantId()); // Value for replaceable parameter 3 in the query
1053 // Piece together the SQL query from its parts
1054 String querySql = selectStatement + joinClauses + whereClause + orderByClause + limitClause;
1056 // Note: PostgreSQL 9.2 introduced a change that may improve performance
1057 // of certain queries using JDBC PreparedStatements. See comments on
1058 // CSPACE-5943 for details.
1059 PreparedStatementBuilder joinControlBuilder = new PreparedStatementBuilder(joinControlSql);
1060 PreparedStatementSimpleBuilder queryBuilder = new PreparedStatementSimpleBuilder(querySql, params);
1061 List<PreparedStatementBuilder> builders = new ArrayList<>();
1062 builders.add(joinControlBuilder);
1063 builders.add(queryBuilder);
1064 String dataSourceName = JDBCTools.NUXEO_DATASOURCE_NAME;
1065 String repositoryName = ctx.getRepositoryName();
1066 final Boolean EXECUTE_WITHIN_TRANSACTION = true;
1067 Set<String> docIds = new HashSet<>();
1069 List<CachedRowSet> resultsList = JDBCTools.executePreparedQueries(builders,
1070 dataSourceName, repositoryName, EXECUTE_WITHIN_TRANSACTION);
1072 // One set of results are expected, from the second prepared statement executed.
1073 // If fewer results are returned, return an empty list of document models
1074 if (resultsList == null || resultsList.size() < 1) {
1077 // Join control query will not return results, so query results will
1078 // be the first set of results (rowSet) returned in the list
1079 CachedRowSet queryResults = resultsList.get(0);
1081 // If the result from executing the query is null or contains zero rows,
1082 // return an empty list of document models
1083 if (queryResults == null) {
1086 queryResults.last();
1087 if (queryResults.getRow() == 0) {
1088 return result; // empty list of document models
1091 // Otherwise, get the document IDs from the results of the query
1093 queryResults.beforeFirst();
1094 while (queryResults.next()) {
1095 id = queryResults.getString(1);
1096 if (Tools.notBlank(id)) {
1100 } catch (SQLException sqle) {
1101 logger.warn("Could not obtain document IDs via SQL query '" + querySql + "': " + sqle.getMessage());
1102 return result; // return an empty list of document models
1105 // Get a list of document models, using the IDs obtained from the query
1106 DocumentModel docModel;
1107 for (String docId : docIds) {
1108 docModel = NuxeoUtils.getDocumentModel(repoSession, docId);
1109 if (docModel == null) {
1110 logger.warn("Could not obtain document model for document with ID " + docId);
1112 result.add(NuxeoUtils.getDocumentModel(repoSession, docId));
1116 // Order the results
1117 final String COMMON_PART_SCHEMA = handler.getServiceContext().getCommonPartLabel();
1118 final String DISPLAY_NAME_XPATH =
1119 "//" + handler.getJDBCQueryParams().get(TERM_GROUP_LIST_NAME) + "/[0]/termDisplayName";
1120 Collections.sort(result, new Comparator<DocumentModel>() {
1122 public int compare(DocumentModel doc1, DocumentModel doc2) {
1123 String termDisplayName1 = (String) NuxeoUtils.getXPathValue(doc1, COMMON_PART_SCHEMA, DISPLAY_NAME_XPATH);
1124 String termDisplayName2 = (String) NuxeoUtils.getXPathValue(doc2, COMMON_PART_SCHEMA, DISPLAY_NAME_XPATH);
1125 return termDisplayName1.compareTo(termDisplayName2);
1133 private DocumentModelList getFilteredCMIS(RepositoryInstance repoSession, ServiceContext ctx, DocumentHandler handler, QueryContext queryContext)
1134 throws DocumentNotFoundException, DocumentException {
1136 DocumentModelList result = new DocumentModelListImpl();
1138 String query = handler.getCMISQuery(queryContext);
1140 DocumentFilter docFilter = handler.getDocumentFilter();
1141 int pageSize = docFilter.getPageSize();
1142 int offset = docFilter.getOffset();
1143 if (logger.isDebugEnabled()) {
1144 logger.debug("Executing CMIS query: " + query.toString()
1145 + "with pageSize: " + pageSize + " at offset: " + offset);
1148 // If we have limit and/or offset, then pass true to get totalSize
1149 // in returned DocumentModelList.
1150 Profiler profiler = new Profiler(this, 2);
1151 profiler.log("Executing CMIS query: " + query.toString());
1154 IterableQueryResult queryResult = makeCMISQLQuery(repoSession, query, queryContext);
1156 int totalSize = (int) queryResult.size();
1157 ((DocumentModelListImpl) result).setTotalSize(totalSize);
1158 // Skip the rows before our offset
1160 queryResult.skipTo(offset);
1163 for (Map<String, Serializable> row : queryResult) {
1164 if (logger.isTraceEnabled()) {
1165 logger.trace(" Hierarchy Table ID is:" + row.get(IQueryManager.CMIS_TARGET_NUXEO_ID)
1166 + " nuxeo:pathSegment is: " + row.get(IQueryManager.CMIS_TARGET_NAME));
1168 String nuxeoId = (String) row.get(IQueryManager.CMIS_TARGET_NUXEO_ID);
1169 DocumentModel docModel = NuxeoUtils.getDocumentModel(repoSession, nuxeoId);
1170 result.add(docModel);
1172 if (nRows >= pageSize && pageSize != 0) { // A page size of zero means that they want all of them
1173 logger.debug("Got page full of items - quitting");
1178 queryResult.close();
1183 } catch (Exception e) {
1184 if (logger.isDebugEnabled()) {
1185 logger.debug("Caught exception ", e);
1187 throw new DocumentException(e);
1191 // Since we're not supporting paging yet for CMIS queries, we need to perform
1192 // a workaround for the paging information we return in our list of results
1195 if (result != null) {
1196 docFilter.setStartPage(0);
1197 if (totalSize > docFilter.getPageSize()) {
1198 docFilter.setPageSize(totalSize);
1199 ((DocumentModelListImpl)result).setTotalSize(totalSize);
1207 private String logException(Exception e, String msg) {
1208 String result = null;
1210 String exceptionMessage = e.getMessage();
1211 exceptionMessage = exceptionMessage != null ? exceptionMessage : "<No details provided>";
1212 result = msg = msg + ". Caught exception:" + exceptionMessage;
1214 if (logger.isTraceEnabled() == true) {
1215 logger.error(msg, e);
1224 * update given document in the Nuxeo repository
1226 * @param ctx service context under which this method is invoked
1227 * @param csid of the document
1228 * @param handler should be used by the caller to provide and transform the
1230 * @throws BadRequestException
1231 * @throws DocumentNotFoundException
1232 * @throws TransactionException if the transaction times out or otherwise
1233 * cannot be successfully completed
1234 * @throws DocumentException
1237 public void update(ServiceContext ctx, String csid, DocumentHandler handler)
1238 throws BadRequestException, DocumentNotFoundException, TransactionException,
1240 if (handler == null) {
1241 throw new IllegalArgumentException(
1242 "RepositoryJavaClient.update: document handler is missing.");
1245 RepositoryInstance repoSession = null;
1247 handler.prepare(Action.UPDATE);
1248 repoSession = getRepositorySession(ctx);
1249 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
1250 DocumentModel doc = null;
1252 doc = repoSession.getDocument(docRef);
1253 } catch (ClientException ce) {
1254 String msg = logException(ce, "Could not find document to update with CSID=" + csid);
1255 throw new DocumentNotFoundException(msg, ce);
1257 // Check for a versioned document, and check In and Out before we proceed.
1258 if (((DocumentModelHandler) handler).supportsVersioning()) {
1259 /* Once we advance to 5.5 or later, we can add this.
1260 * See also https://jira.nuxeo.com/browse/NXP-8506
1261 if(!doc.isVersionable()) {
1262 throw new DocumentException("Configuration for: "
1263 +handler.getServiceContextPath()+" supports versioning, but Nuxeo config does not!");
1266 /* Force a version number - Not working. Apparently we need to configure the uid schema??
1267 if(doc.getProperty("uid","major_version") == null) {
1268 doc.setProperty("uid","major_version",1);
1270 if(doc.getProperty("uid","minor_version") == null) {
1271 doc.setProperty("uid","minor_version",0);
1274 doc.checkIn(VersioningOption.MINOR, null);
1279 // Set reposession to handle the document
1281 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1282 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
1283 handler.handle(Action.UPDATE, wrapDoc);
1284 repoSession.saveDocument(doc);
1286 handler.complete(Action.UPDATE, wrapDoc);
1287 } catch (BadRequestException bre) {
1289 } catch (DocumentException de) {
1291 } catch (WebApplicationException wae) {
1293 } catch (Exception e) {
1294 if (logger.isDebugEnabled()) {
1295 logger.debug("Caught exception ", e);
1297 throw new DocumentException(e);
1299 if (repoSession != null) {
1300 releaseRepositorySession(ctx, repoSession);
1306 * Save a documentModel to the Nuxeo repository.
1308 * @param ctx service context under which this method is invoked
1309 * @param repoSession
1310 * @param docModel the document to save
1311 * @param fSaveSession if TRUE, will call CoreSession.save() to save
1312 * accumulated changes.
1313 * @throws ClientException
1314 * @throws DocumentException
1316 public void saveDocWithoutHandlerProcessing(
1317 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1318 RepositoryInstance repoSession,
1319 DocumentModel docModel,
1320 boolean fSaveSession)
1321 throws ClientException, DocumentException {
1324 repoSession.saveDocument(docModel);
1328 } catch (ClientException ce) {
1330 } catch (Exception e) {
1331 if (logger.isDebugEnabled()) {
1332 logger.debug("Caught exception ", e);
1334 throw new DocumentException(e);
1339 * Save a list of documentModels to the Nuxeo repository.
1341 * @param ctx service context under which this method is invoked
1342 * @param repoSession a repository session
1343 * @param docModelList a list of document models
1344 * @param fSaveSession if TRUE, will call CoreSession.save() to save
1345 * accumulated changes.
1346 * @throws ClientException
1347 * @throws DocumentException
1349 public void saveDocListWithoutHandlerProcessing(
1350 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1351 RepositoryInstance repoSession,
1352 DocumentModelList docList,
1353 boolean fSaveSession)
1354 throws ClientException, DocumentException {
1356 DocumentModel[] docModelArray = new DocumentModel[docList.size()];
1357 repoSession.saveDocuments(docList.toArray(docModelArray));
1361 } catch (ClientException ce) {
1363 } catch (Exception e) {
1364 logger.error("Caught exception ", e);
1365 throw new DocumentException(e);
1370 * delete a document from the Nuxeo repository
1372 * @param ctx service context under which this method is invoked
1373 * @param id of the document
1374 * @throws DocumentException
1377 public void delete(ServiceContext ctx, String id, DocumentHandler handler) throws DocumentNotFoundException,
1378 DocumentException, TransactionException {
1380 throw new IllegalArgumentException(
1381 "delete(ctx, ix, handler): ctx is missing");
1383 if (handler == null) {
1384 throw new IllegalArgumentException(
1385 "delete(ctx, ix, handler): handler is missing");
1387 if (logger.isDebugEnabled()) {
1388 logger.debug("Deleting document with CSID=" + id);
1390 RepositoryInstance repoSession = null;
1392 handler.prepare(Action.DELETE);
1393 repoSession = getRepositorySession(ctx);
1394 DocumentWrapper<DocumentModel> wrapDoc = null;
1396 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
1397 wrapDoc = new DocumentWrapperImpl<DocumentModel>(repoSession.getDocument(docRef));
1398 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1399 handler.handle(Action.DELETE, wrapDoc);
1400 repoSession.removeDocument(docRef);
1401 } catch (ClientException ce) {
1402 String msg = logException(ce, "Could not find document to delete with CSID=" + id);
1403 throw new DocumentNotFoundException(msg, ce);
1406 handler.complete(Action.DELETE, wrapDoc);
1407 } catch (DocumentException de) {
1409 } catch (Exception e) {
1410 if (logger.isDebugEnabled()) {
1411 logger.debug("Caught exception ", e);
1413 throw new DocumentException(e);
1415 if (repoSession != null) {
1416 releaseRepositorySession(ctx, repoSession);
1422 * @see org.collectionspace.services.common.storage.StorageClient#delete(org.collectionspace.services.common.context.ServiceContext, java.lang.String, org.collectionspace.services.common.document.DocumentHandler)
1426 public void delete(@SuppressWarnings("rawtypes") ServiceContext ctx, String id)
1427 throws DocumentNotFoundException, DocumentException {
1428 throw new UnsupportedOperationException();
1429 // Use the other delete instead
1433 public Hashtable<String, String> retrieveWorkspaceIds(RepositoryDomainType repoDomain) throws Exception {
1434 return NuxeoConnectorEmbedded.getInstance().retrieveWorkspaceIds(repoDomain);
1438 public String createDomain(RepositoryDomainType repositoryDomain) throws Exception {
1439 RepositoryInstance repoSession = null;
1440 String domainId = null;
1443 // Open a connection to the domain's repo/db
1445 String repoName = repositoryDomain.getRepositoryName();
1446 repoSession = getRepositorySession(repoName); // domainName=storageName=repoName=databaseName
1448 // First create the top-level domain directory
1450 String domainName = repositoryDomain.getStorageName();
1451 DocumentRef parentDocRef = new PathRef("/");
1452 DocumentModel parentDoc = repoSession.getDocument(parentDocRef);
1453 DocumentModel domainDoc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1454 domainName, NUXEO_CORE_TYPE_DOMAIN);
1455 domainDoc.setPropertyValue("dc:title", domainName);
1456 domainDoc.setPropertyValue("dc:description", "A CollectionSpace domain "
1458 domainDoc = repoSession.createDocument(domainDoc);
1459 domainId = domainDoc.getId();
1462 // Next, create a "Workspaces" root directory to contain the workspace folders for the individual service documents
1464 DocumentModel workspacesRoot = repoSession.createDocumentModel(domainDoc.getPathAsString(),
1465 NuxeoUtils.Workspaces, NUXEO_CORE_TYPE_WORKSPACEROOT);
1466 workspacesRoot.setPropertyValue("dc:title", NuxeoUtils.Workspaces);
1467 workspacesRoot.setPropertyValue("dc:description", "A CollectionSpace workspaces directory for "
1468 + domainDoc.getPathAsString());
1469 workspacesRoot = repoSession.createDocument(workspacesRoot);
1470 String workspacesRootId = workspacesRoot.getId();
1473 if (logger.isDebugEnabled()) {
1474 logger.debug("Created tenant domain name=" + domainName
1475 + " id=" + domainId + " "
1476 + NuxeoUtils.Workspaces + " id=" + workspacesRootId);
1477 logger.debug("Path to Domain: " + domainDoc.getPathAsString());
1478 logger.debug("Path to Workspaces root: " + workspacesRoot.getPathAsString());
1480 } catch (Exception e) {
1481 if (logger.isDebugEnabled()) {
1482 logger.debug("Could not create tenant domain name=" + repositoryDomain.getStorageName() + " caught exception ", e);
1486 if (repoSession != null) {
1487 releaseRepositorySession(null, repoSession);
1495 public String getDomainId(RepositoryDomainType repositoryDomain) throws Exception {
1496 String domainId = null;
1497 RepositoryInstance repoSession = null;
1499 String repoName = repositoryDomain.getRepositoryName();
1500 String domainStorageName = repositoryDomain.getStorageName();
1501 if (domainStorageName != null && !domainStorageName.isEmpty()) {
1503 repoSession = getRepositorySession(repoName);
1504 DocumentRef docRef = new PathRef("/" + domainStorageName);
1505 DocumentModel domain = repoSession.getDocument(docRef);
1506 domainId = domain.getId();
1507 } catch (Exception e) {
1508 if (logger.isTraceEnabled()) {
1509 logger.trace("Caught exception ", e); // The document doesn't exist, this let's us know we need to create it
1511 //there is no way to identify if document does not exist due to
1512 //lack of typed exception for getDocument method
1515 if (repoSession != null) {
1516 releaseRepositorySession(null, repoSession);
1525 * Returns the workspaces root directory for a given domain.
1527 private DocumentModel getWorkspacesRoot(RepositoryInstance repoSession,
1528 String domainName) throws Exception {
1529 DocumentModel result = null;
1531 String domainPath = "/" + domainName;
1532 DocumentRef parentDocRef = new PathRef(domainPath);
1533 DocumentModelList domainChildrenList = repoSession.getChildren(
1535 Iterator<DocumentModel> witer = domainChildrenList.iterator();
1536 while (witer.hasNext()) {
1537 DocumentModel childNode = witer.next();
1538 if (NuxeoUtils.Workspaces.equalsIgnoreCase(childNode.getName())) {
1540 logger.trace("Found workspaces directory at: " + result.getPathAsString());
1545 if (result == null) {
1546 throw new ClientException("Could not find workspace root directory in: "
1554 * @see org.collectionspace.services.common.repository.RepositoryClient#createWorkspace(java.lang.String, java.lang.String)
1557 public String createWorkspace(RepositoryDomainType repositoryDomain, String workspaceName) throws Exception {
1558 RepositoryInstance repoSession = null;
1559 String workspaceId = null;
1561 String repoName = repositoryDomain.getRepositoryName();
1562 repoSession = getRepositorySession(repoName);
1564 String domainStorageName = repositoryDomain.getStorageName();
1565 DocumentModel parentDoc = getWorkspacesRoot(repoSession, domainStorageName);
1566 if (logger.isTraceEnabled()) {
1567 for (String facet : parentDoc.getFacets()) {
1568 logger.trace("Facet: " + facet);
1572 DocumentModel doc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1573 workspaceName, NuxeoUtils.WORKSPACE_DOCUMENT_TYPE);
1574 doc.setPropertyValue("dc:title", workspaceName);
1575 doc.setPropertyValue("dc:description", "A CollectionSpace workspace for "
1577 doc = repoSession.createDocument(doc);
1578 workspaceId = doc.getId();
1580 if (logger.isDebugEnabled()) {
1581 logger.debug("Created workspace name=" + workspaceName
1582 + " id=" + workspaceId);
1584 } catch (Exception e) {
1585 if (logger.isDebugEnabled()) {
1586 logger.debug("createWorkspace caught exception ", e);
1590 if (repoSession != null) {
1591 releaseRepositorySession(null, repoSession);
1598 * @see org.collectionspace.services.common.repository.RepositoryClient#getWorkspaceId(java.lang.String, java.lang.String)
1602 public String getWorkspaceId(String tenantDomain, String workspaceName) throws Exception {
1603 String workspaceId = null;
1605 RepositoryInstance repoSession = null;
1607 repoSession = getRepositorySession((ServiceContext) null);
1608 DocumentRef docRef = new PathRef(
1610 + "/" + NuxeoUtils.Workspaces
1611 + "/" + workspaceName);
1612 DocumentModel workspace = repoSession.getDocument(docRef);
1613 workspaceId = workspace.getId();
1614 } catch (DocumentException de) {
1616 } catch (Exception e) {
1617 if (logger.isDebugEnabled()) {
1618 logger.debug("Caught exception ", e);
1620 throw new DocumentException(e);
1622 if (repoSession != null) {
1623 releaseRepositorySession(null, repoSession);
1630 public RepositoryInstance getRepositorySession(ServiceContext ctx) throws Exception {
1631 return getRepositorySession(ctx, ctx.getRepositoryName());
1634 public RepositoryInstance getRepositorySession(String repoName) throws Exception {
1635 return getRepositorySession(null, repoName);
1639 * Gets the repository session. - Package access only. If the 'ctx' param is
1640 * null then the repo name must be non-mull and vice-versa
1642 * @return the repository session
1643 * @throws Exception the exception
1645 public RepositoryInstance getRepositorySession(ServiceContext ctx, String repoName) throws Exception {
1646 RepositoryInstance repoSession = null;
1648 Profiler profiler = new Profiler("getRepositorySession():", 2);
1651 // To get a connection to the Nuxeo repo, we need either a valid ServiceContext instance or a repository name
1654 repoName = ctx.getRepositoryName(); // Notice we are overriding the passed in 'repoName' since we have a valid service context passed in to us
1655 repoSession = (RepositoryInstance) ctx.getCurrentRepositorySession(); // Look to see if one exists in the context before creating one
1656 } else if (repoName == null || repoName.trim().isEmpty()) {
1657 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.");
1658 logger.error(errMsg);
1659 throw new Exception(errMsg);
1662 // 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
1663 // just the repo name
1665 if (repoSession == null) {
1666 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1667 repoSession = client.openRepository(repoName);
1669 if (logger.isDebugEnabled() == true) {
1670 logger.warn("Reusing the current context's repository session.");
1674 if (logger.isTraceEnabled()) {
1675 logger.trace("Testing call to getRepository() repository root: " + repoSession.getRootDocument());
1681 ctx.setCurrentRepositorySession(repoSession); // For reusing, save the repository session in the current service context
1688 * Release repository session. - Package access only.
1690 * @param repoSession the repo session
1692 public void releaseRepositorySession(ServiceContext ctx, RepositoryInstance repoSession) throws TransactionException {
1694 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1697 ctx.clearCurrentRepositorySession(); //clear the current context of the now closed repo session
1698 if (ctx.getCurrentRepositorySession() == null) {
1699 client.releaseRepository(repoSession); //release the repo session if the service context's ref count is zeo.
1702 client.releaseRepository(repoSession); //repo session was acquired without a service context
1704 } catch (TransactionRuntimeException tre) {
1705 TransactionException te = new TransactionException(tre);
1706 logger.error(te.getMessage(), tre); // Log the standard transaction exception message, plus an exception-specific stack trace
1708 } catch (Exception e) {
1709 logger.error("Could not close the repository session", e);
1710 // no need to throw this service specific exception
1715 public void doWorkflowTransition(ServiceContext ctx, String id,
1716 DocumentHandler handler, TransitionDef transitionDef)
1717 throws BadRequestException, DocumentNotFoundException,
1719 // 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
1722 private String handleProvidedStartingWildcard(String partialTerm) {
1723 if (Tools.notBlank(partialTerm)) {
1724 // FIXME: Get this value from an existing constant, if available
1725 final String USER_SUPPLIED_WILDCARD = "*";
1726 if (partialTerm.substring(0, 1).equals(USER_SUPPLIED_WILDCARD)) {
1727 StringBuffer buffer = new StringBuffer(partialTerm);
1728 buffer.setCharAt(0, JDBCTools.SQL_WILDCARD.charAt(0));
1729 partialTerm = buffer.toString();
1735 private int getMaxItemsLimitOnJdbcQueries(String maxListItemsLimit) {
1736 final int DEFAULT_ITEMS_LIMIT = 40;
1739 itemsLimit = Integer.parseInt(maxListItemsLimit);
1740 if (itemsLimit < 1) {
1741 logger.warn("Value of configuration setting "
1742 + IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES
1743 + " must be a positive integer; current value is " + maxListItemsLimit);
1744 itemsLimit = DEFAULT_ITEMS_LIMIT;
1746 } catch (NumberFormatException nfe) {
1747 logger.warn("Value of configuration setting "
1748 + IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES
1749 + " must be a positive integer; current value is " + maxListItemsLimit);
1750 itemsLimit = DEFAULT_ITEMS_LIMIT;
1756 * Identifies whether a restriction on tenant ID - to return only records
1757 * pertaining to the current tenant - is required in a JDBC query.
1759 * @param tenantBinding a tenant binding configuration.
1760 * @param ctx a service context.
1761 * @return true if a restriction on tenant ID is required in the query;
1762 * false if a restriction is not required.
1764 private boolean restrictJDBCQueryByTenantID(TenantBindingType tenantBinding, ServiceContext ctx) {
1765 boolean restrict = true;
1766 // If data for the current service, in the current tenant, is isolated
1767 // within its own separate, per-tenant repository, as contrasted with
1768 // being intermingled with other tenants' data in the default repository,
1769 // no restriction on Tenant ID is required in the query.
1770 String repositoryDomainName = ConfigUtils.getRepositoryName(tenantBinding, ctx.getRepositoryDomainName());
1771 if (!(repositoryDomainName.equals(ConfigUtils.DEFAULT_NUXEO_REPOSITORY_NAME))) {
1774 // If a configuration setting for this tenant identifies that JDBC
1775 // queries should not be restricted by tenant ID (perhaps because
1776 // there is always expected to be only one tenant's data present in
1777 // the system), no restriction on Tenant ID is required in the query.
1778 String queriesRestrictedByTenantId = TenantBindingUtils.getPropertyValue(tenantBinding,
1779 IQueryManager.JDBC_QUERIES_ARE_TENANT_ID_RESTRICTED);
1780 if (Tools.notBlank(queriesRestrictedByTenantId) &&
1781 queriesRestrictedByTenantId.equalsIgnoreCase(Boolean.FALSE.toString())) {