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.Hashtable;
27 import java.util.Iterator;
28 import java.util.List;
30 import java.util.UUID;
31 import javax.sql.rowset.CachedRowSet;
33 import javax.ws.rs.WebApplicationException;
34 import javax.ws.rs.core.MultivaluedMap;
36 import org.collectionspace.services.client.CollectionSpaceClient;
37 import org.collectionspace.services.client.IQueryManager;
38 import org.collectionspace.services.client.PoxPayloadIn;
39 import org.collectionspace.services.client.PoxPayloadOut;
40 import org.collectionspace.services.client.Profiler;
41 import org.collectionspace.services.client.workflow.WorkflowClient;
42 import org.collectionspace.services.common.context.ServiceContext;
43 import org.collectionspace.services.common.query.QueryContext;
44 import org.collectionspace.services.common.repository.RepositoryClient;
45 import org.collectionspace.services.common.storage.JDBCTools;
46 import org.collectionspace.services.common.storage.PreparedStatementSimpleBuilder;
47 import org.collectionspace.services.lifecycle.TransitionDef;
48 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
50 import org.collectionspace.services.common.document.BadRequestException;
51 import org.collectionspace.services.common.document.DocumentException;
52 import org.collectionspace.services.common.document.DocumentFilter;
53 import org.collectionspace.services.common.document.DocumentHandler;
54 import org.collectionspace.services.common.document.DocumentNotFoundException;
55 import org.collectionspace.services.common.document.DocumentHandler.Action;
56 import org.collectionspace.services.common.document.DocumentWrapper;
57 import org.collectionspace.services.common.document.DocumentWrapperImpl;
58 import org.collectionspace.services.common.document.TransactionException;
59 import org.collectionspace.services.config.tenant.RepositoryDomainType;
61 import org.nuxeo.common.utils.IdUtils;
62 import org.nuxeo.ecm.core.api.ClientException;
63 import org.nuxeo.ecm.core.api.DocumentModel;
64 import org.nuxeo.ecm.core.api.DocumentModelList;
65 import org.nuxeo.ecm.core.api.IterableQueryResult;
66 import org.nuxeo.ecm.core.api.VersioningOption;
67 import org.nuxeo.ecm.core.api.impl.DocumentModelListImpl;
68 import org.nuxeo.ecm.core.api.DocumentRef;
69 import org.nuxeo.ecm.core.api.IdRef;
70 import org.nuxeo.ecm.core.api.PathRef;
71 import org.nuxeo.ecm.core.api.repository.RepositoryInstance;
72 import org.nuxeo.runtime.transaction.TransactionRuntimeException;
75 // CSPACE-5036 - How to make CMISQL queries from Nuxeo
77 import org.apache.chemistry.opencmis.commons.server.CallContext;
78 import org.apache.chemistry.opencmis.server.impl.CallContextImpl;
79 import org.collectionspace.services.common.api.Tools;
80 import org.nuxeo.ecm.core.opencmis.impl.server.NuxeoCmisService;
81 import org.nuxeo.ecm.core.opencmis.impl.server.NuxeoRepository;
83 import org.slf4j.Logger;
84 import org.slf4j.LoggerFactory;
87 * RepositoryJavaClient is used to perform CRUD operations on documents in Nuxeo
88 * repository using Remote Java APIs. It uses
90 * @see DocumentHandler as IOHandler with the client.
92 * $LastChangedRevision: $ $LastChangedDate: $
94 public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn, PoxPayloadOut> {
99 private final Logger logger = LoggerFactory.getLogger(RepositoryJavaClientImpl.class);
100 // private final Logger profilerLogger = LoggerFactory.getLogger("remperf");
101 // private String foo = Profiler.createLogger();
102 public static final String NUXEO_CORE_TYPE_DOMAIN = "Domain";
103 public static final String NUXEO_CORE_TYPE_WORKSPACEROOT = "WorkspaceRoot";
106 * Instantiates a new repository java client impl.
108 public RepositoryJavaClientImpl() {
112 public void assertWorkflowState(ServiceContext ctx,
113 DocumentModel docModel) throws DocumentNotFoundException, ClientException {
114 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
115 if (queryParams != null) {
117 // Look for the workflow "delete" query param and see if we need to assert that the
118 // docModel is in a non-deleted workflow state.
120 String currentState = docModel.getCurrentLifeCycleState();
121 String includeDeletedStr = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_NONDELETED);
122 boolean includeDeleted = includeDeletedStr == null ? true : Boolean.parseBoolean(includeDeletedStr);
123 if (includeDeleted == false) {
125 // We don't wanted soft-deleted object, so throw an exception if this one is soft-deleted.
127 if (currentState.equalsIgnoreCase(WorkflowClient.WORKFLOWSTATE_DELETED)) {
128 String msg = "The GET assertion that docModel not be in 'deleted' workflow state failed.";
130 throw new DocumentNotFoundException(msg);
137 * create document in the Nuxeo repository
139 * @param ctx service context under which this method is invoked
140 * @param handler should be used by the caller to provide and transform the
142 * @return id in repository of the newly created document
143 * @throws BadRequestException
144 * @throws TransactionException
145 * @throws DocumentException
148 public String create(ServiceContext ctx,
149 DocumentHandler handler) throws BadRequestException,
150 TransactionException, DocumentException {
152 String docType = NuxeoUtils.getTenantQualifiedDocType(ctx); //ctx.getDocumentType();
153 if (docType == null) {
154 throw new IllegalArgumentException(
155 "RepositoryJavaClient.create: docType is missing");
158 if (handler == null) {
159 throw new IllegalArgumentException(
160 "RepositoryJavaClient.create: handler is missing");
162 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
163 if (nuxeoWspaceId == null) {
164 throw new DocumentNotFoundException(
165 "Unable to find workspace for service " + ctx.getServiceName()
166 + " check if the workspace exists in the Nuxeo repository");
169 RepositoryInstance repoSession = null;
171 handler.prepare(Action.CREATE);
172 repoSession = getRepositorySession(ctx);
173 DocumentRef nuxeoWspace = new IdRef(nuxeoWspaceId);
174 DocumentModel wspaceDoc = repoSession.getDocument(nuxeoWspace);
175 String wspacePath = wspaceDoc.getPathAsString();
176 //give our own ID so PathRef could be constructed later on
177 String id = IdUtils.generateId(UUID.randomUUID().toString());
178 // create document model
179 DocumentModel doc = repoSession.createDocumentModel(wspacePath, id, docType);
180 /* Check for a versioned document, and check In and Out before we proceed.
181 * This does not work as we do not have the uid schema on our docs.
182 if(((DocumentModelHandler) handler).supportsVersioning()) {
183 doc.setProperty("uid","major_version",1);
184 doc.setProperty("uid","minor_version",0);
187 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
188 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
189 handler.handle(Action.CREATE, wrapDoc);
190 // create document with documentmodel
191 doc = repoSession.createDocument(doc);
193 // TODO for sub-docs need to call into the handler to let it deal with subitems. Pass in the id,
194 // and assume the handler has the state it needs (doc fragments).
195 handler.complete(Action.CREATE, wrapDoc);
197 } catch (BadRequestException bre) {
199 } catch (Exception e) {
200 logger.error("Caught exception ", e);
201 throw new DocumentException(e);
203 if (repoSession != null) {
204 releaseRepositorySession(ctx, repoSession);
211 * get document from the Nuxeo repository
213 * @param ctx service context under which this method is invoked
214 * @param id of the document to retrieve
215 * @param handler should be used by the caller to provide and transform the
217 * @throws DocumentNotFoundException if the document cannot be found in the
219 * @throws TransactionException
220 * @throws DocumentException
223 public void get(ServiceContext ctx, String id, DocumentHandler handler)
224 throws DocumentNotFoundException, TransactionException, DocumentException {
226 if (handler == null) {
227 throw new IllegalArgumentException(
228 "RepositoryJavaClient.get: handler is missing");
231 RepositoryInstance repoSession = null;
233 handler.prepare(Action.GET);
234 repoSession = getRepositorySession(ctx);
235 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
236 DocumentModel docModel = null;
238 docModel = repoSession.getDocument(docRef);
239 assertWorkflowState(ctx, docModel);
240 } catch (ClientException ce) {
241 String msg = logException(ce, "Could not find document with CSID=" + id);
242 throw new DocumentNotFoundException(msg, ce);
245 // Set repository session to handle the document
247 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
248 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(docModel);
249 handler.handle(Action.GET, wrapDoc);
250 handler.complete(Action.GET, wrapDoc);
251 } catch (IllegalArgumentException iae) {
253 } catch (DocumentException de) {
255 } catch (Exception e) {
256 if (logger.isDebugEnabled()) {
257 logger.debug("Caught exception ", e);
259 throw new DocumentException(e);
261 if (repoSession != null) {
262 releaseRepositorySession(ctx, repoSession);
268 * get a document from the Nuxeo repository, using the docFilter params.
270 * @param ctx service context under which this method is invoked
271 * @param handler should be used by the caller to provide and transform the
272 * document. Handler must have a docFilter set to return a single item.
273 * @throws DocumentNotFoundException if the document cannot be found in the
275 * @throws TransactionException
276 * @throws DocumentException
279 public void get(ServiceContext ctx, DocumentHandler handler)
280 throws DocumentNotFoundException, TransactionException, DocumentException {
281 QueryContext queryContext = new QueryContext(ctx, handler);
282 RepositoryInstance repoSession = null;
285 handler.prepare(Action.GET);
286 repoSession = getRepositorySession(ctx);
288 DocumentModelList docList = null;
289 // force limit to 1, and ignore totalSize
290 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
291 docList = repoSession.query(query, null, 1, 0, false);
292 if (docList.size() != 1) {
293 throw new DocumentNotFoundException("No document found matching filter params: " + query);
295 DocumentModel doc = docList.get(0);
297 if (logger.isDebugEnabled()) {
298 logger.debug("Executed NXQL query: " + query);
301 //set reposession to handle the document
302 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
303 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
304 handler.handle(Action.GET, wrapDoc);
305 handler.complete(Action.GET, wrapDoc);
306 } catch (IllegalArgumentException iae) {
308 } catch (DocumentException de) {
310 } catch (Exception e) {
311 if (logger.isDebugEnabled()) {
312 logger.debug("Caught exception ", e);
314 throw new DocumentException(e);
316 if (repoSession != null) {
317 releaseRepositorySession(ctx, repoSession);
322 public DocumentWrapper<DocumentModel> getDoc(
323 RepositoryInstance repoSession,
324 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
325 String csid) throws DocumentNotFoundException, DocumentException {
326 DocumentWrapper<DocumentModel> wrapDoc = null;
329 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
330 DocumentModel doc = null;
332 doc = repoSession.getDocument(docRef);
333 } catch (ClientException ce) {
334 String msg = logException(ce, "Could not find document with CSID=" + csid);
335 throw new DocumentNotFoundException(msg, ce);
337 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
338 } catch (IllegalArgumentException iae) {
340 } catch (DocumentException de) {
348 * Get wrapped documentModel from the Nuxeo repository. The search is
349 * restricted to the workspace of the current context.
351 * @param ctx service context under which this method is invoked
352 * @param csid of the document to retrieve
353 * @throws DocumentNotFoundException
354 * @throws TransactionException
355 * @throws DocumentException
356 * @return a wrapped documentModel
359 public DocumentWrapper<DocumentModel> getDoc(
360 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
361 String csid) throws DocumentNotFoundException, TransactionException, DocumentException {
362 RepositoryInstance repoSession = null;
363 DocumentWrapper<DocumentModel> wrapDoc = null;
366 // Open a new repository session
367 repoSession = getRepositorySession(ctx);
368 wrapDoc = getDoc(repoSession, ctx, csid);
369 } catch (IllegalArgumentException iae) {
371 } catch (DocumentException de) {
373 } catch (Exception e) {
374 if (logger.isDebugEnabled()) {
375 logger.debug("Caught exception ", e);
377 throw new DocumentException(e);
379 if (repoSession != null) {
380 releaseRepositorySession(ctx, repoSession);
384 if (logger.isWarnEnabled() == true) {
385 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
390 public DocumentWrapper<DocumentModel> findDoc(
391 RepositoryInstance repoSession,
392 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
394 throws DocumentNotFoundException, DocumentException {
395 DocumentWrapper<DocumentModel> wrapDoc = null;
398 QueryContext queryContext = new QueryContext(ctx, whereClause);
399 DocumentModelList docList = null;
400 // force limit to 1, and ignore totalSize
401 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
402 docList = repoSession.query(query,
407 if (docList.size() != 1) {
408 if (logger.isDebugEnabled()) {
409 logger.debug("findDoc: Query found: " + docList.size() + " items.");
410 logger.debug(" Query: " + query);
412 throw new DocumentNotFoundException("No document found matching filter params: " + query);
414 DocumentModel doc = docList.get(0);
415 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
416 } catch (IllegalArgumentException iae) {
418 } catch (DocumentException de) {
420 } catch (Exception e) {
421 if (logger.isDebugEnabled()) {
422 logger.debug("Caught exception ", e);
424 throw new DocumentException(e);
431 * find wrapped documentModel from the Nuxeo repository
433 * @param ctx service context under which this method is invoked
434 * @param whereClause where NXQL where clause to get the document
435 * @throws DocumentNotFoundException
436 * @throws TransactionException
437 * @throws DocumentException
438 * @return a wrapped documentModel retrieved by the repository query
441 public DocumentWrapper<DocumentModel> findDoc(
442 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
444 throws DocumentNotFoundException, TransactionException, DocumentException {
445 RepositoryInstance repoSession = null;
446 DocumentWrapper<DocumentModel> wrapDoc = null;
449 repoSession = getRepositorySession(ctx);
450 wrapDoc = findDoc(repoSession, ctx, whereClause);
451 } catch (Exception e) {
452 throw new DocumentException("Unable to create a Nuxeo repository session.", e);
454 if (repoSession != null) {
455 releaseRepositorySession(ctx, repoSession);
459 if (logger.isWarnEnabled() == true) {
460 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
467 * find doc and return CSID from the Nuxeo repository
470 * @param ctx service context under which this method is invoked
471 * @param whereClause where NXQL where clause to get the document
472 * @throws DocumentNotFoundException
473 * @throws TransactionException
474 * @throws DocumentException
475 * @return the CollectionSpace ID (CSID) of the requested document
478 public String findDocCSID(RepositoryInstance repoSession,
479 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String whereClause)
480 throws DocumentNotFoundException, TransactionException, DocumentException {
482 boolean releaseSession = false;
484 if (repoSession == null) {
485 repoSession = this.getRepositorySession(ctx);
486 releaseSession = true;
488 DocumentWrapper<DocumentModel> wrapDoc = findDoc(repoSession, ctx, whereClause);
489 DocumentModel docModel = wrapDoc.getWrappedObject();
490 csid = NuxeoUtils.getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
491 } catch (DocumentNotFoundException dnfe) {
493 } catch (IllegalArgumentException iae) {
495 } catch (DocumentException de) {
497 } catch (Exception e) {
498 if (logger.isDebugEnabled()) {
499 logger.debug("Caught exception ", e);
501 throw new DocumentException(e);
503 if (releaseSession && (repoSession != null)) {
504 this.releaseRepositorySession(ctx, repoSession);
510 public DocumentWrapper<DocumentModelList> findDocs(
511 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
512 RepositoryInstance repoSession,
513 List<String> docTypes,
515 String orderByClause,
518 boolean computeTotal)
519 throws DocumentNotFoundException, DocumentException {
520 DocumentWrapper<DocumentModelList> wrapDoc = null;
523 if (docTypes == null || docTypes.size() < 1) {
524 throw new DocumentNotFoundException(
525 "The findDocs() method must specify at least one DocumentType.");
527 DocumentModelList docList = null;
528 QueryContext queryContext = new QueryContext(ctx, whereClause, orderByClause);
529 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
530 if (logger.isDebugEnabled()) {
531 logger.debug("findDocs() NXQL: " + query);
533 docList = repoSession.query(query, null, pageSize, pageSize * pageNum, computeTotal);
534 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
535 } catch (IllegalArgumentException iae) {
537 } catch (Exception e) {
538 if (logger.isDebugEnabled()) {
539 logger.debug("Caught exception ", e);
541 throw new DocumentException(e);
547 protected static String buildInListForDocTypes(List<String> docTypes) {
548 StringBuilder sb = new StringBuilder();
550 boolean first = true;
551 for (String docType : docTypes) {
562 return sb.toString();
565 public DocumentWrapper<DocumentModelList> findDocs(
566 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
567 DocumentHandler handler,
568 RepositoryInstance repoSession,
569 List<String> docTypes)
570 throws DocumentNotFoundException, DocumentException {
571 DocumentWrapper<DocumentModelList> wrapDoc = null;
573 DocumentFilter filter = handler.getDocumentFilter();
574 String oldOrderBy = filter.getOrderByClause();
575 if (isClauseEmpty(oldOrderBy) == true) {
576 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
578 QueryContext queryContext = new QueryContext(ctx, handler);
581 if (docTypes == null || docTypes.size() < 1) {
582 throw new DocumentNotFoundException(
583 "The findDocs() method must specify at least one DocumentType.");
585 DocumentModelList docList = null;
586 if (handler.isCMISQuery() == true) {
587 String inList = buildInListForDocTypes(docTypes);
588 ctx.getQueryParams().add(IQueryManager.SEARCH_RELATED_MATCH_OBJ_DOCTYPES, inList);
589 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
591 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
592 if (logger.isDebugEnabled()) {
593 logger.debug("findDocs() NXQL: " + query);
595 docList = repoSession.query(query, null, filter.getPageSize(), filter.getOffset(), true);
597 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
598 } catch (IllegalArgumentException iae) {
600 } catch (Exception e) {
601 if (logger.isDebugEnabled()) {
602 logger.debug("Caught exception ", e);
604 throw new DocumentException(e);
611 * Find a list of documentModels from the Nuxeo repository
613 * @param docTypes a list of DocType names to match
614 * @param whereClause where the clause to qualify on
615 * @throws DocumentNotFoundException
616 * @throws TransactionException
617 * @throws DocumentException
618 * @return a list of documentModels
621 public DocumentWrapper<DocumentModelList> findDocs(
622 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
623 List<String> docTypes,
625 int pageSize, int pageNum, boolean computeTotal)
626 throws DocumentNotFoundException, TransactionException, DocumentException {
627 RepositoryInstance repoSession = null;
628 DocumentWrapper<DocumentModelList> wrapDoc = null;
631 repoSession = getRepositorySession(ctx);
632 wrapDoc = findDocs(ctx, repoSession, docTypes, whereClause, null,
633 pageSize, pageNum, computeTotal);
634 } catch (IllegalArgumentException iae) {
636 } catch (Exception e) {
637 if (logger.isDebugEnabled()) {
638 logger.debug("Caught exception ", e);
640 throw new DocumentException(e);
642 if (repoSession != null) {
643 releaseRepositorySession(ctx, repoSession);
647 if (logger.isWarnEnabled() == true) {
648 logger.warn("Returned DocumentModelList instance was created with a repository session that is now closed.");
655 * @see org.collectionspace.services.common.storage.StorageClient#get(org.collectionspace.services.common.context.ServiceContext, java.util.List, org.collectionspace.services.common.document.DocumentHandler)
658 public void get(ServiceContext ctx, List<String> csidList, DocumentHandler handler)
659 throws DocumentNotFoundException, TransactionException, DocumentException {
660 if (handler == null) {
661 throw new IllegalArgumentException(
662 "RepositoryJavaClient.getAll: handler is missing");
665 RepositoryInstance repoSession = null;
667 handler.prepare(Action.GET_ALL);
668 repoSession = getRepositorySession(ctx);
669 DocumentModelList docModelList = new DocumentModelListImpl();
670 //FIXME: Should be using NuxeoUtils.createPathRef for security reasons
671 for (String csid : csidList) {
672 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
673 DocumentModel docModel = repoSession.getDocument(docRef);
674 docModelList.add(docModel);
677 //set reposession to handle the document
678 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
679 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docModelList);
680 handler.handle(Action.GET_ALL, wrapDoc);
681 handler.complete(Action.GET_ALL, wrapDoc);
682 } catch (DocumentException de) {
684 } catch (Exception e) {
685 if (logger.isDebugEnabled()) {
686 logger.debug("Caught exception ", e);
688 throw new DocumentException(e);
690 if (repoSession != null) {
691 releaseRepositorySession(ctx, repoSession);
697 * getAll get all documents for an entity entity service from the Nuxeo
700 * @param ctx service context under which this method is invoked
701 * @param handler should be used by the caller to provide and transform the
703 * @throws DocumentNotFoundException
704 * @throws TransactionException
705 * @throws DocumentException
708 public void getAll(ServiceContext ctx, DocumentHandler handler)
709 throws DocumentNotFoundException, TransactionException, DocumentException {
710 if (handler == null) {
711 throw new IllegalArgumentException(
712 "RepositoryJavaClient.getAll: handler is missing");
714 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
715 if (nuxeoWspaceId == null) {
716 throw new DocumentNotFoundException(
717 "Unable to find workspace for service "
718 + ctx.getServiceName()
719 + " check if the workspace exists in the Nuxeo repository.");
722 RepositoryInstance repoSession = null;
724 handler.prepare(Action.GET_ALL);
725 repoSession = getRepositorySession(ctx);
726 DocumentRef wsDocRef = new IdRef(nuxeoWspaceId);
727 DocumentModelList docList = repoSession.getChildren(wsDocRef);
728 //set reposession to handle the document
729 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
730 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
731 handler.handle(Action.GET_ALL, wrapDoc);
732 handler.complete(Action.GET_ALL, wrapDoc);
733 } catch (DocumentException de) {
735 } catch (Exception e) {
736 if (logger.isDebugEnabled()) {
737 logger.debug("Caught exception ", e);
739 throw new DocumentException(e);
741 if (repoSession != null) {
742 releaseRepositorySession(ctx, repoSession);
747 private boolean isClauseEmpty(String theString) {
748 boolean result = true;
749 if (theString != null && !theString.isEmpty()) {
755 public DocumentWrapper<DocumentModel> getDocFromCsid(
756 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
757 RepositoryInstance repoSession,
760 DocumentWrapper<DocumentModel> result = null;
762 result = new DocumentWrapperImpl(NuxeoUtils.getDocFromCsid(ctx, repoSession, csid));
768 * A method to find a CollectionSpace document (of any type) given just a service context and
769 * its CSID. A search across *all* service workspaces (within a given tenant context) is performed to find
772 * This query searches Nuxeo's Hierarchy table where our CSIDs are stored in the "name" column.
775 public DocumentWrapper<DocumentModel> getDocFromCsid(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
778 DocumentWrapper<DocumentModel> result = null;
779 RepositoryInstance repoSession = null;
781 repoSession = getRepositorySession(ctx);
782 result = getDocFromCsid(ctx, repoSession, csid);
784 if (repoSession != null) {
785 releaseRepositorySession(ctx, repoSession);
789 if (logger.isWarnEnabled() == true) {
790 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
797 * Returns a URI value for a document in the Nuxeo repository
799 * @param wrappedDoc a wrapped documentModel
800 * @throws ClientException
801 * @return a document URI
804 public String getDocURI(DocumentWrapper<DocumentModel> wrappedDoc) throws ClientException {
805 DocumentModel docModel = wrappedDoc.getWrappedObject();
806 String uri = (String) docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
807 CollectionSpaceClient.COLLECTIONSPACE_CORE_URI);
812 * See CSPACE-5036 - How to make CMISQL queries from Nuxeo
814 private IterableQueryResult makeCMISQLQuery(RepositoryInstance repoSession, String query, QueryContext queryContext) {
815 IterableQueryResult result = null;
817 // the NuxeoRepository should be constructed only once, then cached
818 // (its construction is expensive)
820 NuxeoRepository repo = new NuxeoRepository(
821 repoSession.getRepositoryName(), repoSession
822 .getRootDocument().getId());
823 logger.debug("Repository ID:" + repo.getId() + " Root folder:"
824 + repo.getRootFolderId());
826 CallContextImpl callContext = new CallContextImpl(
827 CallContext.BINDING_LOCAL, repo.getId(), false);
828 callContext.put(CallContext.USERNAME, repoSession.getPrincipal()
830 NuxeoCmisService cmisService = new NuxeoCmisService(repo,
831 callContext, repoSession);
833 result = repoSession.queryAndFetch(query, "CMISQL", cmisService);
834 } catch (ClientException e) {
835 // TODO Auto-generated catch block
836 logger.error("Encounter trouble making the following CMIS query: " + query, e);
843 * getFiltered get all documents for an entity service from the Document
844 * repository, given filter parameters specified by the handler.
846 * @param ctx service context under which this method is invoked
847 * @param handler should be used by the caller to provide and transform the
849 * @throws DocumentNotFoundException if workspace not found
850 * @throws TransactionException
851 * @throws DocumentException
854 public void getFiltered(ServiceContext ctx, DocumentHandler handler)
855 throws DocumentNotFoundException, TransactionException, DocumentException {
857 DocumentFilter filter = handler.getDocumentFilter();
858 String oldOrderBy = filter.getOrderByClause();
859 if (isClauseEmpty(oldOrderBy) == true) {
860 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
862 QueryContext queryContext = new QueryContext(ctx, handler);
864 RepositoryInstance repoSession = null;
866 handler.prepare(Action.GET_ALL);
867 repoSession = getRepositorySession(ctx); //Keeps a refcount here for the repository session so you need to release this when finished
869 DocumentModelList docList = null;
870 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
872 if (logger.isDebugEnabled()) {
873 logger.debug("Executing NXQL query: " + query.toString());
876 // If we have limit and/or offset, then pass true to get totalSize
877 // in returned DocumentModelList.
878 Profiler profiler = new Profiler(this, 2);
879 profiler.log("Executing NXQL query: " + query.toString());
881 if (handler.isJDBCQuery() == true) {
882 docList = getFilteredJDBC(repoSession, ctx, handler, queryContext);
883 } else if (handler.isCMISQuery() == true) {
884 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext); //FIXME: REM - Need to deal with paging info in CMIS query
885 } else if ((queryContext.getDocFilter().getOffset() > 0) || (queryContext.getDocFilter().getPageSize() > 0)) {
886 docList = repoSession.query(query, null,
887 queryContext.getDocFilter().getPageSize(), queryContext.getDocFilter().getOffset(), true);
889 docList = repoSession.query(query);
893 //set repoSession to handle the document
894 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
895 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
896 handler.handle(Action.GET_ALL, wrapDoc);
897 handler.complete(Action.GET_ALL, wrapDoc);
898 } catch (DocumentException de) {
900 } catch (Exception e) {
901 if (logger.isDebugEnabled()) {
902 logger.debug("Caught exception ", e);
904 throw new DocumentException(e);
906 if (repoSession != null) {
907 releaseRepositorySession(ctx, repoSession);
912 private DocumentModelList getFilteredJDBC(RepositoryInstance repoSession, ServiceContext ctx,
913 DocumentHandler handler, QueryContext queryContext) throws Exception {
914 DocumentModelList result = new DocumentModelListImpl();
916 final int LIMIT_SIZE = 40; // FIXME: Get from configuration and/or pagination query params
918 String dataSourceName = JDBCTools.NUXEO_DATASOURCE_NAME;
919 String repositoryName = ctx.getRepositoryName();
921 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
922 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
924 // FIXME: Resolve how to handle the case where the partial term
925 // query parameter is included in the request, but has been given an
926 // empty (blank) value. Then implement that here, if current behavior
927 // does not match the required behavior.
929 // (We're currently returning all records in that case.)
931 // FIXME: Get all of the following values from appropriate external constants.
933 // At present, the two constants below are duplicated in both RepositoryJavaClientImpl
934 // and in AuthorityItemDocumentModelHandler.
935 final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
936 final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
937 // Get this from a constant in AuthorityResource or equivalent
938 final String PARENT_WILDCARD = "_ALL_";
940 // Start with the default query
941 String selectStatement =
942 "SELECT DISTINCT hierarchy_termgroup.id as id, hierarchy_termgroup.parentid as parentid"
943 + " FROM " + handler.getJDBCQueryParams().get(TERM_GROUP_TABLE_NAME_PARAM) + " termgroup ";
946 " INNER JOIN hierarchy hierarchy_termgroup "
947 + " ON hierarchy_termgroup.id = termgroup.id "
948 + " INNER JOIN hierarchy hierarchy_commonschema "
949 + " ON hierarchy_commonschema.id = hierarchy_termgroup.parentid ";
952 " WHERE (termgroup.termdisplayname ILIKE ?) ";
955 " LIMIT " + LIMIT_SIZE;
957 List<String> params = new ArrayList<>();
958 // Handle user-provided leading wildcard characters, in the
959 // configuration where a leading wildcard is not automatically inserted.
960 // (The user-provided wildcard must be in the first character position
961 // in the partial term value.)
963 // FIXME: Read tenant bindings configuration to determine whether
964 // to automatically insert leading, as well as trailing, wildcards
965 // into the term matching string.
967 // FIXME: Get this value from an existing constant, if available
968 final String USER_SUPPLIED_WILDCARD = "*";
969 partialTerm = handleProvidedLeadingWildcard(partialTerm, USER_SUPPLIED_WILDCARD);
970 params.add(partialTerm + JDBCTools.SQL_WILDCARD); // Value for replaceable parameter 1 in the query
972 // Restrict the query to filter out deleted records, if requested
973 String includeDeleted = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_NONDELETED);
974 if (includeDeleted != null && includeDeleted.equalsIgnoreCase(Boolean.FALSE.toString())) {
975 joinClauses = joinClauses
976 + " INNER JOIN misc "
977 + " ON misc.id = hierarchy_commonschema.id ";
978 whereClause = whereClause
979 + " AND (misc.lifecyclestate <> '" + WorkflowClient.WORKFLOWSTATE_DELETED + "') ";
982 // If a particular authority is specified, restrict the query further
983 // to return only records within that authority
984 String inAuthorityValue = (String) handler.getJDBCQueryParams().get(IN_AUTHORITY_PARAM);
985 if (Tools.notBlank(inAuthorityValue)) {
986 // Handle the '_ALL_' case for inAuthority
987 if (inAuthorityValue.equals(PARENT_WILDCARD)) {
988 // Add nothing to the query here if it should match within all authorities
990 joinClauses = joinClauses
991 + " INNER JOIN " + handler.getServiceContext().getCommonPartLabel() + " commonschema "
992 + " ON commonschema.id = hierarchy_commonschema.id ";
993 whereClause = whereClause
994 + " AND (commonschema.inauthority = ?)";
995 params.add(inAuthorityValue); // Value for replaceable parameter 2 in the query
999 String sql = selectStatement + joinClauses + whereClause + limitClause;
1001 // FIXME: Look into whether the following performance concern around
1002 // query planning with prepared statements may be affecting us:
1003 // http://stackoverflow.com/a/678452
1004 // If that proves to be a significant concern, we can instead use
1005 // JDBCTools.executeQuery(), and attempt to sanitize user input
1006 // against potential SQL injection attacks.
1007 PreparedStatementSimpleBuilder jdbcFilterQueryBuilder = new PreparedStatementSimpleBuilder(sql, params);
1009 List<String> docIds = new ArrayList<>();
1010 try (CachedRowSet crs = JDBCTools.executePreparedQuery(jdbcFilterQueryBuilder,
1011 dataSourceName, repositoryName, sql)) {
1013 // If the response to the query is null or contains zero rows,
1014 // return an empty list of document models
1019 if (crs.getRow() == 0) {
1020 return result; // empty list of document models
1023 // Otherwise, get the document IDs from the results of the query
1026 while (crs.next()) {
1027 // Obtain parent IDs in the hierarchy table from column 2
1028 // of results. These IDs correspond to parent (authority item)
1029 // document records, rather than to term information group
1031 id = crs.getString(2);
1032 if (Tools.notBlank(id)) {
1036 } catch (SQLException sqle) {
1037 logger.warn("Could not obtain document IDs via SQL query '" + sql + "': " + sqle.getMessage());
1038 return result; // return an empty list of document models
1041 // Get a list of document models, using the IDs obtained from the query
1042 DocumentModel docModel;
1043 for (String docId : docIds) {
1044 docModel = NuxeoUtils.getDocumentModel(repoSession, docId);
1045 if (docModel == null) {
1046 logger.debug("Could not obtain document model for document with ID " + docId);
1048 result.add(NuxeoUtils.getDocumentModel(repoSession, docId));
1056 private DocumentModelList getFilteredCMIS(RepositoryInstance repoSession, ServiceContext ctx, DocumentHandler handler, QueryContext queryContext)
1057 throws DocumentNotFoundException, DocumentException {
1059 DocumentModelList result = new DocumentModelListImpl();
1061 String query = handler.getCMISQuery(queryContext);
1063 DocumentFilter docFilter = handler.getDocumentFilter();
1064 int pageSize = docFilter.getPageSize();
1065 int offset = docFilter.getOffset();
1066 if (logger.isDebugEnabled()) {
1067 logger.debug("Executing CMIS query: " + query.toString()
1068 + "with pageSize: " + pageSize + " at offset: " + offset);
1071 // If we have limit and/or offset, then pass true to get totalSize
1072 // in returned DocumentModelList.
1073 Profiler profiler = new Profiler(this, 2);
1074 profiler.log("Executing CMIS query: " + query.toString());
1077 IterableQueryResult queryResult = makeCMISQLQuery(repoSession, query, queryContext);
1079 int totalSize = (int) queryResult.size();
1080 ((DocumentModelListImpl) result).setTotalSize(totalSize);
1081 // Skip the rows before our offset
1083 queryResult.skipTo(offset);
1086 for (Map<String, Serializable> row : queryResult) {
1087 if (logger.isTraceEnabled()) {
1088 logger.trace(" Hierarchy Table ID is:" + row.get(IQueryManager.CMIS_TARGET_NUXEO_ID)
1089 + " nuxeo:pathSegment is: " + row.get(IQueryManager.CMIS_TARGET_NAME));
1091 String nuxeoId = (String) row.get(IQueryManager.CMIS_TARGET_NUXEO_ID);
1092 DocumentModel docModel = NuxeoUtils.getDocumentModel(repoSession, nuxeoId);
1093 result.add(docModel);
1095 if (nRows >= pageSize && pageSize != 0) { // A page size of zero means that they want all of them
1096 logger.debug("Got page full of items - quitting");
1101 queryResult.close();
1106 } catch (Exception e) {
1107 if (logger.isDebugEnabled()) {
1108 logger.debug("Caught exception ", e);
1110 throw new DocumentException(e);
1114 // Since we're not supporting paging yet for CMIS queries, we need to perform
1115 // a workaround for the paging information we return in our list of results
1118 if (result != null) {
1119 docFilter.setStartPage(0);
1120 if (totalSize > docFilter.getPageSize()) {
1121 docFilter.setPageSize(totalSize);
1122 ((DocumentModelListImpl)result).setTotalSize(totalSize);
1130 private String logException(Exception e, String msg) {
1131 String result = null;
1133 String exceptionMessage = e.getMessage();
1134 exceptionMessage = exceptionMessage != null ? exceptionMessage : "<No details provided>";
1135 result = msg = msg + ". Caught exception:" + exceptionMessage;
1137 if (logger.isTraceEnabled() == true) {
1138 logger.error(msg, e);
1147 * update given document in the Nuxeo repository
1149 * @param ctx service context under which this method is invoked
1150 * @param csid of the document
1151 * @param handler should be used by the caller to provide and transform the
1153 * @throws BadRequestException
1154 * @throws DocumentNotFoundException
1155 * @throws TransactionException if the transaction times out or otherwise
1156 * cannot be successfully completed
1157 * @throws DocumentException
1160 public void update(ServiceContext ctx, String csid, DocumentHandler handler)
1161 throws BadRequestException, DocumentNotFoundException, TransactionException,
1163 if (handler == null) {
1164 throw new IllegalArgumentException(
1165 "RepositoryJavaClient.update: document handler is missing.");
1168 RepositoryInstance repoSession = null;
1170 handler.prepare(Action.UPDATE);
1171 repoSession = getRepositorySession(ctx);
1172 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
1173 DocumentModel doc = null;
1175 doc = repoSession.getDocument(docRef);
1176 } catch (ClientException ce) {
1177 String msg = logException(ce, "Could not find document to update with CSID=" + csid);
1178 throw new DocumentNotFoundException(msg, ce);
1180 // Check for a versioned document, and check In and Out before we proceed.
1181 if (((DocumentModelHandler) handler).supportsVersioning()) {
1182 /* Once we advance to 5.5 or later, we can add this.
1183 * See also https://jira.nuxeo.com/browse/NXP-8506
1184 if(!doc.isVersionable()) {
1185 throw new DocumentException("Configuration for: "
1186 +handler.getServiceContextPath()+" supports versioning, but Nuxeo config does not!");
1189 /* Force a version number - Not working. Apparently we need to configure the uid schema??
1190 if(doc.getProperty("uid","major_version") == null) {
1191 doc.setProperty("uid","major_version",1);
1193 if(doc.getProperty("uid","minor_version") == null) {
1194 doc.setProperty("uid","minor_version",0);
1197 doc.checkIn(VersioningOption.MINOR, null);
1202 // Set reposession to handle the document
1204 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1205 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
1206 handler.handle(Action.UPDATE, wrapDoc);
1207 repoSession.saveDocument(doc);
1209 handler.complete(Action.UPDATE, wrapDoc);
1210 } catch (BadRequestException bre) {
1212 } catch (DocumentException de) {
1214 } catch (WebApplicationException wae) {
1216 } catch (Exception e) {
1217 if (logger.isDebugEnabled()) {
1218 logger.debug("Caught exception ", e);
1220 throw new DocumentException(e);
1222 if (repoSession != null) {
1223 releaseRepositorySession(ctx, repoSession);
1229 * Save a documentModel to the Nuxeo repository.
1231 * @param ctx service context under which this method is invoked
1232 * @param repoSession
1233 * @param docModel the document to save
1234 * @param fSaveSession if TRUE, will call CoreSession.save() to save
1235 * accumulated changes.
1236 * @throws ClientException
1237 * @throws DocumentException
1239 public void saveDocWithoutHandlerProcessing(
1240 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1241 RepositoryInstance repoSession,
1242 DocumentModel docModel,
1243 boolean fSaveSession)
1244 throws ClientException, DocumentException {
1247 repoSession.saveDocument(docModel);
1251 } catch (ClientException ce) {
1253 } catch (Exception e) {
1254 if (logger.isDebugEnabled()) {
1255 logger.debug("Caught exception ", e);
1257 throw new DocumentException(e);
1262 * Save a list of documentModels to the Nuxeo repository.
1264 * @param ctx service context under which this method is invoked
1265 * @param repoSession a repository session
1266 * @param docModelList a list of document models
1267 * @param fSaveSession if TRUE, will call CoreSession.save() to save
1268 * accumulated changes.
1269 * @throws ClientException
1270 * @throws DocumentException
1272 public void saveDocListWithoutHandlerProcessing(
1273 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1274 RepositoryInstance repoSession,
1275 DocumentModelList docList,
1276 boolean fSaveSession)
1277 throws ClientException, DocumentException {
1279 DocumentModel[] docModelArray = new DocumentModel[docList.size()];
1280 repoSession.saveDocuments(docList.toArray(docModelArray));
1284 } catch (ClientException ce) {
1286 } catch (Exception e) {
1287 logger.error("Caught exception ", e);
1288 throw new DocumentException(e);
1293 * delete a document from the Nuxeo repository
1295 * @param ctx service context under which this method is invoked
1296 * @param id of the document
1297 * @throws DocumentException
1300 public void delete(ServiceContext ctx, String id, DocumentHandler handler) throws DocumentNotFoundException,
1301 DocumentException, TransactionException {
1303 throw new IllegalArgumentException(
1304 "delete(ctx, ix, handler): ctx is missing");
1306 if (handler == null) {
1307 throw new IllegalArgumentException(
1308 "delete(ctx, ix, handler): handler is missing");
1310 if (logger.isDebugEnabled()) {
1311 logger.debug("Deleting document with CSID=" + id);
1313 RepositoryInstance repoSession = null;
1315 handler.prepare(Action.DELETE);
1316 repoSession = getRepositorySession(ctx);
1317 DocumentWrapper<DocumentModel> wrapDoc = null;
1319 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
1320 wrapDoc = new DocumentWrapperImpl<DocumentModel>(repoSession.getDocument(docRef));
1321 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1322 handler.handle(Action.DELETE, wrapDoc);
1323 repoSession.removeDocument(docRef);
1324 } catch (ClientException ce) {
1325 String msg = logException(ce, "Could not find document to delete with CSID=" + id);
1326 throw new DocumentNotFoundException(msg, ce);
1329 handler.complete(Action.DELETE, wrapDoc);
1330 } catch (DocumentException de) {
1332 } catch (Exception e) {
1333 if (logger.isDebugEnabled()) {
1334 logger.debug("Caught exception ", e);
1336 throw new DocumentException(e);
1338 if (repoSession != null) {
1339 releaseRepositorySession(ctx, repoSession);
1345 * @see org.collectionspace.services.common.storage.StorageClient#delete(org.collectionspace.services.common.context.ServiceContext, java.lang.String, org.collectionspace.services.common.document.DocumentHandler)
1349 public void delete(@SuppressWarnings("rawtypes") ServiceContext ctx, String id)
1350 throws DocumentNotFoundException, DocumentException {
1351 throw new UnsupportedOperationException();
1352 // Use the other delete instead
1356 public Hashtable<String, String> retrieveWorkspaceIds(RepositoryDomainType repoDomain) throws Exception {
1357 return NuxeoConnectorEmbedded.getInstance().retrieveWorkspaceIds(repoDomain);
1361 public String createDomain(RepositoryDomainType repositoryDomain) throws Exception {
1362 RepositoryInstance repoSession = null;
1363 String domainId = null;
1366 // Open a connection to the domain's repo/db
1368 String repoName = repositoryDomain.getRepositoryName();
1369 repoSession = getRepositorySession(repoName); // domainName=storageName=repoName=databaseName
1371 // First create the top-level domain directory
1373 String domainName = repositoryDomain.getStorageName();
1374 DocumentRef parentDocRef = new PathRef("/");
1375 DocumentModel parentDoc = repoSession.getDocument(parentDocRef);
1376 DocumentModel domainDoc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1377 domainName, NUXEO_CORE_TYPE_DOMAIN);
1378 domainDoc.setPropertyValue("dc:title", domainName);
1379 domainDoc.setPropertyValue("dc:description", "A CollectionSpace domain "
1381 domainDoc = repoSession.createDocument(domainDoc);
1382 domainId = domainDoc.getId();
1385 // Next, create a "Workspaces" root directory to contain the workspace folders for the individual service documents
1387 DocumentModel workspacesRoot = repoSession.createDocumentModel(domainDoc.getPathAsString(),
1388 NuxeoUtils.Workspaces, NUXEO_CORE_TYPE_WORKSPACEROOT);
1389 workspacesRoot.setPropertyValue("dc:title", NuxeoUtils.Workspaces);
1390 workspacesRoot.setPropertyValue("dc:description", "A CollectionSpace workspaces directory for "
1391 + domainDoc.getPathAsString());
1392 workspacesRoot = repoSession.createDocument(workspacesRoot);
1393 String workspacesRootId = workspacesRoot.getId();
1396 if (logger.isDebugEnabled()) {
1397 logger.debug("Created tenant domain name=" + domainName
1398 + " id=" + domainId + " "
1399 + NuxeoUtils.Workspaces + " id=" + workspacesRootId);
1400 logger.debug("Path to Domain: " + domainDoc.getPathAsString());
1401 logger.debug("Path to Workspaces root: " + workspacesRoot.getPathAsString());
1403 } catch (Exception e) {
1404 if (logger.isDebugEnabled()) {
1405 logger.debug("Could not create tenant domain name=" + repositoryDomain.getStorageName() + " caught exception ", e);
1409 if (repoSession != null) {
1410 releaseRepositorySession(null, repoSession);
1418 public String getDomainId(RepositoryDomainType repositoryDomain) throws Exception {
1419 String domainId = null;
1420 RepositoryInstance repoSession = null;
1422 String repoName = repositoryDomain.getRepositoryName();
1423 String domainStorageName = repositoryDomain.getStorageName();
1424 if (domainStorageName != null && !domainStorageName.isEmpty()) {
1426 repoSession = getRepositorySession(repoName);
1427 DocumentRef docRef = new PathRef("/" + domainStorageName);
1428 DocumentModel domain = repoSession.getDocument(docRef);
1429 domainId = domain.getId();
1430 } catch (Exception e) {
1431 if (logger.isTraceEnabled()) {
1432 logger.trace("Caught exception ", e); // The document doesn't exist, this let's us know we need to create it
1434 //there is no way to identify if document does not exist due to
1435 //lack of typed exception for getDocument method
1438 if (repoSession != null) {
1439 releaseRepositorySession(null, repoSession);
1448 * Returns the workspaces root directory for a given domain.
1450 private DocumentModel getWorkspacesRoot(RepositoryInstance repoSession,
1451 String domainName) throws Exception {
1452 DocumentModel result = null;
1454 String domainPath = "/" + domainName;
1455 DocumentRef parentDocRef = new PathRef(domainPath);
1456 DocumentModelList domainChildrenList = repoSession.getChildren(
1458 Iterator<DocumentModel> witer = domainChildrenList.iterator();
1459 while (witer.hasNext()) {
1460 DocumentModel childNode = witer.next();
1461 if (NuxeoUtils.Workspaces.equalsIgnoreCase(childNode.getName())) {
1463 logger.trace("Found workspaces directory at: " + result.getPathAsString());
1468 if (result == null) {
1469 throw new ClientException("Could not find workspace root directory in: "
1477 * @see org.collectionspace.services.common.repository.RepositoryClient#createWorkspace(java.lang.String, java.lang.String)
1480 public String createWorkspace(RepositoryDomainType repositoryDomain, String workspaceName) throws Exception {
1481 RepositoryInstance repoSession = null;
1482 String workspaceId = null;
1484 String repoName = repositoryDomain.getRepositoryName();
1485 repoSession = getRepositorySession(repoName);
1487 String domainStorageName = repositoryDomain.getStorageName();
1488 DocumentModel parentDoc = getWorkspacesRoot(repoSession, domainStorageName);
1489 if (logger.isTraceEnabled()) {
1490 for (String facet : parentDoc.getFacets()) {
1491 logger.trace("Facet: " + facet);
1495 DocumentModel doc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1496 workspaceName, NuxeoUtils.WORKSPACE_DOCUMENT_TYPE);
1497 doc.setPropertyValue("dc:title", workspaceName);
1498 doc.setPropertyValue("dc:description", "A CollectionSpace workspace for "
1500 doc = repoSession.createDocument(doc);
1501 workspaceId = doc.getId();
1503 if (logger.isDebugEnabled()) {
1504 logger.debug("Created workspace name=" + workspaceName
1505 + " id=" + workspaceId);
1507 } catch (Exception e) {
1508 if (logger.isDebugEnabled()) {
1509 logger.debug("createWorkspace caught exception ", e);
1513 if (repoSession != null) {
1514 releaseRepositorySession(null, repoSession);
1521 * @see org.collectionspace.services.common.repository.RepositoryClient#getWorkspaceId(java.lang.String, java.lang.String)
1525 public String getWorkspaceId(String tenantDomain, String workspaceName) throws Exception {
1526 String workspaceId = null;
1528 RepositoryInstance repoSession = null;
1530 repoSession = getRepositorySession((ServiceContext) null);
1531 DocumentRef docRef = new PathRef(
1533 + "/" + NuxeoUtils.Workspaces
1534 + "/" + workspaceName);
1535 DocumentModel workspace = repoSession.getDocument(docRef);
1536 workspaceId = workspace.getId();
1537 } catch (DocumentException de) {
1539 } catch (Exception e) {
1540 if (logger.isDebugEnabled()) {
1541 logger.debug("Caught exception ", e);
1543 throw new DocumentException(e);
1545 if (repoSession != null) {
1546 releaseRepositorySession(null, repoSession);
1553 public RepositoryInstance getRepositorySession(ServiceContext ctx) throws Exception {
1554 return getRepositorySession(ctx, ctx.getRepositoryName());
1557 public RepositoryInstance getRepositorySession(String repoName) throws Exception {
1558 return getRepositorySession(null, repoName);
1562 * Gets the repository session. - Package access only. If the 'ctx' param is
1563 * null then the repo name must be non-mull and vice-versa
1565 * @return the repository session
1566 * @throws Exception the exception
1568 public RepositoryInstance getRepositorySession(ServiceContext ctx, String repoName) throws Exception {
1569 RepositoryInstance repoSession = null;
1571 Profiler profiler = new Profiler("getRepositorySession():", 2);
1574 // To get a connection to the Nuxeo repo, we need either a valid ServiceContext instance or a repository name
1577 repoName = ctx.getRepositoryName(); // Notice we are overriding the passed in 'repoName' since we have a valid service context passed in to us
1578 repoSession = (RepositoryInstance) ctx.getCurrentRepositorySession(); // Look to see if one exists in the context before creating one
1579 } else if (repoName == null || repoName.trim().isEmpty()) {
1580 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.");
1581 logger.error(errMsg);
1582 throw new Exception(errMsg);
1585 // 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
1586 // just the repo name
1588 if (repoSession == null) {
1589 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1590 repoSession = client.openRepository(repoName);
1592 if (logger.isDebugEnabled() == true) {
1593 logger.warn("Reusing the current context's repository session.");
1597 if (logger.isTraceEnabled()) {
1598 logger.trace("Testing call to getRepository() repository root: " + repoSession.getRootDocument());
1604 ctx.setCurrentRepositorySession(repoSession); // For reusing, save the repository session in the current service context
1611 * Release repository session. - Package access only.
1613 * @param repoSession the repo session
1615 public void releaseRepositorySession(ServiceContext ctx, RepositoryInstance repoSession) throws TransactionException {
1617 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1620 ctx.clearCurrentRepositorySession(); //clear the current context of the now closed repo session
1621 if (ctx.getCurrentRepositorySession() == null) {
1622 client.releaseRepository(repoSession); //release the repo session if the service context's ref count is zeo.
1625 client.releaseRepository(repoSession); //repo session was acquired without a service context
1627 } catch (TransactionRuntimeException tre) {
1628 TransactionException te = new TransactionException(tre);
1629 logger.error(te.getMessage(), tre); // Log the standard transaction exception message, plus an exception-specific stack trace
1631 } catch (Exception e) {
1632 logger.error("Could not close the repository session", e);
1633 // no need to throw this service specific exception
1638 public void doWorkflowTransition(ServiceContext ctx, String id,
1639 DocumentHandler handler, TransitionDef transitionDef)
1640 throws BadRequestException, DocumentNotFoundException,
1642 // 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
1645 private String handleProvidedLeadingWildcard(String partialTerm, final String USER_SUPPLIED_WILDCARD) {
1646 if (Tools.notBlank(partialTerm)) {
1647 if (partialTerm.substring(0, 1).equals(USER_SUPPLIED_WILDCARD)) {
1648 StringBuffer buffer = new StringBuffer(partialTerm);
1649 buffer.setCharAt(0, JDBCTools.SQL_WILDCARD.charAt(0));
1650 partialTerm = buffer.toString();