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.apache.commons.lang.StringUtils;
32 import org.collectionspace.services.client.Profiler;
33 import org.collectionspace.services.client.CollectionSpaceClient;
34 import org.collectionspace.services.client.IQueryManager;
35 import org.collectionspace.services.client.IRelationsManager;
36 import org.collectionspace.services.client.PoxPayloadIn;
37 import org.collectionspace.services.client.PoxPayloadOut;
38 import org.collectionspace.services.common.api.CommonAPI;
39 import org.collectionspace.services.common.api.GregorianCalendarDateTimeUtils;
40 import org.collectionspace.services.common.api.RefName;
41 import org.collectionspace.services.common.api.RefName.RefNameInterface;
42 import org.collectionspace.services.common.api.RefNameUtils;
43 import org.collectionspace.services.common.api.Tools;
44 import org.collectionspace.services.common.authorityref.AuthorityRefList;
45 import org.collectionspace.services.common.context.ServiceContext;
46 import org.collectionspace.services.common.document.AbstractMultipartDocumentHandlerImpl;
47 import org.collectionspace.services.common.document.DocumentException;
48 import org.collectionspace.services.common.document.DocumentFilter;
49 import org.collectionspace.services.common.document.DocumentWrapper;
50 import org.collectionspace.services.common.document.DocumentWrapperImpl;
51 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
52 import org.collectionspace.services.common.query.QueryContext;
53 import org.collectionspace.services.common.repository.RepositoryClient;
54 import org.collectionspace.services.common.repository.RepositoryClientFactory;
55 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.AuthRefConfigInfo;
56 import org.collectionspace.services.lifecycle.Lifecycle;
57 import org.collectionspace.services.lifecycle.State;
58 import org.collectionspace.services.lifecycle.StateList;
59 import org.collectionspace.services.lifecycle.TransitionDef;
60 import org.collectionspace.services.lifecycle.TransitionDefList;
61 import org.collectionspace.services.lifecycle.TransitionList;
62 import org.nuxeo.ecm.core.NXCore;
63 import org.nuxeo.ecm.core.api.ClientException;
64 import org.nuxeo.ecm.core.api.DocumentModel;
65 import org.nuxeo.ecm.core.api.DocumentModelList;
66 import org.nuxeo.ecm.core.api.model.PropertyException;
67 import org.nuxeo.ecm.core.lifecycle.LifeCycleService;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
72 * DocumentModelHandler is a base abstract Nuxeo document handler
73 * using Nuxeo Java Remote APIs for CollectionSpace services
75 * $LastChangedRevision: $
78 public abstract class DocumentModelHandler<T, TL>
79 extends AbstractMultipartDocumentHandlerImpl<T, TL, DocumentModel, DocumentModelList> {
81 private final Logger logger = LoggerFactory.getLogger(DocumentModelHandler.class);
82 private CoreSessionInterface repositorySession;
84 protected String oldRefNameOnUpdate = null; // FIXME: REM - We should have setters and getters for these
85 protected String newRefNameOnUpdate = null; // FIXME: two fields.
88 * Map Nuxeo's life cycle object to our JAX-B based life cycle object
90 private Lifecycle createCollectionSpaceLifecycle(org.nuxeo.ecm.core.lifecycle.LifeCycle nuxeoLifecyle) {
91 Lifecycle result = null;
93 if (nuxeoLifecyle != null) {
95 // Copy the life cycle's name
96 result = new Lifecycle();
97 result.setName(nuxeoLifecyle.getName());
99 // We currently support only one initial state, so take the first one from Nuxeo
100 Collection<String> initialStateNames = nuxeoLifecyle.getInitialStateNames();
101 result.setDefaultInitial(initialStateNames.iterator().next());
103 // Next, we copy the state and corresponding transition lists
104 StateList stateList = new StateList();
105 List<State> states = stateList.getState();
106 Collection<org.nuxeo.ecm.core.lifecycle.LifeCycleState> nuxeoStates = nuxeoLifecyle.getStates();
107 for (org.nuxeo.ecm.core.lifecycle.LifeCycleState nuxeoState : nuxeoStates) {
108 State tempState = new State();
109 tempState.setDescription(nuxeoState.getDescription());
110 tempState.setInitial(nuxeoState.isInitial());
111 tempState.setName(nuxeoState.getName());
112 // Now get the list of transitions
113 TransitionList transitionList = new TransitionList();
114 List<String> transitions = transitionList.getTransition();
115 Collection<String> nuxeoTransitions = nuxeoState.getAllowedStateTransitions();
116 for (String nuxeoTransition : nuxeoTransitions) {
117 transitions.add(nuxeoTransition);
119 tempState.setTransitionList(transitionList);
120 states.add(tempState);
122 result.setStateList(stateList);
124 // Finally, we create the transition definitions
125 TransitionDefList transitionDefList = new TransitionDefList();
126 List<TransitionDef> transitionDefs = transitionDefList.getTransitionDef();
127 Collection<org.nuxeo.ecm.core.lifecycle.LifeCycleTransition> nuxeoTransitionDefs = nuxeoLifecyle.getTransitions();
128 for (org.nuxeo.ecm.core.lifecycle.LifeCycleTransition nuxeoTransitionDef : nuxeoTransitionDefs) {
129 TransitionDef tempTransitionDef = new TransitionDef();
130 tempTransitionDef.setDescription(nuxeoTransitionDef.getDescription());
131 tempTransitionDef.setDestinationState(nuxeoTransitionDef.getDestinationStateName());
132 tempTransitionDef.setName(nuxeoTransitionDef.getName());
133 transitionDefs.add(tempTransitionDef);
135 result.setTransitionDefList(transitionDefList);
142 * Returns the the life cycle definition of the related Nuxeo document type for this handler.
144 * @see org.collectionspace.services.common.document.DocumentHandler#getLifecycle()
147 public Lifecycle getLifecycle() {
148 Lifecycle result = null;
150 String docTypeName = null;
152 docTypeName = this.getServiceContext().getDocumentType();
153 result = getLifecycle(docTypeName);
154 } catch (Exception e) {
155 if (logger.isTraceEnabled() == true) {
156 logger.trace("Could not retrieve lifecycle definition for Nuxeo doctype: " + docTypeName);
164 * Returns the the life cycle definition of the related Nuxeo document type for this handler.
166 * @see org.collectionspace.services.common.document.DocumentHandler#getLifecycle(java.lang.String)
169 public Lifecycle getLifecycle(String docTypeName) {
170 org.nuxeo.ecm.core.lifecycle.LifeCycle nuxeoLifecyle;
171 Lifecycle result = null;
174 LifeCycleService lifeCycleService = null;
176 lifeCycleService = NXCore.getLifeCycleService();
177 } catch (Exception e) {
181 String lifeCycleName;
182 lifeCycleName = lifeCycleService.getLifeCycleNameFor(docTypeName);
183 nuxeoLifecyle = lifeCycleService.getLifeCycleByName(lifeCycleName);
185 result = createCollectionSpaceLifecycle(nuxeoLifecyle);
186 // result = (Lifecycle)FileTools.getJaxbObjectFromFile(Lifecycle.class, "default-lifecycle.xml");
187 } catch (Exception e) {
188 // TODO Auto-generated catch block
189 logger.error("Could not retreive life cycle information for Nuxeo doctype: " + docTypeName, e);
196 * We're using the "name" field of Nuxeo's DocumentModel to store
199 public String getCsid(DocumentModel docModel) {
200 return NuxeoUtils.getCsid(docModel);
203 public String getUri(DocumentModel docModel) {
204 return getServiceContextPath()+getCsid(docModel);
207 public RepositoryClient<PoxPayloadIn, PoxPayloadOut> getRepositoryClient(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
208 RepositoryClient<PoxPayloadIn, PoxPayloadOut> repositoryClient =
209 (RepositoryClient<PoxPayloadIn, PoxPayloadOut>) RepositoryClientFactory.getInstance().getClient(ctx.getRepositoryClientName());
210 return repositoryClient;
214 * getRepositorySession returns Nuxeo Repository Session
217 public CoreSessionInterface getRepositorySession() {
219 return repositorySession;
223 * setRepositorySession sets repository session
226 public void setRepositorySession(CoreSessionInterface repoSession) {
227 this.repositorySession = repoSession;
231 public void handleCreate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
232 // TODO for sub-docs - check to see if the current service context is a multipart input,
233 // OR a docfragment, and call a variant to fill the DocModel.
234 fillAllParts(wrapDoc, Action.CREATE);
235 handleCoreValues(wrapDoc, Action.CREATE);
238 // TODO for sub-docs - Add completeCreate in which we look for set-aside doc fragments
239 // and create the subitems. We will create service contexts with the doc fragments
244 public void handleUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
245 // TODO for sub-docs - check to see if the current service context is a multipart input,
246 // OR a docfragment, and call a variant to fill the DocModel.
247 fillAllParts(wrapDoc, Action.UPDATE);
248 handleCoreValues(wrapDoc, Action.UPDATE);
252 public void handleGet(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
253 extractAllParts(wrapDoc);
257 public void handleGetAll(DocumentWrapper<DocumentModelList> wrapDoc) throws Exception {
258 Profiler profiler = new Profiler(this, 2);
260 setCommonPartList(extractCommonPartList(wrapDoc));
265 public abstract void completeUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception;
268 public abstract void extractAllParts(DocumentWrapper<DocumentModel> wrapDoc) throws Exception;
271 public abstract T extractCommonPart(DocumentWrapper<DocumentModel> wrapDoc) throws Exception;
274 public abstract void fillAllParts(DocumentWrapper<DocumentModel> wrapDoc, Action action) throws Exception;
277 public abstract void fillCommonPart(T obj, DocumentWrapper<DocumentModel> wrapDoc) throws Exception;
280 public abstract TL extractCommonPartList(DocumentWrapper<DocumentModelList> wrapDoc) throws Exception;
283 public abstract T getCommonPart();
286 public abstract void setCommonPart(T obj);
289 public abstract TL getCommonPartList();
292 public abstract void setCommonPartList(TL obj);
295 public DocumentFilter createDocumentFilter() {
296 DocumentFilter filter = new NuxeoDocumentFilter(this.getServiceContext());
301 * Gets the authority refs.
303 * @param docWrapper the doc wrapper
304 * @param authRefFields the auth ref fields
305 * @return the authority refs
306 * @throws PropertyException the property exception
308 abstract public AuthorityRefList getAuthorityRefs(String csid,
309 List<AuthRefConfigInfo> authRefsInfo) throws PropertyException, Exception;
312 * Subclasses should override this method if they need to customize their refname generation
314 protected RefName.RefNameInterface getRefName(ServiceContext ctx,
315 DocumentModel docModel) {
316 return getRefName(new DocumentWrapperImpl<DocumentModel>(docModel), ctx.getTenantName(), ctx.getServiceName());
320 * By default, we'll use the CSID as the short ID. Sub-classes can override this method if they want to use
321 * something else for a short ID.
324 * @see org.collectionspace.services.common.document.AbstractDocumentHandlerImpl#getRefName(org.collectionspace.services.common.document.DocumentWrapper, java.lang.String, java.lang.String)
327 protected RefName.RefNameInterface getRefName(DocumentWrapper<DocumentModel> docWrapper,
328 String tenantName, String serviceName) {
329 String csid = docWrapper.getWrappedObject().getName();
330 String refnameDisplayName = getRefnameDisplayName(docWrapper);
331 RefName.RefNameInterface refname = RefName.Authority.buildAuthority(tenantName, serviceName,
332 csid, null, refnameDisplayName);
336 private void handleCoreValues(DocumentWrapper<DocumentModel> docWrapper,
337 Action action) throws ClientException {
338 DocumentModel documentModel = docWrapper.getWrappedObject();
339 String now = GregorianCalendarDateTimeUtils.timestampUTC();
340 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
341 String userId = ctx.getUserId();
342 if (action == Action.CREATE) {
344 // Add the tenant ID value to the new entity
346 String tenantId = ctx.getTenantId();
347 documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
348 CollectionSpaceClient.COLLECTIONSPACE_CORE_TENANTID, tenantId);
350 // Add the uri value to the new entity
352 documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
353 CollectionSpaceClient.COLLECTIONSPACE_CORE_URI, getUri(documentModel));
355 // Add the CSID to the DublinCore title so we can see the CSID in the default
359 documentModel.setProperty(CommonAPI.NUXEO_DUBLINCORE_SCHEMANAME, CommonAPI.NUXEO_DUBLINCORE_TITLE,
360 documentModel.getName());
361 } catch (Exception x) {
362 if (logger.isWarnEnabled() == true) {
363 logger.warn("Could not set the Dublin Core 'title' field on document CSID:" +
364 documentModel.getName());
368 // Add createdAt timestamp and createdBy user
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) {
378 // Add/update the resource's refname
380 handleRefNameChanges(ctx, documentModel);
382 // Add updatedAt timestamp and updateBy user
384 documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
385 CollectionSpaceClient.COLLECTIONSPACE_CORE_UPDATED_AT, now);
386 documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
387 CollectionSpaceClient.COLLECTIONSPACE_CORE_UPDATED_BY, userId);
391 protected boolean hasRefNameUpdate() {
392 boolean result = false;
394 if (Tools.notBlank(newRefNameOnUpdate) && Tools.notBlank(oldRefNameOnUpdate)) {
395 // CSPACE-6372: refNames are different if:
396 // - any part of the refName is different, using a case insensitive comparison, or
397 // - the display name portions are different, using a case sensitive comparison
398 if (newRefNameOnUpdate.equalsIgnoreCase(oldRefNameOnUpdate) == false) {
399 result = true; // refNames are different so updates are needed
402 String newDisplayNameOnUpdate = RefNameUtils.getDisplayName(newRefNameOnUpdate);
403 String oldDisplayNameOnUpdate = RefNameUtils.getDisplayName(oldRefNameOnUpdate);
405 if (StringUtils.equals(newDisplayNameOnUpdate, oldDisplayNameOnUpdate) == false) {
406 result = true; // display names are different so updates are needed
414 protected void handleRefNameChanges(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, DocumentModel docModel) throws ClientException {
415 // First get the old refName
416 this.oldRefNameOnUpdate = (String)docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
417 CollectionSpaceClient.COLLECTIONSPACE_CORE_REFNAME);
418 // Next, get the new refName
419 RefNameInterface refName = getRefName(ctx, docModel); // Sub-classes may override the getRefName() method called here.
420 if (refName != null) {
421 this.newRefNameOnUpdate = refName.toString();
423 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?
426 // Set the refName if it is an update or if the old refName was empty or null
428 if (hasRefNameUpdate() == true || this.oldRefNameOnUpdate == null) {
429 docModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
430 CollectionSpaceClient.COLLECTIONSPACE_CORE_REFNAME, this.newRefNameOnUpdate);
435 * If we see the "rtSbj" query param then we need to perform a CMIS query. Currently, we have only one
436 * CMIS query, but we could add more. If we do, this method should look at the incoming request and corresponding
437 * query params to determine if we need to do a CMIS query
439 * @see org.collectionspace.services.common.document.AbstractDocumentHandlerImpl#isCMISQuery()
441 public boolean isCMISQuery() {
442 boolean result = false;
444 MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams();
446 // Look the query params to see if we need to make a CMSIS query.
448 String asSubjectCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT);
449 String asOjectCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT);
450 String asEither = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_EITHER);
451 if (asSubjectCsid != null || asOjectCsid != null || asEither != null) {
459 * Creates the CMIS query from the service context. Each document handler is
460 * responsible for returning (can override) a valid CMIS query using the information in the
461 * current service context -which includes things like the query parameters,
464 * This method implementation supports three mutually exclusive cases. We will build a query
465 * that can find a document(s) 'A' in a relationship with another document
466 * 'B' where document 'B' has a CSID equal to the query param passed in and:
467 * 1. Document 'B' is the subject of the relationship
468 * 2. Document 'B' is the object of the relationship
469 * 3. Document 'B' is either the object or the subject of the relationship
470 * @throws DocumentException
473 public String getCMISQuery(QueryContext queryContext) throws DocumentException {
474 String result = null;
476 if (isCMISQuery() == true) {
478 // Build up the query arguments
480 String theOnClause = "";
481 String theWhereClause = "";
482 MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams();
483 String asSubjectCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT);
484 String asObjectCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT);
485 String asEitherCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_EITHER);
486 String matchObjDocTypes = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_MATCH_OBJ_DOCTYPES);
487 String selectDocType = (String)queryParams.getFirst(IQueryManager.SELECT_DOC_TYPE_FIELD);
489 String docType = this.getServiceContext().getDocumentType();
490 if (selectDocType != null && !selectDocType.isEmpty()) {
491 docType = selectDocType;
493 String selectFields = IQueryManager.CMIS_TARGET_CSID + ", "
494 + IQueryManager.CMIS_TARGET_TITLE + ", "
495 + IRelationsManager.CMIS_CSPACE_RELATIONS_TITLE + ", "
496 + IRelationsManager.CMIS_CSPACE_RELATIONS_OBJECT_ID + ", "
497 + IRelationsManager.CMIS_CSPACE_RELATIONS_SUBJECT_ID;
498 String targetTable = docType + " " + IQueryManager.CMIS_TARGET_PREFIX;
499 String relTable = IRelationsManager.DOC_TYPE + " " + IQueryManager.CMIS_RELATIONS_PREFIX;
500 String relObjectCsidCol = IRelationsManager.CMIS_CSPACE_RELATIONS_OBJECT_ID;
501 String relSubjectCsidCol = IRelationsManager.CMIS_CSPACE_RELATIONS_SUBJECT_ID;
502 String targetCsidCol = IQueryManager.CMIS_TARGET_CSID;
503 String tenantID = this.getServiceContext().getTenantId();
506 // Create the "ON" and "WHERE" query clauses based on the params passed into the HTTP request.
508 // First come, first serve -the first match determines the "ON" and "WHERE" query clauses.
510 if (asSubjectCsid != null && !asSubjectCsid.isEmpty()) {
511 // 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.
512 theOnClause = relObjectCsidCol + " = " + targetCsidCol;
513 theWhereClause = relSubjectCsidCol + " = " + "'" + asSubjectCsid + "'";
514 } else if (asObjectCsid != null && !asObjectCsid.isEmpty()) {
515 // 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.
516 theOnClause = relSubjectCsidCol + " = " + targetCsidCol;
517 theWhereClause = relObjectCsidCol + " = " + "'" + asObjectCsid + "'";
518 } else if (asEitherCsid != null && !asEitherCsid.isEmpty()) {
519 theOnClause = relObjectCsidCol + " = " + targetCsidCol
520 + " OR " + relSubjectCsidCol + " = " + targetCsidCol;
521 theWhereClause = relSubjectCsidCol + " = " + "'" + asEitherCsid + "'"
522 + " OR " + relObjectCsidCol + " = " + "'" + asEitherCsid + "'";
524 //Since the call to isCMISQuery() return true, we should never get here.
525 logger.error("Attempt to make CMIS query failed because the HTTP request was missing valid query parameters.");
528 // Now consider a constraint on the object doc types (for search by service group)
529 if (matchObjDocTypes != null && !matchObjDocTypes.isEmpty()) {
530 // 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.
531 theWhereClause += " AND (" + IRelationsManager.CMIS_CSPACE_RELATIONS_OBJECT_TYPE
532 + " IN " + matchObjDocTypes + ")";
535 // Qualify the query with the current tenant ID.
536 theWhereClause += IQueryManager.SEARCH_QUALIFIER_AND + IQueryManager.CMIS_JOIN_TENANT_ID_FILTER + " = '" + tenantID + "'";
538 // This could later be in control of a queryParam, to omit if we want to see versions, or to
539 // only see old versions.
540 theWhereClause += IQueryManager.SEARCH_QUALIFIER_AND + IQueryManager.CMIS_JOIN_NUXEO_IS_VERSION_FILTER;
542 StringBuilder query = new StringBuilder();
543 // assemble the query from the string arguments
544 query.append("SELECT ");
545 query.append(selectFields);
546 query.append(" FROM " + targetTable + " JOIN " + relTable);
547 query.append(" ON " + theOnClause);
548 query.append(" WHERE " + theWhereClause);
551 NuxeoUtils.appendCMISOrderBy(query, queryContext);
552 } catch (Exception e) {
553 logger.error("Could not append ORDER BY clause to CMIS query", e);
557 // SELECT D.cmis:name, D.dc:title, R.dc:title, R.relations_common:subjectCsid
558 // FROM Dimension D JOIN Relation R
559 // ON R.relations_common:objectCsid = D.cmis:name
560 // WHERE R.relations_common:subjectCsid = '737527ec-a560-4776-99de'
561 // ORDER BY D.collectionspace_core:updatedAt DESC
563 result = query.toString();
564 if (logger.isDebugEnabled() == true && result != null) {
565 logger.debug("The CMIS query is: " + result);