2 * This document is a part of the source code and related artifacts
3 * for CollectionSpace, an open source collections management system
4 * for museums and related institutions:
6 * http://www.collectionspace.org
7 * http://wiki.collectionspace.org
9 * Copyright 2009 University of California at Berkeley
11 * Licensed under the Educational Community License (ECL), Version 2.0.
12 * You may not use this file except in compliance with this License.
14 * You may obtain a copy of the ECL 2.0 License at
16 * https://source.collectionspace.org/collection-space/LICENSE.txt
18 package org.collectionspace.services.nuxeo.client.java;
20 import java.io.Serializable;
21 import java.sql.Connection;
22 import java.sql.ResultSet;
23 import java.sql.Statement;
24 import java.util.ArrayList;
25 import java.util.Hashtable;
26 import java.util.Iterator;
27 import java.util.List;
29 import java.util.UUID;
31 import javax.ws.rs.WebApplicationException;
32 import javax.ws.rs.core.MultivaluedMap;
34 import org.collectionspace.services.client.CollectionSpaceClient;
35 import org.collectionspace.services.client.IQueryManager;
36 import org.collectionspace.services.client.PoxPayloadIn;
37 import org.collectionspace.services.client.PoxPayloadOut;
38 import org.collectionspace.services.client.Profiler;
39 import org.collectionspace.services.client.workflow.WorkflowClient;
40 import org.collectionspace.services.common.context.ServiceContext;
41 import org.collectionspace.services.common.query.QueryContext;
42 import org.collectionspace.services.common.repository.RepositoryClient;
43 import org.collectionspace.services.common.storage.JDBCTools;
44 import org.collectionspace.services.lifecycle.TransitionDef;
45 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
47 import org.collectionspace.services.common.document.BadRequestException;
48 import org.collectionspace.services.common.document.DocumentException;
49 import org.collectionspace.services.common.document.DocumentFilter;
50 import org.collectionspace.services.common.document.DocumentHandler;
51 import org.collectionspace.services.common.document.DocumentNotFoundException;
52 import org.collectionspace.services.common.document.DocumentHandler.Action;
53 import org.collectionspace.services.common.document.DocumentWrapper;
54 import org.collectionspace.services.common.document.DocumentWrapperImpl;
55 import org.collectionspace.services.common.document.TransactionException;
56 import org.collectionspace.services.config.tenant.RepositoryDomainType;
58 import org.nuxeo.common.utils.IdUtils;
59 import org.nuxeo.ecm.core.api.ClientException;
60 import org.nuxeo.ecm.core.api.DocumentModel;
61 import org.nuxeo.ecm.core.api.DocumentModelList;
62 import org.nuxeo.ecm.core.api.IterableQueryResult;
63 import org.nuxeo.ecm.core.api.VersioningOption;
64 import org.nuxeo.ecm.core.api.impl.DocumentModelListImpl;
65 import org.nuxeo.ecm.core.api.DocumentRef;
66 import org.nuxeo.ecm.core.api.IdRef;
67 import org.nuxeo.ecm.core.api.PathRef;
68 import org.nuxeo.ecm.core.api.repository.RepositoryInstance;
69 import org.nuxeo.runtime.transaction.TransactionRuntimeException;
72 // CSPACE-5036 - How to make CMISQL queries from Nuxeo
74 import org.apache.chemistry.opencmis.commons.server.CallContext;
75 import org.apache.chemistry.opencmis.server.impl.CallContextImpl;
76 import org.collectionspace.services.common.api.Tools;
77 import org.nuxeo.ecm.core.opencmis.impl.server.NuxeoCmisService;
78 import org.nuxeo.ecm.core.opencmis.impl.server.NuxeoRepository;
80 import org.slf4j.Logger;
81 import org.slf4j.LoggerFactory;
84 * RepositoryJavaClient is used to perform CRUD operations on documents in Nuxeo
85 * repository using Remote Java APIs. It uses @see DocumentHandler as IOHandler
88 * $LastChangedRevision: $ $LastChangedDate: $
90 public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn, PoxPayloadOut> {
93 private final Logger logger = LoggerFactory.getLogger(RepositoryJavaClientImpl.class);
94 // private final Logger profilerLogger = LoggerFactory.getLogger("remperf");
95 // private String foo = Profiler.createLogger();
97 public static final String NUXEO_CORE_TYPE_DOMAIN = "Domain";
98 public static final String NUXEO_CORE_TYPE_WORKSPACEROOT = "WorkspaceRoot";
101 * Instantiates a new repository java client impl.
103 public RepositoryJavaClientImpl() {
108 public void assertWorkflowState(ServiceContext ctx,
109 DocumentModel docModel) throws DocumentNotFoundException, ClientException {
110 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
111 if (queryParams != null) {
113 // Look for the workflow "delete" query param and see if we need to assert that the
114 // docModel is in a non-deleted workflow state.
116 String currentState = docModel.getCurrentLifeCycleState();
117 String includeDeletedStr = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_NONDELETED);
118 boolean includeDeleted = includeDeletedStr == null ? true : Boolean.parseBoolean(includeDeletedStr);
119 if (includeDeleted == false) {
121 // We don't wanted soft-deleted object, so throw an exception if this one is soft-deleted.
123 if (currentState.equalsIgnoreCase(WorkflowClient.WORKFLOWSTATE_DELETED)) {
124 String msg = "The GET assertion that docModel not be in 'deleted' workflow state failed.";
126 throw new DocumentNotFoundException(msg);
133 * create document in the Nuxeo repository
135 * @param ctx service context under which this method is invoked
137 * should be used by the caller to provide and transform the
139 * @return id in repository of the newly created document
140 * @throws BadRequestException
141 * @throws TransactionException
142 * @throws DocumentException
145 public String create(ServiceContext ctx,
146 DocumentHandler handler) throws BadRequestException,
147 TransactionException, DocumentException {
149 String docType = NuxeoUtils.getTenantQualifiedDocType(ctx); //ctx.getDocumentType();
150 if (docType == null) {
151 throw new IllegalArgumentException(
152 "RepositoryJavaClient.create: docType is missing");
155 if (handler == null) {
156 throw new IllegalArgumentException(
157 "RepositoryJavaClient.create: handler is missing");
159 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
160 if (nuxeoWspaceId == null) {
161 throw new DocumentNotFoundException(
162 "Unable to find workspace for service " + ctx.getServiceName()
163 + " check if the workspace exists in the Nuxeo repository");
166 RepositoryInstance repoSession = null;
168 handler.prepare(Action.CREATE);
169 repoSession = getRepositorySession(ctx);
170 DocumentRef nuxeoWspace = new IdRef(nuxeoWspaceId);
171 DocumentModel wspaceDoc = repoSession.getDocument(nuxeoWspace);
172 String wspacePath = wspaceDoc.getPathAsString();
173 //give our own ID so PathRef could be constructed later on
174 String id = IdUtils.generateId(UUID.randomUUID().toString());
175 // create document model
176 DocumentModel doc = repoSession.createDocumentModel(wspacePath, id, docType);
177 /* Check for a versioned document, and check In and Out before we proceed.
178 * This does not work as we do not have the uid schema on our docs.
179 if(((DocumentModelHandler) handler).supportsVersioning()) {
180 doc.setProperty("uid","major_version",1);
181 doc.setProperty("uid","minor_version",0);
184 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
185 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
186 handler.handle(Action.CREATE, wrapDoc);
187 // create document with documentmodel
188 doc = repoSession.createDocument(doc);
190 // TODO for sub-docs need to call into the handler to let it deal with subitems. Pass in the id,
191 // and assume the handler has the state it needs (doc fragments).
192 handler.complete(Action.CREATE, wrapDoc);
194 } catch (BadRequestException bre) {
196 } catch (Exception e) {
197 logger.error("Caught exception ", e);
198 throw new DocumentException(e);
200 if (repoSession != null) {
201 releaseRepositorySession(ctx, repoSession);
208 * get document from the Nuxeo repository
209 * @param ctx service context under which this method is invoked
211 * of the document to retrieve
213 * should be used by the caller to provide and transform the
215 * @throws DocumentNotFoundException if the document cannot be found in the repository
216 * @throws TransactionException
217 * @throws DocumentException
220 public void get(ServiceContext ctx, String id, DocumentHandler handler)
221 throws DocumentNotFoundException, TransactionException, DocumentException {
223 if (handler == null) {
224 throw new IllegalArgumentException(
225 "RepositoryJavaClient.get: handler is missing");
228 RepositoryInstance repoSession = null;
230 handler.prepare(Action.GET);
231 repoSession = getRepositorySession(ctx);
232 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
233 DocumentModel docModel = null;
235 docModel = repoSession.getDocument(docRef);
236 assertWorkflowState(ctx, docModel);
237 } catch (ClientException ce) {
238 String msg = logException(ce, "Could not find document with CSID=" + id);
239 throw new DocumentNotFoundException(msg, ce);
242 // Set repository session to handle the document
244 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
245 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(docModel);
246 handler.handle(Action.GET, wrapDoc);
247 handler.complete(Action.GET, wrapDoc);
248 } catch (IllegalArgumentException iae) {
250 } catch (DocumentException de) {
252 } catch (Exception e) {
253 if (logger.isDebugEnabled()) {
254 logger.debug("Caught exception ", e);
256 throw new DocumentException(e);
258 if (repoSession != null) {
259 releaseRepositorySession(ctx, repoSession);
265 * get a document from the Nuxeo repository, using the docFilter params.
266 * @param ctx service context under which this method is invoked
268 * should be used by the caller to provide and transform the
269 * document. Handler must have a docFilter set to return a single item.
270 * @throws DocumentNotFoundException if the document cannot be found in the repository
271 * @throws TransactionException
272 * @throws DocumentException
275 public void get(ServiceContext ctx, DocumentHandler handler)
276 throws DocumentNotFoundException, TransactionException, DocumentException {
277 QueryContext queryContext = new QueryContext(ctx, handler);
278 RepositoryInstance repoSession = null;
281 handler.prepare(Action.GET);
282 repoSession = getRepositorySession(ctx);
284 DocumentModelList docList = null;
285 // force limit to 1, and ignore totalSize
286 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
287 docList = repoSession.query(query, null, 1, 0, false);
288 if (docList.size() != 1) {
289 throw new DocumentNotFoundException("No document found matching filter params: " + query);
291 DocumentModel doc = docList.get(0);
293 if (logger.isDebugEnabled()) {
294 logger.debug("Executed NXQL query: " + query);
297 //set reposession to handle the document
298 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
299 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
300 handler.handle(Action.GET, wrapDoc);
301 handler.complete(Action.GET, wrapDoc);
302 } catch (IllegalArgumentException iae) {
304 } catch (DocumentException de) {
306 } catch (Exception e) {
307 if (logger.isDebugEnabled()) {
308 logger.debug("Caught exception ", e);
310 throw new DocumentException(e);
312 if (repoSession != null) {
313 releaseRepositorySession(ctx, repoSession);
318 public DocumentWrapper<DocumentModel> getDoc(
319 RepositoryInstance repoSession,
320 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
321 String csid) throws DocumentNotFoundException, DocumentException {
322 DocumentWrapper<DocumentModel> wrapDoc = null;
325 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
326 DocumentModel doc = null;
328 doc = repoSession.getDocument(docRef);
329 } catch (ClientException ce) {
330 String msg = logException(ce, "Could not find document with CSID=" + csid);
331 throw new DocumentNotFoundException(msg, ce);
333 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
334 } catch (IllegalArgumentException iae) {
336 } catch (DocumentException de) {
344 * Get wrapped documentModel from the Nuxeo repository. The search is restricted to the workspace
345 * of the current context.
347 * @param ctx service context under which this method is invoked
349 * of the document to retrieve
350 * @throws DocumentNotFoundException
351 * @throws TransactionException
352 * @throws DocumentException
353 * @return a wrapped documentModel
356 public DocumentWrapper<DocumentModel> getDoc(
357 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
358 String csid) throws DocumentNotFoundException, TransactionException, DocumentException {
359 RepositoryInstance repoSession = null;
360 DocumentWrapper<DocumentModel> wrapDoc = null;
363 // Open a new repository session
364 repoSession = getRepositorySession(ctx);
365 wrapDoc = getDoc(repoSession, ctx, csid);
366 } catch (IllegalArgumentException iae) {
368 } catch (DocumentException de) {
370 } catch (Exception e) {
371 if (logger.isDebugEnabled()) {
372 logger.debug("Caught exception ", e);
374 throw new DocumentException(e);
376 if (repoSession != null) {
377 releaseRepositorySession(ctx, repoSession);
381 if (logger.isWarnEnabled() == true) {
382 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
387 public DocumentWrapper<DocumentModel> findDoc(
388 RepositoryInstance repoSession,
389 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
391 throws DocumentNotFoundException, DocumentException {
392 DocumentWrapper<DocumentModel> wrapDoc = null;
395 QueryContext queryContext = new QueryContext(ctx, whereClause);
396 DocumentModelList docList = null;
397 // force limit to 1, and ignore totalSize
398 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
399 docList = repoSession.query(query,
404 if (docList.size() != 1) {
405 if (logger.isDebugEnabled()) {
406 logger.debug("findDoc: Query found: " + docList.size() + " items.");
407 logger.debug(" Query: " + query);
409 throw new DocumentNotFoundException("No document found matching filter params: " + query);
411 DocumentModel doc = docList.get(0);
412 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
413 } catch (IllegalArgumentException iae) {
415 } catch (DocumentException de) {
417 } catch (Exception e) {
418 if (logger.isDebugEnabled()) {
419 logger.debug("Caught exception ", e);
421 throw new DocumentException(e);
428 * find wrapped documentModel from the Nuxeo repository
429 * @param ctx service context under which this method is invoked
430 * @param whereClause where NXQL where clause to get the document
431 * @throws DocumentNotFoundException
432 * @throws TransactionException
433 * @throws DocumentException
434 * @return a wrapped documentModel retrieved by the repository query
437 public DocumentWrapper<DocumentModel> findDoc(
438 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
440 throws DocumentNotFoundException, TransactionException, DocumentException {
441 RepositoryInstance repoSession = null;
442 DocumentWrapper<DocumentModel> wrapDoc = null;
445 repoSession = getRepositorySession(ctx);
446 wrapDoc = findDoc(repoSession, ctx, whereClause);
447 } catch (Exception e) {
448 throw new DocumentException("Unable to create a Nuxeo repository session.", e);
450 if (repoSession != null) {
451 releaseRepositorySession(ctx, repoSession);
455 if (logger.isWarnEnabled() == true) {
456 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
463 * find doc and return CSID from the Nuxeo repository
465 * @param ctx service context under which this method is invoked
466 * @param whereClause where NXQL where clause to get the document
467 * @throws DocumentNotFoundException
468 * @throws TransactionException
469 * @throws DocumentException
470 * @return the CollectionSpace ID (CSID) of the requested document
473 public String findDocCSID(RepositoryInstance repoSession,
474 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String whereClause)
475 throws DocumentNotFoundException, TransactionException, DocumentException {
477 boolean releaseSession = false;
479 if (repoSession == null) {
480 repoSession = this.getRepositorySession(ctx);
481 releaseSession = true;
483 DocumentWrapper<DocumentModel> wrapDoc = findDoc(repoSession, ctx, whereClause);
484 DocumentModel docModel = wrapDoc.getWrappedObject();
485 csid = NuxeoUtils.getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
486 } catch (DocumentNotFoundException dnfe) {
488 } catch (IllegalArgumentException iae) {
490 } catch (DocumentException de) {
492 } catch (Exception e) {
493 if (logger.isDebugEnabled()) {
494 logger.debug("Caught exception ", e);
496 throw new DocumentException(e);
498 if(releaseSession && (repoSession != null)) {
499 this.releaseRepositorySession(ctx, repoSession);
505 public DocumentWrapper<DocumentModelList> findDocs(
506 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
507 RepositoryInstance repoSession,
508 List<String> docTypes,
510 String orderByClause,
513 boolean computeTotal)
514 throws DocumentNotFoundException, DocumentException {
515 DocumentWrapper<DocumentModelList> wrapDoc = null;
518 if (docTypes == null || docTypes.size() < 1) {
519 throw new DocumentNotFoundException(
520 "The findDocs() method must specify at least one DocumentType.");
522 DocumentModelList docList = null;
523 QueryContext queryContext = new QueryContext(ctx, whereClause, orderByClause);
524 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
525 if (logger.isDebugEnabled()) {
526 logger.debug("findDocs() NXQL: "+query);
528 docList = repoSession.query(query, null, pageSize, pageSize*pageNum, computeTotal);
529 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
530 } catch (IllegalArgumentException iae) {
532 } catch (Exception e) {
533 if (logger.isDebugEnabled()) {
534 logger.debug("Caught exception ", e);
536 throw new DocumentException(e);
542 protected static String buildInListForDocTypes(List<String> docTypes) {
543 StringBuilder sb = new StringBuilder();
545 boolean first = true;
546 for(String docType:docTypes) {
557 return sb.toString();
560 public DocumentWrapper<DocumentModelList> findDocs(
561 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
562 DocumentHandler handler,
563 RepositoryInstance repoSession,
564 List<String> docTypes)
565 throws DocumentNotFoundException, DocumentException {
566 DocumentWrapper<DocumentModelList> wrapDoc = null;
568 DocumentFilter filter = handler.getDocumentFilter();
569 String oldOrderBy = filter.getOrderByClause();
570 if (isClauseEmpty(oldOrderBy) == true){
571 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
573 QueryContext queryContext = new QueryContext(ctx, handler);
576 if (docTypes == null || docTypes.size() < 1) {
577 throw new DocumentNotFoundException(
578 "The findDocs() method must specify at least one DocumentType.");
580 DocumentModelList docList = null;
581 if (handler.isCMISQuery() == true) {
582 String inList = buildInListForDocTypes(docTypes);
583 ctx.getQueryParams().add(IQueryManager.SEARCH_RELATED_MATCH_OBJ_DOCTYPES, inList);
584 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
586 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
587 if (logger.isDebugEnabled()) {
588 logger.debug("findDocs() NXQL: "+query);
590 docList = repoSession.query(query, null, filter.getPageSize(), filter.getOffset(), true);
592 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
593 } catch (IllegalArgumentException iae) {
595 } catch (Exception e) {
596 if (logger.isDebugEnabled()) {
597 logger.debug("Caught exception ", e);
599 throw new DocumentException(e);
608 * Find a list of documentModels from the Nuxeo repository
609 * @param docTypes a list of DocType names to match
610 * @param whereClause where the clause to qualify on
611 * @throws DocumentNotFoundException
612 * @throws TransactionException
613 * @throws DocumentException
614 * @return a list of documentModels
617 public DocumentWrapper<DocumentModelList> findDocs(
618 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
619 List<String> docTypes,
621 int pageSize, int pageNum, boolean computeTotal)
622 throws DocumentNotFoundException, TransactionException, DocumentException {
623 RepositoryInstance repoSession = null;
624 DocumentWrapper<DocumentModelList> wrapDoc = null;
627 repoSession = getRepositorySession(ctx);
628 wrapDoc = findDocs(ctx, repoSession, docTypes, whereClause, null,
629 pageSize, pageNum, computeTotal);
630 } catch (IllegalArgumentException iae) {
632 } catch (Exception e) {
633 if (logger.isDebugEnabled()) {
634 logger.debug("Caught exception ", e);
636 throw new DocumentException(e);
638 if (repoSession != null) {
639 releaseRepositorySession(ctx, repoSession);
643 if (logger.isWarnEnabled() == true) {
644 logger.warn("Returned DocumentModelList instance was created with a repository session that is now closed.");
651 * @see org.collectionspace.services.common.storage.StorageClient#get(org.collectionspace.services.common.context.ServiceContext, java.util.List, org.collectionspace.services.common.document.DocumentHandler)
654 public void get(ServiceContext ctx, List<String> csidList, DocumentHandler handler)
655 throws DocumentNotFoundException, TransactionException, DocumentException {
656 if (handler == null) {
657 throw new IllegalArgumentException(
658 "RepositoryJavaClient.getAll: handler is missing");
661 RepositoryInstance repoSession = null;
663 handler.prepare(Action.GET_ALL);
664 repoSession = getRepositorySession(ctx);
665 DocumentModelList docModelList = new DocumentModelListImpl();
666 //FIXME: Should be using NuxeoUtils.createPathRef for security reasons
667 for (String csid : csidList) {
668 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
669 DocumentModel docModel = repoSession.getDocument(docRef);
670 docModelList.add(docModel);
673 //set reposession to handle the document
674 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
675 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docModelList);
676 handler.handle(Action.GET_ALL, wrapDoc);
677 handler.complete(Action.GET_ALL, wrapDoc);
678 } catch (DocumentException de) {
680 } catch (Exception e) {
681 if (logger.isDebugEnabled()) {
682 logger.debug("Caught exception ", e);
684 throw new DocumentException(e);
686 if (repoSession != null) {
687 releaseRepositorySession(ctx, repoSession);
693 * getAll get all documents for an entity entity service from the Nuxeo
696 * @param ctx service context under which this method is invoked
698 * should be used by the caller to provide and transform the
700 * @throws DocumentNotFoundException
701 * @throws TransactionException
702 * @throws DocumentException
705 public void getAll(ServiceContext ctx, DocumentHandler handler)
706 throws DocumentNotFoundException, TransactionException, DocumentException {
707 if (handler == null) {
708 throw new IllegalArgumentException(
709 "RepositoryJavaClient.getAll: handler is missing");
711 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
712 if (nuxeoWspaceId == null) {
713 throw new DocumentNotFoundException(
714 "Unable to find workspace for service "
715 + ctx.getServiceName()
716 + " check if the workspace exists in the Nuxeo repository.");
719 RepositoryInstance repoSession = null;
721 handler.prepare(Action.GET_ALL);
722 repoSession = getRepositorySession(ctx);
723 DocumentRef wsDocRef = new IdRef(nuxeoWspaceId);
724 DocumentModelList docList = repoSession.getChildren(wsDocRef);
725 //set reposession to handle the document
726 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
727 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
728 handler.handle(Action.GET_ALL, wrapDoc);
729 handler.complete(Action.GET_ALL, wrapDoc);
730 } catch (DocumentException de) {
732 } catch (Exception e) {
733 if (logger.isDebugEnabled()) {
734 logger.debug("Caught exception ", e);
736 throw new DocumentException(e);
738 if (repoSession != null) {
739 releaseRepositorySession(ctx, repoSession);
744 private boolean isClauseEmpty(String theString) {
745 boolean result = true;
746 if (theString != null && !theString.isEmpty()) {
752 public DocumentWrapper<DocumentModel> getDocFromCsid(
753 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
754 RepositoryInstance repoSession,
757 DocumentWrapper<DocumentModel> result = null;
759 result = new DocumentWrapperImpl(NuxeoUtils.getDocFromCsid(ctx, repoSession, csid));
765 * A method to find a CollectionSpace document (of any type) given just a service context and
766 * its CSID. A search across *all* service workspaces (within a given tenant context) is performed to find
769 * This query searches Nuxeo's Hierarchy table where our CSIDs are stored in the "name" column.
772 public DocumentWrapper<DocumentModel> getDocFromCsid(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
775 DocumentWrapper<DocumentModel> result = null;
776 RepositoryInstance repoSession = null;
778 repoSession = getRepositorySession(ctx);
779 result = getDocFromCsid(ctx, repoSession, csid);
781 if (repoSession != null) {
782 releaseRepositorySession(ctx, repoSession);
786 if (logger.isWarnEnabled() == true) {
787 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
794 * Returns a URI value for a document in the Nuxeo repository
795 * @param wrappedDoc a wrapped documentModel
796 * @throws ClientException
797 * @return a document URI
800 public String getDocURI(DocumentWrapper<DocumentModel> wrappedDoc) throws ClientException {
801 DocumentModel docModel = wrappedDoc.getWrappedObject();
802 String uri = (String)docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
803 CollectionSpaceClient.COLLECTIONSPACE_CORE_URI);
808 * See CSPACE-5036 - How to make CMISQL queries from Nuxeo
810 private IterableQueryResult makeCMISQLQuery(RepositoryInstance repoSession, String query, QueryContext queryContext) {
811 IterableQueryResult result = null;
813 // the NuxeoRepository should be constructed only once, then cached
814 // (its construction is expensive)
816 NuxeoRepository repo = new NuxeoRepository(
817 repoSession.getRepositoryName(), repoSession
818 .getRootDocument().getId());
819 logger.debug("Repository ID:" + repo.getId() + " Root folder:"
820 + repo.getRootFolderId());
822 CallContextImpl callContext = new CallContextImpl(
823 CallContext.BINDING_LOCAL, repo.getId(), false);
824 callContext.put(CallContext.USERNAME, repoSession.getPrincipal()
826 NuxeoCmisService cmisService = new NuxeoCmisService(repo,
827 callContext, repoSession);
829 result = repoSession.queryAndFetch(query, "CMISQL", cmisService);
830 } catch (ClientException e) {
831 // TODO Auto-generated catch block
832 logger.error("Encounter trouble making the following CMIS query: " + query, e);
839 * getFiltered get all documents for an entity service from the Document repository,
840 * given filter parameters specified by the handler.
841 * @param ctx service context under which this method is invoked
842 * @param handler should be used by the caller to provide and transform the document
843 * @throws DocumentNotFoundException if workspace not found
844 * @throws TransactionException
845 * @throws DocumentException
848 public void getFiltered(ServiceContext ctx, DocumentHandler handler)
849 throws DocumentNotFoundException, TransactionException, DocumentException {
851 DocumentFilter filter = handler.getDocumentFilter();
852 String oldOrderBy = filter.getOrderByClause();
853 if (isClauseEmpty(oldOrderBy) == true){
854 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
856 QueryContext queryContext = new QueryContext(ctx, handler);
858 RepositoryInstance repoSession = null;
860 handler.prepare(Action.GET_ALL);
861 repoSession = getRepositorySession(ctx); //Keeps a refcount here for the repository session so you need to release this when finished
863 DocumentModelList docList = null;
864 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
866 if (logger.isDebugEnabled()) {
867 logger.debug("Executing NXQL query: " + query.toString());
870 // If we have limit and/or offset, then pass true to get totalSize
871 // in returned DocumentModelList.
872 Profiler profiler = new Profiler(this, 2);
873 profiler.log("Executing NXQL query: " + query.toString());
875 if (handler.isJDBCQuery() == true) {
876 docList = getFilteredJDBC(repoSession, ctx, handler, queryContext);
877 } else if (handler.isCMISQuery() == true) {
878 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext); //FIXME: REM - Need to deal with paging info in CMIS query
879 } else if ((queryContext.getDocFilter().getOffset() > 0) || (queryContext.getDocFilter().getPageSize() > 0)) {
880 docList = repoSession.query(query, null,
881 queryContext.getDocFilter().getPageSize(), queryContext.getDocFilter().getOffset(), true);
883 docList = repoSession.query(query);
887 //set repoSession to handle the document
888 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
889 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
890 handler.handle(Action.GET_ALL, wrapDoc);
891 handler.complete(Action.GET_ALL, wrapDoc);
892 } catch (DocumentException de) {
894 } catch (Exception e) {
895 if (logger.isDebugEnabled()) {
896 logger.debug("Caught exception ", e);
898 throw new DocumentException(e);
900 if (repoSession != null) {
901 releaseRepositorySession(ctx, repoSession);
906 private DocumentModelList getFilteredJDBC(RepositoryInstance repoSession, ServiceContext ctx, DocumentHandler handler, QueryContext queryContext)
908 DocumentModelList result = new DocumentModelListImpl();
910 String dataSourceName = JDBCTools.NUXEO_DATASOURCE_NAME;
911 String repositoryName = ctx.getRepositoryName();
912 Connection connection = JDBCTools.getConnection(dataSourceName, repositoryName);
914 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
915 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
917 // FIXME: Replace this placeholder with an appropriate per-authority value
918 // obtained from the relevant document handler
919 String termInfoGroupTable = "loctermgroup";
921 // FIXME: Replace this placeholder query with an actual query from CSPACE-5945
922 // FIXME: Consider using a prepared statement here
924 "SELECT termdisplayname FROM "
926 + " WHERE termdisplayname LIKE '" + partialTerm + "%'";
928 // Make sure autocommit is off. See:
929 // http://jdbc.postgresql.org/documentation/80/query.html#query-with-cursor
930 // http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html
931 connection.setAutoCommit(false);
933 // FIXME: Add exception handling and 'finally' blocks to ensure we close resources
934 // FIXME: Identify whether we can piggyback on existing JDBC method(s) in common.storage,
935 // and if so, add whatever additional functionality may be required to those method(s)
936 // FIXME: Add pagination handling
938 Statement st = connection.createStatement();
939 // Enable use of the cursor for pagination
941 List<String> docIds = new ArrayList<String>();
942 ResultSet rs = st.executeQuery(theQuery);
945 id = rs.getString("id");
946 if (Tools.notBlank(id)) {
952 // Close the statement.
955 // Get a list of document models, using the IDs obtained from the query
956 for (String docId : docIds) {
957 result.add(NuxeoUtils.getDocumentModel(repoSession, docId));
963 private DocumentModelList getFilteredCMIS(RepositoryInstance repoSession, ServiceContext ctx, DocumentHandler handler, QueryContext queryContext)
964 throws DocumentNotFoundException, DocumentException {
966 DocumentModelList result = new DocumentModelListImpl();
968 String query = handler.getCMISQuery(queryContext);
970 DocumentFilter docFilter = handler.getDocumentFilter();
971 int pageSize = docFilter.getPageSize();
972 int offset = docFilter.getOffset();
973 if (logger.isDebugEnabled()) {
974 logger.debug("Executing CMIS query: " + query.toString()
975 + "with pageSize: "+pageSize+" at offset: "+offset);
978 // If we have limit and/or offset, then pass true to get totalSize
979 // in returned DocumentModelList.
980 Profiler profiler = new Profiler(this, 2);
981 profiler.log("Executing CMIS query: " + query.toString());
984 IterableQueryResult queryResult = makeCMISQLQuery(repoSession, query, queryContext);
986 int totalSize = (int)queryResult.size();
987 ((DocumentModelListImpl)result).setTotalSize(totalSize);
988 // Skip the rows before our offset
990 queryResult.skipTo(offset);
993 for (Map<String, Serializable> row : queryResult) {
994 if (logger.isTraceEnabled()) {
995 logger.trace(" Hierarchy Table ID is:" + row.get(IQueryManager.CMIS_TARGET_NUXEO_ID)
996 + " nuxeo:pathSegment is: " + row.get(IQueryManager.CMIS_TARGET_NAME));
998 String nuxeoId = (String) row.get(IQueryManager.CMIS_TARGET_NUXEO_ID);
999 DocumentModel docModel = NuxeoUtils.getDocumentModel(repoSession, nuxeoId);
1000 result.add(docModel);
1002 if (nRows >= pageSize && pageSize != 0 ) { // A page size of zero means that they want all of them
1003 logger.debug("Got page full of items - quitting");
1008 queryResult.close();
1013 } catch (Exception e) {
1014 if (logger.isDebugEnabled()) {
1015 logger.debug("Caught exception ", e);
1017 throw new DocumentException(e);
1021 // Since we're not supporting paging yet for CMIS queries, we need to perform
1022 // a workaround for the paging information we return in our list of results
1025 if (result != null) {
1026 docFilter.setStartPage(0);
1027 if (totalSize > docFilter.getPageSize()) {
1028 docFilter.setPageSize(totalSize);
1029 ((DocumentModelListImpl)result).setTotalSize(totalSize);
1037 private String logException(Exception e, String msg) {
1038 String result = null;
1040 String exceptionMessage = e.getMessage();
1041 exceptionMessage = exceptionMessage != null ? exceptionMessage : "<No details provided>";
1042 result = msg = msg + ". Caught exception:" + exceptionMessage;
1044 if (logger.isTraceEnabled() == true) {
1045 logger.error(msg, e);
1054 * update given document in the Nuxeo repository
1056 * @param ctx service context under which this method is invoked
1060 * should be used by the caller to provide and transform the
1062 * @throws BadRequestException
1063 * @throws DocumentNotFoundException
1064 * @throws TransactionException if the transaction times out or otherwise cannot be successfully completed
1065 * @throws DocumentException
1068 public void update(ServiceContext ctx, String csid, DocumentHandler handler)
1069 throws BadRequestException, DocumentNotFoundException, TransactionException,
1071 if (handler == null) {
1072 throw new IllegalArgumentException(
1073 "RepositoryJavaClient.update: document handler is missing.");
1076 RepositoryInstance repoSession = null;
1078 handler.prepare(Action.UPDATE);
1079 repoSession = getRepositorySession(ctx);
1080 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
1081 DocumentModel doc = null;
1083 doc = repoSession.getDocument(docRef);
1084 } catch (ClientException ce) {
1085 String msg = logException(ce, "Could not find document to update with CSID=" + csid);
1086 throw new DocumentNotFoundException(msg, ce);
1088 // Check for a versioned document, and check In and Out before we proceed.
1089 if(((DocumentModelHandler) handler).supportsVersioning()) {
1090 /* Once we advance to 5.5 or later, we can add this.
1091 * See also https://jira.nuxeo.com/browse/NXP-8506
1092 if(!doc.isVersionable()) {
1093 throw new DocumentException("Configuration for: "
1094 +handler.getServiceContextPath()+" supports versioning, but Nuxeo config does not!");
1097 /* Force a version number - Not working. Apparently we need to configure the uid schema??
1098 if(doc.getProperty("uid","major_version") == null) {
1099 doc.setProperty("uid","major_version",1);
1101 if(doc.getProperty("uid","minor_version") == null) {
1102 doc.setProperty("uid","minor_version",0);
1105 doc.checkIn(VersioningOption.MINOR, null);
1110 // Set reposession to handle the document
1112 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1113 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
1114 handler.handle(Action.UPDATE, wrapDoc);
1115 repoSession.saveDocument(doc);
1117 handler.complete(Action.UPDATE, wrapDoc);
1118 } catch (BadRequestException bre) {
1120 } catch (DocumentException de) {
1122 } catch (WebApplicationException wae){
1124 } catch (Exception e) {
1125 if (logger.isDebugEnabled()) {
1126 logger.debug("Caught exception ", e);
1128 throw new DocumentException(e);
1130 if (repoSession != null) {
1131 releaseRepositorySession(ctx, repoSession);
1137 * Save a documentModel to the Nuxeo repository.
1138 * @param ctx service context under which this method is invoked
1139 * @param repoSession
1140 * @param docModel the document to save
1141 * @param fSaveSession if TRUE, will call CoreSession.save() to save accumulated changes.
1142 * @throws ClientException
1143 * @throws DocumentException
1145 public void saveDocWithoutHandlerProcessing(
1146 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1147 RepositoryInstance repoSession,
1148 DocumentModel docModel,
1149 boolean fSaveSession)
1150 throws ClientException, DocumentException {
1153 repoSession.saveDocument(docModel);
1157 } catch (ClientException ce) {
1159 } catch (Exception e) {
1160 if (logger.isDebugEnabled()) {
1161 logger.debug("Caught exception ", e);
1163 throw new DocumentException(e);
1169 * Save a list of documentModels to the Nuxeo repository.
1171 * @param ctx service context under which this method is invoked
1172 * @param repoSession a repository session
1173 * @param docModelList a list of document models
1174 * @param fSaveSession if TRUE, will call CoreSession.save() to save accumulated changes.
1175 * @throws ClientException
1176 * @throws DocumentException
1178 public void saveDocListWithoutHandlerProcessing(
1179 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1180 RepositoryInstance repoSession,
1181 DocumentModelList docList,
1182 boolean fSaveSession)
1183 throws ClientException, DocumentException {
1185 DocumentModel[] docModelArray = new DocumentModel[docList.size()];
1186 repoSession.saveDocuments(docList.toArray(docModelArray));
1190 } catch (ClientException ce) {
1192 } catch (Exception e) {
1193 logger.error("Caught exception ", e);
1194 throw new DocumentException(e);
1199 * delete a document from the Nuxeo repository
1200 * @param ctx service context under which this method is invoked
1203 * @throws DocumentException
1206 public void delete(ServiceContext ctx, String id, DocumentHandler handler) throws DocumentNotFoundException,
1207 DocumentException, TransactionException {
1209 throw new IllegalArgumentException(
1210 "delete(ctx, ix, handler): ctx is missing");
1212 if (handler == null) {
1213 throw new IllegalArgumentException(
1214 "delete(ctx, ix, handler): handler is missing");
1216 if (logger.isDebugEnabled()) {
1217 logger.debug("Deleting document with CSID=" + id);
1219 RepositoryInstance repoSession = null;
1221 handler.prepare(Action.DELETE);
1222 repoSession = getRepositorySession(ctx);
1223 DocumentWrapper<DocumentModel> wrapDoc = null;
1225 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
1226 wrapDoc = new DocumentWrapperImpl<DocumentModel>(repoSession.getDocument(docRef));
1227 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1228 handler.handle(Action.DELETE, wrapDoc);
1229 repoSession.removeDocument(docRef);
1230 } catch (ClientException ce) {
1231 String msg = logException(ce, "Could not find document to delete with CSID=" + id);
1232 throw new DocumentNotFoundException(msg, ce);
1235 handler.complete(Action.DELETE, wrapDoc);
1236 } catch (DocumentException de) {
1238 } catch (Exception e) {
1239 if (logger.isDebugEnabled()) {
1240 logger.debug("Caught exception ", e);
1242 throw new DocumentException(e);
1244 if (repoSession != null) {
1245 releaseRepositorySession(ctx, repoSession);
1251 * @see org.collectionspace.services.common.storage.StorageClient#delete(org.collectionspace.services.common.context.ServiceContext, java.lang.String, org.collectionspace.services.common.document.DocumentHandler)
1255 public void delete(@SuppressWarnings("rawtypes") ServiceContext ctx, String id)
1256 throws DocumentNotFoundException, DocumentException {
1257 throw new UnsupportedOperationException();
1258 // Use the other delete instead
1262 public Hashtable<String, String> retrieveWorkspaceIds(RepositoryDomainType repoDomain) throws Exception {
1263 return NuxeoConnectorEmbedded.getInstance().retrieveWorkspaceIds(repoDomain);
1267 public String createDomain(RepositoryDomainType repositoryDomain) throws Exception {
1268 RepositoryInstance repoSession = null;
1269 String domainId = null;
1272 // Open a connection to the domain's repo/db
1274 String repoName = repositoryDomain.getRepositoryName();
1275 repoSession = getRepositorySession(repoName); // domainName=storageName=repoName=databaseName
1277 // First create the top-level domain directory
1279 String domainName = repositoryDomain.getStorageName();
1280 DocumentRef parentDocRef = new PathRef("/");
1281 DocumentModel parentDoc = repoSession.getDocument(parentDocRef);
1282 DocumentModel domainDoc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1283 domainName, NUXEO_CORE_TYPE_DOMAIN);
1284 domainDoc.setPropertyValue("dc:title", domainName);
1285 domainDoc.setPropertyValue("dc:description", "A CollectionSpace domain "
1287 domainDoc = repoSession.createDocument(domainDoc);
1288 domainId = domainDoc.getId();
1291 // Next, create a "Workspaces" root directory to contain the workspace folders for the individual service documents
1293 DocumentModel workspacesRoot = repoSession.createDocumentModel(domainDoc.getPathAsString(),
1294 NuxeoUtils.Workspaces, NUXEO_CORE_TYPE_WORKSPACEROOT);
1295 workspacesRoot.setPropertyValue("dc:title", NuxeoUtils.Workspaces);
1296 workspacesRoot.setPropertyValue("dc:description", "A CollectionSpace workspaces directory for "
1297 + domainDoc.getPathAsString());
1298 workspacesRoot = repoSession.createDocument(workspacesRoot);
1299 String workspacesRootId = workspacesRoot.getId();
1302 if (logger.isDebugEnabled()) {
1303 logger.debug("Created tenant domain name=" + domainName
1304 + " id=" + domainId + " " +
1305 NuxeoUtils.Workspaces + " id=" + workspacesRootId);
1306 logger.debug("Path to Domain: "+domainDoc.getPathAsString());
1307 logger.debug("Path to Workspaces root: "+workspacesRoot.getPathAsString());
1309 } catch (Exception e) {
1310 if (logger.isDebugEnabled()) {
1311 logger.debug("Could not create tenant domain name=" + repositoryDomain.getStorageName() + " caught exception ", e);
1315 if (repoSession != null) {
1316 releaseRepositorySession(null, repoSession);
1324 public String getDomainId(RepositoryDomainType repositoryDomain) throws Exception {
1325 String domainId = null;
1326 RepositoryInstance repoSession = null;
1328 String repoName = repositoryDomain.getRepositoryName();
1329 String domainStorageName = repositoryDomain.getStorageName();
1330 if (domainStorageName != null && !domainStorageName.isEmpty()) {
1332 repoSession = getRepositorySession(repoName);
1333 DocumentRef docRef = new PathRef("/" + domainStorageName);
1334 DocumentModel domain = repoSession.getDocument(docRef);
1335 domainId = domain.getId();
1336 } catch (Exception e) {
1337 if (logger.isTraceEnabled()) {
1338 logger.trace("Caught exception ", e); // The document doesn't exist, this let's us know we need to create it
1340 //there is no way to identify if document does not exist due to
1341 //lack of typed exception for getDocument method
1344 if (repoSession != null) {
1345 releaseRepositorySession(null, repoSession);
1354 * Returns the workspaces root directory for a given domain.
1356 private DocumentModel getWorkspacesRoot(RepositoryInstance repoSession,
1357 String domainName) throws Exception {
1358 DocumentModel result = null;
1360 String domainPath = "/" + domainName;
1361 DocumentRef parentDocRef = new PathRef(domainPath);
1362 DocumentModelList domainChildrenList = repoSession.getChildren(
1364 Iterator<DocumentModel> witer = domainChildrenList.iterator();
1365 while (witer.hasNext()) {
1366 DocumentModel childNode = witer.next();
1367 if (NuxeoUtils.Workspaces.equalsIgnoreCase(childNode.getName())) {
1369 logger.trace("Found workspaces directory at: " + result.getPathAsString());
1374 if (result == null) {
1375 throw new ClientException("Could not find workspace root directory in: "
1383 * @see org.collectionspace.services.common.repository.RepositoryClient#createWorkspace(java.lang.String, java.lang.String)
1386 public String createWorkspace(RepositoryDomainType repositoryDomain, String workspaceName) throws Exception {
1387 RepositoryInstance repoSession = null;
1388 String workspaceId = null;
1390 String repoName = repositoryDomain.getRepositoryName();
1391 repoSession = getRepositorySession(repoName);
1393 String domainStorageName = repositoryDomain.getStorageName();
1394 DocumentModel parentDoc = getWorkspacesRoot(repoSession, domainStorageName);
1395 if (logger.isTraceEnabled()) {
1396 for (String facet : parentDoc.getFacets()) {
1397 logger.trace("Facet: " + facet);
1401 DocumentModel doc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1402 workspaceName, NuxeoUtils.WORKSPACE_DOCUMENT_TYPE);
1403 doc.setPropertyValue("dc:title", workspaceName);
1404 doc.setPropertyValue("dc:description", "A CollectionSpace workspace for "
1406 doc = repoSession.createDocument(doc);
1407 workspaceId = doc.getId();
1409 if (logger.isDebugEnabled()) {
1410 logger.debug("Created workspace name=" + workspaceName
1411 + " id=" + workspaceId);
1413 } catch (Exception e) {
1414 if (logger.isDebugEnabled()) {
1415 logger.debug("createWorkspace caught exception ", e);
1419 if (repoSession != null) {
1420 releaseRepositorySession(null, repoSession);
1427 * @see org.collectionspace.services.common.repository.RepositoryClient#getWorkspaceId(java.lang.String, java.lang.String)
1431 public String getWorkspaceId(String tenantDomain, String workspaceName) throws Exception {
1432 String workspaceId = null;
1434 RepositoryInstance repoSession = null;
1436 repoSession = getRepositorySession((ServiceContext)null);
1437 DocumentRef docRef = new PathRef(
1439 + "/" + NuxeoUtils.Workspaces
1440 + "/" + workspaceName);
1441 DocumentModel workspace = repoSession.getDocument(docRef);
1442 workspaceId = workspace.getId();
1443 } catch (DocumentException de) {
1445 } catch (Exception e) {
1446 if (logger.isDebugEnabled()) {
1447 logger.debug("Caught exception ", e);
1449 throw new DocumentException(e);
1451 if (repoSession != null) {
1452 releaseRepositorySession(null, repoSession);
1459 public RepositoryInstance getRepositorySession(ServiceContext ctx) throws Exception {
1460 return getRepositorySession(ctx, ctx.getRepositoryName());
1463 public RepositoryInstance getRepositorySession(String repoName) throws Exception {
1464 return getRepositorySession(null, repoName);
1468 * Gets the repository session. - Package access only. If the 'ctx' param is null then the repo name must be non-mull and vice-versa
1470 * @return the repository session
1471 * @throws Exception the exception
1473 public RepositoryInstance getRepositorySession(ServiceContext ctx, String repoName) throws Exception {
1474 RepositoryInstance repoSession = null;
1476 Profiler profiler = new Profiler("getRepositorySession():", 2);
1479 // To get a connection to the Nuxeo repo, we need either a valid ServiceContext instance or a repository name
1482 repoName = ctx.getRepositoryName(); // Notice we are overriding the passed in 'repoName' since we have a valid service context passed in to us
1483 repoSession = (RepositoryInstance)ctx.getCurrentRepositorySession(); // Look to see if one exists in the context before creating one
1484 } else if (repoName == null || repoName.trim().isEmpty()) {
1485 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.");
1486 logger.error(errMsg);
1487 throw new Exception(errMsg);
1490 // 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
1491 // just the repo name
1493 if (repoSession == null) {
1494 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1495 repoSession = client.openRepository(repoName);
1497 if (logger.isDebugEnabled() == true) {
1498 logger.warn("Reusing the current context's repository session.");
1502 if (logger.isTraceEnabled()) {
1503 logger.trace("Testing call to getRepository() repository root: " + repoSession.getRootDocument());
1509 ctx.setCurrentRepositorySession(repoSession); // For reusing, save the repository session in the current service context
1516 * Release repository session. - Package access only.
1518 * @param repoSession the repo session
1520 public void releaseRepositorySession(ServiceContext ctx, RepositoryInstance repoSession) throws TransactionException {
1522 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1525 ctx.clearCurrentRepositorySession(); //clear the current context of the now closed repo session
1526 if (ctx.getCurrentRepositorySession() == null) {
1527 client.releaseRepository(repoSession); //release the repo session if the service context's ref count is zeo.
1530 client.releaseRepository(repoSession); //repo session was acquired without a service context
1532 } catch (TransactionRuntimeException tre) {
1533 TransactionException te = new TransactionException(tre);
1534 logger.error(te.getMessage(), tre); // Log the standard transaction exception message, plus an exception-specific stack trace
1536 } catch (Exception e) {
1537 logger.error("Could not close the repository session", e);
1538 // no need to throw this service specific exception
1543 public void doWorkflowTransition(ServiceContext ctx, String id,
1544 DocumentHandler handler, TransitionDef transitionDef)
1545 throws BadRequestException, DocumentNotFoundException,
1547 // 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