1 package org.collectionspace.services.listener;
3 import java.util.GregorianCalendar;
4 import java.util.HashSet;
6 import org.apache.commons.logging.Log;
7 import org.apache.commons.logging.LogFactory;
8 import org.collectionspace.services.client.workflow.WorkflowClient;
9 import org.collectionspace.services.common.api.Tools;
10 import org.collectionspace.services.movement.nuxeo.MovementConstants;
11 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
12 import org.nuxeo.ecm.core.api.ClientException;
13 import org.nuxeo.ecm.core.api.CoreSession;
14 import org.nuxeo.ecm.core.api.DocumentModel;
15 import org.nuxeo.ecm.core.api.DocumentModelList;
16 import org.nuxeo.ecm.core.event.Event;
17 import org.nuxeo.ecm.core.event.EventContext;
18 import org.nuxeo.ecm.core.event.EventListener;
19 import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
21 public abstract class AbstractUpdateObjectLocationValues implements EventListener {
23 // FIXME: We might experiment here with using log4j instead of Apache Commons Logging;
24 // am using the latter to follow Ray's pattern for now
25 private final static Log logger = LogFactory.getLog(AbstractUpdateObjectLocationValues.class);
26 // FIXME: Make the following message, or its equivalent, a constant usable by all event listeners
27 private final static String NO_FURTHER_PROCESSING_MESSAGE =
28 "This event listener will not continue processing this event ...";
29 private final static GregorianCalendar EARLIEST_COMPARISON_DATE = new GregorianCalendar(1600, 1, 1);
30 private final static String RELATIONS_COMMON_SCHEMA = "relations_common"; // FIXME: Get from external constant
31 private final static String RELATION_DOCTYPE = "Relation"; // FIXME: Get from external constant
32 private final static String SUBJECT_CSID_PROPERTY = "subjectCsid"; // FIXME: Get from external constant
33 private final static String OBJECT_CSID_PROPERTY = "objectCsid"; // FIXME: Get from external constant
34 private final static String SUBJECT_DOCTYPE_PROPERTY = "subjectDocumentType"; // FIXME: Get from external constant
35 private final static String OBJECT_DOCTYPE_PROPERTY = "objectDocumentType"; // FIXME: Get from external constant
36 protected final static String COLLECTIONOBJECTS_COMMON_SCHEMA = "collectionobjects_common"; // FIXME: Get from external constant
37 private final static String COLLECTIONOBJECT_DOCTYPE = "CollectionObject"; // FIXME: Get from external constant
38 protected final static String COMPUTED_CURRENT_LOCATION_PROPERTY = "computedCurrentLocation"; // FIXME: Create and then get from external constant
39 protected final static String MOVEMENTS_COMMON_SCHEMA = "movements_common"; // FIXME: Get from external constant
40 private final static String MOVEMENT_DOCTYPE = MovementConstants.NUXEO_DOCTYPE;
41 private final static String LOCATION_DATE_PROPERTY = "locationDate"; // FIXME: Get from external constant
42 protected final static String CURRENT_LOCATION_PROPERTY = "currentLocation"; // FIXME: Get from external constant
43 protected final static String COLLECTIONSPACE_CORE_SCHEMA = "collectionspace_core"; // FIXME: Get from external constant
44 protected final static String CREATED_AT_PROPERTY = "createdAt"; // FIXME: Get from external constant
45 private final static String NONVERSIONED_NONPROXY_DOCUMENT_WHERE_CLAUSE_FRAGMENT =
46 "AND ecm:isCheckedInVersion = 0"
47 + "AND ecm:isProxy = 0 ";
48 private final static String ACTIVE_DOCUMENT_WHERE_CLAUSE_FRAGMENT =
49 "AND (ecm:currentLifeCycleState <> 'deleted') "
50 + NONVERSIONED_NONPROXY_DOCUMENT_WHERE_CLAUSE_FRAGMENT;
52 public enum EventNotificationDocumentType {
53 // Document type about which we've received a notification
59 public void handleEvent(Event event) throws ClientException {
61 logger.trace("In handleEvent in UpdateObjectLocationOnMove ...");
63 EventContext eventContext = event.getContext();
64 if (eventContext == null) {
68 if (!(eventContext instanceof DocumentEventContext)) {
71 DocumentEventContext docEventContext = (DocumentEventContext) eventContext;
72 DocumentModel docModel = docEventContext.getSourceDocument();
74 // If this document event involves a Relation record, does this pertain to
75 // a relationship between a Movement record and a CollectionObject record?
77 // If not, we're not interested in processing this document event
78 // in this event handler, as it will have no bearing on updating a
79 // computed current location for a CollectionObject.
82 // (The rest of the code flow below is then identical to that which
83 // is followed when this document event involves a Movement record.
84 String movementCsid = "";
85 Enum notificationDocumentType;
86 if (documentMatchesType(docModel, RELATION_DOCTYPE)) {
87 if (logger.isTraceEnabled()) {
88 logger.trace("An event involving a Relation document was received by UpdateObjectLocationOnMove ...");
90 // Get a Movement CSID from the Relation record. (If we can't
91 // get it, then we don't have a pertinent relation record.)
92 movementCsid = getCsidForDesiredDocTypeFromRelation(docModel, MOVEMENT_DOCTYPE, COLLECTIONOBJECT_DOCTYPE);
93 if (Tools.isBlank(movementCsid)) {
94 logger.warn("Could not obtain CSID for Movement record from document event.");
95 logger.warn(NO_FURTHER_PROCESSING_MESSAGE);
98 notificationDocumentType = EventNotificationDocumentType.RELATION;
99 } else if (documentMatchesType(docModel, MOVEMENT_DOCTYPE)) {
100 // Otherwise, get a Movement CSID directly from the Movement record.
101 if (logger.isTraceEnabled()) {
102 logger.trace("An event involving a Movement document was received by UpdateObjectLocationOnMove ...");
104 // FIXME: exclude creation events for Movement records here, if we can
105 // identify that we'l still be properly handling creation events
106 // that include a relations list as part of the creation payload,
107 // perhaps because that may trigger a separate event notification.
108 movementCsid = NuxeoUtils.getCsid(docModel);
109 if (Tools.isBlank(movementCsid)) {
110 logger.warn("Could not obtain CSID for Movement record from document event.");
111 logger.warn(NO_FURTHER_PROCESSING_MESSAGE);
114 notificationDocumentType = EventNotificationDocumentType.MOVEMENT;
116 if (logger.isTraceEnabled()) {
117 logger.trace("This event did not involve a document relevant to UpdateObjectLocationOnMove ...");
122 // Note: currently, all Document lifecycle transitions on
123 // the relevant doctype(s) are handled by this event handler,
124 // not just transitions between 'soft deleted' and active states.
126 // We are assuming that we'll want to re-compute current locations
127 // for related CollectionObjects on all such transitions, as the
128 // semantics of such transitions are opaque to this event handler,
129 // because arbitrary workflows can be bound to those doctype(s).
131 // If we need to filter out some of those lifecycle transitions,
132 // such as excluding transitions to the 'locked' workflow state; or,
133 // alternately, if we want to restrict this event handler's
134 // scope to handle only transitions into the 'soft deleted' state,
135 // we can add additional checks for doing so at this point in the code.
138 if (logger.isTraceEnabled()) {
139 logger.trace("Movement CSID=" + movementCsid);
140 logger.trace("Notification document type=" + notificationDocumentType.name());
143 CoreSession coreSession = docEventContext.getCoreSession();
144 Set<String> collectionObjectCsids = new HashSet<>();
146 if (notificationDocumentType == EventNotificationDocumentType.RELATION) {
147 String relatedCollectionObjectCsid =
148 getCsidForDesiredDocTypeFromRelation(docModel, COLLECTIONOBJECT_DOCTYPE, MOVEMENT_DOCTYPE);
149 collectionObjectCsids.add(relatedCollectionObjectCsid);
150 } else if (notificationDocumentType == EventNotificationDocumentType.MOVEMENT) {
151 collectionObjectCsids.addAll(getCollectionObjectCsidsRelatedToMovement(movementCsid, coreSession));
154 if (collectionObjectCsids.isEmpty()) {
155 logger.warn("Could not obtain any CSIDs of related CollectionObject records.");
156 logger.warn(NO_FURTHER_PROCESSING_MESSAGE);
159 if (logger.isTraceEnabled()) {
160 logger.trace("Found " + collectionObjectCsids.size() + " CSIDs of related CollectionObject records.");
163 // Iterate through the list of CollectionObject CSIDs found.
164 // For each CollectionObject, obtain its most recent, related Movement,
165 // and update relevant field(s) with values from that Movement record.
166 DocumentModel collectionObjectDocModel;
167 DocumentModel mostRecentMovementDocModel;
168 for (String collectionObjectCsid : collectionObjectCsids) {
169 if (logger.isTraceEnabled()) {
170 logger.trace("CollectionObject CSID=" + collectionObjectCsid);
172 // Verify that the CollectionObject is both retrievable and active.
173 collectionObjectDocModel = getCurrentDocModelFromCsid(coreSession, collectionObjectCsid);
174 if (collectionObjectDocModel == null) {
175 if (logger.isTraceEnabled()) {
176 logger.trace("CollectionObject is not current (i.e. is a non-current version), is a proxy, or is unretrievable.");
180 // Verify that the CollectionObject record is active.
181 if (!isActiveDocument(collectionObjectDocModel)) {
182 if (logger.isTraceEnabled()) {
183 logger.trace("CollectionObject is inactive (i.e. deleted or in an otherwise inactive lifestyle state).");
187 // Get the CollectionObject's most recent, related Movement.
188 mostRecentMovementDocModel = getMostRecentMovement(coreSession, collectionObjectCsid);
189 if (mostRecentMovementDocModel == null) {
192 // Update the CollectionObject with values from that Movement.
193 collectionObjectDocModel =
194 updateCollectionObjectValuesFromMovement(collectionObjectDocModel, mostRecentMovementDocModel);
195 coreSession.saveDocument(collectionObjectDocModel);
200 * Returns the CSIDs of CollectionObject records that are related to a
203 * @param movementCsid the CSID of a Movement record.
204 * @param coreSession a repository session.
205 * @throws ClientException
206 * @return the CSIDs of the CollectionObject records, if any, which are
207 * related to the Movement record.
209 private Set<String> getCollectionObjectCsidsRelatedToMovement(String movementCsid,
210 CoreSession coreSession) throws ClientException {
212 Set<String> csids = new HashSet<>();
214 // Via an NXQL query, get a list of active relation records where:
215 // * This movement record's CSID is the subject CSID of the relation,
216 // and its object document type is a CollectionObject doctype;
218 // * This movement record's CSID is the object CSID of the relation,
219 // and its subject document type is a CollectionObject doctype.
221 // Some values below are hard-coded for readability, rather than
222 // being obtained from constants.
223 String query = String.format(
224 "SELECT * FROM %1$s WHERE " // collectionspace_core:tenantId = 1 "
226 + " (%2$s:subjectCsid = '%3$s' "
227 + " AND %2$s:objectDocumentType = '%4$s') "
229 + " (%2$s:objectCsid = '%3$s' "
230 + " AND %2$s:subjectDocumentType = '%4$s') "
232 + ACTIVE_DOCUMENT_WHERE_CLAUSE_FRAGMENT,
233 RELATION_DOCTYPE, RELATIONS_COMMON_SCHEMA, movementCsid, COLLECTIONOBJECT_DOCTYPE);
234 DocumentModelList relationDocModels = coreSession.query(query);
235 if (relationDocModels == null || relationDocModels.isEmpty()) {
236 // Encountering a Movement record that is not related to any
237 // CollectionObject is potentially a normal occurrence, so no
238 // error messages are logged here when we stop handling this event.
241 // Iterate through the list of Relation records found and build
242 // a list of CollectionObject CSIDs, by extracting the relevant CSIDs
243 // from those Relation records.
245 for (DocumentModel relationDocModel : relationDocModels) {
246 csid = getCsidForDesiredDocTypeFromRelation(relationDocModel, COLLECTIONOBJECT_DOCTYPE, MOVEMENT_DOCTYPE);
247 if (Tools.notBlank(csid)) {
254 // FIXME: Generic methods like many of those below might be split off from
255 // this specific event listener/handler, into an event handler utilities
256 // class, base classes, or otherwise.
258 // FIXME: Identify whether the equivalent of the documentMatchesType utility
259 // method is already implemented and substitute a call to the latter if so.
260 // This may well already exist.
262 * Identifies whether a document matches a supplied document type.
264 * @param docModel a document model.
265 * @param docType a document type string.
266 * @return true if the document matches the supplied document type; false if
269 protected static boolean documentMatchesType(DocumentModel docModel, String docType) {
270 if (docModel == null || Tools.isBlank(docType)) {
273 if (docModel.getType().startsWith(docType)) {
281 * Identifies whether a document is an active document; currently, whether
282 * it is not in the 'deleted' workflow state.
285 * @return true if the document is an active document; false if it is not.
287 protected static boolean isActiveDocument(DocumentModel docModel) {
288 if (docModel == null) {
291 boolean isActiveDocument = false;
293 if (!docModel.getCurrentLifeCycleState().equals(WorkflowClient.WORKFLOWSTATE_DELETED)) {
294 isActiveDocument = true;
296 } catch (ClientException ce) {
297 logger.warn("Error while identifying whether document is an active document: ", ce);
299 return isActiveDocument;
303 * Returns the current document model for a record identified by a CSID.
305 * Excludes documents which have been versioned (i.e. are a non-current
306 * version of a document), are a proxy for another document, or are
307 * un-retrievable via their CSIDs.
309 * @param session a repository session.
310 * @param collectionObjectCsid a CollectionObject identifier (CSID)
311 * @return a document model for the document identified by the supplied
314 protected static DocumentModel getCurrentDocModelFromCsid(CoreSession session, String collectionObjectCsid) {
315 DocumentModelList collectionObjectDocModels = null;
317 final String query = "SELECT * FROM "
318 + NuxeoUtils.BASE_DOCUMENT_TYPE
320 + NuxeoUtils.getByNameWhereClause(collectionObjectCsid)
322 + NONVERSIONED_NONPROXY_DOCUMENT_WHERE_CLAUSE_FRAGMENT;
323 collectionObjectDocModels = session.query(query);
324 } catch (Exception e) {
325 logger.warn("Exception in query to get active document model for CollectionObject: ", e);
327 if (collectionObjectDocModels == null || collectionObjectDocModels.isEmpty()) {
328 logger.warn("Could not get active document models for CollectionObject(s).");
330 } else if (collectionObjectDocModels.size() != 1) {
331 logger.debug("Found more than 1 active document with CSID=" + collectionObjectCsid);
334 return collectionObjectDocModels.get(0);
337 // FIXME: A quick first pass, using an only partly query-based technique for
338 // getting the most recent Movement record related to a CollectionObject,
339 // augmented by procedural code.
341 // Could be replaced by a potentially more performant method, based on a query.
343 // E.g. the following is a sample CMIS query for retrieving Movement records
344 // related to a CollectionObject, which might serve as the basis for that query.
346 "SELECT DOC.nuxeo:pathSegment, DOC.dc:title, REL.dc:title,"
347 + "REL.relations_common:objectCsid, REL.relations_common:subjectCsid FROM Movement DOC "
348 + "JOIN Relation REL ON REL.relations_common:objectCsid = DOC.nuxeo:pathSegment "
349 + "WHERE REL.relations_common:subjectCsid = '5b4c617e-53a0-484b-804e' "
350 + "AND DOC.nuxeo:isVersion = false "
351 + "ORDER BY DOC.collectionspace_core:updatedAt DESC";
354 * Returns the most recent Movement record related to a CollectionObject.
356 * This method currently returns the related Movement record with the latest
357 * (i.e. most recent in time) Location Date field value.
359 * @param session a repository session.
360 * @param collectionObjectCsid a CollectionObject identifier (CSID)
361 * @throws ClientException
362 * @return the most recent Movement record related to the CollectionObject
363 * identified by the supplied CSID.
365 protected static DocumentModel getMostRecentMovement(CoreSession session, String collectionObjectCsid)
366 throws ClientException {
367 DocumentModel mostRecentMovementDocModel = null;
368 // Get Relation records for Movements related to this CollectionObject.
370 // Some values below are hard-coded for readability, rather than
371 // being obtained from constants.
372 String query = String.format(
373 "SELECT * FROM %1$s WHERE " // collectionspace_core:tenantId = 1 "
375 + " (%2$s:subjectCsid = '%3$s' "
376 + " AND %2$s:objectDocumentType = '%4$s') "
378 + " (%2$s:objectCsid = '%3$s' "
379 + " AND %2$s:subjectDocumentType = '%4$s') "
381 + ACTIVE_DOCUMENT_WHERE_CLAUSE_FRAGMENT,
382 RELATION_DOCTYPE, RELATIONS_COMMON_SCHEMA, collectionObjectCsid, MOVEMENT_DOCTYPE);
383 if (logger.isTraceEnabled()) {
384 logger.trace("query=" + query);
386 DocumentModelList relationDocModels = session.query(query);
387 if (relationDocModels == null || relationDocModels.isEmpty()) {
388 logger.warn("Unexpectedly found no relations to Movement records to/from to this CollectionObject record.");
389 return mostRecentMovementDocModel;
391 if (logger.isTraceEnabled()) {
392 logger.trace("Found " + relationDocModels.size() + " relations to Movement records to/from this CollectionObject record.");
395 // Iterate through related movement records, to find the related
396 // Movement record with the most recent location date.
397 GregorianCalendar mostRecentLocationDate = EARLIEST_COMPARISON_DATE;
398 // Note: the following value is used to compare any two records, rather
399 // than to identify the most recent value so far encountered. Thus, it may
400 // occasionally be set backward or forward in time, within the loop below.
401 GregorianCalendar comparisonCreationDate = EARLIEST_COMPARISON_DATE;
402 DocumentModel movementDocModel;
403 Set<String> alreadyProcessedMovementCsids = new HashSet<>();
404 String relatedMovementCsid;
405 for (DocumentModel relationDocModel : relationDocModels) {
406 // Due to the 'OR' operator in the query above, related Movement
407 // record CSIDs may reside in either the subject or object CSID fields
408 // of the relation record. Whichever CSID value doesn't match the
409 // CollectionObject's CSID is inferred to be the related Movement record's CSID.
410 relatedMovementCsid = (String) relationDocModel.getProperty(RELATIONS_COMMON_SCHEMA, SUBJECT_CSID_PROPERTY);
411 if (relatedMovementCsid.equals(collectionObjectCsid)) {
412 relatedMovementCsid = (String) relationDocModel.getProperty(RELATIONS_COMMON_SCHEMA, OBJECT_CSID_PROPERTY);
414 if (Tools.isBlank(relatedMovementCsid)) {
417 // Because of the OR clause used in the query above, there may be
418 // two or more Relation records returned in the query results that
419 // reference the same Movement record, as either the subject
420 // or object of a relation to the same CollectionObject record;
421 // we need to filter out those duplicates.
422 if (alreadyProcessedMovementCsids.contains(relatedMovementCsid)) {
425 alreadyProcessedMovementCsids.add(relatedMovementCsid);
427 if (logger.isTraceEnabled()) {
428 logger.trace("Related movement CSID=" + relatedMovementCsid);
430 movementDocModel = getCurrentDocModelFromCsid(session, relatedMovementCsid);
431 if (movementDocModel == null) {
432 if (logger.isTraceEnabled()) {
433 logger.trace("Movement is not current (i.e. is a non-current version), is a proxy, or is unretrievable.");
437 // Verify that the Movement record is active.
438 if (!isActiveDocument(movementDocModel)) {
439 if (logger.isTraceEnabled()) {
440 logger.trace("Movement is inactive (i.e. is deleted or in another inactive lifestyle state).");
444 GregorianCalendar locationDate =
445 (GregorianCalendar) movementDocModel.getProperty(MOVEMENTS_COMMON_SCHEMA, LOCATION_DATE_PROPERTY);
446 // If the current Movement record lacks a location date, it cannot
447 // be established as the most recent Movement record; skip over it.
448 if (locationDate == null) {
451 GregorianCalendar creationDate =
452 (GregorianCalendar) movementDocModel.getProperty(COLLECTIONSPACE_CORE_SCHEMA, CREATED_AT_PROPERTY);
453 if (locationDate.after(mostRecentLocationDate)) {
454 mostRecentLocationDate = locationDate;
455 if (creationDate != null) {
456 comparisonCreationDate = creationDate;
458 mostRecentMovementDocModel = movementDocModel;
459 // If the current Movement record's location date is identical
460 // to that of the (at this time) most recent Movement record, then
461 // instead compare the two records using their creation date values
462 } else if (locationDate.compareTo(mostRecentLocationDate) == 0) {
463 if (creationDate != null && creationDate.after(comparisonCreationDate)) {
464 // The most recent location date value doesn't need to be
465 // updated here, as the two records' values are identical
466 comparisonCreationDate = creationDate;
467 mostRecentMovementDocModel = movementDocModel;
471 return mostRecentMovementDocModel;
475 * Returns the CSID for a desired document type from a Relation record,
476 * where the relationship involves two specified, different document types.
478 * @param relationDocModel a document model for a Relation record.
479 * @param desiredDocType a desired document type.
480 * @param relatedDocType a related document type.
481 * @throws ClientException
482 * @return the CSID from the desired document type in the relation. Returns
483 * an empty string if the Relation record does not involve both the desired
484 * and related document types, or if the desired document type is at both
485 * ends of the relation.
487 protected static String getCsidForDesiredDocTypeFromRelation(DocumentModel relationDocModel,
488 String desiredDocType, String relatedDocType) throws ClientException {
490 String subjectDocType = (String) relationDocModel.getProperty(RELATIONS_COMMON_SCHEMA, SUBJECT_DOCTYPE_PROPERTY);
491 String objectDocType = (String) relationDocModel.getProperty(RELATIONS_COMMON_SCHEMA, OBJECT_DOCTYPE_PROPERTY);
492 if (subjectDocType.startsWith(desiredDocType) && objectDocType.startsWith(desiredDocType)) {
495 if (subjectDocType.startsWith(desiredDocType) && objectDocType.startsWith(relatedDocType)) {
496 csid = (String) relationDocModel.getProperty(RELATIONS_COMMON_SCHEMA, SUBJECT_CSID_PROPERTY);
497 } else if (subjectDocType.startsWith(relatedDocType) && objectDocType.startsWith(desiredDocType)) {
498 csid = (String) relationDocModel.getProperty(RELATIONS_COMMON_SCHEMA, OBJECT_CSID_PROPERTY);
503 // The following method can be extended by sub-classes to update
504 // different/multiple values; e.g. values for moveable locations ("crates").
506 * Updates a CollectionObject record with selected values from a Movement
509 * @param collectionObjectDocModel a document model for a CollectionObject
511 * @param movementDocModel a document model for a Movement record.
512 * @return a potentially updated document model for the CollectionObject
514 * @throws ClientException
516 protected abstract DocumentModel updateCollectionObjectValuesFromMovement(DocumentModel collectionObjectDocModel,
517 DocumentModel movementDocModel)
518 throws ClientException;