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";
104 public static final String JDBC_TABLE_NAME_PARAM = "TABLE_NAME";
107 * Instantiates a new repository java client impl.
109 public RepositoryJavaClientImpl() {
113 public void assertWorkflowState(ServiceContext ctx,
114 DocumentModel docModel) throws DocumentNotFoundException, ClientException {
115 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
116 if (queryParams != null) {
118 // Look for the workflow "delete" query param and see if we need to assert that the
119 // docModel is in a non-deleted workflow state.
121 String currentState = docModel.getCurrentLifeCycleState();
122 String includeDeletedStr = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_NONDELETED);
123 boolean includeDeleted = includeDeletedStr == null ? true : Boolean.parseBoolean(includeDeletedStr);
124 if (includeDeleted == false) {
126 // We don't wanted soft-deleted object, so throw an exception if this one is soft-deleted.
128 if (currentState.equalsIgnoreCase(WorkflowClient.WORKFLOWSTATE_DELETED)) {
129 String msg = "The GET assertion that docModel not be in 'deleted' workflow state failed.";
131 throw new DocumentNotFoundException(msg);
138 * create document in the Nuxeo repository
140 * @param ctx service context under which this method is invoked
141 * @param handler should be used by the caller to provide and transform the
143 * @return id in repository of the newly created document
144 * @throws BadRequestException
145 * @throws TransactionException
146 * @throws DocumentException
149 public String create(ServiceContext ctx,
150 DocumentHandler handler) throws BadRequestException,
151 TransactionException, DocumentException {
153 String docType = NuxeoUtils.getTenantQualifiedDocType(ctx); //ctx.getDocumentType();
154 if (docType == null) {
155 throw new IllegalArgumentException(
156 "RepositoryJavaClient.create: docType is missing");
159 if (handler == null) {
160 throw new IllegalArgumentException(
161 "RepositoryJavaClient.create: handler is missing");
163 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
164 if (nuxeoWspaceId == null) {
165 throw new DocumentNotFoundException(
166 "Unable to find workspace for service " + ctx.getServiceName()
167 + " check if the workspace exists in the Nuxeo repository");
170 RepositoryInstance repoSession = null;
172 handler.prepare(Action.CREATE);
173 repoSession = getRepositorySession(ctx);
174 DocumentRef nuxeoWspace = new IdRef(nuxeoWspaceId);
175 DocumentModel wspaceDoc = repoSession.getDocument(nuxeoWspace);
176 String wspacePath = wspaceDoc.getPathAsString();
177 //give our own ID so PathRef could be constructed later on
178 String id = IdUtils.generateId(UUID.randomUUID().toString());
179 // create document model
180 DocumentModel doc = repoSession.createDocumentModel(wspacePath, id, docType);
181 /* Check for a versioned document, and check In and Out before we proceed.
182 * This does not work as we do not have the uid schema on our docs.
183 if(((DocumentModelHandler) handler).supportsVersioning()) {
184 doc.setProperty("uid","major_version",1);
185 doc.setProperty("uid","minor_version",0);
188 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
189 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
190 handler.handle(Action.CREATE, wrapDoc);
191 // create document with documentmodel
192 doc = repoSession.createDocument(doc);
194 // TODO for sub-docs need to call into the handler to let it deal with subitems. Pass in the id,
195 // and assume the handler has the state it needs (doc fragments).
196 handler.complete(Action.CREATE, wrapDoc);
198 } catch (BadRequestException bre) {
200 } catch (Exception e) {
201 logger.error("Caught exception ", e);
202 throw new DocumentException(e);
204 if (repoSession != null) {
205 releaseRepositorySession(ctx, repoSession);
212 * get document from the Nuxeo repository
214 * @param ctx service context under which this method is invoked
215 * @param id of the document to retrieve
216 * @param handler should be used by the caller to provide and transform the
218 * @throws DocumentNotFoundException if the document cannot be found in the
220 * @throws TransactionException
221 * @throws DocumentException
224 public void get(ServiceContext ctx, String id, DocumentHandler handler)
225 throws DocumentNotFoundException, TransactionException, DocumentException {
227 if (handler == null) {
228 throw new IllegalArgumentException(
229 "RepositoryJavaClient.get: handler is missing");
232 RepositoryInstance repoSession = null;
234 handler.prepare(Action.GET);
235 repoSession = getRepositorySession(ctx);
236 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
237 DocumentModel docModel = null;
239 docModel = repoSession.getDocument(docRef);
240 assertWorkflowState(ctx, docModel);
241 } catch (ClientException ce) {
242 String msg = logException(ce, "Could not find document with CSID=" + id);
243 throw new DocumentNotFoundException(msg, ce);
246 // Set repository session to handle the document
248 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
249 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(docModel);
250 handler.handle(Action.GET, wrapDoc);
251 handler.complete(Action.GET, wrapDoc);
252 } catch (IllegalArgumentException iae) {
254 } catch (DocumentException de) {
256 } catch (Exception e) {
257 if (logger.isDebugEnabled()) {
258 logger.debug("Caught exception ", e);
260 throw new DocumentException(e);
262 if (repoSession != null) {
263 releaseRepositorySession(ctx, repoSession);
269 * get a document from the Nuxeo repository, using the docFilter params.
271 * @param ctx service context under which this method is invoked
272 * @param handler should be used by the caller to provide and transform the
273 * document. Handler must have a docFilter set to return a single item.
274 * @throws DocumentNotFoundException if the document cannot be found in the
276 * @throws TransactionException
277 * @throws DocumentException
280 public void get(ServiceContext ctx, DocumentHandler handler)
281 throws DocumentNotFoundException, TransactionException, DocumentException {
282 QueryContext queryContext = new QueryContext(ctx, handler);
283 RepositoryInstance repoSession = null;
286 handler.prepare(Action.GET);
287 repoSession = getRepositorySession(ctx);
289 DocumentModelList docList = null;
290 // force limit to 1, and ignore totalSize
291 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
292 docList = repoSession.query(query, null, 1, 0, false);
293 if (docList.size() != 1) {
294 throw new DocumentNotFoundException("No document found matching filter params: " + query);
296 DocumentModel doc = docList.get(0);
298 if (logger.isDebugEnabled()) {
299 logger.debug("Executed NXQL query: " + query);
302 //set reposession to handle the document
303 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
304 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
305 handler.handle(Action.GET, wrapDoc);
306 handler.complete(Action.GET, wrapDoc);
307 } catch (IllegalArgumentException iae) {
309 } catch (DocumentException de) {
311 } catch (Exception e) {
312 if (logger.isDebugEnabled()) {
313 logger.debug("Caught exception ", e);
315 throw new DocumentException(e);
317 if (repoSession != null) {
318 releaseRepositorySession(ctx, repoSession);
323 public DocumentWrapper<DocumentModel> getDoc(
324 RepositoryInstance repoSession,
325 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
326 String csid) throws DocumentNotFoundException, DocumentException {
327 DocumentWrapper<DocumentModel> wrapDoc = null;
330 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
331 DocumentModel doc = null;
333 doc = repoSession.getDocument(docRef);
334 } catch (ClientException ce) {
335 String msg = logException(ce, "Could not find document with CSID=" + csid);
336 throw new DocumentNotFoundException(msg, ce);
338 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
339 } catch (IllegalArgumentException iae) {
341 } catch (DocumentException de) {
349 * Get wrapped documentModel from the Nuxeo repository. The search is
350 * restricted to the workspace of the current context.
352 * @param ctx service context under which this method is invoked
353 * @param csid of the document to retrieve
354 * @throws DocumentNotFoundException
355 * @throws TransactionException
356 * @throws DocumentException
357 * @return a wrapped documentModel
360 public DocumentWrapper<DocumentModel> getDoc(
361 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
362 String csid) throws DocumentNotFoundException, TransactionException, DocumentException {
363 RepositoryInstance repoSession = null;
364 DocumentWrapper<DocumentModel> wrapDoc = null;
367 // Open a new repository session
368 repoSession = getRepositorySession(ctx);
369 wrapDoc = getDoc(repoSession, ctx, csid);
370 } catch (IllegalArgumentException iae) {
372 } catch (DocumentException de) {
374 } catch (Exception e) {
375 if (logger.isDebugEnabled()) {
376 logger.debug("Caught exception ", e);
378 throw new DocumentException(e);
380 if (repoSession != null) {
381 releaseRepositorySession(ctx, repoSession);
385 if (logger.isWarnEnabled() == true) {
386 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
391 public DocumentWrapper<DocumentModel> findDoc(
392 RepositoryInstance repoSession,
393 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
395 throws DocumentNotFoundException, DocumentException {
396 DocumentWrapper<DocumentModel> wrapDoc = null;
399 QueryContext queryContext = new QueryContext(ctx, whereClause);
400 DocumentModelList docList = null;
401 // force limit to 1, and ignore totalSize
402 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
403 docList = repoSession.query(query,
408 if (docList.size() != 1) {
409 if (logger.isDebugEnabled()) {
410 logger.debug("findDoc: Query found: " + docList.size() + " items.");
411 logger.debug(" Query: " + query);
413 throw new DocumentNotFoundException("No document found matching filter params: " + query);
415 DocumentModel doc = docList.get(0);
416 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
417 } catch (IllegalArgumentException iae) {
419 } catch (DocumentException de) {
421 } catch (Exception e) {
422 if (logger.isDebugEnabled()) {
423 logger.debug("Caught exception ", e);
425 throw new DocumentException(e);
432 * find wrapped documentModel from the Nuxeo repository
434 * @param ctx service context under which this method is invoked
435 * @param whereClause where NXQL where clause to get the document
436 * @throws DocumentNotFoundException
437 * @throws TransactionException
438 * @throws DocumentException
439 * @return a wrapped documentModel retrieved by the repository query
442 public DocumentWrapper<DocumentModel> findDoc(
443 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
445 throws DocumentNotFoundException, TransactionException, DocumentException {
446 RepositoryInstance repoSession = null;
447 DocumentWrapper<DocumentModel> wrapDoc = null;
450 repoSession = getRepositorySession(ctx);
451 wrapDoc = findDoc(repoSession, ctx, whereClause);
452 } catch (Exception e) {
453 throw new DocumentException("Unable to create a Nuxeo repository session.", e);
455 if (repoSession != null) {
456 releaseRepositorySession(ctx, repoSession);
460 if (logger.isWarnEnabled() == true) {
461 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
468 * find doc and return CSID from the Nuxeo repository
471 * @param ctx service context under which this method is invoked
472 * @param whereClause where NXQL where clause to get the document
473 * @throws DocumentNotFoundException
474 * @throws TransactionException
475 * @throws DocumentException
476 * @return the CollectionSpace ID (CSID) of the requested document
479 public String findDocCSID(RepositoryInstance repoSession,
480 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String whereClause)
481 throws DocumentNotFoundException, TransactionException, DocumentException {
483 boolean releaseSession = false;
485 if (repoSession == null) {
486 repoSession = this.getRepositorySession(ctx);
487 releaseSession = true;
489 DocumentWrapper<DocumentModel> wrapDoc = findDoc(repoSession, ctx, whereClause);
490 DocumentModel docModel = wrapDoc.getWrappedObject();
491 csid = NuxeoUtils.getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
492 } catch (DocumentNotFoundException dnfe) {
494 } catch (IllegalArgumentException iae) {
496 } catch (DocumentException de) {
498 } catch (Exception e) {
499 if (logger.isDebugEnabled()) {
500 logger.debug("Caught exception ", e);
502 throw new DocumentException(e);
504 if (releaseSession && (repoSession != null)) {
505 this.releaseRepositorySession(ctx, repoSession);
511 public DocumentWrapper<DocumentModelList> findDocs(
512 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
513 RepositoryInstance repoSession,
514 List<String> docTypes,
516 String orderByClause,
519 boolean computeTotal)
520 throws DocumentNotFoundException, DocumentException {
521 DocumentWrapper<DocumentModelList> wrapDoc = null;
524 if (docTypes == null || docTypes.size() < 1) {
525 throw new DocumentNotFoundException(
526 "The findDocs() method must specify at least one DocumentType.");
528 DocumentModelList docList = null;
529 QueryContext queryContext = new QueryContext(ctx, whereClause, orderByClause);
530 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
531 if (logger.isDebugEnabled()) {
532 logger.debug("findDocs() NXQL: " + query);
534 docList = repoSession.query(query, null, pageSize, pageSize * pageNum, computeTotal);
535 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
536 } catch (IllegalArgumentException iae) {
538 } catch (Exception e) {
539 if (logger.isDebugEnabled()) {
540 logger.debug("Caught exception ", e);
542 throw new DocumentException(e);
548 protected static String buildInListForDocTypes(List<String> docTypes) {
549 StringBuilder sb = new StringBuilder();
551 boolean first = true;
552 for (String docType : docTypes) {
563 return sb.toString();
566 public DocumentWrapper<DocumentModelList> findDocs(
567 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
568 DocumentHandler handler,
569 RepositoryInstance repoSession,
570 List<String> docTypes)
571 throws DocumentNotFoundException, DocumentException {
572 DocumentWrapper<DocumentModelList> wrapDoc = null;
574 DocumentFilter filter = handler.getDocumentFilter();
575 String oldOrderBy = filter.getOrderByClause();
576 if (isClauseEmpty(oldOrderBy) == true) {
577 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
579 QueryContext queryContext = new QueryContext(ctx, handler);
582 if (docTypes == null || docTypes.size() < 1) {
583 throw new DocumentNotFoundException(
584 "The findDocs() method must specify at least one DocumentType.");
586 DocumentModelList docList = null;
587 if (handler.isCMISQuery() == true) {
588 String inList = buildInListForDocTypes(docTypes);
589 ctx.getQueryParams().add(IQueryManager.SEARCH_RELATED_MATCH_OBJ_DOCTYPES, inList);
590 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
592 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
593 if (logger.isDebugEnabled()) {
594 logger.debug("findDocs() NXQL: " + query);
596 docList = repoSession.query(query, null, filter.getPageSize(), filter.getOffset(), true);
598 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
599 } catch (IllegalArgumentException iae) {
601 } catch (Exception e) {
602 if (logger.isDebugEnabled()) {
603 logger.debug("Caught exception ", e);
605 throw new DocumentException(e);
612 * Find a list of documentModels from the Nuxeo repository
614 * @param docTypes a list of DocType names to match
615 * @param whereClause where the clause to qualify on
616 * @throws DocumentNotFoundException
617 * @throws TransactionException
618 * @throws DocumentException
619 * @return a list of documentModels
622 public DocumentWrapper<DocumentModelList> findDocs(
623 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
624 List<String> docTypes,
626 int pageSize, int pageNum, boolean computeTotal)
627 throws DocumentNotFoundException, TransactionException, DocumentException {
628 RepositoryInstance repoSession = null;
629 DocumentWrapper<DocumentModelList> wrapDoc = null;
632 repoSession = getRepositorySession(ctx);
633 wrapDoc = findDocs(ctx, repoSession, docTypes, whereClause, null,
634 pageSize, pageNum, computeTotal);
635 } catch (IllegalArgumentException iae) {
637 } catch (Exception e) {
638 if (logger.isDebugEnabled()) {
639 logger.debug("Caught exception ", e);
641 throw new DocumentException(e);
643 if (repoSession != null) {
644 releaseRepositorySession(ctx, repoSession);
648 if (logger.isWarnEnabled() == true) {
649 logger.warn("Returned DocumentModelList instance was created with a repository session that is now closed.");
656 * @see org.collectionspace.services.common.storage.StorageClient#get(org.collectionspace.services.common.context.ServiceContext, java.util.List, org.collectionspace.services.common.document.DocumentHandler)
659 public void get(ServiceContext ctx, List<String> csidList, DocumentHandler handler)
660 throws DocumentNotFoundException, TransactionException, DocumentException {
661 if (handler == null) {
662 throw new IllegalArgumentException(
663 "RepositoryJavaClient.getAll: handler is missing");
666 RepositoryInstance repoSession = null;
668 handler.prepare(Action.GET_ALL);
669 repoSession = getRepositorySession(ctx);
670 DocumentModelList docModelList = new DocumentModelListImpl();
671 //FIXME: Should be using NuxeoUtils.createPathRef for security reasons
672 for (String csid : csidList) {
673 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
674 DocumentModel docModel = repoSession.getDocument(docRef);
675 docModelList.add(docModel);
678 //set reposession to handle the document
679 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
680 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docModelList);
681 handler.handle(Action.GET_ALL, wrapDoc);
682 handler.complete(Action.GET_ALL, wrapDoc);
683 } catch (DocumentException de) {
685 } catch (Exception e) {
686 if (logger.isDebugEnabled()) {
687 logger.debug("Caught exception ", e);
689 throw new DocumentException(e);
691 if (repoSession != null) {
692 releaseRepositorySession(ctx, repoSession);
698 * getAll get all documents for an entity entity service from the Nuxeo
701 * @param ctx service context under which this method is invoked
702 * @param handler should be used by the caller to provide and transform the
704 * @throws DocumentNotFoundException
705 * @throws TransactionException
706 * @throws DocumentException
709 public void getAll(ServiceContext ctx, DocumentHandler handler)
710 throws DocumentNotFoundException, TransactionException, DocumentException {
711 if (handler == null) {
712 throw new IllegalArgumentException(
713 "RepositoryJavaClient.getAll: handler is missing");
715 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
716 if (nuxeoWspaceId == null) {
717 throw new DocumentNotFoundException(
718 "Unable to find workspace for service "
719 + ctx.getServiceName()
720 + " check if the workspace exists in the Nuxeo repository.");
723 RepositoryInstance repoSession = null;
725 handler.prepare(Action.GET_ALL);
726 repoSession = getRepositorySession(ctx);
727 DocumentRef wsDocRef = new IdRef(nuxeoWspaceId);
728 DocumentModelList docList = repoSession.getChildren(wsDocRef);
729 //set reposession to handle the document
730 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
731 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
732 handler.handle(Action.GET_ALL, wrapDoc);
733 handler.complete(Action.GET_ALL, wrapDoc);
734 } catch (DocumentException de) {
736 } catch (Exception e) {
737 if (logger.isDebugEnabled()) {
738 logger.debug("Caught exception ", e);
740 throw new DocumentException(e);
742 if (repoSession != null) {
743 releaseRepositorySession(ctx, repoSession);
748 private boolean isClauseEmpty(String theString) {
749 boolean result = true;
750 if (theString != null && !theString.isEmpty()) {
756 public DocumentWrapper<DocumentModel> getDocFromCsid(
757 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
758 RepositoryInstance repoSession,
761 DocumentWrapper<DocumentModel> result = null;
763 result = new DocumentWrapperImpl(NuxeoUtils.getDocFromCsid(ctx, repoSession, csid));
769 * A method to find a CollectionSpace document (of any type) given just a service context and
770 * its CSID. A search across *all* service workspaces (within a given tenant context) is performed to find
773 * This query searches Nuxeo's Hierarchy table where our CSIDs are stored in the "name" column.
776 public DocumentWrapper<DocumentModel> getDocFromCsid(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
779 DocumentWrapper<DocumentModel> result = null;
780 RepositoryInstance repoSession = null;
782 repoSession = getRepositorySession(ctx);
783 result = getDocFromCsid(ctx, repoSession, csid);
785 if (repoSession != null) {
786 releaseRepositorySession(ctx, repoSession);
790 if (logger.isWarnEnabled() == true) {
791 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
798 * Returns a URI value for a document in the Nuxeo repository
800 * @param wrappedDoc a wrapped documentModel
801 * @throws ClientException
802 * @return a document URI
805 public String getDocURI(DocumentWrapper<DocumentModel> wrappedDoc) throws ClientException {
806 DocumentModel docModel = wrappedDoc.getWrappedObject();
807 String uri = (String) docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
808 CollectionSpaceClient.COLLECTIONSPACE_CORE_URI);
813 * See CSPACE-5036 - How to make CMISQL queries from Nuxeo
815 private IterableQueryResult makeCMISQLQuery(RepositoryInstance repoSession, String query, QueryContext queryContext) {
816 IterableQueryResult result = null;
818 // the NuxeoRepository should be constructed only once, then cached
819 // (its construction is expensive)
821 NuxeoRepository repo = new NuxeoRepository(
822 repoSession.getRepositoryName(), repoSession
823 .getRootDocument().getId());
824 logger.debug("Repository ID:" + repo.getId() + " Root folder:"
825 + repo.getRootFolderId());
827 CallContextImpl callContext = new CallContextImpl(
828 CallContext.BINDING_LOCAL, repo.getId(), false);
829 callContext.put(CallContext.USERNAME, repoSession.getPrincipal()
831 NuxeoCmisService cmisService = new NuxeoCmisService(repo,
832 callContext, repoSession);
834 result = repoSession.queryAndFetch(query, "CMISQL", cmisService);
835 } catch (ClientException e) {
836 // TODO Auto-generated catch block
837 logger.error("Encounter trouble making the following CMIS query: " + query, e);
844 * getFiltered get all documents for an entity service from the Document
845 * repository, given filter parameters specified by the handler.
847 * @param ctx service context under which this method is invoked
848 * @param handler should be used by the caller to provide and transform the
850 * @throws DocumentNotFoundException if workspace not found
851 * @throws TransactionException
852 * @throws DocumentException
855 public void getFiltered(ServiceContext ctx, DocumentHandler handler)
856 throws DocumentNotFoundException, TransactionException, DocumentException {
858 DocumentFilter filter = handler.getDocumentFilter();
859 String oldOrderBy = filter.getOrderByClause();
860 if (isClauseEmpty(oldOrderBy) == true) {
861 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
863 QueryContext queryContext = new QueryContext(ctx, handler);
865 RepositoryInstance repoSession = null;
867 handler.prepare(Action.GET_ALL);
868 repoSession = getRepositorySession(ctx); //Keeps a refcount here for the repository session so you need to release this when finished
870 DocumentModelList docList = null;
871 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
873 if (logger.isDebugEnabled()) {
874 logger.debug("Executing NXQL query: " + query.toString());
877 // If we have limit and/or offset, then pass true to get totalSize
878 // in returned DocumentModelList.
879 Profiler profiler = new Profiler(this, 2);
880 profiler.log("Executing NXQL query: " + query.toString());
882 if (handler.isJDBCQuery() == true) {
883 docList = getFilteredJDBC(repoSession, ctx, handler, queryContext);
884 } else if (handler.isCMISQuery() == true) {
885 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext); //FIXME: REM - Need to deal with paging info in CMIS query
886 } else if ((queryContext.getDocFilter().getOffset() > 0) || (queryContext.getDocFilter().getPageSize() > 0)) {
887 docList = repoSession.query(query, null,
888 queryContext.getDocFilter().getPageSize(), queryContext.getDocFilter().getOffset(), true);
890 docList = repoSession.query(query);
894 //set repoSession to handle the document
895 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
896 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
897 handler.handle(Action.GET_ALL, wrapDoc);
898 handler.complete(Action.GET_ALL, wrapDoc);
899 } catch (DocumentException de) {
901 } catch (Exception e) {
902 if (logger.isDebugEnabled()) {
903 logger.debug("Caught exception ", e);
905 throw new DocumentException(e);
907 if (repoSession != null) {
908 releaseRepositorySession(ctx, repoSession);
913 private DocumentModelList getFilteredJDBC(RepositoryInstance repoSession, ServiceContext ctx,
914 DocumentHandler handler, QueryContext queryContext) throws Exception {
915 DocumentModelList result = new DocumentModelListImpl();
917 String dataSourceName = JDBCTools.NUXEO_DATASOURCE_NAME;
918 String repositoryName = ctx.getRepositoryName();
920 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
921 final String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
923 // FIXME: Look into whether this performance concern specific to query
924 // planning with prepared statements may be affecting us:
925 // http://stackoverflow.com/a/678452
926 // If that proves to be a significant concern, we can instead use
927 // JDBCTools.executeQuery(), and attempt to sanitize user input
928 // against potential SQL injection attacks.
930 // FIXME: Replace this placeholder query with an actual query resulting
931 // from CSPACE-5945 work
933 "SELECT DISTINCT hierarchy.id as id"
935 + " LEFT JOIN hierarchy h1 "
936 + " ON h1.parentid = hierarchy.id "
937 + " LEFT JOIN " + handler.getJDBCQueryParams().get(JDBC_TABLE_NAME_PARAM) + " tg "
938 + " ON tg.id = h1.id "
939 + " LEFT JOIN " + handler.getServiceContext().getCommonPartLabel() + " commonschema "
940 + " ON commonschema.id = hierarchy.id "
942 + " ON misc.id = hierarchy.id "
943 + " WHERE (tg.termdisplayname ILIKE ?) "
944 + " AND (misc.lifecyclestate <> 'deleted') ";
947 // FIXME: Need to add a WHERE clause restriction on inAuthority
949 // FIXME: Need to handle the '_ALL_' case for inAuthority by removing
950 // that restriction (see AuthorityResource.getAuthorityItemList())
953 Pseudo-code-like continuation
954 String inAuthority = handler.getJDBCQueryParams().get(IN_AUTHORITY_PARAM);
955 if (Tools.notBlank(inAuthority) {
956 if (!inAuthority.equals.(AuthorityResource.PARENT_WILDCARD)) {
957 sql = sql + " AND (commonschema.inauthority = '" + handler.getInAuthorityValue() + "') ";
962 // FIXME: We might also consider skipping the JOIN on the common schema table
963 // in the '_ALL_' case, where we are not restricting by inAuthority value
965 List<String> params = new ArrayList<>();
966 params.add(partialTerm + JDBCTools.SQL_WILDCARD);
967 PreparedStatementSimpleBuilder jdbcFilterQueryBuilder = new PreparedStatementSimpleBuilder(sql, params);
969 List<String> docIds = new ArrayList<>();
970 try (CachedRowSet crs = JDBCTools.executePreparedQuery(jdbcFilterQueryBuilder,
971 dataSourceName, repositoryName, sql)) {
973 // If the response to the query is null or contains zero rows,
974 // return an empty list of document models
979 if (crs.getRow() == 0) {
980 return result; // empty list of document models
983 // Otherwise, get the document IDs from the results of the query
987 id = crs.getString(1);
988 if (Tools.notBlank(id)) {
992 } catch (SQLException sqle) {
993 logger.warn("Could not obtain document IDs via SQL query '" + sql + "': " + sqle.getMessage());
994 return result; // return an empty list of document models
997 // Get a list of document models, using the IDs obtained from the query
998 for (String docId : docIds) {
999 result.add(NuxeoUtils.getDocumentModel(repoSession, docId));
1006 private DocumentModelList getFilteredCMIS(RepositoryInstance repoSession, ServiceContext ctx, DocumentHandler handler, QueryContext queryContext)
1007 throws DocumentNotFoundException, DocumentException {
1009 DocumentModelList result = new DocumentModelListImpl();
1011 String query = handler.getCMISQuery(queryContext);
1013 DocumentFilter docFilter = handler.getDocumentFilter();
1014 int pageSize = docFilter.getPageSize();
1015 int offset = docFilter.getOffset();
1016 if (logger.isDebugEnabled()) {
1017 logger.debug("Executing CMIS query: " + query.toString()
1018 + "with pageSize: " + pageSize + " at offset: " + offset);
1021 // If we have limit and/or offset, then pass true to get totalSize
1022 // in returned DocumentModelList.
1023 Profiler profiler = new Profiler(this, 2);
1024 profiler.log("Executing CMIS query: " + query.toString());
1027 IterableQueryResult queryResult = makeCMISQLQuery(repoSession, query, queryContext);
1029 int totalSize = (int) queryResult.size();
1030 ((DocumentModelListImpl) result).setTotalSize(totalSize);
1031 // Skip the rows before our offset
1033 queryResult.skipTo(offset);
1036 for (Map<String, Serializable> row : queryResult) {
1037 if (logger.isTraceEnabled()) {
1038 logger.trace(" Hierarchy Table ID is:" + row.get(IQueryManager.CMIS_TARGET_NUXEO_ID)
1039 + " nuxeo:pathSegment is: " + row.get(IQueryManager.CMIS_TARGET_NAME));
1041 String nuxeoId = (String) row.get(IQueryManager.CMIS_TARGET_NUXEO_ID);
1042 DocumentModel docModel = NuxeoUtils.getDocumentModel(repoSession, nuxeoId);
1043 result.add(docModel);
1045 if (nRows >= pageSize && pageSize != 0) { // A page size of zero means that they want all of them
1046 logger.debug("Got page full of items - quitting");
1051 queryResult.close();
1056 } catch (Exception e) {
1057 if (logger.isDebugEnabled()) {
1058 logger.debug("Caught exception ", e);
1060 throw new DocumentException(e);
1064 // Since we're not supporting paging yet for CMIS queries, we need to perform
1065 // a workaround for the paging information we return in our list of results
1068 if (result != null) {
1069 docFilter.setStartPage(0);
1070 if (totalSize > docFilter.getPageSize()) {
1071 docFilter.setPageSize(totalSize);
1072 ((DocumentModelListImpl)result).setTotalSize(totalSize);
1080 private String logException(Exception e, String msg) {
1081 String result = null;
1083 String exceptionMessage = e.getMessage();
1084 exceptionMessage = exceptionMessage != null ? exceptionMessage : "<No details provided>";
1085 result = msg = msg + ". Caught exception:" + exceptionMessage;
1087 if (logger.isTraceEnabled() == true) {
1088 logger.error(msg, e);
1097 * update given document in the Nuxeo repository
1099 * @param ctx service context under which this method is invoked
1100 * @param csid of the document
1101 * @param handler should be used by the caller to provide and transform the
1103 * @throws BadRequestException
1104 * @throws DocumentNotFoundException
1105 * @throws TransactionException if the transaction times out or otherwise
1106 * cannot be successfully completed
1107 * @throws DocumentException
1110 public void update(ServiceContext ctx, String csid, DocumentHandler handler)
1111 throws BadRequestException, DocumentNotFoundException, TransactionException,
1113 if (handler == null) {
1114 throw new IllegalArgumentException(
1115 "RepositoryJavaClient.update: document handler is missing.");
1118 RepositoryInstance repoSession = null;
1120 handler.prepare(Action.UPDATE);
1121 repoSession = getRepositorySession(ctx);
1122 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
1123 DocumentModel doc = null;
1125 doc = repoSession.getDocument(docRef);
1126 } catch (ClientException ce) {
1127 String msg = logException(ce, "Could not find document to update with CSID=" + csid);
1128 throw new DocumentNotFoundException(msg, ce);
1130 // Check for a versioned document, and check In and Out before we proceed.
1131 if (((DocumentModelHandler) handler).supportsVersioning()) {
1132 /* Once we advance to 5.5 or later, we can add this.
1133 * See also https://jira.nuxeo.com/browse/NXP-8506
1134 if(!doc.isVersionable()) {
1135 throw new DocumentException("Configuration for: "
1136 +handler.getServiceContextPath()+" supports versioning, but Nuxeo config does not!");
1139 /* Force a version number - Not working. Apparently we need to configure the uid schema??
1140 if(doc.getProperty("uid","major_version") == null) {
1141 doc.setProperty("uid","major_version",1);
1143 if(doc.getProperty("uid","minor_version") == null) {
1144 doc.setProperty("uid","minor_version",0);
1147 doc.checkIn(VersioningOption.MINOR, null);
1152 // Set reposession to handle the document
1154 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1155 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
1156 handler.handle(Action.UPDATE, wrapDoc);
1157 repoSession.saveDocument(doc);
1159 handler.complete(Action.UPDATE, wrapDoc);
1160 } catch (BadRequestException bre) {
1162 } catch (DocumentException de) {
1164 } catch (WebApplicationException wae) {
1166 } catch (Exception e) {
1167 if (logger.isDebugEnabled()) {
1168 logger.debug("Caught exception ", e);
1170 throw new DocumentException(e);
1172 if (repoSession != null) {
1173 releaseRepositorySession(ctx, repoSession);
1179 * Save a documentModel to the Nuxeo repository.
1181 * @param ctx service context under which this method is invoked
1182 * @param repoSession
1183 * @param docModel the document to save
1184 * @param fSaveSession if TRUE, will call CoreSession.save() to save
1185 * accumulated changes.
1186 * @throws ClientException
1187 * @throws DocumentException
1189 public void saveDocWithoutHandlerProcessing(
1190 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1191 RepositoryInstance repoSession,
1192 DocumentModel docModel,
1193 boolean fSaveSession)
1194 throws ClientException, DocumentException {
1197 repoSession.saveDocument(docModel);
1201 } catch (ClientException ce) {
1203 } catch (Exception e) {
1204 if (logger.isDebugEnabled()) {
1205 logger.debug("Caught exception ", e);
1207 throw new DocumentException(e);
1212 * Save a list of documentModels to the Nuxeo repository.
1214 * @param ctx service context under which this method is invoked
1215 * @param repoSession a repository session
1216 * @param docModelList a list of document models
1217 * @param fSaveSession if TRUE, will call CoreSession.save() to save
1218 * accumulated changes.
1219 * @throws ClientException
1220 * @throws DocumentException
1222 public void saveDocListWithoutHandlerProcessing(
1223 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1224 RepositoryInstance repoSession,
1225 DocumentModelList docList,
1226 boolean fSaveSession)
1227 throws ClientException, DocumentException {
1229 DocumentModel[] docModelArray = new DocumentModel[docList.size()];
1230 repoSession.saveDocuments(docList.toArray(docModelArray));
1234 } catch (ClientException ce) {
1236 } catch (Exception e) {
1237 logger.error("Caught exception ", e);
1238 throw new DocumentException(e);
1243 * delete a document from the Nuxeo repository
1245 * @param ctx service context under which this method is invoked
1246 * @param id of the document
1247 * @throws DocumentException
1250 public void delete(ServiceContext ctx, String id, DocumentHandler handler) throws DocumentNotFoundException,
1251 DocumentException, TransactionException {
1253 throw new IllegalArgumentException(
1254 "delete(ctx, ix, handler): ctx is missing");
1256 if (handler == null) {
1257 throw new IllegalArgumentException(
1258 "delete(ctx, ix, handler): handler is missing");
1260 if (logger.isDebugEnabled()) {
1261 logger.debug("Deleting document with CSID=" + id);
1263 RepositoryInstance repoSession = null;
1265 handler.prepare(Action.DELETE);
1266 repoSession = getRepositorySession(ctx);
1267 DocumentWrapper<DocumentModel> wrapDoc = null;
1269 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
1270 wrapDoc = new DocumentWrapperImpl<DocumentModel>(repoSession.getDocument(docRef));
1271 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1272 handler.handle(Action.DELETE, wrapDoc);
1273 repoSession.removeDocument(docRef);
1274 } catch (ClientException ce) {
1275 String msg = logException(ce, "Could not find document to delete with CSID=" + id);
1276 throw new DocumentNotFoundException(msg, ce);
1279 handler.complete(Action.DELETE, wrapDoc);
1280 } catch (DocumentException de) {
1282 } catch (Exception e) {
1283 if (logger.isDebugEnabled()) {
1284 logger.debug("Caught exception ", e);
1286 throw new DocumentException(e);
1288 if (repoSession != null) {
1289 releaseRepositorySession(ctx, repoSession);
1295 * @see org.collectionspace.services.common.storage.StorageClient#delete(org.collectionspace.services.common.context.ServiceContext, java.lang.String, org.collectionspace.services.common.document.DocumentHandler)
1299 public void delete(@SuppressWarnings("rawtypes") ServiceContext ctx, String id)
1300 throws DocumentNotFoundException, DocumentException {
1301 throw new UnsupportedOperationException();
1302 // Use the other delete instead
1306 public Hashtable<String, String> retrieveWorkspaceIds(RepositoryDomainType repoDomain) throws Exception {
1307 return NuxeoConnectorEmbedded.getInstance().retrieveWorkspaceIds(repoDomain);
1311 public String createDomain(RepositoryDomainType repositoryDomain) throws Exception {
1312 RepositoryInstance repoSession = null;
1313 String domainId = null;
1316 // Open a connection to the domain's repo/db
1318 String repoName = repositoryDomain.getRepositoryName();
1319 repoSession = getRepositorySession(repoName); // domainName=storageName=repoName=databaseName
1321 // First create the top-level domain directory
1323 String domainName = repositoryDomain.getStorageName();
1324 DocumentRef parentDocRef = new PathRef("/");
1325 DocumentModel parentDoc = repoSession.getDocument(parentDocRef);
1326 DocumentModel domainDoc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1327 domainName, NUXEO_CORE_TYPE_DOMAIN);
1328 domainDoc.setPropertyValue("dc:title", domainName);
1329 domainDoc.setPropertyValue("dc:description", "A CollectionSpace domain "
1331 domainDoc = repoSession.createDocument(domainDoc);
1332 domainId = domainDoc.getId();
1335 // Next, create a "Workspaces" root directory to contain the workspace folders for the individual service documents
1337 DocumentModel workspacesRoot = repoSession.createDocumentModel(domainDoc.getPathAsString(),
1338 NuxeoUtils.Workspaces, NUXEO_CORE_TYPE_WORKSPACEROOT);
1339 workspacesRoot.setPropertyValue("dc:title", NuxeoUtils.Workspaces);
1340 workspacesRoot.setPropertyValue("dc:description", "A CollectionSpace workspaces directory for "
1341 + domainDoc.getPathAsString());
1342 workspacesRoot = repoSession.createDocument(workspacesRoot);
1343 String workspacesRootId = workspacesRoot.getId();
1346 if (logger.isDebugEnabled()) {
1347 logger.debug("Created tenant domain name=" + domainName
1348 + " id=" + domainId + " "
1349 + NuxeoUtils.Workspaces + " id=" + workspacesRootId);
1350 logger.debug("Path to Domain: " + domainDoc.getPathAsString());
1351 logger.debug("Path to Workspaces root: " + workspacesRoot.getPathAsString());
1353 } catch (Exception e) {
1354 if (logger.isDebugEnabled()) {
1355 logger.debug("Could not create tenant domain name=" + repositoryDomain.getStorageName() + " caught exception ", e);
1359 if (repoSession != null) {
1360 releaseRepositorySession(null, repoSession);
1368 public String getDomainId(RepositoryDomainType repositoryDomain) throws Exception {
1369 String domainId = null;
1370 RepositoryInstance repoSession = null;
1372 String repoName = repositoryDomain.getRepositoryName();
1373 String domainStorageName = repositoryDomain.getStorageName();
1374 if (domainStorageName != null && !domainStorageName.isEmpty()) {
1376 repoSession = getRepositorySession(repoName);
1377 DocumentRef docRef = new PathRef("/" + domainStorageName);
1378 DocumentModel domain = repoSession.getDocument(docRef);
1379 domainId = domain.getId();
1380 } catch (Exception e) {
1381 if (logger.isTraceEnabled()) {
1382 logger.trace("Caught exception ", e); // The document doesn't exist, this let's us know we need to create it
1384 //there is no way to identify if document does not exist due to
1385 //lack of typed exception for getDocument method
1388 if (repoSession != null) {
1389 releaseRepositorySession(null, repoSession);
1398 * Returns the workspaces root directory for a given domain.
1400 private DocumentModel getWorkspacesRoot(RepositoryInstance repoSession,
1401 String domainName) throws Exception {
1402 DocumentModel result = null;
1404 String domainPath = "/" + domainName;
1405 DocumentRef parentDocRef = new PathRef(domainPath);
1406 DocumentModelList domainChildrenList = repoSession.getChildren(
1408 Iterator<DocumentModel> witer = domainChildrenList.iterator();
1409 while (witer.hasNext()) {
1410 DocumentModel childNode = witer.next();
1411 if (NuxeoUtils.Workspaces.equalsIgnoreCase(childNode.getName())) {
1413 logger.trace("Found workspaces directory at: " + result.getPathAsString());
1418 if (result == null) {
1419 throw new ClientException("Could not find workspace root directory in: "
1427 * @see org.collectionspace.services.common.repository.RepositoryClient#createWorkspace(java.lang.String, java.lang.String)
1430 public String createWorkspace(RepositoryDomainType repositoryDomain, String workspaceName) throws Exception {
1431 RepositoryInstance repoSession = null;
1432 String workspaceId = null;
1434 String repoName = repositoryDomain.getRepositoryName();
1435 repoSession = getRepositorySession(repoName);
1437 String domainStorageName = repositoryDomain.getStorageName();
1438 DocumentModel parentDoc = getWorkspacesRoot(repoSession, domainStorageName);
1439 if (logger.isTraceEnabled()) {
1440 for (String facet : parentDoc.getFacets()) {
1441 logger.trace("Facet: " + facet);
1445 DocumentModel doc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1446 workspaceName, NuxeoUtils.WORKSPACE_DOCUMENT_TYPE);
1447 doc.setPropertyValue("dc:title", workspaceName);
1448 doc.setPropertyValue("dc:description", "A CollectionSpace workspace for "
1450 doc = repoSession.createDocument(doc);
1451 workspaceId = doc.getId();
1453 if (logger.isDebugEnabled()) {
1454 logger.debug("Created workspace name=" + workspaceName
1455 + " id=" + workspaceId);
1457 } catch (Exception e) {
1458 if (logger.isDebugEnabled()) {
1459 logger.debug("createWorkspace caught exception ", e);
1463 if (repoSession != null) {
1464 releaseRepositorySession(null, repoSession);
1471 * @see org.collectionspace.services.common.repository.RepositoryClient#getWorkspaceId(java.lang.String, java.lang.String)
1475 public String getWorkspaceId(String tenantDomain, String workspaceName) throws Exception {
1476 String workspaceId = null;
1478 RepositoryInstance repoSession = null;
1480 repoSession = getRepositorySession((ServiceContext) null);
1481 DocumentRef docRef = new PathRef(
1483 + "/" + NuxeoUtils.Workspaces
1484 + "/" + workspaceName);
1485 DocumentModel workspace = repoSession.getDocument(docRef);
1486 workspaceId = workspace.getId();
1487 } catch (DocumentException de) {
1489 } catch (Exception e) {
1490 if (logger.isDebugEnabled()) {
1491 logger.debug("Caught exception ", e);
1493 throw new DocumentException(e);
1495 if (repoSession != null) {
1496 releaseRepositorySession(null, repoSession);
1503 public RepositoryInstance getRepositorySession(ServiceContext ctx) throws Exception {
1504 return getRepositorySession(ctx, ctx.getRepositoryName());
1507 public RepositoryInstance getRepositorySession(String repoName) throws Exception {
1508 return getRepositorySession(null, repoName);
1512 * Gets the repository session. - Package access only. If the 'ctx' param is
1513 * null then the repo name must be non-mull and vice-versa
1515 * @return the repository session
1516 * @throws Exception the exception
1518 public RepositoryInstance getRepositorySession(ServiceContext ctx, String repoName) throws Exception {
1519 RepositoryInstance repoSession = null;
1521 Profiler profiler = new Profiler("getRepositorySession():", 2);
1524 // To get a connection to the Nuxeo repo, we need either a valid ServiceContext instance or a repository name
1527 repoName = ctx.getRepositoryName(); // Notice we are overriding the passed in 'repoName' since we have a valid service context passed in to us
1528 repoSession = (RepositoryInstance) ctx.getCurrentRepositorySession(); // Look to see if one exists in the context before creating one
1529 } else if (repoName == null || repoName.trim().isEmpty()) {
1530 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.");
1531 logger.error(errMsg);
1532 throw new Exception(errMsg);
1535 // 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
1536 // just the repo name
1538 if (repoSession == null) {
1539 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1540 repoSession = client.openRepository(repoName);
1542 if (logger.isDebugEnabled() == true) {
1543 logger.warn("Reusing the current context's repository session.");
1547 if (logger.isTraceEnabled()) {
1548 logger.trace("Testing call to getRepository() repository root: " + repoSession.getRootDocument());
1554 ctx.setCurrentRepositorySession(repoSession); // For reusing, save the repository session in the current service context
1561 * Release repository session. - Package access only.
1563 * @param repoSession the repo session
1565 public void releaseRepositorySession(ServiceContext ctx, RepositoryInstance repoSession) throws TransactionException {
1567 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1570 ctx.clearCurrentRepositorySession(); //clear the current context of the now closed repo session
1571 if (ctx.getCurrentRepositorySession() == null) {
1572 client.releaseRepository(repoSession); //release the repo session if the service context's ref count is zeo.
1575 client.releaseRepository(repoSession); //repo session was acquired without a service context
1577 } catch (TransactionRuntimeException tre) {
1578 TransactionException te = new TransactionException(tre);
1579 logger.error(te.getMessage(), tre); // Log the standard transaction exception message, plus an exception-specific stack trace
1581 } catch (Exception e) {
1582 logger.error("Could not close the repository session", e);
1583 // no need to throw this service specific exception
1588 public void doWorkflowTransition(ServiceContext ctx, String id,
1589 DocumentHandler handler, TransitionDef transitionDef)
1590 throws BadRequestException, DocumentNotFoundException,
1592 // 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