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 * Unless required by applicable law or agreed to in writing, software
19 * distributed under the License is distributed on an "AS IS" BASIS,
20 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21 * See the License for the specific language governing permissions and
22 * limitations under the License.
24 package org.collectionspace.services.nuxeo.client.java;
26 import java.util.Collection;
27 import java.util.List;
29 import javax.ws.rs.core.MultivaluedMap;
31 import org.collectionspace.services.client.Profiler;
32 import org.collectionspace.services.client.CollectionSpaceClient;
33 import org.collectionspace.services.client.IQueryManager;
34 import org.collectionspace.services.client.IRelationsManager;
35 import org.collectionspace.services.client.PoxPayloadIn;
36 import org.collectionspace.services.client.PoxPayloadOut;
37 import org.collectionspace.services.common.api.GregorianCalendarDateTimeUtils;
38 import org.collectionspace.services.common.api.RefName;
39 import org.collectionspace.services.common.api.RefName.RefNameInterface;
40 import org.collectionspace.services.common.authorityref.AuthorityRefList;
41 import org.collectionspace.services.common.context.ServiceContext;
42 import org.collectionspace.services.common.document.AbstractMultipartDocumentHandlerImpl;
43 import org.collectionspace.services.common.document.DocumentFilter;
44 import org.collectionspace.services.common.document.DocumentWrapper;
45 import org.collectionspace.services.common.document.DocumentWrapperImpl;
46 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
47 import org.collectionspace.services.common.query.QueryContext;
48 import org.collectionspace.services.common.repository.RepositoryClient;
49 import org.collectionspace.services.common.repository.RepositoryClientFactory;
50 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.AuthRefConfigInfo;
51 import org.collectionspace.services.lifecycle.Lifecycle;
52 import org.collectionspace.services.lifecycle.State;
53 import org.collectionspace.services.lifecycle.StateList;
54 import org.collectionspace.services.lifecycle.TransitionDef;
55 import org.collectionspace.services.lifecycle.TransitionDefList;
56 import org.collectionspace.services.lifecycle.TransitionList;
58 import org.nuxeo.ecm.core.NXCore;
59 import org.nuxeo.ecm.core.api.ClientException;
60 import org.nuxeo.ecm.core.api.DocumentModel;
61 import org.nuxeo.ecm.core.api.DocumentModelList;
62 import org.nuxeo.ecm.core.api.model.PropertyException;
63 import org.nuxeo.ecm.core.api.repository.RepositoryInstance;
64 import org.nuxeo.ecm.core.lifecycle.LifeCycleService;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
70 * DocumentModelHandler is a base abstract Nuxeo document handler
71 * using Nuxeo Java Remote APIs for CollectionSpace services
73 * $LastChangedRevision: $
76 public abstract class DocumentModelHandler<T, TL>
77 extends AbstractMultipartDocumentHandlerImpl<T, TL, DocumentModel, DocumentModelList> {
79 private final Logger logger = LoggerFactory.getLogger(DocumentModelHandler.class);
80 private RepositoryInstance repositorySession;
83 * Map Nuxeo's life cycle object to our JAX-B based life cycle object
85 private Lifecycle createCollectionSpaceLifecycle(org.nuxeo.ecm.core.lifecycle.LifeCycle nuxeoLifecyle) {
86 Lifecycle result = null;
88 if (nuxeoLifecyle != null) {
90 // Copy the life cycle's name
91 result = new Lifecycle();
92 result.setName(nuxeoLifecyle.getName());
94 // We currently support only one initial state, so take the first one from Nuxeo
95 Collection<String> initialStateNames = nuxeoLifecyle.getInitialStateNames();
96 result.setDefaultInitial(initialStateNames.iterator().next());
98 // Next, we copy the state and corresponding transition lists
99 StateList stateList = new StateList();
100 List<State> states = stateList.getState();
101 Collection<org.nuxeo.ecm.core.lifecycle.LifeCycleState> nuxeoStates = nuxeoLifecyle.getStates();
102 for (org.nuxeo.ecm.core.lifecycle.LifeCycleState nuxeoState : nuxeoStates) {
103 State tempState = new State();
104 tempState.setDescription(nuxeoState.getDescription());
105 tempState.setInitial(nuxeoState.isInitial());
106 tempState.setName(nuxeoState.getName());
107 // Now get the list of transitions
108 TransitionList transitionList = new TransitionList();
109 List<String> transitions = transitionList.getTransition();
110 Collection<String> nuxeoTransitions = nuxeoState.getAllowedStateTransitions();
111 for (String nuxeoTransition : nuxeoTransitions) {
112 transitions.add(nuxeoTransition);
114 tempState.setTransitionList(transitionList);
115 states.add(tempState);
117 result.setStateList(stateList);
119 // Finally, we create the transition definitions
120 TransitionDefList transitionDefList = new TransitionDefList();
121 List<TransitionDef> transitionDefs = transitionDefList.getTransitionDef();
122 Collection<org.nuxeo.ecm.core.lifecycle.LifeCycleTransition> nuxeoTransitionDefs = nuxeoLifecyle.getTransitions();
123 for (org.nuxeo.ecm.core.lifecycle.LifeCycleTransition nuxeoTransitionDef : nuxeoTransitionDefs) {
124 TransitionDef tempTransitionDef = new TransitionDef();
125 tempTransitionDef.setDescription(nuxeoTransitionDef.getDescription());
126 tempTransitionDef.setDestinationState(nuxeoTransitionDef.getDestinationStateName());
127 tempTransitionDef.setName(nuxeoTransitionDef.getName());
128 transitionDefs.add(tempTransitionDef);
130 result.setTransitionDefList(transitionDefList);
137 * Returns the the life cycle definition of the related Nuxeo document type for this handler.
139 * @see org.collectionspace.services.common.document.DocumentHandler#getLifecycle()
142 public Lifecycle getLifecycle() {
143 Lifecycle result = null;
145 String docTypeName = null;
147 docTypeName = this.getServiceContext().getDocumentType();
148 result = getLifecycle(docTypeName);
149 } catch (Exception e) {
150 if (logger.isTraceEnabled() == true) {
151 logger.trace("Could not retrieve lifecycle definition for Nuxeo doctype: " + docTypeName);
159 * Returns the the life cycle definition of the related Nuxeo document type for this handler.
161 * @see org.collectionspace.services.common.document.DocumentHandler#getLifecycle(java.lang.String)
164 public Lifecycle getLifecycle(String docTypeName) {
165 org.nuxeo.ecm.core.lifecycle.LifeCycle nuxeoLifecyle;
166 Lifecycle result = null;
169 LifeCycleService lifeCycleService = null;
171 lifeCycleService = NXCore.getLifeCycleService();
172 } catch (Exception e) {
176 String lifeCycleName;
177 lifeCycleName = lifeCycleService.getLifeCycleNameFor(docTypeName);
178 nuxeoLifecyle = lifeCycleService.getLifeCycleByName(lifeCycleName);
180 result = createCollectionSpaceLifecycle(nuxeoLifecyle);
181 // result = (Lifecycle)FileTools.getJaxbObjectFromFile(Lifecycle.class, "default-lifecycle.xml");
182 } catch (Exception e) {
183 // TODO Auto-generated catch block
184 logger.error("Could not retreive life cycle information for Nuxeo doctype: " + docTypeName, e);
191 * We're using the "name" field of Nuxeo's DocumentModel to store
194 public String getCsid(DocumentModel docModel) {
195 return NuxeoUtils.getCsid(docModel);
198 public String getUri(DocumentModel docModel) {
199 return getServiceContextPath()+getCsid(docModel);
202 public RepositoryClient<PoxPayloadIn, PoxPayloadOut> getRepositoryClient(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
203 RepositoryClient<PoxPayloadIn, PoxPayloadOut> repositoryClient = RepositoryClientFactory.getInstance().getClient(ctx.getRepositoryClientName());
204 return repositoryClient;
208 * getRepositorySession returns Nuxeo Repository Session
211 public RepositoryInstance getRepositorySession() {
213 return repositorySession;
217 * setRepositorySession sets repository session
220 public void setRepositorySession(RepositoryInstance repoSession) {
221 this.repositorySession = repoSession;
225 public void handleCreate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
226 // TODO for sub-docs - check to see if the current service context is a multipart input,
227 // OR a docfragment, and call a variant to fill the DocModel.
228 fillAllParts(wrapDoc, Action.CREATE);
229 handleCoreValues(wrapDoc, Action.CREATE);
232 // TODO for sub-docs - Add completeCreate in which we look for set-aside doc fragments
233 // and create the subitems. We will create service contexts with the doc fragments
238 public void handleUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
239 // TODO for sub-docs - check to see if the current service context is a multipart input,
240 // OR a docfragment, and call a variant to fill the DocModel.
241 fillAllParts(wrapDoc, Action.UPDATE);
242 handleCoreValues(wrapDoc, Action.UPDATE);
246 public void handleGet(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
247 extractAllParts(wrapDoc);
251 public void handleGetAll(DocumentWrapper<DocumentModelList> wrapDoc) throws Exception {
252 Profiler profiler = new Profiler(this, 2);
254 setCommonPartList(extractCommonPartList(wrapDoc));
259 public abstract void completeUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception;
262 public abstract void extractAllParts(DocumentWrapper<DocumentModel> wrapDoc) throws Exception;
265 public abstract T extractCommonPart(DocumentWrapper<DocumentModel> wrapDoc) throws Exception;
268 public abstract void fillAllParts(DocumentWrapper<DocumentModel> wrapDoc, Action action) throws Exception;
271 public abstract void fillCommonPart(T obj, DocumentWrapper<DocumentModel> wrapDoc) throws Exception;
274 public abstract TL extractCommonPartList(DocumentWrapper<DocumentModelList> wrapDoc) throws Exception;
277 public abstract T getCommonPart();
280 public abstract void setCommonPart(T obj);
283 public abstract TL getCommonPartList();
286 public abstract void setCommonPartList(TL obj);
289 public DocumentFilter createDocumentFilter() {
290 DocumentFilter filter = new NuxeoDocumentFilter(this.getServiceContext());
295 * Gets the authority refs.
297 * @param docWrapper the doc wrapper
298 * @param authRefFields the auth ref fields
299 * @return the authority refs
300 * @throws PropertyException the property exception
302 abstract public AuthorityRefList getAuthorityRefs(String csid,
303 List<AuthRefConfigInfo> authRefsInfo) throws PropertyException;
306 * Subclasses should override this method if they need to customize their refname generation
308 protected RefName.RefNameInterface getRefName(ServiceContext ctx,
309 DocumentModel docModel) {
310 return getRefName(new DocumentWrapperImpl<DocumentModel>(docModel), ctx.getTenantName(), ctx.getServiceName());
314 * By default, we'll use the CSID as the short ID. Sub-classes can override this method if they want to use
315 * something else for a short ID.
318 * @see org.collectionspace.services.common.document.AbstractDocumentHandlerImpl#getRefName(org.collectionspace.services.common.document.DocumentWrapper, java.lang.String, java.lang.String)
321 protected RefName.RefNameInterface getRefName(DocumentWrapper<DocumentModel> docWrapper,
322 String tenantName, String serviceName) {
323 String csid = docWrapper.getWrappedObject().getName();
324 String refnameDisplayName = getRefnameDisplayName(docWrapper);
325 RefName.RefNameInterface refname = RefName.Authority.buildAuthority(tenantName, serviceName,
326 csid, null, refnameDisplayName);
330 private void handleCoreValues(DocumentWrapper<DocumentModel> docWrapper,
331 Action action) throws ClientException {
332 DocumentModel documentModel = docWrapper.getWrappedObject();
333 String now = GregorianCalendarDateTimeUtils.timestampUTC();
334 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
335 String userId = ctx.getUserId();
336 if (action == Action.CREATE) {
338 // Add the tenant ID value to the new entity
340 String tenantId = ctx.getTenantId();
341 documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
342 CollectionSpaceClient.COLLECTIONSPACE_CORE_TENANTID, tenantId);
344 // Add the uri value to the new entity
346 documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
347 CollectionSpaceClient.COLLECTIONSPACE_CORE_URI, getUri(documentModel));
349 // Add the resource's refname
351 RefNameInterface refname = getRefName(ctx, documentModel); // Sub-classes may override the getRefName() method called here.
352 if (refname != null) {
353 String refnameStr = refname.toString();
354 documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
355 CollectionSpaceClient.COLLECTIONSPACE_CORE_REFNAME, refnameStr);
358 // Add the CSID to the DublinCore title so we can see the CSID in the default
362 documentModel.setProperty("dublincore", "title",
363 documentModel.getName());
364 } catch (Exception x) {
365 if (logger.isWarnEnabled() == true) {
366 logger.warn("Could not set the Dublin Core 'title' field on document CSID:" +
367 documentModel.getName());
370 documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
371 CollectionSpaceClient.COLLECTIONSPACE_CORE_CREATED_AT, now);
372 documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
373 CollectionSpaceClient.COLLECTIONSPACE_CORE_CREATED_BY, userId);
376 if (action == Action.CREATE || action == Action.UPDATE) {
377 documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
378 CollectionSpaceClient.COLLECTIONSPACE_CORE_UPDATED_AT, now);
379 documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
380 CollectionSpaceClient.COLLECTIONSPACE_CORE_UPDATED_BY, userId);
385 * If we see the "rtSbj" query param then we need to perform a CMIS query. Currently, we have only one
386 * CMIS query, but we could add more. If we do, this method should look at the incoming request and corresponding
387 * query params to determine if we need to do a CMIS query
389 * @see org.collectionspace.services.common.document.AbstractDocumentHandlerImpl#isCMISQuery()
391 public boolean isCMISQuery() {
392 boolean result = false;
394 MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams();
396 // Look the query params to see if we need to make a CMSIS query.
398 String asSubjectCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT);
399 String asOjectCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT);
400 String asEither = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_EITHER);
401 if (asSubjectCsid != null || asOjectCsid != null || asEither != null) {
409 * Creates the CMIS query from the service context. Each document handler is
410 * responsible for returning (can override) a valid CMIS query using the information in the
411 * current service context -which includes things like the query parameters,
414 * This method implementation supports three mutually exclusive cases. We will build a query
415 * that can find a document(s) 'A' in a relationship with another document
416 * 'B' where document 'B' has a CSID equal to the query param passed in and:
417 * 1. Document 'B' is the subject of the relationship
418 * 2. Document 'B' is the object of the relationship
419 * 3. Document 'B' is either the object or the subject of the relationship
422 public String getCMISQuery(QueryContext queryContext) {
423 String result = null;
425 if (isCMISQuery() == true) {
427 // Build up the query arguments
429 String theOnClause = "";
430 String theWhereClause = "";
431 MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams();
432 String asSubjectCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT);
433 String asObjectCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT);
434 String asEitherCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_EITHER);
435 String matchObjDocTypes = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_MATCH_OBJ_DOCTYPES);
436 String selectDocType = (String)queryParams.getFirst(IQueryManager.SELECT_DOC_TYPE_FIELD);
438 String docType = this.getServiceContext().getDocumentType();
439 if (selectDocType != null && !selectDocType.isEmpty()) {
440 docType = selectDocType;
442 String selectFields = IQueryManager.CMIS_TARGET_CSID + ", "
443 + IQueryManager.CMIS_TARGET_TITLE + ", "
444 + IRelationsManager.CMIS_CSPACE_RELATIONS_TITLE + ", "
445 + IRelationsManager.CMIS_CSPACE_RELATIONS_OBJECT_ID + ", "
446 + IRelationsManager.CMIS_CSPACE_RELATIONS_SUBJECT_ID;
447 String targetTable = docType + " " + IQueryManager.CMIS_TARGET_PREFIX;
448 String relTable = IRelationsManager.DOC_TYPE + " " + IQueryManager.CMIS_RELATIONS_PREFIX;
449 String relObjectCsidCol = IRelationsManager.CMIS_CSPACE_RELATIONS_OBJECT_ID;
450 String relSubjectCsidCol = IRelationsManager.CMIS_CSPACE_RELATIONS_SUBJECT_ID;
451 String targetCsidCol = IQueryManager.CMIS_TARGET_CSID;
454 // Create the "ON" and "WHERE" query clauses based on the params passed into the HTTP request.
456 // First come, first serve -the first match determines the "ON" and "WHERE" query clauses.
458 if (asSubjectCsid != null && !asSubjectCsid.isEmpty()) {
459 // Since our query param is the "subject" value, join the tables where the CSID of the document is the other side (the "object") of the relationship.
460 theOnClause = relObjectCsidCol + " = " + targetCsidCol;
461 theWhereClause = relSubjectCsidCol + " = " + "'" + asSubjectCsid + "'";
462 } else if (asObjectCsid != null && !asObjectCsid.isEmpty()) {
463 // Since our query param is the "object" value, join the tables where the CSID of the document is the other side (the "subject") of the relationship.
464 theOnClause = relSubjectCsidCol + " = " + targetCsidCol;
465 theWhereClause = relObjectCsidCol + " = " + "'" + asObjectCsid + "'";
466 } else if (asEitherCsid != null && !asEitherCsid.isEmpty()) {
467 theOnClause = relObjectCsidCol + " = " + targetCsidCol
468 + " OR " + relSubjectCsidCol + " = " + targetCsidCol;
469 theWhereClause = relSubjectCsidCol + " = " + "'" + asEitherCsid + "'"
470 + " OR " + relObjectCsidCol + " = " + "'" + asEitherCsid + "'";
472 //Since the call to isCMISQuery() return true, we should never get here.
473 logger.error("Attempt to make CMIS query failed because the HTTP request was missing valid query parameters.");
476 // Now consider a constraint on the object doc types (for search by service group)
477 if (matchObjDocTypes != null && !matchObjDocTypes.isEmpty()) {
478 // Since our query param is the "subject" value, join the tables where the CSID of the document is the other side (the "object") of the relationship.
479 theWhereClause += " AND (" + IRelationsManager.CMIS_CSPACE_RELATIONS_OBJECT_TYPE
480 + " IN " + matchObjDocTypes + ")";
483 StringBuilder query = new StringBuilder();
484 // assemble the query from the string arguments
485 query.append("SELECT ");
486 query.append(selectFields);
487 query.append(" FROM " + targetTable + " JOIN " + relTable);
488 query.append(" ON " + theOnClause);
489 query.append(" WHERE " + theWhereClause);
492 NuxeoUtils.appendCMISOrderBy(query, queryContext);
493 } catch (Exception e) {
494 logger.error("Could not append ORDER BY clause to CMIS query", e);
498 // SELECT D.cmis:name, D.dc:title, R.dc:title, R.relations_common:subjectCsid
499 // FROM Dimension D JOIN Relation R
500 // ON R.relations_common:objectCsid = D.cmis:name
501 // WHERE R.relations_common:subjectCsid = '737527ec-a560-4776-99de'
502 // ORDER BY D.collectionspace_core:updatedAt DESC
504 result = query.toString();
505 if (logger.isDebugEnabled() == true && result != null) {
506 logger.debug("The CMIS query is: " + result);