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.HashSet;
27 import java.util.Hashtable;
28 import java.util.Iterator;
29 import java.util.List;
32 import java.util.UUID;
33 import javax.sql.rowset.CachedRowSet;
35 import javax.ws.rs.WebApplicationException;
36 import javax.ws.rs.core.MultivaluedMap;
38 import org.collectionspace.services.client.CollectionSpaceClient;
39 import org.collectionspace.services.client.IQueryManager;
40 import org.collectionspace.services.client.PoxPayloadIn;
41 import org.collectionspace.services.client.PoxPayloadOut;
42 import org.collectionspace.services.client.Profiler;
43 import org.collectionspace.services.client.workflow.WorkflowClient;
44 import org.collectionspace.services.common.context.ServiceContext;
45 import org.collectionspace.services.common.query.QueryContext;
46 import org.collectionspace.services.common.repository.RepositoryClient;
47 import org.collectionspace.services.common.storage.JDBCTools;
48 import org.collectionspace.services.common.storage.PreparedStatementSimpleBuilder;
49 import org.collectionspace.services.lifecycle.TransitionDef;
50 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
52 import org.collectionspace.services.common.document.BadRequestException;
53 import org.collectionspace.services.common.document.DocumentException;
54 import org.collectionspace.services.common.document.DocumentFilter;
55 import org.collectionspace.services.common.document.DocumentHandler;
56 import org.collectionspace.services.common.document.DocumentNotFoundException;
57 import org.collectionspace.services.common.document.DocumentHandler.Action;
58 import org.collectionspace.services.common.document.DocumentWrapper;
59 import org.collectionspace.services.common.document.DocumentWrapperImpl;
60 import org.collectionspace.services.common.document.TransactionException;
61 import org.collectionspace.services.config.tenant.RepositoryDomainType;
63 import org.nuxeo.common.utils.IdUtils;
64 import org.nuxeo.ecm.core.api.ClientException;
65 import org.nuxeo.ecm.core.api.DocumentModel;
66 import org.nuxeo.ecm.core.api.DocumentModelList;
67 import org.nuxeo.ecm.core.api.IterableQueryResult;
68 import org.nuxeo.ecm.core.api.VersioningOption;
69 import org.nuxeo.ecm.core.api.impl.DocumentModelListImpl;
70 import org.nuxeo.ecm.core.api.DocumentRef;
71 import org.nuxeo.ecm.core.api.IdRef;
72 import org.nuxeo.ecm.core.api.PathRef;
73 import org.nuxeo.ecm.core.api.repository.RepositoryInstance;
74 import org.nuxeo.runtime.transaction.TransactionRuntimeException;
77 // CSPACE-5036 - How to make CMISQL queries from Nuxeo
79 import org.apache.chemistry.opencmis.commons.server.CallContext;
80 import org.apache.chemistry.opencmis.server.impl.CallContextImpl;
81 import org.collectionspace.services.common.ServiceMain;
82 import org.collectionspace.services.common.api.Tools;
83 import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl;
84 import org.collectionspace.services.common.config.TenantBindingUtils;
85 import org.collectionspace.services.config.tenant.TenantBindingType;
86 import org.nuxeo.ecm.core.opencmis.impl.server.NuxeoCmisService;
87 import org.nuxeo.ecm.core.opencmis.impl.server.NuxeoRepository;
89 import org.slf4j.Logger;
90 import org.slf4j.LoggerFactory;
93 * RepositoryJavaClient is used to perform CRUD operations on documents in Nuxeo
94 * repository using Remote Java APIs. It uses
96 * @see DocumentHandler as IOHandler with the client.
98 * $LastChangedRevision: $ $LastChangedDate: $
100 public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn, PoxPayloadOut> {
105 private final Logger logger = LoggerFactory.getLogger(RepositoryJavaClientImpl.class);
106 // private final Logger profilerLogger = LoggerFactory.getLogger("remperf");
107 // private String foo = Profiler.createLogger();
108 public static final String NUXEO_CORE_TYPE_DOMAIN = "Domain";
109 public static final String NUXEO_CORE_TYPE_WORKSPACEROOT = "WorkspaceRoot";
112 * Instantiates a new repository java client impl.
114 public RepositoryJavaClientImpl() {
118 public void assertWorkflowState(ServiceContext ctx,
119 DocumentModel docModel) throws DocumentNotFoundException, ClientException {
120 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
121 if (queryParams != null) {
123 // Look for the workflow "delete" query param and see if we need to assert that the
124 // docModel is in a non-deleted workflow state.
126 String currentState = docModel.getCurrentLifeCycleState();
127 String includeDeletedStr = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_NONDELETED);
128 boolean includeDeleted = includeDeletedStr == null ? true : Boolean.parseBoolean(includeDeletedStr);
129 if (includeDeleted == false) {
131 // We don't wanted soft-deleted object, so throw an exception if this one is soft-deleted.
133 if (currentState.equalsIgnoreCase(WorkflowClient.WORKFLOWSTATE_DELETED)) {
134 String msg = "The GET assertion that docModel not be in 'deleted' workflow state failed.";
136 throw new DocumentNotFoundException(msg);
143 * create document in the Nuxeo repository
145 * @param ctx service context under which this method is invoked
146 * @param handler should be used by the caller to provide and transform the
148 * @return id in repository of the newly created document
149 * @throws BadRequestException
150 * @throws TransactionException
151 * @throws DocumentException
154 public String create(ServiceContext ctx,
155 DocumentHandler handler) throws BadRequestException,
156 TransactionException, DocumentException {
158 String docType = NuxeoUtils.getTenantQualifiedDocType(ctx); //ctx.getDocumentType();
159 if (docType == null) {
160 throw new IllegalArgumentException(
161 "RepositoryJavaClient.create: docType is missing");
164 if (handler == null) {
165 throw new IllegalArgumentException(
166 "RepositoryJavaClient.create: handler is missing");
168 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
169 if (nuxeoWspaceId == null) {
170 throw new DocumentNotFoundException(
171 "Unable to find workspace for service " + ctx.getServiceName()
172 + " check if the workspace exists in the Nuxeo repository");
175 RepositoryInstance repoSession = null;
177 handler.prepare(Action.CREATE);
178 repoSession = getRepositorySession(ctx);
179 DocumentRef nuxeoWspace = new IdRef(nuxeoWspaceId);
180 DocumentModel wspaceDoc = repoSession.getDocument(nuxeoWspace);
181 String wspacePath = wspaceDoc.getPathAsString();
182 //give our own ID so PathRef could be constructed later on
183 String id = IdUtils.generateId(UUID.randomUUID().toString());
184 // create document model
185 DocumentModel doc = repoSession.createDocumentModel(wspacePath, id, docType);
186 /* Check for a versioned document, and check In and Out before we proceed.
187 * This does not work as we do not have the uid schema on our docs.
188 if(((DocumentModelHandler) handler).supportsVersioning()) {
189 doc.setProperty("uid","major_version",1);
190 doc.setProperty("uid","minor_version",0);
193 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
194 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
195 handler.handle(Action.CREATE, wrapDoc);
196 // create document with documentmodel
197 doc = repoSession.createDocument(doc);
199 // TODO for sub-docs need to call into the handler to let it deal with subitems. Pass in the id,
200 // and assume the handler has the state it needs (doc fragments).
201 handler.complete(Action.CREATE, wrapDoc);
203 } catch (BadRequestException bre) {
205 } catch (Exception e) {
206 logger.error("Caught exception ", e);
207 throw new DocumentException(e);
209 if (repoSession != null) {
210 releaseRepositorySession(ctx, repoSession);
217 * get document from the Nuxeo repository
219 * @param ctx service context under which this method is invoked
220 * @param id of the document to retrieve
221 * @param handler should be used by the caller to provide and transform the
223 * @throws DocumentNotFoundException if the document cannot be found in the
225 * @throws TransactionException
226 * @throws DocumentException
229 public void get(ServiceContext ctx, String id, DocumentHandler handler)
230 throws DocumentNotFoundException, TransactionException, DocumentException {
232 if (handler == null) {
233 throw new IllegalArgumentException(
234 "RepositoryJavaClient.get: handler is missing");
237 RepositoryInstance repoSession = null;
239 handler.prepare(Action.GET);
240 repoSession = getRepositorySession(ctx);
241 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
242 DocumentModel docModel = null;
244 docModel = repoSession.getDocument(docRef);
245 assertWorkflowState(ctx, docModel);
246 } catch (ClientException ce) {
247 String msg = logException(ce, "Could not find document with CSID=" + id);
248 throw new DocumentNotFoundException(msg, ce);
251 // Set repository session to handle the document
253 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
254 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(docModel);
255 handler.handle(Action.GET, wrapDoc);
256 handler.complete(Action.GET, wrapDoc);
257 } catch (IllegalArgumentException iae) {
259 } catch (DocumentException de) {
261 } catch (Exception e) {
262 if (logger.isDebugEnabled()) {
263 logger.debug("Caught exception ", e);
265 throw new DocumentException(e);
267 if (repoSession != null) {
268 releaseRepositorySession(ctx, repoSession);
274 * get a document from the Nuxeo repository, using the docFilter params.
276 * @param ctx service context under which this method is invoked
277 * @param handler should be used by the caller to provide and transform the
278 * document. Handler must have a docFilter set to return a single item.
279 * @throws DocumentNotFoundException if the document cannot be found in the
281 * @throws TransactionException
282 * @throws DocumentException
285 public void get(ServiceContext ctx, DocumentHandler handler)
286 throws DocumentNotFoundException, TransactionException, DocumentException {
287 QueryContext queryContext = new QueryContext(ctx, handler);
288 RepositoryInstance repoSession = null;
291 handler.prepare(Action.GET);
292 repoSession = getRepositorySession(ctx);
294 DocumentModelList docList = null;
295 // force limit to 1, and ignore totalSize
296 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
297 docList = repoSession.query(query, null, 1, 0, false);
298 if (docList.size() != 1) {
299 throw new DocumentNotFoundException("No document found matching filter params: " + query);
301 DocumentModel doc = docList.get(0);
303 if (logger.isDebugEnabled()) {
304 logger.debug("Executed NXQL query: " + query);
307 //set reposession to handle the document
308 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
309 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
310 handler.handle(Action.GET, wrapDoc);
311 handler.complete(Action.GET, wrapDoc);
312 } catch (IllegalArgumentException iae) {
314 } catch (DocumentException de) {
316 } catch (Exception e) {
317 if (logger.isDebugEnabled()) {
318 logger.debug("Caught exception ", e);
320 throw new DocumentException(e);
322 if (repoSession != null) {
323 releaseRepositorySession(ctx, repoSession);
328 public DocumentWrapper<DocumentModel> getDoc(
329 RepositoryInstance repoSession,
330 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
331 String csid) throws DocumentNotFoundException, DocumentException {
332 DocumentWrapper<DocumentModel> wrapDoc = null;
335 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
336 DocumentModel doc = null;
338 doc = repoSession.getDocument(docRef);
339 } catch (ClientException ce) {
340 String msg = logException(ce, "Could not find document with CSID=" + csid);
341 throw new DocumentNotFoundException(msg, ce);
343 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
344 } catch (IllegalArgumentException iae) {
346 } catch (DocumentException de) {
354 * Get wrapped documentModel from the Nuxeo repository. The search is
355 * restricted to the workspace of the current context.
357 * @param ctx service context under which this method is invoked
358 * @param csid of the document to retrieve
359 * @throws DocumentNotFoundException
360 * @throws TransactionException
361 * @throws DocumentException
362 * @return a wrapped documentModel
365 public DocumentWrapper<DocumentModel> getDoc(
366 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
367 String csid) throws DocumentNotFoundException, TransactionException, DocumentException {
368 RepositoryInstance repoSession = null;
369 DocumentWrapper<DocumentModel> wrapDoc = null;
372 // Open a new repository session
373 repoSession = getRepositorySession(ctx);
374 wrapDoc = getDoc(repoSession, ctx, csid);
375 } catch (IllegalArgumentException iae) {
377 } catch (DocumentException de) {
379 } catch (Exception e) {
380 if (logger.isDebugEnabled()) {
381 logger.debug("Caught exception ", e);
383 throw new DocumentException(e);
385 if (repoSession != null) {
386 releaseRepositorySession(ctx, repoSession);
390 if (logger.isWarnEnabled() == true) {
391 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
396 public DocumentWrapper<DocumentModel> findDoc(
397 RepositoryInstance repoSession,
398 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
400 throws DocumentNotFoundException, DocumentException {
401 DocumentWrapper<DocumentModel> wrapDoc = null;
404 QueryContext queryContext = new QueryContext(ctx, whereClause);
405 DocumentModelList docList = null;
406 // force limit to 1, and ignore totalSize
407 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
408 docList = repoSession.query(query,
413 if (docList.size() != 1) {
414 if (logger.isDebugEnabled()) {
415 logger.debug("findDoc: Query found: " + docList.size() + " items.");
416 logger.debug(" Query: " + query);
418 throw new DocumentNotFoundException("No document found matching filter params: " + query);
420 DocumentModel doc = docList.get(0);
421 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
422 } catch (IllegalArgumentException iae) {
424 } catch (DocumentException de) {
426 } catch (Exception e) {
427 if (logger.isDebugEnabled()) {
428 logger.debug("Caught exception ", e);
430 throw new DocumentException(e);
437 * find wrapped documentModel from the Nuxeo repository
439 * @param ctx service context under which this method is invoked
440 * @param whereClause where NXQL where clause to get the document
441 * @throws DocumentNotFoundException
442 * @throws TransactionException
443 * @throws DocumentException
444 * @return a wrapped documentModel retrieved by the repository query
447 public DocumentWrapper<DocumentModel> findDoc(
448 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
450 throws DocumentNotFoundException, TransactionException, DocumentException {
451 RepositoryInstance repoSession = null;
452 DocumentWrapper<DocumentModel> wrapDoc = null;
455 repoSession = getRepositorySession(ctx);
456 wrapDoc = findDoc(repoSession, ctx, whereClause);
457 } catch (Exception e) {
458 throw new DocumentException("Unable to create a Nuxeo repository session.", e);
460 if (repoSession != null) {
461 releaseRepositorySession(ctx, repoSession);
465 if (logger.isWarnEnabled() == true) {
466 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
473 * find doc and return CSID from the Nuxeo repository
476 * @param ctx service context under which this method is invoked
477 * @param whereClause where NXQL where clause to get the document
478 * @throws DocumentNotFoundException
479 * @throws TransactionException
480 * @throws DocumentException
481 * @return the CollectionSpace ID (CSID) of the requested document
484 public String findDocCSID(RepositoryInstance repoSession,
485 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String whereClause)
486 throws DocumentNotFoundException, TransactionException, DocumentException {
488 boolean releaseSession = false;
490 if (repoSession == null) {
491 repoSession = this.getRepositorySession(ctx);
492 releaseSession = true;
494 DocumentWrapper<DocumentModel> wrapDoc = findDoc(repoSession, ctx, whereClause);
495 DocumentModel docModel = wrapDoc.getWrappedObject();
496 csid = NuxeoUtils.getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
497 } catch (DocumentNotFoundException dnfe) {
499 } catch (IllegalArgumentException iae) {
501 } catch (DocumentException de) {
503 } catch (Exception e) {
504 if (logger.isDebugEnabled()) {
505 logger.debug("Caught exception ", e);
507 throw new DocumentException(e);
509 if (releaseSession && (repoSession != null)) {
510 this.releaseRepositorySession(ctx, repoSession);
516 public DocumentWrapper<DocumentModelList> findDocs(
517 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
518 RepositoryInstance repoSession,
519 List<String> docTypes,
521 String orderByClause,
524 boolean computeTotal)
525 throws DocumentNotFoundException, DocumentException {
526 DocumentWrapper<DocumentModelList> wrapDoc = null;
529 if (docTypes == null || docTypes.size() < 1) {
530 throw new DocumentNotFoundException(
531 "The findDocs() method must specify at least one DocumentType.");
533 DocumentModelList docList = null;
534 QueryContext queryContext = new QueryContext(ctx, whereClause, orderByClause);
535 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
536 if (logger.isDebugEnabled()) {
537 logger.debug("findDocs() NXQL: " + query);
539 docList = repoSession.query(query, null, pageSize, pageSize * pageNum, computeTotal);
540 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
541 } catch (IllegalArgumentException iae) {
543 } catch (Exception e) {
544 if (logger.isDebugEnabled()) {
545 logger.debug("Caught exception ", e);
547 throw new DocumentException(e);
553 protected static String buildInListForDocTypes(List<String> docTypes) {
554 StringBuilder sb = new StringBuilder();
556 boolean first = true;
557 for (String docType : docTypes) {
568 return sb.toString();
571 public DocumentWrapper<DocumentModelList> findDocs(
572 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
573 DocumentHandler handler,
574 RepositoryInstance repoSession,
575 List<String> docTypes)
576 throws DocumentNotFoundException, DocumentException {
577 DocumentWrapper<DocumentModelList> wrapDoc = null;
579 DocumentFilter filter = handler.getDocumentFilter();
580 String oldOrderBy = filter.getOrderByClause();
581 if (isClauseEmpty(oldOrderBy) == true) {
582 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
584 QueryContext queryContext = new QueryContext(ctx, handler);
587 if (docTypes == null || docTypes.size() < 1) {
588 throw new DocumentNotFoundException(
589 "The findDocs() method must specify at least one DocumentType.");
591 DocumentModelList docList = null;
592 if (handler.isCMISQuery() == true) {
593 String inList = buildInListForDocTypes(docTypes);
594 ctx.getQueryParams().add(IQueryManager.SEARCH_RELATED_MATCH_OBJ_DOCTYPES, inList);
595 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext);
597 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
598 if (logger.isDebugEnabled()) {
599 logger.debug("findDocs() NXQL: " + query);
601 docList = repoSession.query(query, null, filter.getPageSize(), filter.getOffset(), true);
603 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
604 } catch (IllegalArgumentException iae) {
606 } catch (Exception e) {
607 if (logger.isDebugEnabled()) {
608 logger.debug("Caught exception ", e);
610 throw new DocumentException(e);
617 * Find a list of documentModels from the Nuxeo repository
619 * @param docTypes a list of DocType names to match
620 * @param whereClause where the clause to qualify on
621 * @throws DocumentNotFoundException
622 * @throws TransactionException
623 * @throws DocumentException
624 * @return a list of documentModels
627 public DocumentWrapper<DocumentModelList> findDocs(
628 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
629 List<String> docTypes,
631 int pageSize, int pageNum, boolean computeTotal)
632 throws DocumentNotFoundException, TransactionException, DocumentException {
633 RepositoryInstance repoSession = null;
634 DocumentWrapper<DocumentModelList> wrapDoc = null;
637 repoSession = getRepositorySession(ctx);
638 wrapDoc = findDocs(ctx, repoSession, docTypes, whereClause, null,
639 pageSize, pageNum, computeTotal);
640 } catch (IllegalArgumentException iae) {
642 } catch (Exception e) {
643 if (logger.isDebugEnabled()) {
644 logger.debug("Caught exception ", e);
646 throw new DocumentException(e);
648 if (repoSession != null) {
649 releaseRepositorySession(ctx, repoSession);
653 if (logger.isWarnEnabled() == true) {
654 logger.warn("Returned DocumentModelList instance was created with a repository session that is now closed.");
661 * @see org.collectionspace.services.common.storage.StorageClient#get(org.collectionspace.services.common.context.ServiceContext, java.util.List, org.collectionspace.services.common.document.DocumentHandler)
664 public void get(ServiceContext ctx, List<String> csidList, DocumentHandler handler)
665 throws DocumentNotFoundException, TransactionException, DocumentException {
666 if (handler == null) {
667 throw new IllegalArgumentException(
668 "RepositoryJavaClient.getAll: handler is missing");
671 RepositoryInstance repoSession = null;
673 handler.prepare(Action.GET_ALL);
674 repoSession = getRepositorySession(ctx);
675 DocumentModelList docModelList = new DocumentModelListImpl();
676 //FIXME: Should be using NuxeoUtils.createPathRef for security reasons
677 for (String csid : csidList) {
678 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
679 DocumentModel docModel = repoSession.getDocument(docRef);
680 docModelList.add(docModel);
683 //set reposession to handle the document
684 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
685 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docModelList);
686 handler.handle(Action.GET_ALL, wrapDoc);
687 handler.complete(Action.GET_ALL, wrapDoc);
688 } catch (DocumentException de) {
690 } catch (Exception e) {
691 if (logger.isDebugEnabled()) {
692 logger.debug("Caught exception ", e);
694 throw new DocumentException(e);
696 if (repoSession != null) {
697 releaseRepositorySession(ctx, repoSession);
703 * getAll get all documents for an entity entity service from the Nuxeo
706 * @param ctx service context under which this method is invoked
707 * @param handler should be used by the caller to provide and transform the
709 * @throws DocumentNotFoundException
710 * @throws TransactionException
711 * @throws DocumentException
714 public void getAll(ServiceContext ctx, DocumentHandler handler)
715 throws DocumentNotFoundException, TransactionException, DocumentException {
716 if (handler == null) {
717 throw new IllegalArgumentException(
718 "RepositoryJavaClient.getAll: handler is missing");
720 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
721 if (nuxeoWspaceId == null) {
722 throw new DocumentNotFoundException(
723 "Unable to find workspace for service "
724 + ctx.getServiceName()
725 + " check if the workspace exists in the Nuxeo repository.");
728 RepositoryInstance repoSession = null;
730 handler.prepare(Action.GET_ALL);
731 repoSession = getRepositorySession(ctx);
732 DocumentRef wsDocRef = new IdRef(nuxeoWspaceId);
733 DocumentModelList docList = repoSession.getChildren(wsDocRef);
734 //set reposession to handle the document
735 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
736 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
737 handler.handle(Action.GET_ALL, wrapDoc);
738 handler.complete(Action.GET_ALL, wrapDoc);
739 } catch (DocumentException de) {
741 } catch (Exception e) {
742 if (logger.isDebugEnabled()) {
743 logger.debug("Caught exception ", e);
745 throw new DocumentException(e);
747 if (repoSession != null) {
748 releaseRepositorySession(ctx, repoSession);
753 private boolean isClauseEmpty(String theString) {
754 boolean result = true;
755 if (theString != null && !theString.isEmpty()) {
761 public DocumentWrapper<DocumentModel> getDocFromCsid(
762 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
763 RepositoryInstance repoSession,
766 DocumentWrapper<DocumentModel> result = null;
768 result = new DocumentWrapperImpl(NuxeoUtils.getDocFromCsid(ctx, repoSession, csid));
774 * A method to find a CollectionSpace document (of any type) given just a service context and
775 * its CSID. A search across *all* service workspaces (within a given tenant context) is performed to find
778 * This query searches Nuxeo's Hierarchy table where our CSIDs are stored in the "name" column.
781 public DocumentWrapper<DocumentModel> getDocFromCsid(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
784 DocumentWrapper<DocumentModel> result = null;
785 RepositoryInstance repoSession = null;
787 repoSession = getRepositorySession(ctx);
788 result = getDocFromCsid(ctx, repoSession, csid);
790 if (repoSession != null) {
791 releaseRepositorySession(ctx, repoSession);
795 if (logger.isWarnEnabled() == true) {
796 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
803 * Returns a URI value for a document in the Nuxeo repository
805 * @param wrappedDoc a wrapped documentModel
806 * @throws ClientException
807 * @return a document URI
810 public String getDocURI(DocumentWrapper<DocumentModel> wrappedDoc) throws ClientException {
811 DocumentModel docModel = wrappedDoc.getWrappedObject();
812 String uri = (String) docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
813 CollectionSpaceClient.COLLECTIONSPACE_CORE_URI);
818 * See CSPACE-5036 - How to make CMISQL queries from Nuxeo
820 private IterableQueryResult makeCMISQLQuery(RepositoryInstance repoSession, String query, QueryContext queryContext) {
821 IterableQueryResult result = null;
823 // the NuxeoRepository should be constructed only once, then cached
824 // (its construction is expensive)
826 NuxeoRepository repo = new NuxeoRepository(
827 repoSession.getRepositoryName(), repoSession
828 .getRootDocument().getId());
829 logger.debug("Repository ID:" + repo.getId() + " Root folder:"
830 + repo.getRootFolderId());
832 CallContextImpl callContext = new CallContextImpl(
833 CallContext.BINDING_LOCAL, repo.getId(), false);
834 callContext.put(CallContext.USERNAME, repoSession.getPrincipal()
836 NuxeoCmisService cmisService = new NuxeoCmisService(repo,
837 callContext, repoSession);
839 result = repoSession.queryAndFetch(query, "CMISQL", cmisService);
840 } catch (ClientException e) {
841 // TODO Auto-generated catch block
842 logger.error("Encounter trouble making the following CMIS query: " + query, e);
849 * getFiltered get all documents for an entity service from the Document
850 * repository, given filter parameters specified by the handler.
852 * @param ctx service context under which this method is invoked
853 * @param handler should be used by the caller to provide and transform the
855 * @throws DocumentNotFoundException if workspace not found
856 * @throws TransactionException
857 * @throws DocumentException
860 public void getFiltered(ServiceContext ctx, DocumentHandler handler)
861 throws DocumentNotFoundException, TransactionException, DocumentException {
863 DocumentFilter filter = handler.getDocumentFilter();
864 String oldOrderBy = filter.getOrderByClause();
865 if (isClauseEmpty(oldOrderBy) == true) {
866 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED);
868 QueryContext queryContext = new QueryContext(ctx, handler);
870 RepositoryInstance repoSession = null;
872 handler.prepare(Action.GET_ALL);
873 repoSession = getRepositorySession(ctx); //Keeps a refcount here for the repository session so you need to release this when finished
875 DocumentModelList docList = null;
876 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
878 if (logger.isDebugEnabled()) {
879 logger.debug("Executing NXQL query: " + query.toString());
882 // If we have limit and/or offset, then pass true to get totalSize
883 // in returned DocumentModelList.
884 Profiler profiler = new Profiler(this, 2);
885 profiler.log("Executing NXQL query: " + query.toString());
887 if (handler.isJDBCQuery() == true) {
888 docList = getFilteredJDBC(repoSession, ctx, handler, queryContext);
889 } else if (handler.isCMISQuery() == true) {
890 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext); //FIXME: REM - Need to deal with paging info in CMIS query
891 } else if ((queryContext.getDocFilter().getOffset() > 0) || (queryContext.getDocFilter().getPageSize() > 0)) {
892 docList = repoSession.query(query, null,
893 queryContext.getDocFilter().getPageSize(), queryContext.getDocFilter().getOffset(), true);
895 docList = repoSession.query(query);
899 //set repoSession to handle the document
900 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
901 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
902 handler.handle(Action.GET_ALL, wrapDoc);
903 handler.complete(Action.GET_ALL, wrapDoc);
904 } catch (DocumentException de) {
906 } catch (Exception e) {
907 if (logger.isDebugEnabled()) {
908 logger.debug("Caught exception ", e);
910 throw new DocumentException(e);
912 if (repoSession != null) {
913 releaseRepositorySession(ctx, repoSession);
918 private DocumentModelList getFilteredJDBC(RepositoryInstance repoSession, ServiceContext ctx,
919 DocumentHandler handler, QueryContext queryContext) throws Exception {
920 DocumentModelList result = new DocumentModelListImpl();
922 String dataSourceName = JDBCTools.NUXEO_DATASOURCE_NAME;
923 String repositoryName = ctx.getRepositoryName();
925 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
926 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
928 // FIXME: Resolve how to handle the case where the partial term
929 // query parameter is included in the request, but has been given an
930 // empty (blank) value ("...?pt=") Then implement the required
931 // behavior here, if current behavior does not match what is required.
933 // (We're currently returning all records in that case.)
935 // FIXME: Get all of the following values from appropriate external constants.
937 // At present, the two constants below are duplicated in both RepositoryJavaClientImpl
938 // and in AuthorityItemDocumentModelHandler.
939 final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
940 final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
941 // Get this from a constant in AuthorityResource or equivalent
942 final String PARENT_WILDCARD = "_ALL_";
944 // Start with the default query
945 String selectStatement =
946 "SELECT DISTINCT hierarchy_termgroup.parentid as id"
947 + " FROM " + handler.getJDBCQueryParams().get(TERM_GROUP_TABLE_NAME_PARAM) + " termgroup ";
950 " INNER JOIN hierarchy hierarchy_termgroup "
951 + " ON hierarchy_termgroup.id = termgroup.id "
952 + " INNER JOIN hierarchy hierarchy_commonschema "
953 + " ON hierarchy_commonschema.id = hierarchy_termgroup.parentid ";
956 " WHERE (termgroup.termdisplayname ILIKE ?) ";
958 TenantBindingConfigReaderImpl tReader =
959 ServiceMain.getInstance().getTenantBindingConfigReader();
960 TenantBindingType tenantBinding = tReader.getTenantBinding(ctx.getTenantId());
961 String maxListItemsLimit = TenantBindingUtils.getPropertyValue(tenantBinding,
962 IQueryManager.MAX_LIST_ITEMS_RETURNED_LIMIT_ON_JDBC_QUERIES);
964 " LIMIT " + getMaxItemsLimitOnJdbcQueries(maxListItemsLimit); // implicit int-to-String conversion
966 List<String> params = new ArrayList<>();
968 // Read tenant bindings configuration to determine whether
969 // to automatically insert leading, as well as trailing, wildcards
970 // into the term matching string.
971 String usesStartingWildcard = TenantBindingUtils.getPropertyValue(tenantBinding,
972 IQueryManager.TENANT_USES_STARTING_WILDCARD_FOR_PARTIAL_TERM);
973 // Handle user-provided leading wildcard characters, in the
974 // configuration where a leading wildcard is not automatically inserted.
975 // (The user-provided wildcard must be in the first, or "starting"
976 // character position in the partial term value.)
977 if (Tools.notBlank(usesStartingWildcard) && usesStartingWildcard.equalsIgnoreCase(Boolean.FALSE.toString())) {
978 partialTerm = handleProvidedStartingWildcard(partialTerm);
979 // Otherwise, automatically insert a leading wildcard
981 partialTerm = JDBCTools.SQL_WILDCARD + partialTerm;
983 // Automatically insert a trailing wildcard
984 params.add(partialTerm + JDBCTools.SQL_WILDCARD); // Value for replaceable parameter 1 in the query
986 // Restrict the query to filter out deleted records, if requested
987 String includeDeleted = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_NONDELETED);
988 if (includeDeleted != null && includeDeleted.equalsIgnoreCase(Boolean.FALSE.toString())) {
989 joinClauses = joinClauses
990 + " INNER JOIN misc "
991 + " ON misc.id = hierarchy_commonschema.id ";
992 whereClause = whereClause
993 + " AND (misc.lifecyclestate <> '" + WorkflowClient.WORKFLOWSTATE_DELETED + "') ";
996 // If a particular authority is specified, restrict the query further
997 // to return only records within that authority
998 String inAuthorityValue = (String) handler.getJDBCQueryParams().get(IN_AUTHORITY_PARAM);
999 if (Tools.notBlank(inAuthorityValue)) {
1000 // Handle the '_ALL_' case for inAuthority
1001 if (inAuthorityValue.equals(PARENT_WILDCARD)) {
1002 // Add nothing to the query here if it should match within all authorities
1004 joinClauses = joinClauses
1005 + " INNER JOIN " + handler.getServiceContext().getCommonPartLabel() + " commonschema "
1006 + " ON commonschema.id = hierarchy_commonschema.id ";
1007 whereClause = whereClause
1008 + " AND (commonschema.inauthority = ?)";
1009 params.add(inAuthorityValue); // Value for replaceable parameter 2 in the query
1013 String sql = selectStatement + joinClauses + whereClause + limitClause;
1015 // FIXME: Look into whether the following performance concern around
1016 // query planning with prepared statements may be affecting us:
1017 // http://stackoverflow.com/a/678452
1018 // If that proves to be a significant concern, we can instead use
1019 // JDBCTools.executeQuery(), and attempt to sanitize user input
1020 // against potential SQL injection attacks.
1021 PreparedStatementSimpleBuilder jdbcFilterQueryBuilder = new PreparedStatementSimpleBuilder(sql, params);
1023 Set<String> docIds = new HashSet<>();
1024 try (CachedRowSet crs = JDBCTools.executePreparedQuery(jdbcFilterQueryBuilder,
1025 dataSourceName, repositoryName, sql)) {
1027 // If the response to the query is null or contains zero rows,
1028 // return an empty list of document models
1033 if (crs.getRow() == 0) {
1034 return result; // empty list of document models
1037 // Otherwise, get the document IDs from the results of the query
1040 while (crs.next()) {
1041 id = crs.getString(1);
1042 if (Tools.notBlank(id)) {
1046 } catch (SQLException sqle) {
1047 logger.warn("Could not obtain document IDs via SQL query '" + sql + "': " + sqle.getMessage());
1048 return result; // return an empty list of document models
1051 // Get a list of document models, using the IDs obtained from the query
1052 DocumentModel docModel;
1053 for (String docId : docIds) {
1054 docModel = NuxeoUtils.getDocumentModel(repoSession, docId);
1055 if (docModel == null) {
1056 logger.debug("Could not obtain document model for document with ID " + docId);
1058 result.add(NuxeoUtils.getDocumentModel(repoSession, docId));
1066 private DocumentModelList getFilteredCMIS(RepositoryInstance repoSession, ServiceContext ctx, DocumentHandler handler, QueryContext queryContext)
1067 throws DocumentNotFoundException, DocumentException {
1069 DocumentModelList result = new DocumentModelListImpl();
1071 String query = handler.getCMISQuery(queryContext);
1073 DocumentFilter docFilter = handler.getDocumentFilter();
1074 int pageSize = docFilter.getPageSize();
1075 int offset = docFilter.getOffset();
1076 if (logger.isDebugEnabled()) {
1077 logger.debug("Executing CMIS query: " + query.toString()
1078 + "with pageSize: " + pageSize + " at offset: " + offset);
1081 // If we have limit and/or offset, then pass true to get totalSize
1082 // in returned DocumentModelList.
1083 Profiler profiler = new Profiler(this, 2);
1084 profiler.log("Executing CMIS query: " + query.toString());
1087 IterableQueryResult queryResult = makeCMISQLQuery(repoSession, query, queryContext);
1089 int totalSize = (int) queryResult.size();
1090 ((DocumentModelListImpl) result).setTotalSize(totalSize);
1091 // Skip the rows before our offset
1093 queryResult.skipTo(offset);
1096 for (Map<String, Serializable> row : queryResult) {
1097 if (logger.isTraceEnabled()) {
1098 logger.trace(" Hierarchy Table ID is:" + row.get(IQueryManager.CMIS_TARGET_NUXEO_ID)
1099 + " nuxeo:pathSegment is: " + row.get(IQueryManager.CMIS_TARGET_NAME));
1101 String nuxeoId = (String) row.get(IQueryManager.CMIS_TARGET_NUXEO_ID);
1102 DocumentModel docModel = NuxeoUtils.getDocumentModel(repoSession, nuxeoId);
1103 result.add(docModel);
1105 if (nRows >= pageSize && pageSize != 0) { // A page size of zero means that they want all of them
1106 logger.debug("Got page full of items - quitting");
1111 queryResult.close();
1116 } catch (Exception e) {
1117 if (logger.isDebugEnabled()) {
1118 logger.debug("Caught exception ", e);
1120 throw new DocumentException(e);
1124 // Since we're not supporting paging yet for CMIS queries, we need to perform
1125 // a workaround for the paging information we return in our list of results
1128 if (result != null) {
1129 docFilter.setStartPage(0);
1130 if (totalSize > docFilter.getPageSize()) {
1131 docFilter.setPageSize(totalSize);
1132 ((DocumentModelListImpl)result).setTotalSize(totalSize);
1140 private String logException(Exception e, String msg) {
1141 String result = null;
1143 String exceptionMessage = e.getMessage();
1144 exceptionMessage = exceptionMessage != null ? exceptionMessage : "<No details provided>";
1145 result = msg = msg + ". Caught exception:" + exceptionMessage;
1147 if (logger.isTraceEnabled() == true) {
1148 logger.error(msg, e);
1157 * update given document in the Nuxeo repository
1159 * @param ctx service context under which this method is invoked
1160 * @param csid of the document
1161 * @param handler should be used by the caller to provide and transform the
1163 * @throws BadRequestException
1164 * @throws DocumentNotFoundException
1165 * @throws TransactionException if the transaction times out or otherwise
1166 * cannot be successfully completed
1167 * @throws DocumentException
1170 public void update(ServiceContext ctx, String csid, DocumentHandler handler)
1171 throws BadRequestException, DocumentNotFoundException, TransactionException,
1173 if (handler == null) {
1174 throw new IllegalArgumentException(
1175 "RepositoryJavaClient.update: document handler is missing.");
1178 RepositoryInstance repoSession = null;
1180 handler.prepare(Action.UPDATE);
1181 repoSession = getRepositorySession(ctx);
1182 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
1183 DocumentModel doc = null;
1185 doc = repoSession.getDocument(docRef);
1186 } catch (ClientException ce) {
1187 String msg = logException(ce, "Could not find document to update with CSID=" + csid);
1188 throw new DocumentNotFoundException(msg, ce);
1190 // Check for a versioned document, and check In and Out before we proceed.
1191 if (((DocumentModelHandler) handler).supportsVersioning()) {
1192 /* Once we advance to 5.5 or later, we can add this.
1193 * See also https://jira.nuxeo.com/browse/NXP-8506
1194 if(!doc.isVersionable()) {
1195 throw new DocumentException("Configuration for: "
1196 +handler.getServiceContextPath()+" supports versioning, but Nuxeo config does not!");
1199 /* Force a version number - Not working. Apparently we need to configure the uid schema??
1200 if(doc.getProperty("uid","major_version") == null) {
1201 doc.setProperty("uid","major_version",1);
1203 if(doc.getProperty("uid","minor_version") == null) {
1204 doc.setProperty("uid","minor_version",0);
1207 doc.checkIn(VersioningOption.MINOR, null);
1212 // Set reposession to handle the document
1214 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1215 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
1216 handler.handle(Action.UPDATE, wrapDoc);
1217 repoSession.saveDocument(doc);
1219 handler.complete(Action.UPDATE, wrapDoc);
1220 } catch (BadRequestException bre) {
1222 } catch (DocumentException de) {
1224 } catch (WebApplicationException wae) {
1226 } catch (Exception e) {
1227 if (logger.isDebugEnabled()) {
1228 logger.debug("Caught exception ", e);
1230 throw new DocumentException(e);
1232 if (repoSession != null) {
1233 releaseRepositorySession(ctx, repoSession);
1239 * Save a documentModel to the Nuxeo repository.
1241 * @param ctx service context under which this method is invoked
1242 * @param repoSession
1243 * @param docModel the document to save
1244 * @param fSaveSession if TRUE, will call CoreSession.save() to save
1245 * accumulated changes.
1246 * @throws ClientException
1247 * @throws DocumentException
1249 public void saveDocWithoutHandlerProcessing(
1250 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1251 RepositoryInstance repoSession,
1252 DocumentModel docModel,
1253 boolean fSaveSession)
1254 throws ClientException, DocumentException {
1257 repoSession.saveDocument(docModel);
1261 } catch (ClientException ce) {
1263 } catch (Exception e) {
1264 if (logger.isDebugEnabled()) {
1265 logger.debug("Caught exception ", e);
1267 throw new DocumentException(e);
1272 * Save a list of documentModels to the Nuxeo repository.
1274 * @param ctx service context under which this method is invoked
1275 * @param repoSession a repository session
1276 * @param docModelList a list of document models
1277 * @param fSaveSession if TRUE, will call CoreSession.save() to save
1278 * accumulated changes.
1279 * @throws ClientException
1280 * @throws DocumentException
1282 public void saveDocListWithoutHandlerProcessing(
1283 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1284 RepositoryInstance repoSession,
1285 DocumentModelList docList,
1286 boolean fSaveSession)
1287 throws ClientException, DocumentException {
1289 DocumentModel[] docModelArray = new DocumentModel[docList.size()];
1290 repoSession.saveDocuments(docList.toArray(docModelArray));
1294 } catch (ClientException ce) {
1296 } catch (Exception e) {
1297 logger.error("Caught exception ", e);
1298 throw new DocumentException(e);
1303 * delete a document from the Nuxeo repository
1305 * @param ctx service context under which this method is invoked
1306 * @param id of the document
1307 * @throws DocumentException
1310 public void delete(ServiceContext ctx, String id, DocumentHandler handler) throws DocumentNotFoundException,
1311 DocumentException, TransactionException {
1313 throw new IllegalArgumentException(
1314 "delete(ctx, ix, handler): ctx is missing");
1316 if (handler == null) {
1317 throw new IllegalArgumentException(
1318 "delete(ctx, ix, handler): handler is missing");
1320 if (logger.isDebugEnabled()) {
1321 logger.debug("Deleting document with CSID=" + id);
1323 RepositoryInstance repoSession = null;
1325 handler.prepare(Action.DELETE);
1326 repoSession = getRepositorySession(ctx);
1327 DocumentWrapper<DocumentModel> wrapDoc = null;
1329 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
1330 wrapDoc = new DocumentWrapperImpl<DocumentModel>(repoSession.getDocument(docRef));
1331 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1332 handler.handle(Action.DELETE, wrapDoc);
1333 repoSession.removeDocument(docRef);
1334 } catch (ClientException ce) {
1335 String msg = logException(ce, "Could not find document to delete with CSID=" + id);
1336 throw new DocumentNotFoundException(msg, ce);
1339 handler.complete(Action.DELETE, wrapDoc);
1340 } catch (DocumentException de) {
1342 } catch (Exception e) {
1343 if (logger.isDebugEnabled()) {
1344 logger.debug("Caught exception ", e);
1346 throw new DocumentException(e);
1348 if (repoSession != null) {
1349 releaseRepositorySession(ctx, repoSession);
1355 * @see org.collectionspace.services.common.storage.StorageClient#delete(org.collectionspace.services.common.context.ServiceContext, java.lang.String, org.collectionspace.services.common.document.DocumentHandler)
1359 public void delete(@SuppressWarnings("rawtypes") ServiceContext ctx, String id)
1360 throws DocumentNotFoundException, DocumentException {
1361 throw new UnsupportedOperationException();
1362 // Use the other delete instead
1366 public Hashtable<String, String> retrieveWorkspaceIds(RepositoryDomainType repoDomain) throws Exception {
1367 return NuxeoConnectorEmbedded.getInstance().retrieveWorkspaceIds(repoDomain);
1371 public String createDomain(RepositoryDomainType repositoryDomain) throws Exception {
1372 RepositoryInstance repoSession = null;
1373 String domainId = null;
1376 // Open a connection to the domain's repo/db
1378 String repoName = repositoryDomain.getRepositoryName();
1379 repoSession = getRepositorySession(repoName); // domainName=storageName=repoName=databaseName
1381 // First create the top-level domain directory
1383 String domainName = repositoryDomain.getStorageName();
1384 DocumentRef parentDocRef = new PathRef("/");
1385 DocumentModel parentDoc = repoSession.getDocument(parentDocRef);
1386 DocumentModel domainDoc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1387 domainName, NUXEO_CORE_TYPE_DOMAIN);
1388 domainDoc.setPropertyValue("dc:title", domainName);
1389 domainDoc.setPropertyValue("dc:description", "A CollectionSpace domain "
1391 domainDoc = repoSession.createDocument(domainDoc);
1392 domainId = domainDoc.getId();
1395 // Next, create a "Workspaces" root directory to contain the workspace folders for the individual service documents
1397 DocumentModel workspacesRoot = repoSession.createDocumentModel(domainDoc.getPathAsString(),
1398 NuxeoUtils.Workspaces, NUXEO_CORE_TYPE_WORKSPACEROOT);
1399 workspacesRoot.setPropertyValue("dc:title", NuxeoUtils.Workspaces);
1400 workspacesRoot.setPropertyValue("dc:description", "A CollectionSpace workspaces directory for "
1401 + domainDoc.getPathAsString());
1402 workspacesRoot = repoSession.createDocument(workspacesRoot);
1403 String workspacesRootId = workspacesRoot.getId();
1406 if (logger.isDebugEnabled()) {
1407 logger.debug("Created tenant domain name=" + domainName
1408 + " id=" + domainId + " "
1409 + NuxeoUtils.Workspaces + " id=" + workspacesRootId);
1410 logger.debug("Path to Domain: " + domainDoc.getPathAsString());
1411 logger.debug("Path to Workspaces root: " + workspacesRoot.getPathAsString());
1413 } catch (Exception e) {
1414 if (logger.isDebugEnabled()) {
1415 logger.debug("Could not create tenant domain name=" + repositoryDomain.getStorageName() + " caught exception ", e);
1419 if (repoSession != null) {
1420 releaseRepositorySession(null, repoSession);
1428 public String getDomainId(RepositoryDomainType repositoryDomain) throws Exception {
1429 String domainId = null;
1430 RepositoryInstance repoSession = null;
1432 String repoName = repositoryDomain.getRepositoryName();
1433 String domainStorageName = repositoryDomain.getStorageName();
1434 if (domainStorageName != null && !domainStorageName.isEmpty()) {
1436 repoSession = getRepositorySession(repoName);
1437 DocumentRef docRef = new PathRef("/" + domainStorageName);
1438 DocumentModel domain = repoSession.getDocument(docRef);
1439 domainId = domain.getId();
1440 } catch (Exception e) {
1441 if (logger.isTraceEnabled()) {
1442 logger.trace("Caught exception ", e); // The document doesn't exist, this let's us know we need to create it
1444 //there is no way to identify if document does not exist due to
1445 //lack of typed exception for getDocument method
1448 if (repoSession != null) {
1449 releaseRepositorySession(null, repoSession);
1458 * Returns the workspaces root directory for a given domain.
1460 private DocumentModel getWorkspacesRoot(RepositoryInstance repoSession,
1461 String domainName) throws Exception {
1462 DocumentModel result = null;
1464 String domainPath = "/" + domainName;
1465 DocumentRef parentDocRef = new PathRef(domainPath);
1466 DocumentModelList domainChildrenList = repoSession.getChildren(
1468 Iterator<DocumentModel> witer = domainChildrenList.iterator();
1469 while (witer.hasNext()) {
1470 DocumentModel childNode = witer.next();
1471 if (NuxeoUtils.Workspaces.equalsIgnoreCase(childNode.getName())) {
1473 logger.trace("Found workspaces directory at: " + result.getPathAsString());
1478 if (result == null) {
1479 throw new ClientException("Could not find workspace root directory in: "
1487 * @see org.collectionspace.services.common.repository.RepositoryClient#createWorkspace(java.lang.String, java.lang.String)
1490 public String createWorkspace(RepositoryDomainType repositoryDomain, String workspaceName) throws Exception {
1491 RepositoryInstance repoSession = null;
1492 String workspaceId = null;
1494 String repoName = repositoryDomain.getRepositoryName();
1495 repoSession = getRepositorySession(repoName);
1497 String domainStorageName = repositoryDomain.getStorageName();
1498 DocumentModel parentDoc = getWorkspacesRoot(repoSession, domainStorageName);
1499 if (logger.isTraceEnabled()) {
1500 for (String facet : parentDoc.getFacets()) {
1501 logger.trace("Facet: " + facet);
1505 DocumentModel doc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1506 workspaceName, NuxeoUtils.WORKSPACE_DOCUMENT_TYPE);
1507 doc.setPropertyValue("dc:title", workspaceName);
1508 doc.setPropertyValue("dc:description", "A CollectionSpace workspace for "
1510 doc = repoSession.createDocument(doc);
1511 workspaceId = doc.getId();
1513 if (logger.isDebugEnabled()) {
1514 logger.debug("Created workspace name=" + workspaceName
1515 + " id=" + workspaceId);
1517 } catch (Exception e) {
1518 if (logger.isDebugEnabled()) {
1519 logger.debug("createWorkspace caught exception ", e);
1523 if (repoSession != null) {
1524 releaseRepositorySession(null, repoSession);
1531 * @see org.collectionspace.services.common.repository.RepositoryClient#getWorkspaceId(java.lang.String, java.lang.String)
1535 public String getWorkspaceId(String tenantDomain, String workspaceName) throws Exception {
1536 String workspaceId = null;
1538 RepositoryInstance repoSession = null;
1540 repoSession = getRepositorySession((ServiceContext) null);
1541 DocumentRef docRef = new PathRef(
1543 + "/" + NuxeoUtils.Workspaces
1544 + "/" + workspaceName);
1545 DocumentModel workspace = repoSession.getDocument(docRef);
1546 workspaceId = workspace.getId();
1547 } catch (DocumentException de) {
1549 } catch (Exception e) {
1550 if (logger.isDebugEnabled()) {
1551 logger.debug("Caught exception ", e);
1553 throw new DocumentException(e);
1555 if (repoSession != null) {
1556 releaseRepositorySession(null, repoSession);
1563 public RepositoryInstance getRepositorySession(ServiceContext ctx) throws Exception {
1564 return getRepositorySession(ctx, ctx.getRepositoryName());
1567 public RepositoryInstance getRepositorySession(String repoName) throws Exception {
1568 return getRepositorySession(null, repoName);
1572 * Gets the repository session. - Package access only. If the 'ctx' param is
1573 * null then the repo name must be non-mull and vice-versa
1575 * @return the repository session
1576 * @throws Exception the exception
1578 public RepositoryInstance getRepositorySession(ServiceContext ctx, String repoName) throws Exception {
1579 RepositoryInstance repoSession = null;
1581 Profiler profiler = new Profiler("getRepositorySession():", 2);
1584 // To get a connection to the Nuxeo repo, we need either a valid ServiceContext instance or a repository name
1587 repoName = ctx.getRepositoryName(); // Notice we are overriding the passed in 'repoName' since we have a valid service context passed in to us
1588 repoSession = (RepositoryInstance) ctx.getCurrentRepositorySession(); // Look to see if one exists in the context before creating one
1589 } else if (repoName == null || repoName.trim().isEmpty()) {
1590 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.");
1591 logger.error(errMsg);
1592 throw new Exception(errMsg);
1595 // 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
1596 // just the repo name
1598 if (repoSession == null) {
1599 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1600 repoSession = client.openRepository(repoName);
1602 if (logger.isDebugEnabled() == true) {
1603 logger.warn("Reusing the current context's repository session.");
1607 if (logger.isTraceEnabled()) {
1608 logger.trace("Testing call to getRepository() repository root: " + repoSession.getRootDocument());
1614 ctx.setCurrentRepositorySession(repoSession); // For reusing, save the repository session in the current service context
1621 * Release repository session. - Package access only.
1623 * @param repoSession the repo session
1625 public void releaseRepositorySession(ServiceContext ctx, RepositoryInstance repoSession) throws TransactionException {
1627 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1630 ctx.clearCurrentRepositorySession(); //clear the current context of the now closed repo session
1631 if (ctx.getCurrentRepositorySession() == null) {
1632 client.releaseRepository(repoSession); //release the repo session if the service context's ref count is zeo.
1635 client.releaseRepository(repoSession); //repo session was acquired without a service context
1637 } catch (TransactionRuntimeException tre) {
1638 TransactionException te = new TransactionException(tre);
1639 logger.error(te.getMessage(), tre); // Log the standard transaction exception message, plus an exception-specific stack trace
1641 } catch (Exception e) {
1642 logger.error("Could not close the repository session", e);
1643 // no need to throw this service specific exception
1648 public void doWorkflowTransition(ServiceContext ctx, String id,
1649 DocumentHandler handler, TransitionDef transitionDef)
1650 throws BadRequestException, DocumentNotFoundException,
1652 // 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
1655 private String handleProvidedStartingWildcard(String partialTerm) {
1656 if (Tools.notBlank(partialTerm)) {
1657 // FIXME: Get this value from an existing constant, if available
1658 final String USER_SUPPLIED_WILDCARD = "*";
1659 if (partialTerm.substring(0, 1).equals(USER_SUPPLIED_WILDCARD)) {
1660 StringBuffer buffer = new StringBuffer(partialTerm);
1661 buffer.setCharAt(0, JDBCTools.SQL_WILDCARD.charAt(0));
1662 partialTerm = buffer.toString();
1668 private int getMaxItemsLimitOnJdbcQueries(String maxListItemsLimit) {
1669 final int DEFAULT_ITEMS_LIMIT = 40;
1672 itemsLimit = Integer.parseInt(maxListItemsLimit);
1673 if (itemsLimit < 1) {
1674 itemsLimit = DEFAULT_ITEMS_LIMIT;
1676 } catch (NumberFormatException nfe) {
1677 itemsLimit = DEFAULT_ITEMS_LIMIT;