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.IClientQueryParams;
35 import org.collectionspace.services.client.IQueryManager;
36 import org.collectionspace.services.client.IRelationsManager;
37 import org.collectionspace.services.client.PoxPayloadIn;
38 import org.collectionspace.services.client.PoxPayloadOut;
39 import org.collectionspace.services.common.api.CommonAPI;
40 import org.collectionspace.services.common.api.GregorianCalendarDateTimeUtils;
41 import org.collectionspace.services.common.api.RefName;
42 import org.collectionspace.services.common.api.RefName.RefNameInterface;
43 import org.collectionspace.services.common.api.RefNameUtils;
44 import org.collectionspace.services.common.api.Tools;
45 import org.collectionspace.services.common.authorityref.AuthorityRefList;
46 import org.collectionspace.services.common.context.ServiceContext;
47 import org.collectionspace.services.common.document.AbstractMultipartDocumentHandlerImpl;
48 import org.collectionspace.services.common.document.DocumentException;
49 import org.collectionspace.services.common.document.DocumentFilter;
50 import org.collectionspace.services.common.document.DocumentNotFoundException;
51 import org.collectionspace.services.common.document.DocumentWrapper;
52 import org.collectionspace.services.common.document.DocumentWrapperImpl;
53 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
54 import org.collectionspace.services.common.query.QueryContext;
55 import org.collectionspace.services.common.repository.RepositoryClient;
56 import org.collectionspace.services.common.repository.RepositoryClientFactory;
57 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.AuthRefConfigInfo;
58 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.Specifier;
59 import org.collectionspace.services.lifecycle.Lifecycle;
60 import org.collectionspace.services.lifecycle.State;
61 import org.collectionspace.services.lifecycle.StateList;
62 import org.collectionspace.services.lifecycle.TransitionDef;
63 import org.collectionspace.services.lifecycle.TransitionDefList;
64 import org.collectionspace.services.lifecycle.TransitionList;
65 import org.nuxeo.ecm.core.NXCore;
66 import org.nuxeo.ecm.core.api.ClientException;
67 import org.nuxeo.ecm.core.api.DocumentModel;
68 import org.nuxeo.ecm.core.api.DocumentModelList;
69 import org.nuxeo.ecm.core.api.model.PropertyException;
70 import org.nuxeo.ecm.core.lifecycle.LifeCycle;
71 import org.nuxeo.ecm.core.lifecycle.LifeCycleService;
72 import org.slf4j.Logger;
73 import org.slf4j.LoggerFactory;
76 * DocumentModelHandler is a base abstract Nuxeo document handler
77 * using Nuxeo Java Remote APIs for CollectionSpace services
79 * $LastChangedRevision: $
82 public abstract class DocumentModelHandler<T, TL>
83 extends AbstractMultipartDocumentHandlerImpl<T, TL, DocumentModel, DocumentModelList> {
85 private final Logger logger = LoggerFactory.getLogger(DocumentModelHandler.class);
86 private CoreSessionInterface repositorySession;
88 protected String oldRefNameOnUpdate = null; // FIXME: REM - We should have setters and getters for these
89 protected String newRefNameOnUpdate = null; // FIXME: two fields.
93 * Returns the the life cycle definition of the related Nuxeo document type for this handler.
95 * @see org.collectionspace.services.common.document.DocumentHandler#getLifecycle()
98 public Lifecycle getLifecycle() {
99 Lifecycle result = null;
101 String docTypeName = null;
103 docTypeName = this.getServiceContext().getDocumentType();
104 result = getLifecycle(docTypeName);
105 } catch (Exception e) {
106 if (logger.isTraceEnabled() == true) {
107 logger.trace("Could not retrieve lifecycle definition for Nuxeo doctype: " + docTypeName);
115 * Returns the the life cycle definition of the related Nuxeo document type for this handler.
117 * @see org.collectionspace.services.common.document.DocumentHandler#getLifecycle(java.lang.String)
120 public Lifecycle getLifecycle(String docTypeName) {
121 return NuxeoUtils.getLifecycle(docTypeName);
125 * We're using the "name" field of Nuxeo's DocumentModel to store
128 public String getCsid(DocumentModel docModel) {
129 return NuxeoUtils.getCsid(docModel);
132 public String getUri(DocumentModel docModel) {
133 return getServiceContextPath()+getCsid(docModel);
136 public String getUri(Specifier specifier) {
137 return getServiceContextPath() + specifier.value;
141 public RepositoryClient<PoxPayloadIn, PoxPayloadOut> getRepositoryClient(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx) {
142 RepositoryClient<PoxPayloadIn, PoxPayloadOut> repositoryClient =
143 (RepositoryClient<PoxPayloadIn, PoxPayloadOut>) RepositoryClientFactory.getInstance().getClient(ctx.getRepositoryClientName());
144 return repositoryClient;
148 * getRepositorySession returns Nuxeo Repository Session
151 public CoreSessionInterface getRepositorySession() {
153 return repositorySession;
157 * setRepositorySession sets repository session
160 public void setRepositorySession(CoreSessionInterface repoSession) {
161 this.repositorySession = repoSession;
165 public void handleCreate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
166 // TODO for sub-docs - check to see if the current service context is a multipart input,
167 // OR a docfragment, and call a variant to fill the DocModel.
168 fillAllParts(wrapDoc, Action.CREATE);
169 handleCoreValues(wrapDoc, Action.CREATE);
172 // TODO for sub-docs - Add completeCreate in which we look for set-aside doc fragments
173 // and create the subitems. We will create service contexts with the doc fragments
178 public void handleUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
179 // TODO for sub-docs - check to see if the current service context is a multipart input,
180 // OR a docfragment, and call a variant to fill the DocModel.
181 fillAllParts(wrapDoc, Action.UPDATE);
182 handleCoreValues(wrapDoc, Action.UPDATE);
186 public void handleGet(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
187 extractAllParts(wrapDoc);
191 public void handleGetAll(DocumentWrapper<DocumentModelList> wrapDoc) throws Exception {
192 Profiler profiler = new Profiler(this, 2);
194 setCommonPartList(extractCommonPartList(wrapDoc));
199 public abstract void completeUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception;
202 public abstract void extractAllParts(DocumentWrapper<DocumentModel> wrapDoc) throws Exception;
205 public abstract T extractCommonPart(DocumentWrapper<DocumentModel> wrapDoc) throws Exception;
208 public abstract void fillAllParts(DocumentWrapper<DocumentModel> wrapDoc, Action action) throws Exception;
211 public abstract void fillCommonPart(T obj, DocumentWrapper<DocumentModel> wrapDoc) throws Exception;
214 public abstract TL extractCommonPartList(DocumentWrapper<DocumentModelList> wrapDoc) throws Exception;
217 public abstract T getCommonPart();
220 public abstract void setCommonPart(T obj);
223 public abstract TL getCommonPartList();
226 public abstract void setCommonPartList(TL obj);
229 public DocumentFilter createDocumentFilter() {
230 DocumentFilter filter = new NuxeoDocumentFilter(this.getServiceContext());
235 * Gets the authority refs.
237 * @param docWrapper the doc wrapper
238 * @param authRefFields the auth ref fields
239 * @return the authority refs
240 * @throws PropertyException the property exception
242 abstract public AuthorityRefList getAuthorityRefs(String csid,
243 List<AuthRefConfigInfo> authRefConfigInfoList) throws PropertyException, Exception;
246 * Subclasses should override this method if they need to customize their refname generation
248 protected RefName.RefNameInterface getRefName(ServiceContext ctx,
249 DocumentModel docModel) {
250 return getRefName(new DocumentWrapperImpl<DocumentModel>(docModel), ctx.getTenantName(), ctx.getServiceName());
254 * By default, we'll use the CSID as the short ID. Sub-classes can override this method if they want to use
255 * something else for a short ID.
258 * @see org.collectionspace.services.common.document.AbstractDocumentHandlerImpl#getRefName(org.collectionspace.services.common.document.DocumentWrapper, java.lang.String, java.lang.String)
261 protected RefName.RefNameInterface getRefName(DocumentWrapper<DocumentModel> docWrapper,
262 String tenantName, String serviceName) {
263 String csid = docWrapper.getWrappedObject().getName();
264 String refnameDisplayName = getRefnameDisplayName(docWrapper);
265 RefName.RefNameInterface refname = RefName.Authority.buildAuthority(tenantName, serviceName,
266 csid, null, refnameDisplayName);
270 private void handleCoreValues(DocumentWrapper<DocumentModel> docWrapper,
271 Action action) throws ClientException {
272 DocumentModel documentModel = docWrapper.getWrappedObject();
273 String now = GregorianCalendarDateTimeUtils.timestampUTC();
274 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
275 String userId = ctx.getUserId();
276 if (action == Action.CREATE) {
278 // Add the tenant ID value to the new entity
280 String tenantId = ctx.getTenantId();
281 documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
282 CollectionSpaceClient.COLLECTIONSPACE_CORE_TENANTID, tenantId);
284 // Add the uri value to the new entity
286 documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
287 CollectionSpaceClient.COLLECTIONSPACE_CORE_URI, getUri(documentModel));
289 // Add the CSID to the DublinCore title so we can see the CSID in the default
293 documentModel.setProperty(CommonAPI.NUXEO_DUBLINCORE_SCHEMANAME, CommonAPI.NUXEO_DUBLINCORE_TITLE,
294 documentModel.getName());
295 } catch (Exception x) {
296 if (logger.isWarnEnabled() == true) {
297 logger.warn("Could not set the Dublin Core 'title' field on document CSID:" +
298 documentModel.getName());
302 // Add createdAt timestamp and createdBy user
304 documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
305 CollectionSpaceClient.COLLECTIONSPACE_CORE_CREATED_AT, now);
306 documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
307 CollectionSpaceClient.COLLECTIONSPACE_CORE_CREATED_BY, userId);
310 if (action == Action.CREATE || action == Action.UPDATE) {
312 // Add/update the resource's refname
314 handleRefNameChanges(ctx, documentModel);
316 // Add updatedAt timestamp and updateBy user
318 if (ctx.shouldUpdateCoreValues() == true) { // Ensure that our caller wants us to record this update
319 documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
320 CollectionSpaceClient.COLLECTIONSPACE_CORE_UPDATED_AT, now);
321 documentModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
322 CollectionSpaceClient.COLLECTIONSPACE_CORE_UPDATED_BY, userId);
324 logger.debug(String.format("Document with CSID=%s updated %s by user %s", documentModel.getName(), now, userId));
329 protected boolean hasRefNameUpdate() {
330 boolean result = false;
333 // Check to see if the request contains a query parameter asking us to force a refname update
335 if (getServiceContext().shouldForceUpdateRefnameReferences() == true) {
339 if (Tools.notBlank(newRefNameOnUpdate) && Tools.notBlank(oldRefNameOnUpdate)) {
340 // CSPACE-6372: refNames are different if:
341 // - any part of the refName is different, using a case insensitive comparison, or
342 // - the display name portions are different, using a case sensitive comparison
343 if (newRefNameOnUpdate.equalsIgnoreCase(oldRefNameOnUpdate) == false) {
344 result = true; // refNames are different so updates are needed
347 String newDisplayNameOnUpdate = RefNameUtils.getDisplayName(newRefNameOnUpdate);
348 String oldDisplayNameOnUpdate = RefNameUtils.getDisplayName(oldRefNameOnUpdate);
350 if (StringUtils.equals(newDisplayNameOnUpdate, oldDisplayNameOnUpdate) == false) {
351 result = true; // display names are different so updates are needed
359 protected void handleRefNameChanges(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx, DocumentModel docModel) throws ClientException {
360 // First get the old refName
361 this.oldRefNameOnUpdate = (String)docModel.getProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
362 CollectionSpaceClient.COLLECTIONSPACE_CORE_REFNAME);
363 // Next, get the new refName
364 RefNameInterface refName = getRefName(ctx, docModel); // Sub-classes may override the getRefName() method called here.
365 if (refName != null) {
366 this.newRefNameOnUpdate = refName.toString();
368 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?
371 // Set the refName if it is an update or if the old refName was empty or null
373 if (hasRefNameUpdate() == true || this.oldRefNameOnUpdate == null) {
374 docModel.setProperty(CollectionSpaceClient.COLLECTIONSPACE_CORE_SCHEMA,
375 CollectionSpaceClient.COLLECTIONSPACE_CORE_REFNAME, this.newRefNameOnUpdate);
380 * If we see the "rtSbj" query param then we need to perform a CMIS query. Currently, we have only one
381 * CMIS query, but we could add more. If we do, this method should look at the incoming request and corresponding
382 * query params to determine if we need to do a CMIS query
384 * @see org.collectionspace.services.common.document.AbstractDocumentHandlerImpl#isCMISQuery()
386 public boolean isCMISQuery() {
387 boolean result = false;
389 MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams();
391 // Look the query params to see if we need to make a CMSIS query.
393 String asSubjectCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT);
394 String asOjectCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT);
395 String asEither = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_EITHER);
396 if (asSubjectCsid != null || asOjectCsid != null || asEither != null) {
404 public String getDocumentsToIndexQuery(String indexId, String csid) throws DocumentException, Exception {
405 String result = null;
407 ServiceContext<PoxPayloadIn,PoxPayloadOut> ctx = this.getServiceContext();
408 String selectClause = "SELECT ecm:uuid, ecm:primaryType FROM ";
409 String docFilterWhereClause = this.getDocumentFilter().getWhereClause();
411 // The where clause could be a combination of the document filter's where clause plus a CSID qualifier
413 String whereClause = (csid == null) ? null : String.format("ecm:name = '%s'", csid); // AND ecm:currentLifeCycleState <> 'deleted'"
414 if (whereClause != null && !whereClause.trim().isEmpty()) {
415 // Due to an apparent bug/issue in how Nuxeo translates the NXQL query string
416 // into SQL, we need to parenthesize our 'where' clause
417 if (docFilterWhereClause != null && !docFilterWhereClause.trim().isEmpty()) {
418 whereClause = whereClause + IQueryManager.SEARCH_QUALIFIER_AND + "(" + docFilterWhereClause + ")";
421 whereClause = docFilterWhereClause;
423 String orderByClause = "ecm:uuid";
426 QueryContext queryContext = new QueryContext(ctx, selectClause, whereClause, orderByClause);
427 result = NuxeoUtils.buildNXQLQuery(queryContext);
428 } catch (DocumentException de) {
430 } catch (Exception x) {
438 * Creates the CMIS query from the service context. Each document handler is
439 * responsible for returning (can override) a valid CMIS query using the information in the
440 * current service context -which includes things like the query parameters,
443 * This method implementation supports three mutually exclusive cases. We will build a query
444 * that can find a document(s) 'A' in a relationship with another document
445 * 'B' where document 'B' has a CSID equal to the query param passed in and:
446 * 1. Document 'B' is the subject of the relationship
447 * 2. Document 'B' is the object of the relationship
448 * 3. Document 'B' is either the object or the subject of the relationship
449 * @throws DocumentException
452 public String getCMISQuery(QueryContext queryContext) throws DocumentException {
453 String result = null;
455 if (isCMISQuery() == true) {
457 // Build up the query arguments
459 String theOnClause = "";
460 String theWhereClause = "";
461 MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams();
462 String asSubjectCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT);
463 String asObjectCsid = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT);
465 String matchObjDocTypes = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_MATCH_OBJ_DOCTYPES);
466 String selectDocType = (String)queryParams.getFirst(IQueryManager.SELECT_DOC_TYPE_FIELD);
468 String docType = NuxeoUtils.getTenantQualifiedDocType(this.getServiceContext()); // Fixed for https://issues.collectionspace.org/browse/DRYD-302
469 if (selectDocType != null && !selectDocType.isEmpty()) {
470 docType = selectDocType;
472 String selectFields = IQueryManager.CMIS_TARGET_CSID + ", "
473 + IQueryManager.CMIS_TARGET_TITLE + ", "
474 + IRelationsManager.CMIS_CSPACE_RELATIONS_TITLE + ", "
475 + IRelationsManager.CMIS_CSPACE_RELATIONS_OBJECT_ID + ", "
476 + IRelationsManager.CMIS_CSPACE_RELATIONS_SUBJECT_ID;
478 String targetTable = docType + " " + IQueryManager.CMIS_TARGET_PREFIX;
479 String relTable = IRelationsManager.DOC_TYPE + " " + IQueryManager.CMIS_RELATIONS_PREFIX;
481 String relSubjectCsidCol = IRelationsManager.CMIS_CSPACE_RELATIONS_SUBJECT_ID;
482 String relObjectCsidCol = IRelationsManager.CMIS_CSPACE_RELATIONS_OBJECT_ID;
484 String targetCsidCol = IQueryManager.CMIS_TARGET_CSID;
485 String tenantID = this.getServiceContext().getTenantId();
488 // Create the "ON" and "WHERE" query clauses based on the params passed into the HTTP request.
490 // First come, first serve -the first match determines the "ON" and "WHERE" query clauses.
492 if (asSubjectCsid != null && !asSubjectCsid.isEmpty()) {
493 // 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.
494 theOnClause = relObjectCsidCol + " = " + targetCsidCol;
495 theWhereClause = relSubjectCsidCol + " = " + "'" + asSubjectCsid + "'";
496 } else if (asObjectCsid != null && !asObjectCsid.isEmpty()) {
497 // 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.
498 theOnClause = relSubjectCsidCol + " = " + targetCsidCol;
499 theWhereClause = relObjectCsidCol + " = " + "'" + asObjectCsid + "'";
501 //Since the call to isCMISQuery() return true, we should never get here.
502 logger.error("Attempt to make CMIS query failed because the HTTP request was missing valid query parameters.");
505 // Now consider a constraint on the object doc types (for search by service group)
506 if (matchObjDocTypes != null && !matchObjDocTypes.isEmpty()) {
507 // 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.
508 theWhereClause += " AND (" + IRelationsManager.CMIS_CSPACE_RELATIONS_OBJECT_TYPE
509 + " IN " + matchObjDocTypes + ")";
512 // Qualify the search for predicate types
513 theWhereClause = addWhereClauseForPredicates(theWhereClause, queryParams);
515 // Qualify the query with the current tenant ID.
516 theWhereClause += IQueryManager.SEARCH_QUALIFIER_AND + IQueryManager.CMIS_JOIN_TENANT_ID_FILTER + " = '" + tenantID + "'";
518 // This could later be in control of a queryParam, to omit if we want to see versions, or to
519 // only see old versions.
520 theWhereClause += IQueryManager.SEARCH_QUALIFIER_AND + IQueryManager.CMIS_JOIN_NUXEO_IS_VERSION_FILTER;
522 StringBuilder query = new StringBuilder();
523 // assemble the query from the string arguments
524 query.append("SELECT ");
525 query.append(selectFields);
526 query.append(" FROM " + targetTable + " JOIN " + relTable);
527 query.append(" ON " + theOnClause);
528 query.append(" WHERE " + theWhereClause);
531 NuxeoUtils.appendCMISOrderBy(query, queryContext);
532 } catch (Exception e) {
533 logger.error("Could not append ORDER BY clause to CMIS query", e);
537 // SELECT D.cmis:name, D.dc:title, R.dc:title, R.relations_common:subjectCsid
538 // FROM Dimension D JOIN Relation R
539 // ON R.relations_common:objectCsid = D.cmis:name
540 // WHERE R.relations_common:subjectCsid = '737527ec-a560-4776-99de'
541 // ORDER BY D.collectionspace_core:updatedAt DESC
543 result = query.toString();
544 if (logger.isDebugEnabled() == true && result != null) {
545 logger.debug("The CMIS query is: " + result);
552 private String addWhereClauseForPredicates(String theWhereClause, MultivaluedMap<String, String> queryParams) {
553 if (queryParams.containsKey(IQueryManager.SEARCH_RELATED_PREDICATE)) {
554 List<String> predicateList = queryParams.get(IQueryManager.SEARCH_RELATED_PREDICATE);
556 if (predicateList.size() == 1) {
557 String predicate = (String)queryParams.getFirst(IQueryManager.SEARCH_RELATED_PREDICATE);
558 if (predicate != null && !predicate.trim().isEmpty()) {
559 theWhereClause += IQueryManager.SEARCH_QUALIFIER_AND + IRelationsManager.CMIS_CSPACE_RELATIONS_PREDICATE + " = '" + predicate + "'";
561 } else if (predicateList.size() > 1) {
562 StringBuffer partialClause = new StringBuffer();
563 for (String predicate : predicateList) {
564 if (!predicate.trim().isEmpty()) {
565 partialClause.append("'" + predicate + "', ");
568 String inValues = partialClause.toString().replaceAll(", $", ""); // remove the last ', ' squence
569 if (!inValues.trim().isEmpty()) {
570 theWhereClause += IQueryManager.SEARCH_QUALIFIER_AND + IRelationsManager.CMIS_CSPACE_RELATIONS_PREDICATE + " IN (" + inValues + ")";
575 return theWhereClause;