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.api.Tools;
41 import org.collectionspace.services.common.authorityref.AuthorityRefList;
42 import org.collectionspace.services.common.context.ServiceContext;
43 import org.collectionspace.services.common.document.AbstractMultipartDocumentHandlerImpl;
44 import org.collectionspace.services.common.document.DocumentFilter;
45 import org.collectionspace.services.common.document.DocumentWrapper;
46 import org.collectionspace.services.common.document.DocumentWrapperImpl;
47 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
48 import org.collectionspace.services.common.query.QueryContext;
49 import org.collectionspace.services.common.repository.RepositoryClient;
50 import org.collectionspace.services.common.repository.RepositoryClientFactory;
51 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.AuthRefConfigInfo;
52 import org.collectionspace.services.lifecycle.Lifecycle;
53 import org.collectionspace.services.lifecycle.State;
54 import org.collectionspace.services.lifecycle.StateList;
55 import org.collectionspace.services.lifecycle.TransitionDef;
56 import org.collectionspace.services.lifecycle.TransitionDefList;
57 import org.collectionspace.services.lifecycle.TransitionList;
59 import org.nuxeo.ecm.core.NXCore;
60 import org.nuxeo.ecm.core.api.ClientException;
61 import org.nuxeo.ecm.core.api.DocumentModel;
62 import org.nuxeo.ecm.core.api.DocumentModelList;
63 import org.nuxeo.ecm.core.api.model.PropertyException;
64 import org.nuxeo.ecm.core.api.repository.RepositoryInstance;
65 import org.nuxeo.ecm.core.lifecycle.LifeCycleService;
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
71 * DocumentModelHandler is a base abstract Nuxeo document handler
72 * using Nuxeo Java Remote APIs for CollectionSpace services
74 * $LastChangedRevision: $
77 public abstract class DocumentModelHandler<T, TL>
78 extends AbstractMultipartDocumentHandlerImpl<T, TL, DocumentModel, DocumentModelList> {
80 private final Logger logger = LoggerFactory.getLogger(DocumentModelHandler.class);
81 private RepositoryInstance repositorySession;
83 protected String oldRefNameOnUpdate = null; // FIXME: REM - We should have setters and getters for these
84 protected String newRefNameOnUpdate = null; // FIXME: two fields.
87 * Map Nuxeo's life cycle object to our JAX-B based life cycle object
89 private Lifecycle createCollectionSpaceLifecycle(org.nuxeo.ecm.core.lifecycle.LifeCycle nuxeoLifecyle) {
90 Lifecycle result = null;
92 if (nuxeoLifecyle != null) {
94 // Copy the life cycle's name
95 result = new Lifecycle();
96 result.setName(nuxeoLifecyle.getName());
98 // We currently support only one initial state, so take the first one from Nuxeo
99 Collection<String> initialStateNames = nuxeoLifecyle.getInitialStateNames();
100 result.setDefaultInitial(initialStateNames.iterator().next());
102 // Next, we copy the state and corresponding transition lists
103 StateList stateList = new StateList();
104 List<State> states = stateList.getState();
105 Collection<org.nuxeo.ecm.core.lifecycle.LifeCycleState> nuxeoStates = nuxeoLifecyle.getStates();
106 for (org.nuxeo.ecm.core.lifecycle.LifeCycleState nuxeoState : nuxeoStates) {
107 State tempState = new State();
108 tempState.setDescription(nuxeoState.getDescription());
109 tempState.setInitial(nuxeoState.isInitial());
110 tempState.setName(nuxeoState.getName());
111 // Now get the list of transitions
112 TransitionList transitionList = new TransitionList();
113 List<String> transitions = transitionList.getTransition();
114 Collection<String> nuxeoTransitions = nuxeoState.getAllowedStateTransitions();
115 for (String nuxeoTransition : nuxeoTransitions) {
116 transitions.add(nuxeoTransition);
118 tempState.setTransitionList(transitionList);
119 states.add(tempState);
121 result.setStateList(stateList);
123 // Finally, we create the transition definitions
124 TransitionDefList transitionDefList = new TransitionDefList();
125 List<TransitionDef> transitionDefs = transitionDefList.getTransitionDef();
126 Collection<org.nuxeo.ecm.core.lifecycle.LifeCycleTransition> nuxeoTransitionDefs = nuxeoLifecyle.getTransitions();
127 for (org.nuxeo.ecm.core.lifecycle.LifeCycleTransition nuxeoTransitionDef : nuxeoTransitionDefs) {
128 TransitionDef tempTransitionDef = new TransitionDef();
129 tempTransitionDef.setDescription(nuxeoTransitionDef.getDescription());
130 tempTransitionDef.setDestinationState(nuxeoTransitionDef.getDestinationStateName());
131 tempTransitionDef.setName(nuxeoTransitionDef.getName());
132 transitionDefs.add(tempTransitionDef);
134 result.setTransitionDefList(transitionDefList);
141 * Returns the the life cycle definition of the related Nuxeo document type for this handler.
143 * @see org.collectionspace.services.common.document.DocumentHandler#getLifecycle()
146 public Lifecycle getLifecycle() {
147 Lifecycle result = null;
149 String docTypeName = null;
151 docTypeName = this.getServiceContext().getDocumentType();
152 result = getLifecycle(docTypeName);
153 } catch (Exception e) {
154 if (logger.isTraceEnabled() == true) {
155 logger.trace("Could not retrieve lifecycle definition for Nuxeo doctype: " + docTypeName);
163 * Returns the the life cycle definition of the related Nuxeo document type for this handler.
165 * @see org.collectionspace.services.common.document.DocumentHandler#getLifecycle(java.lang.String)
168 public Lifecycle getLifecycle(String docTypeName) {
169 org.nuxeo.ecm.core.lifecycle.LifeCycle nuxeoLifecyle;
170 Lifecycle result = null;
173 LifeCycleService lifeCycleService = null;
175 lifeCycleService = NXCore.getLifeCycleService();
176 } catch (Exception e) {
180 String lifeCycleName;
181 lifeCycleName = lifeCycleService.getLifeCycleNameFor(docTypeName);
182 nuxeoLifecyle = lifeCycleService.getLifeCycleByName(lifeCycleName);
184 result = createCollectionSpaceLifecycle(nuxeoLifecyle);
185 // result = (Lifecycle)FileTools.getJaxbObjectFromFile(Lifecycle.class, "default-lifecycle.xml");
186 } catch (Exception e) {
187 // TODO Auto-generated catch block
188 logger.error("Could not retreive life cycle information for Nuxeo doctype: " + docTypeName, e);
195 * We're using the "name" field of Nuxeo's DocumentModel to store
198 public String getCsid(DocumentModel docModel) {
199 return NuxeoUtils.getCsid(docModel);
202 public String getUri(DocumentModel docModel) {
203 return getServiceContextPath()+getCsid(docModel);
206 public RepositoryClient<PoxPayloadIn, PoxPayloadOut> getRepositoryClient(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
207 RepositoryClient<PoxPayloadIn, PoxPayloadOut> repositoryClient = RepositoryClientFactory.getInstance().getClient(ctx.getRepositoryClientName());
208 return repositoryClient;
212 * getRepositorySession returns Nuxeo Repository Session
215 public RepositoryInstance getRepositorySession() {
217 return repositorySession;
221 * setRepositorySession sets repository session
224 public void setRepositorySession(RepositoryInstance repoSession) {
225 this.repositorySession = repoSession;
229 public void handleCreate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
230 // TODO for sub-docs - check to see if the current service context is a multipart input,
231 // OR a docfragment, and call a variant to fill the DocModel.
232 fillAllParts(wrapDoc, Action.CREATE);
233 handleCoreValues(wrapDoc, Action.CREATE);
236 // TODO for sub-docs - Add completeCreate in which we look for set-aside doc fragments
237 // and create the subitems. We will create service contexts with the doc fragments
242 public void handleUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
243 // TODO for sub-docs - check to see if the current service context is a multipart input,
244 // OR a docfragment, and call a variant to fill the DocModel.
245 fillAllParts(wrapDoc, Action.UPDATE);
246 handleCoreValues(wrapDoc, Action.UPDATE);
250 public void handleGet(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
251 extractAllParts(wrapDoc);
255 public void handleGetAll(DocumentWrapper<DocumentModelList> wrapDoc) throws Exception {
256 Profiler profiler = new Profiler(this, 2);
258 setCommonPartList(extractCommonPartList(wrapDoc));
263 public abstract void completeUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception;
266 public abstract void extractAllParts(DocumentWrapper<DocumentModel> wrapDoc) throws Exception;
269 public abstract T extractCommonPart(DocumentWrapper<DocumentModel> wrapDoc) throws Exception;
272 public abstract void fillAllParts(DocumentWrapper<DocumentModel> wrapDoc, Action action) throws Exception;
275 public abstract void fillCommonPart(T obj, DocumentWrapper<DocumentModel> wrapDoc) throws Exception;
278 public abstract TL extractCommonPartList(DocumentWrapper<DocumentModelList> wrapDoc) throws Exception;
281 public abstract T getCommonPart();
284 public abstract void setCommonPart(T obj);
287 public abstract TL getCommonPartList();
290 public abstract void setCommonPartList(TL obj);
293 public DocumentFilter createDocumentFilter() {
294 DocumentFilter filter = new NuxeoDocumentFilter(this.getServiceContext());
299 * Gets the authority refs.
301 * @param docWrapper the doc wrapper
302 * @param authRefFields the auth ref fields
303 * @return the authority refs
304 * @throws PropertyException the property exception
306 abstract public AuthorityRefList getAuthorityRefs(String csid,
307 List<AuthRefConfigInfo> authRefsInfo) throws PropertyException, Exception;
310 * Subclasses should override this method if they need to customize their refname generation
312 protected RefName.RefNameInterface getRefName(ServiceContext ctx,
313 DocumentModel docModel) {
314 return getRefName(new DocumentWrapperImpl<DocumentModel>(docModel), ctx.getTenantName(), ctx.getServiceName());
318 * By default, we'll use the CSID as the short ID. Sub-classes can override this method if they want to use
319 * something else for a short ID.
322 * @see org.collectionspace.services.common.document.AbstractDocumentHandlerImpl#getRefName(org.collectionspace.services.common.document.DocumentWrapper, java.lang.String, java.lang.String)
325 protected RefName.RefNameInterface getRefName(DocumentWrapper<DocumentModel> docWrapper,
326 String tenantName, String serviceName) {
327 String csid = docWrapper.getWrappedObject().getName();
328 String refnameDisplayName = getRefnameDisplayName(docWrapper);
329 RefName.RefNameInterface refname = RefName.Authority.buildAuthority(tenantName, serviceName,
330 csid, null, refnameDisplayName);
334 private void handleCoreValues(DocumentWrapper<DocumentModel> docWrapper,
335 Action action) throws ClientException {
336 DocumentModel documentModel = docWrapper.getWrappedObject();
337 String now = GregorianCalendarDateTimeUtils.timestampUTC();
338 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
339 String userId = ctx.getUserId();
340 if (action == Action.CREATE) {
342 // Add the tenant ID value to the new entity
344 String tenantId = ctx.getTenantId();
345 documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
346 CollectionSpaceClient.COLLECTIONSPACE_CORE_TENANTID, tenantId);
348 // Add the uri value to the new entity
350 documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
351 CollectionSpaceClient.COLLECTIONSPACE_CORE_URI, getUri(documentModel));
353 // Add the CSID to the DublinCore title so we can see the CSID in the default
357 documentModel.setProperty("dublincore", "title",
358 documentModel.getName());
359 } catch (Exception x) {
360 if (logger.isWarnEnabled() == true) {
361 logger.warn("Could not set the Dublin Core 'title' field on document CSID:" +
362 documentModel.getName());
366 // Add createdAt timestamp and createdBy user
368 documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
369 CollectionSpaceClient.COLLECTIONSPACE_CORE_CREATED_AT, now);
370 documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
371 CollectionSpaceClient.COLLECTIONSPACE_CORE_CREATED_BY, userId);
374 if (action == Action.CREATE || action == Action.UPDATE) {
376 // Add/update the resource's refname
378 handleRefNameChanges(ctx, documentModel);
380 // Add updatedAt timestamp and updateBy user
382 documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
383 CollectionSpaceClient.COLLECTIONSPACE_CORE_UPDATED_AT, now);
384 documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
385 CollectionSpaceClient.COLLECTIONSPACE_CORE_UPDATED_BY, userId);
389 protected boolean hasRefNameUpdate() {
390 boolean result = false;
392 if (Tools.notBlank(newRefNameOnUpdate) && Tools.notBlank(oldRefNameOnUpdate)) {
393 if (newRefNameOnUpdate.equalsIgnoreCase(oldRefNameOnUpdate) == false) {
394 result = true; // refNames are different so updates are needed
401 protected void handleRefNameChanges(ServiceContext ctx, DocumentModel docModel) throws ClientException {
402 // First get the old refName
403 this.oldRefNameOnUpdate = (String)docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
404 CollectionSpaceClient.COLLECTIONSPACE_CORE_REFNAME);
405 // Next, get the new refName
406 RefNameInterface refName = getRefName(ctx, docModel); // Sub-classes may override the getRefName() method called here.
407 if (refName != null) {
408 this.newRefNameOnUpdate = refName.toString();
410 logger.error(String.format("The refName for document is missing. Document CSID=%s", docModel.getName())); // FIXME: REM - We should probably be throwing an exception here?
413 // Set the refName if it is an update or if the old refName was empty or null
415 if (hasRefNameUpdate() == true || this.oldRefNameOnUpdate == null) {
416 docModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
417 CollectionSpaceClient.COLLECTIONSPACE_CORE_REFNAME, this.newRefNameOnUpdate);
422 * If we see the "rtSbj" query param then we need to perform a CMIS query. Currently, we have only one
423 * CMIS query, but we could add more. If we do, this method should look at the incoming request and corresponding
424 * query params to determine if we need to do a CMIS query
426 * @see org.collectionspace.services.common.document.AbstractDocumentHandlerImpl#isCMISQuery()
428 public boolean isCMISQuery() {
429 boolean result = false;
431 MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams();
433 // Look the query params to see if we need to make a CMSIS query.
435 String asSubjectCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT);
436 String asOjectCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT);
437 String asEither = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_EITHER);
438 if (asSubjectCsid != null || asOjectCsid != null || asEither != null) {
446 * Creates the CMIS query from the service context. Each document handler is
447 * responsible for returning (can override) a valid CMIS query using the information in the
448 * current service context -which includes things like the query parameters,
451 * This method implementation supports three mutually exclusive cases. We will build a query
452 * that can find a document(s) 'A' in a relationship with another document
453 * 'B' where document 'B' has a CSID equal to the query param passed in and:
454 * 1. Document 'B' is the subject of the relationship
455 * 2. Document 'B' is the object of the relationship
456 * 3. Document 'B' is either the object or the subject of the relationship
459 public String getCMISQuery(QueryContext queryContext) {
460 String result = null;
462 if (isCMISQuery() == true) {
464 // Build up the query arguments
466 String theOnClause = "";
467 String theWhereClause = "";
468 MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams();
469 String asSubjectCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT);
470 String asObjectCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT);
471 String asEitherCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_EITHER);
472 String matchObjDocTypes = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_MATCH_OBJ_DOCTYPES);
473 String selectDocType = (String)queryParams.getFirst(IQueryManager.SELECT_DOC_TYPE_FIELD);
475 String docType = this.getServiceContext().getDocumentType();
476 if (selectDocType != null && !selectDocType.isEmpty()) {
477 docType = selectDocType;
479 String selectFields = IQueryManager.CMIS_TARGET_CSID + ", "
480 + IQueryManager.CMIS_TARGET_TITLE + ", "
481 + IRelationsManager.CMIS_CSPACE_RELATIONS_TITLE + ", "
482 + IRelationsManager.CMIS_CSPACE_RELATIONS_OBJECT_ID + ", "
483 + IRelationsManager.CMIS_CSPACE_RELATIONS_SUBJECT_ID;
484 String targetTable = docType + " " + IQueryManager.CMIS_TARGET_PREFIX;
485 String relTable = IRelationsManager.DOC_TYPE + " " + IQueryManager.CMIS_RELATIONS_PREFIX;
486 String relObjectCsidCol = IRelationsManager.CMIS_CSPACE_RELATIONS_OBJECT_ID;
487 String relSubjectCsidCol = IRelationsManager.CMIS_CSPACE_RELATIONS_SUBJECT_ID;
488 String targetCsidCol = IQueryManager.CMIS_TARGET_CSID;
491 // Create the "ON" and "WHERE" query clauses based on the params passed into the HTTP request.
493 // First come, first serve -the first match determines the "ON" and "WHERE" query clauses.
495 if (asSubjectCsid != null && !asSubjectCsid.isEmpty()) {
496 // 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.
497 theOnClause = relObjectCsidCol + " = " + targetCsidCol;
498 theWhereClause = relSubjectCsidCol + " = " + "'" + asSubjectCsid + "'";
499 } else if (asObjectCsid != null && !asObjectCsid.isEmpty()) {
500 // 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.
501 theOnClause = relSubjectCsidCol + " = " + targetCsidCol;
502 theWhereClause = relObjectCsidCol + " = " + "'" + asObjectCsid + "'";
503 } else if (asEitherCsid != null && !asEitherCsid.isEmpty()) {
504 theOnClause = relObjectCsidCol + " = " + targetCsidCol
505 + " OR " + relSubjectCsidCol + " = " + targetCsidCol;
506 theWhereClause = relSubjectCsidCol + " = " + "'" + asEitherCsid + "'"
507 + " OR " + relObjectCsidCol + " = " + "'" + asEitherCsid + "'";
509 //Since the call to isCMISQuery() return true, we should never get here.
510 logger.error("Attempt to make CMIS query failed because the HTTP request was missing valid query parameters.");
513 // Now consider a constraint on the object doc types (for search by service group)
514 if (matchObjDocTypes != null && !matchObjDocTypes.isEmpty()) {
515 // 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.
516 theWhereClause += " AND (" + IRelationsManager.CMIS_CSPACE_RELATIONS_OBJECT_TYPE
517 + " IN " + matchObjDocTypes + ")";
520 // This could later be in control of a queryParam, to omit if we want to see versions, or to
521 // only see old versions.
522 theWhereClause += IQueryManager.SEARCH_QUALIFIER_AND + IQueryManager.CMIS_JOIN_NUXEO_IS_VERSION_FILTER;
524 StringBuilder query = new StringBuilder();
525 // assemble the query from the string arguments
526 query.append("SELECT ");
527 query.append(selectFields);
528 query.append(" FROM " + targetTable + " JOIN " + relTable);
529 query.append(" ON " + theOnClause);
530 query.append(" WHERE " + theWhereClause);
533 NuxeoUtils.appendCMISOrderBy(query, queryContext);
534 } catch (Exception e) {
535 logger.error("Could not append ORDER BY clause to CMIS query", e);
539 // SELECT D.cmis:name, D.dc:title, R.dc:title, R.relations_common:subjectCsid
540 // FROM Dimension D JOIN Relation R
541 // ON R.relations_common:objectCsid = D.cmis:name
542 // WHERE R.relations_common:subjectCsid = '737527ec-a560-4776-99de'
543 // ORDER BY D.collectionspace_core:updatedAt DESC
545 result = query.toString();
546 if (logger.isDebugEnabled() == true && result != null) {
547 logger.debug("The CMIS query is: " + result);