2 * This document is a part of the source code and related artifacts
3 * for CollectionSpace, an open source collections management system
4 * for museums and related institutions:
6 * http://www.collectionspace.org
7 * http://wiki.collectionspace.org
9 * Copyright 2009 University of California at Berkeley
11 * Licensed under the Educational Community License (ECL), Version 2.0.
12 * You may not use this file except in compliance with this License.
14 * You may obtain a copy of the ECL 2.0 License at
16 * https://source.collectionspace.org/collection-space/LICENSE.txt
18 package org.collectionspace.services.nuxeo.client.java;
20 import java.io.Serializable;
21 import java.util.Hashtable;
22 import java.util.Iterator;
23 import java.util.List;
25 import java.util.UUID;
27 import javax.ws.rs.WebApplicationException;
28 import javax.ws.rs.core.MultivaluedMap;
30 import org.collectionspace.services.client.IQueryManager;
31 import org.collectionspace.services.client.PoxPayloadIn;
32 import org.collectionspace.services.client.PoxPayloadOut;
33 import org.collectionspace.services.client.workflow.WorkflowClient;
34 import org.collectionspace.services.common.context.ServiceContext;
35 import org.collectionspace.services.common.query.QueryContext;
36 import org.collectionspace.services.common.repository.RepositoryClient;
37 import org.collectionspace.services.common.profile.Profiler;
38 import org.collectionspace.services.lifecycle.TransitionDef;
39 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
41 import org.collectionspace.services.common.document.BadRequestException;
42 import org.collectionspace.services.common.document.DocumentException;
43 import org.collectionspace.services.common.document.DocumentFilter;
44 import org.collectionspace.services.common.document.DocumentHandler;
45 import org.collectionspace.services.common.document.DocumentNotFoundException;
46 import org.collectionspace.services.common.document.DocumentHandler.Action;
47 import org.collectionspace.services.common.document.DocumentWrapper;
48 import org.collectionspace.services.common.document.DocumentWrapperImpl;
50 import org.nuxeo.common.utils.IdUtils;
51 import org.nuxeo.ecm.core.api.ClientException;
52 import org.nuxeo.ecm.core.api.DocumentModel;
53 import org.nuxeo.ecm.core.api.DocumentModelList;
54 import org.nuxeo.ecm.core.api.IterableQueryResult;
55 import org.nuxeo.ecm.core.api.impl.DocumentModelListImpl;
56 import org.nuxeo.ecm.core.api.DocumentRef;
57 import org.nuxeo.ecm.core.api.IdRef;
58 import org.nuxeo.ecm.core.api.PathRef;
59 import org.nuxeo.ecm.core.api.repository.RepositoryInstance;
62 // CSPACE-5036 - How to make CMISQL queries from Nuxeo
64 import org.apache.chemistry.opencmis.commons.server.CallContext;
65 import org.apache.chemistry.opencmis.server.impl.CallContextImpl;
66 import org.nuxeo.ecm.core.opencmis.impl.server.NuxeoCmisService;
67 import org.nuxeo.ecm.core.opencmis.impl.server.NuxeoRepository;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
73 * RepositoryJavaClient is used to perform CRUD operations on documents in Nuxeo
74 * repository using Remote Java APIs. It uses @see DocumentHandler as IOHandler
77 * $LastChangedRevision: $ $LastChangedDate: $
79 public class RepositoryJavaClientImpl implements RepositoryClient<PoxPayloadIn, PoxPayloadOut> {
82 private final Logger logger = LoggerFactory.getLogger(RepositoryJavaClientImpl.class);
83 // private final Logger profilerLogger = LoggerFactory.getLogger("remperf");
84 // private String foo = Profiler.createLogger();
86 public static final String NUXEO_CORE_TYPE_DOMAIN = "Domain";
87 public static final String NUXEO_CORE_TYPE_WORKSPACEROOT = "WorkspaceRoot";
90 * Instantiates a new repository java client impl.
92 public RepositoryJavaClientImpl() {
97 public void assertWorkflowState(ServiceContext ctx,
98 DocumentModel docModel) throws DocumentNotFoundException, ClientException {
99 MultivaluedMap<String, String> queryParams = ctx.getQueryParams();
100 if (queryParams != null) {
102 // Look for the workflow "delete" query param and see if we need to assert that the
103 // docModel is in a non-deleted workflow state.
105 String currentState = docModel.getCurrentLifeCycleState();
106 String includeDeletedStr = queryParams.getFirst(WorkflowClient.WORKFLOW_QUERY_NONDELETED);
107 boolean includeDeleted = includeDeletedStr == null ? true : Boolean.parseBoolean(includeDeletedStr);
108 if (includeDeleted == false) {
110 // We don't wanted soft-deleted object, so throw an exception if this one is soft-deleted.
112 if (currentState.equalsIgnoreCase(WorkflowClient.WORKFLOWSTATE_DELETED)) {
113 String msg = "The GET assertion that docModel not be in 'deleted' workflow state failed.";
115 throw new DocumentNotFoundException(msg);
122 * create document in the Nuxeo repository
124 * @param ctx service context under which this method is invoked
126 * should be used by the caller to provide and transform the
128 * @return id in repository of the newly created document
129 * @throws DocumentException
132 public String create(ServiceContext ctx,
133 DocumentHandler handler) throws BadRequestException,
136 String docType = NuxeoUtils.getTenantQualifiedDocType(ctx); //ctx.getDocumentType();
137 if (docType == null) {
138 throw new IllegalArgumentException(
139 "RepositoryJavaClient.create: docType is missing");
142 if (handler == null) {
143 throw new IllegalArgumentException(
144 "RepositoryJavaClient.create: handler is missing");
146 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
147 if (nuxeoWspaceId == null) {
148 throw new DocumentNotFoundException(
149 "Unable to find workspace for service " + ctx.getServiceName()
150 + " check if the workspace exists in the Nuxeo repository");
153 RepositoryInstance repoSession = null;
155 handler.prepare(Action.CREATE);
156 repoSession = getRepositorySession();
157 DocumentRef nuxeoWspace = new IdRef(nuxeoWspaceId);
158 DocumentModel wspaceDoc = repoSession.getDocument(nuxeoWspace);
159 String wspacePath = wspaceDoc.getPathAsString();
160 //give our own ID so PathRef could be constructed later on
161 String id = IdUtils.generateId(UUID.randomUUID().toString());
162 // create document model
163 DocumentModel doc = repoSession.createDocumentModel(wspacePath, id, docType);
164 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
165 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
166 handler.handle(Action.CREATE, wrapDoc);
167 // create document with documentmodel
168 doc = repoSession.createDocument(doc);
170 // TODO for sub-docs need to call into the handler to let it deal with subitems. Pass in the id,
171 // and assume the handler has the state it needs (doc fragments).
172 handler.complete(Action.CREATE, wrapDoc);
174 } catch (BadRequestException bre) {
176 } catch (Exception e) {
177 logger.error("Caught exception ", e);
178 throw new DocumentException(e);
180 if (repoSession != null) {
181 releaseRepositorySession(repoSession);
188 * get document from the Nuxeo repository
189 * @param ctx service context under which this method is invoked
191 * of the document to retrieve
193 * should be used by the caller to provide and transform the
195 * @throws DocumentException
198 public void get(ServiceContext ctx, String id, DocumentHandler handler)
199 throws DocumentNotFoundException, DocumentException {
201 if (handler == null) {
202 throw new IllegalArgumentException(
203 "RepositoryJavaClient.get: handler is missing");
206 RepositoryInstance repoSession = null;
208 handler.prepare(Action.GET);
209 repoSession = getRepositorySession();
210 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
211 DocumentModel docModel = null;
213 docModel = repoSession.getDocument(docRef);
214 assertWorkflowState(ctx, docModel);
215 } catch (ClientException ce) {
216 String msg = logException(ce, "Could not find document with CSID=" + id);
217 throw new DocumentNotFoundException(msg, ce);
220 // Set repository session to handle the document
222 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
223 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(docModel);
224 handler.handle(Action.GET, wrapDoc);
225 handler.complete(Action.GET, wrapDoc);
226 } catch (IllegalArgumentException iae) {
228 } catch (DocumentException de) {
230 } catch (Exception e) {
231 if (logger.isDebugEnabled()) {
232 logger.debug("Caught exception ", e);
234 throw new DocumentException(e);
236 if (repoSession != null) {
237 releaseRepositorySession(repoSession);
243 * get document from the Nuxeo repository, using the docFilter params.
244 * @param ctx service context under which this method is invoked
246 * should be used by the caller to provide and transform the
247 * document. Handler must have a docFilter set to return a single item.
248 * @throws DocumentException
251 public void get(ServiceContext ctx, DocumentHandler handler)
252 throws DocumentNotFoundException, DocumentException {
253 QueryContext queryContext = new QueryContext(ctx, handler);
254 RepositoryInstance repoSession = null;
257 handler.prepare(Action.GET);
258 repoSession = getRepositorySession();
260 DocumentModelList docList = null;
261 // force limit to 1, and ignore totalSize
262 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
263 docList = repoSession.query(query, null, 1, 0, false);
264 if (docList.size() != 1) {
265 throw new DocumentNotFoundException("No document found matching filter params: " + query);
267 DocumentModel doc = docList.get(0);
269 if (logger.isDebugEnabled()) {
270 logger.debug("Executed NXQL query: " + query);
273 //set reposession to handle the document
274 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
275 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
276 handler.handle(Action.GET, wrapDoc);
277 handler.complete(Action.GET, wrapDoc);
278 } catch (IllegalArgumentException iae) {
280 } catch (DocumentException de) {
282 } catch (Exception e) {
283 if (logger.isDebugEnabled()) {
284 logger.debug("Caught exception ", e);
286 throw new DocumentException(e);
288 if (repoSession != null) {
289 releaseRepositorySession(repoSession);
294 public DocumentWrapper<DocumentModel> getDoc(
295 RepositoryInstance repoSession,
296 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
297 String csid) throws DocumentNotFoundException, DocumentException {
298 DocumentWrapper<DocumentModel> wrapDoc = null;
301 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
302 DocumentModel doc = null;
304 doc = repoSession.getDocument(docRef);
305 } catch (ClientException ce) {
306 String msg = logException(ce, "Could not find document with CSID=" + csid);
307 throw new DocumentNotFoundException(msg, ce);
309 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
310 } catch (IllegalArgumentException iae) {
312 } catch (DocumentException de) {
320 * Get wrapped documentModel from the Nuxeo repository. The search is restricted to the workspace
321 * of the current context.
323 * @param ctx service context under which this method is invoked
325 * of the document to retrieve
326 * @throws DocumentException
329 public DocumentWrapper<DocumentModel> getDoc(
330 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
331 String csid) throws DocumentNotFoundException, DocumentException {
332 RepositoryInstance repoSession = null;
333 DocumentWrapper<DocumentModel> wrapDoc = null;
336 // Open a new repository session
337 repoSession = getRepositorySession();
338 wrapDoc = getDoc(repoSession, ctx, csid);
339 } catch (IllegalArgumentException iae) {
341 } catch (DocumentException de) {
343 } catch (Exception e) {
344 if (logger.isDebugEnabled()) {
345 logger.debug("Caught exception ", e);
347 throw new DocumentException(e);
349 if (repoSession != null) {
350 releaseRepositorySession(repoSession);
354 if (logger.isWarnEnabled() == true) {
355 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
360 public DocumentWrapper<DocumentModel> findDoc(
361 RepositoryInstance repoSession,
362 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
364 throws DocumentNotFoundException, DocumentException {
365 DocumentWrapper<DocumentModel> wrapDoc = null;
368 QueryContext queryContext = new QueryContext(ctx, whereClause);
369 DocumentModelList docList = null;
370 // force limit to 1, and ignore totalSize
371 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
372 docList = repoSession.query(query,
377 if (docList.size() != 1) {
378 if (logger.isDebugEnabled()) {
379 logger.debug("findDoc: Query found: " + docList.size() + " items.");
380 logger.debug(" Query: " + query);
382 throw new DocumentNotFoundException("No document found matching filter params: " + query);
384 DocumentModel doc = docList.get(0);
385 wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
386 } catch (IllegalArgumentException iae) {
388 } catch (DocumentException de) {
390 } catch (Exception e) {
391 if (logger.isDebugEnabled()) {
392 logger.debug("Caught exception ", e);
394 throw new DocumentException(e);
401 * find wrapped documentModel from the Nuxeo repository
402 * @param ctx service context under which this method is invoked
403 * @param whereClause where NXQL where clause to get the document
404 * @throws DocumentException
407 public DocumentWrapper<DocumentModel> findDoc(
408 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
410 throws DocumentNotFoundException, DocumentException {
411 RepositoryInstance repoSession = null;
412 DocumentWrapper<DocumentModel> wrapDoc = null;
415 repoSession = getRepositorySession();
416 wrapDoc = findDoc(repoSession, ctx, whereClause);
417 } catch (Exception e) {
418 throw new DocumentException("Unable to create a Nuxeo repository session.", e);
420 if (repoSession != null) {
421 releaseRepositorySession(repoSession);
425 if (logger.isWarnEnabled() == true) {
426 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
433 * find doc and return CSID 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 DocumentException
439 public String findDocCSID(RepositoryInstance repoSession,
440 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, String whereClause)
441 throws DocumentNotFoundException, DocumentException {
443 boolean releaseSession = false;
445 if(repoSession== null) {
446 repoSession = this.getRepositorySession();
447 releaseSession = true;
449 DocumentWrapper<DocumentModel> wrapDoc = findDoc(repoSession, ctx, whereClause);
450 DocumentModel docModel = wrapDoc.getWrappedObject();
451 csid = NuxeoUtils.getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
452 } catch (DocumentNotFoundException dnfe) {
454 } catch (IllegalArgumentException iae) {
456 } catch (DocumentException de) {
458 } catch (Exception e) {
459 if (logger.isDebugEnabled()) {
460 logger.debug("Caught exception ", e);
462 throw new DocumentException(e);
464 if(releaseSession && (repoSession != null)) {
465 this.releaseRepositorySession(repoSession);
471 public DocumentWrapper<DocumentModelList> findDocs(
472 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
473 RepositoryInstance repoSession,
474 List<String> docTypes,
476 int pageSize, int pageNum, boolean computeTotal)
477 throws DocumentNotFoundException, DocumentException {
478 DocumentWrapper<DocumentModelList> wrapDoc = null;
481 if (docTypes == null || docTypes.size() < 1) {
482 throw new DocumentNotFoundException(
483 "The findDocs() method must specify at least one DocumentType.");
485 DocumentModelList docList = null;
486 QueryContext queryContext = new QueryContext(ctx, whereClause);
487 String query = NuxeoUtils.buildNXQLQuery(docTypes, queryContext);
488 if (logger.isDebugEnabled()) {
489 logger.debug("findDocs() NXQL: "+query);
491 docList = repoSession.query(query, null, pageSize, pageNum, computeTotal);
492 wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
493 } catch (IllegalArgumentException iae) {
495 } catch (Exception e) {
496 if (logger.isDebugEnabled()) {
497 logger.debug("Caught exception ", e);
499 throw new DocumentException(e);
506 * Find a list of documentModels from the Nuxeo repository
507 * @param docTypes a list of DocType names to match
508 * @param whereClause where the clause to qualify on
512 public DocumentWrapper<DocumentModelList> findDocs(
513 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
514 List<String> docTypes,
516 int pageSize, int pageNum, boolean computeTotal)
517 throws DocumentNotFoundException, DocumentException {
518 RepositoryInstance repoSession = null;
519 DocumentWrapper<DocumentModelList> wrapDoc = null;
522 repoSession = getRepositorySession();
523 wrapDoc = findDocs(ctx, repoSession, docTypes, whereClause,
524 pageSize, pageNum, computeTotal);
525 } catch (IllegalArgumentException iae) {
527 } catch (Exception e) {
528 if (logger.isDebugEnabled()) {
529 logger.debug("Caught exception ", e);
531 throw new DocumentException(e);
533 if (repoSession != null) {
534 releaseRepositorySession(repoSession);
538 if (logger.isWarnEnabled() == true) {
539 logger.warn("Returned DocumentModelList instance was created with a repository session that is now closed.");
546 * @see org.collectionspace.services.common.storage.StorageClient#get(org.collectionspace.services.common.context.ServiceContext, java.util.List, org.collectionspace.services.common.document.DocumentHandler)
549 public void get(ServiceContext ctx, List<String> csidList, DocumentHandler handler)
550 throws DocumentNotFoundException, DocumentException {
551 if (handler == null) {
552 throw new IllegalArgumentException(
553 "RepositoryJavaClient.getAll: handler is missing");
556 RepositoryInstance repoSession = null;
558 handler.prepare(Action.GET_ALL);
559 repoSession = getRepositorySession();
560 DocumentModelList docModelList = new DocumentModelListImpl();
561 //FIXME: Should be using NuxeoUtils.createPathRef for security reasons
562 for (String csid : csidList) {
563 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
564 DocumentModel docModel = repoSession.getDocument(docRef);
565 docModelList.add(docModel);
568 //set reposession to handle the document
569 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
570 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docModelList);
571 handler.handle(Action.GET_ALL, wrapDoc);
572 handler.complete(Action.GET_ALL, wrapDoc);
573 } catch (DocumentException de) {
575 } catch (Exception e) {
576 if (logger.isDebugEnabled()) {
577 logger.debug("Caught exception ", e);
579 throw new DocumentException(e);
581 if (repoSession != null) {
582 releaseRepositorySession(repoSession);
588 * getAll get all documents for an entity entity service from the Nuxeo
591 * @param ctx service context under which this method is invoked
593 * should be used by the caller to provide and transform the
595 * @throws DocumentException
598 public void getAll(ServiceContext ctx, DocumentHandler handler)
599 throws DocumentNotFoundException, DocumentException {
600 if (handler == null) {
601 throw new IllegalArgumentException(
602 "RepositoryJavaClient.getAll: handler is missing");
604 String nuxeoWspaceId = ctx.getRepositoryWorkspaceId();
605 if (nuxeoWspaceId == null) {
606 throw new DocumentNotFoundException(
607 "Unable to find workspace for service "
608 + ctx.getServiceName()
609 + " check if the workspace exists in the Nuxeo repository.");
612 RepositoryInstance repoSession = null;
614 handler.prepare(Action.GET_ALL);
615 repoSession = getRepositorySession();
616 DocumentRef wsDocRef = new IdRef(nuxeoWspaceId);
617 DocumentModelList docList = repoSession.getChildren(wsDocRef);
618 //set reposession to handle the document
619 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
620 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
621 handler.handle(Action.GET_ALL, wrapDoc);
622 handler.complete(Action.GET_ALL, wrapDoc);
623 } catch (DocumentException de) {
625 } catch (Exception e) {
626 if (logger.isDebugEnabled()) {
627 logger.debug("Caught exception ", e);
629 throw new DocumentException(e);
631 if (repoSession != null) {
632 releaseRepositorySession(repoSession);
637 private boolean isClauseEmpty(String theString) {
638 boolean result = true;
639 if (theString != null && !theString.isEmpty()) {
645 public DocumentWrapper<DocumentModel> getDocFromCsid(
646 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
647 RepositoryInstance repoSession,
650 DocumentWrapper<DocumentModel> result = null;
652 result = new DocumentWrapperImpl(NuxeoUtils.getDocFromCsid(ctx, repoSession, csid));
658 * A method to find a CollectionSpace document (of any type) given just a service context and
659 * its CSID. A search across *all* service workspaces (within a given tenant context) is performed to find
662 * This query searches Nuxeo's Hierarchy table where our CSIDs are stored in the "name" column.
665 public DocumentWrapper<DocumentModel> getDocFromCsid(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
668 DocumentWrapper<DocumentModel> result = null;
669 RepositoryInstance repoSession = null;
671 repoSession = getRepositorySession();
672 result = getDocFromCsid(ctx, repoSession, csid);
674 if (repoSession != null) {
675 releaseRepositorySession(repoSession);
679 if (logger.isWarnEnabled() == true) {
680 logger.warn("Returned DocumentModel instance was created with a repository session that is now closed.");
687 * find doc and return CSID from the Nuxeo repository
688 * @param ctx service context under which this method is invoked
689 * @param whereClause where NXQL where clause to get the document
690 * @throws DocumentException
693 public String getDocURI(DocumentWrapper<DocumentModel> wrappedDoc) throws ClientException {
694 DocumentModel docModel = wrappedDoc.getWrappedObject();
695 String uri = (String)docModel.getProperty(DocumentModelHandler.COLLECTIONSPACE_CORE_SCHEMA,
696 DocumentModelHandler.COLLECTIONSPACE_CORE_URI);
701 * See CSPACE-5036 - How to make CMISQL queries from Nuxeo
703 private IterableQueryResult makeCMISQLQuery(RepositoryInstance repoSession, String query) {
704 IterableQueryResult result = null;
706 // the NuxeoRepository should be constructed only once, then cached
707 // (its construction is expensive)
709 NuxeoRepository repo = new NuxeoRepository(
710 repoSession.getRepositoryName(), repoSession
711 .getRootDocument().getId());
712 logger.debug("Repository ID:" + repo.getId() + " Root folder:"
713 + repo.getRootFolderId());
715 CallContextImpl callContext = new CallContextImpl(
716 CallContext.BINDING_LOCAL, repo.getId(), false);
717 callContext.put(CallContext.USERNAME, repoSession.getPrincipal()
719 NuxeoCmisService cmisService = new NuxeoCmisService(repo,
720 callContext, repoSession);
722 result = repoSession.queryAndFetch(query,
723 "CMISQL", cmisService);
724 } catch (ClientException e) {
725 // TODO Auto-generated catch block
726 logger.error("Encounter trouble making the following CMIS query: " + query, e);
733 * getFiltered get all documents for an entity service from the Document repository,
734 * given filter parameters specified by the handler.
735 * @param ctx service context under which this method is invoked
736 * @param handler should be used by the caller to provide and transform the document
737 * @throws DocumentNotFoundException if workspace not found
738 * @throws DocumentException
741 public void getFiltered(ServiceContext ctx, DocumentHandler handler)
742 throws DocumentNotFoundException, DocumentException {
744 DocumentFilter filter = handler.getDocumentFilter();
745 String oldOrderBy = filter.getOrderByClause();
746 if (isClauseEmpty(oldOrderBy) == true){
747 filter.setOrderByClause(DocumentFilter.ORDER_BY_LAST_UPDATED); //per http://issues.collectionspace.org/browse/CSPACE-705 (Doesn't this conflict with what happens with the QueryContext instance that we create below?)
749 QueryContext queryContext = new QueryContext(ctx, handler);
751 RepositoryInstance repoSession = null;
753 handler.prepare(Action.GET_ALL);
754 repoSession = getRepositorySession();
756 DocumentModelList docList = null;
757 String query = NuxeoUtils.buildNXQLQuery(ctx, queryContext);
759 if (logger.isDebugEnabled()) {
760 logger.debug("Executing NXQL query: " + query.toString());
763 // If we have limit and/or offset, then pass true to get totalSize
764 // in returned DocumentModelList.
765 Profiler profiler = new Profiler(this, 2);
766 profiler.log("Executing NXQL query: " + query.toString());
768 if (handler.isCMISQuery() == true) {
769 docList = getFilteredCMIS(repoSession, ctx, handler, queryContext); //FIXME: REM - Need to deal with paging info in CMIS query
770 } else if ((queryContext.getDocFilter().getOffset() > 0) || (queryContext.getDocFilter().getPageSize() > 0)) {
771 docList = repoSession.query(query, null,
772 queryContext.getDocFilter().getPageSize(), queryContext.getDocFilter().getOffset(), true);
774 docList = repoSession.query(query);
778 //set repoSession to handle the document
779 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
780 DocumentWrapper<DocumentModelList> wrapDoc = new DocumentWrapperImpl<DocumentModelList>(docList);
781 handler.handle(Action.GET_ALL, wrapDoc);
782 handler.complete(Action.GET_ALL, wrapDoc);
783 } catch (DocumentException de) {
785 } catch (Exception e) {
786 if (logger.isDebugEnabled()) {
787 logger.debug("Caught exception ", e);
789 throw new DocumentException(e);
791 if (repoSession != null) {
792 releaseRepositorySession(repoSession);
797 private DocumentModelList getFilteredCMIS(RepositoryInstance repoSession, ServiceContext ctx, DocumentHandler handler, QueryContext queryContext)
798 throws DocumentNotFoundException, DocumentException {
800 DocumentModelList result = new DocumentModelListImpl();
802 String query = handler.getCMISQuery();
804 if (logger.isDebugEnabled()) {
805 logger.debug("Executing CMIS query: " + query.toString());
808 // If we have limit and/or offset, then pass true to get totalSize
809 // in returned DocumentModelList.
810 Profiler profiler = new Profiler(this, 2);
811 profiler.log("Executing CMIS query: " + query.toString());
814 IterableQueryResult queryResult = makeCMISQLQuery(repoSession, query);
816 for (Map<String, Serializable> row : queryResult) {
818 // + " dc:title is: " + (String)row.get("dc:title")
819 + " Hierarchy Table ID is:" + row.get(IQueryManager.CMIS_TARGET_NUXEO_ID)
820 + " cmis:name is: " + row.get(IQueryManager.CMIS_TARGET_NAME)
821 // + " nuxeo:lifecycleState is: " + row.get("nuxeo:lifecycleState")
823 String nuxeoId = (String) row.get(IQueryManager.CMIS_TARGET_NUXEO_ID);
824 DocumentModel docModel = NuxeoUtils.getDocumentModel(repoSession, nuxeoId);
825 result.add(docModel);
833 } catch (Exception e) {
834 if (logger.isDebugEnabled()) {
835 logger.debug("Caught exception ", e);
837 throw new DocumentException(e);
843 private String logException(Exception e, String msg) {
844 String result = null;
846 String exceptionMessage = e.getMessage();
847 exceptionMessage = exceptionMessage != null ? exceptionMessage : "<No details provided>";
848 result = msg = msg + ". Caught exception:" + exceptionMessage;
850 if (logger.isTraceEnabled() == true) {
851 logger.error(msg, e);
860 * update given document in the Nuxeo repository
862 * @param ctx service context under which this method is invoked
866 * should be used by the caller to provide and transform the
868 * @throws DocumentException
871 public void update(ServiceContext ctx, String csid, DocumentHandler handler)
872 throws BadRequestException, DocumentNotFoundException,
874 if (handler == null) {
875 throw new IllegalArgumentException(
876 "RepositoryJavaClient.update: document handler is missing.");
879 RepositoryInstance repoSession = null;
881 handler.prepare(Action.UPDATE);
882 repoSession = getRepositorySession();
883 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, csid);
884 DocumentModel doc = null;
886 doc = repoSession.getDocument(docRef);
887 } catch (ClientException ce) {
888 String msg = logException(ce, "Could not find document to update with CSID=" + csid);
889 throw new DocumentNotFoundException(msg, ce);
892 // Set reposession to handle the document
894 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
895 DocumentWrapper<DocumentModel> wrapDoc = new DocumentWrapperImpl<DocumentModel>(doc);
896 handler.handle(Action.UPDATE, wrapDoc);
897 repoSession.saveDocument(doc);
899 handler.complete(Action.UPDATE, wrapDoc);
900 } catch (BadRequestException bre) {
902 } catch (DocumentException de) {
904 } catch (WebApplicationException wae){
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(repoSession);
919 * Save a documentModel to the Nuxeo repository.
920 * @param ctx service context under which this method is invoked
921 * @param docModel the document to save
922 * @param fSaveSession if TRUE, will call CoreSession.save() to save accumulated changes.
923 * @throws DocumentException
925 public void saveDocWithoutHandlerProcessing(
926 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
927 RepositoryInstance repoSession,
928 DocumentModel docModel,
929 boolean fSaveSession)
930 throws ClientException, DocumentException {
933 repoSession.saveDocument(docModel);
937 } catch (ClientException ce) {
939 } catch (Exception e) {
940 if (logger.isDebugEnabled()) {
941 logger.debug("Caught exception ", e);
943 throw new DocumentException(e);
949 * Save a list of documentModels to the Nuxeo repository.
951 * @param ctx service context under which this method is invoked
952 * @param docModel the document to save
953 * @param fSaveSession if TRUE, will call CoreSession.save() to save accumulated changes.
954 * @throws DocumentException
956 public void saveDocListWithoutHandlerProcessing(
957 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
958 RepositoryInstance repoSession,
959 DocumentModelList docList,
960 boolean fSaveSession)
961 throws ClientException, DocumentException {
963 repoSession = getRepositorySession();
964 DocumentModel[] docModelArray = new DocumentModel[docList.size()];
965 repoSession.saveDocuments(docList.toArray(docModelArray));
969 } catch (ClientException ce) {
971 } catch (Exception e) {
972 logger.error("Caught exception ", e);
973 throw new DocumentException(e);
978 * delete a document from the Nuxeo repository
979 * @param ctx service context under which this method is invoked
982 * @throws DocumentException
985 public void delete(ServiceContext ctx, String id, DocumentHandler handler) throws DocumentNotFoundException,
988 throw new IllegalArgumentException(
989 "delete(ctx, ix, handler): ctx is missing");
991 if (handler == null) {
992 throw new IllegalArgumentException(
993 "delete(ctx, ix, handler): handler is missing");
995 if (logger.isDebugEnabled()) {
996 logger.debug("Deleting document with CSID=" + id);
998 RepositoryInstance repoSession = null;
1000 handler.prepare(Action.DELETE);
1001 repoSession = getRepositorySession();
1002 DocumentWrapper<DocumentModel> wrapDoc = null;
1004 DocumentRef docRef = NuxeoUtils.createPathRef(ctx, id);
1005 wrapDoc = new DocumentWrapperImpl<DocumentModel>(repoSession.getDocument(docRef));
1006 ((DocumentModelHandler) handler).setRepositorySession(repoSession);
1007 handler.handle(Action.DELETE, wrapDoc);
1008 repoSession.removeDocument(docRef);
1009 } catch (ClientException ce) {
1010 String msg = logException(ce, "Could not find document to delete with CSID=" + id);
1011 throw new DocumentNotFoundException(msg, ce);
1014 handler.complete(Action.DELETE, wrapDoc);
1015 } catch (DocumentException de) {
1017 } catch (Exception e) {
1018 if (logger.isDebugEnabled()) {
1019 logger.debug("Caught exception ", e);
1021 throw new DocumentException(e);
1023 if (repoSession != null) {
1024 releaseRepositorySession(repoSession);
1030 * @see org.collectionspace.services.common.storage.StorageClient#delete(org.collectionspace.services.common.context.ServiceContext, java.lang.String, org.collectionspace.services.common.document.DocumentHandler)
1034 public void delete(@SuppressWarnings("rawtypes") ServiceContext ctx, String id)
1035 throws DocumentNotFoundException, DocumentException {
1036 throw new UnsupportedOperationException();
1037 // Use the other delete instead
1041 public Hashtable<String, String> retrieveWorkspaceIds(String domainName) throws Exception {
1042 return NuxeoConnectorEmbedded.getInstance().retrieveWorkspaceIds(domainName);
1046 public String createDomain(String domainName) throws Exception {
1047 RepositoryInstance repoSession = null;
1048 String domainId = null;
1051 // First create the top-level domain directory
1053 repoSession = getRepositorySession();
1054 DocumentRef parentDocRef = new PathRef("/");
1055 DocumentModel parentDoc = repoSession.getDocument(parentDocRef);
1056 DocumentModel domainDoc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1057 domainName, NUXEO_CORE_TYPE_DOMAIN);
1058 domainDoc.setPropertyValue("dc:title", domainName);
1059 domainDoc.setPropertyValue("dc:description", "A CollectionSpace domain "
1061 domainDoc = repoSession.createDocument(domainDoc);
1062 domainId = domainDoc.getId();
1065 // Next, create a "Workspaces" root directory to contain the workspace folders for the individual service documents
1067 DocumentModel workspacesRoot = repoSession.createDocumentModel(domainDoc.getPathAsString(),
1068 NuxeoUtils.Workspaces, NUXEO_CORE_TYPE_WORKSPACEROOT);
1069 workspacesRoot.setPropertyValue("dc:title", NuxeoUtils.Workspaces);
1070 workspacesRoot.setPropertyValue("dc:description", "A CollectionSpace workspaces directory for "
1071 + domainDoc.getPathAsString());
1072 workspacesRoot = repoSession.createDocument(workspacesRoot);
1073 String workspacesRootId = workspacesRoot.getId();
1076 if (logger.isDebugEnabled()) {
1077 logger.debug("Created tenant domain name=" + domainName
1078 + " id=" + domainId + " " +
1079 NuxeoUtils.Workspaces + " id=" + workspacesRootId);
1080 logger.debug("Path to Domain: "+domainDoc.getPathAsString());
1081 logger.debug("Path to Workspaces root: "+workspacesRoot.getPathAsString());
1083 } catch (Exception e) {
1084 if (logger.isDebugEnabled()) {
1085 logger.debug("Could not create tenant domain name=" + domainName + " caught exception ", e);
1089 if (repoSession != null) {
1090 releaseRepositorySession(repoSession);
1098 public String getDomainId(String domainName) throws Exception {
1099 String domainId = null;
1100 RepositoryInstance repoSession = null;
1102 if (domainName != null && !domainName.isEmpty()) {
1104 repoSession = getRepositorySession();
1105 DocumentRef docRef = new PathRef(
1107 DocumentModel domain = repoSession.getDocument(docRef);
1108 domainId = domain.getId();
1109 } catch (Exception e) {
1110 if (logger.isTraceEnabled()) {
1111 logger.trace("Caught exception ", e);
1113 //there is no way to identify if document does not exist due to
1114 //lack of typed exception for getDocument method
1117 if (repoSession != null) {
1118 releaseRepositorySession(repoSession);
1127 * Returns the workspaces root directory for a given domain.
1129 private DocumentModel getWorkspacesRoot(RepositoryInstance repoSession,
1130 String domainName) throws Exception {
1131 DocumentModel result = null;
1133 String domainPath = "/" + domainName;
1134 DocumentRef parentDocRef = new PathRef(domainPath);
1135 DocumentModelList domainChildrenList = repoSession.getChildren(
1137 Iterator<DocumentModel> witer = domainChildrenList.iterator();
1138 while (witer.hasNext()) {
1139 DocumentModel childNode = witer.next();
1140 if (NuxeoUtils.Workspaces.equalsIgnoreCase(childNode.getName())) {
1142 logger.trace("Found workspaces directory at: " + result.getPathAsString());
1147 if (result == null) {
1148 throw new ClientException("Could not find workspace root directory in: "
1156 * @see org.collectionspace.services.common.repository.RepositoryClient#createWorkspace(java.lang.String, java.lang.String)
1159 public String createWorkspace(String domainName, String workspaceName) throws Exception {
1160 RepositoryInstance repoSession = null;
1161 String workspaceId = null;
1163 repoSession = getRepositorySession();
1164 DocumentModel parentDoc = getWorkspacesRoot(repoSession, domainName);
1165 DocumentModel doc = repoSession.createDocumentModel(parentDoc.getPathAsString(),
1166 workspaceName, NuxeoUtils.WORKSPACE_DOCUMENT_TYPE);
1167 doc.setPropertyValue("dc:title", workspaceName);
1168 doc.setPropertyValue("dc:description", "A CollectionSpace workspace for "
1170 doc = repoSession.createDocument(doc);
1171 workspaceId = doc.getId();
1173 if (logger.isDebugEnabled()) {
1174 logger.debug("Created workspace name=" + workspaceName
1175 + " id=" + workspaceId);
1177 } catch (Exception e) {
1178 if (logger.isDebugEnabled()) {
1179 logger.debug("createWorkspace caught exception ", e);
1183 if (repoSession != null) {
1184 releaseRepositorySession(repoSession);
1191 * @see org.collectionspace.services.common.repository.RepositoryClient#getWorkspaceId(java.lang.String, java.lang.String)
1194 public String getWorkspaceId(String tenantDomain, String workspaceName) throws Exception {
1195 String workspaceId = null;
1197 RepositoryInstance repoSession = null;
1199 repoSession = getRepositorySession();
1200 DocumentRef docRef = new PathRef(
1202 + "/" + NuxeoUtils.Workspaces
1203 + "/" + workspaceName);
1204 DocumentModel workspace = repoSession.getDocument(docRef);
1205 workspaceId = workspace.getId();
1206 } catch (DocumentException de) {
1208 } catch (Exception e) {
1209 if (logger.isDebugEnabled()) {
1210 logger.debug("Caught exception ", e);
1212 throw new DocumentException(e);
1214 if (repoSession != null) {
1215 releaseRepositorySession(repoSession);
1224 * Gets the repository session. - Package access only.
1226 * @return the repository session
1227 * @throws Exception the exception
1229 public RepositoryInstance getRepositorySession() throws Exception {
1230 // FIXME: is it possible to reuse repository session?
1231 // Authentication failures happen while trying to reuse the session
1232 Profiler profiler = new Profiler("getRepositorySession():", 2);
1235 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1236 RepositoryInstance repoSession = client.openRepository();
1237 if (logger.isTraceEnabled()) {
1238 logger.trace("Testing call to getRepository() repository root: " + repoSession.getRootDocument());
1246 * Release repository session. - Package access only.
1248 * @param repoSession the repo session
1250 public void releaseRepositorySession(RepositoryInstance repoSession) {
1252 NuxeoClientEmbedded client = NuxeoConnectorEmbedded.getInstance().getClient();
1254 client.releaseRepository(repoSession);
1255 } catch (Exception e) {
1256 logger.error("Could not close the repository session", e);
1257 // no need to throw this service specific exception
1262 public void doWorkflowTransition(ServiceContext ctx, String id,
1263 DocumentHandler handler, TransitionDef transitionDef)
1264 throws BadRequestException, DocumentNotFoundException,
1266 // 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