1 package org.collectionspace.services.listener;
3 import java.util.GregorianCalendar;
4 import java.util.HashSet;
8 import org.apache.commons.logging.Log;
9 import org.apache.commons.logging.LogFactory;
11 import org.collectionspace.services.client.LocationAuthorityClient;
12 import org.collectionspace.services.client.workflow.WorkflowClient;
13 import org.collectionspace.services.collectionobject.nuxeo.CollectionObjectConstants;
14 import org.collectionspace.services.common.api.Tools;
15 import org.collectionspace.services.common.relation.nuxeo.RelationConstants;
16 import org.collectionspace.services.common.api.RefName;
17 import org.collectionspace.services.movement.nuxeo.MovementConstants;
18 import org.collectionspace.services.nuxeo.client.java.CoreSessionInterface;
19 import org.collectionspace.services.nuxeo.client.java.CoreSessionWrapper;
20 import org.collectionspace.services.nuxeo.listener.AbstractCSEventListenerImpl;
21 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
23 import org.nuxeo.ecm.core.api.DocumentModel;
24 import org.nuxeo.ecm.core.api.DocumentModelList;
25 import org.nuxeo.ecm.core.api.event.DocumentEventTypes;
26 import org.nuxeo.ecm.core.api.impl.DocumentModelListImpl;
27 import org.nuxeo.ecm.core.event.Event;
28 import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
30 public abstract class AbstractUpdateObjectLocationValues extends AbstractCSEventListenerImpl {
32 // FIXME: We might experiment here with using log4j instead of Apache Commons Logging;
33 // am using the latter to follow Ray's pattern for now
34 private final static Log logger = LogFactory.getLog(AbstractUpdateObjectLocationValues.class);
36 // FIXME: Make the following message, or its equivalent, a constant usable by all event listeners
37 private final static String NO_FURTHER_PROCESSING_MESSAGE =
38 "This event listener will not continue processing this event ...";
40 private final static GregorianCalendar EARLIEST_COMPARISON_DATE = new GregorianCalendar(1600, 1, 1);
41 private final static String RELATIONS_COMMON_SCHEMA = "relations_common"; // FIXME: Get from external constant
43 private final static String COLLECTIONOBJECT_DOCTYPE = CollectionObjectConstants.NUXEO_DOCTYPE;
44 private final static String RELATION_DOCTYPE = RelationConstants.NUXEO_DOCTYPE;//"Relation"; // FIXME: Get from external constant
45 private final static String MOVEMENT_DOCTYPE = MovementConstants.NUXEO_DOCTYPE;
47 private final static String SUBJECT_CSID_PROPERTY = "subjectCsid"; // FIXME: Get from external constant
48 private final static String OBJECT_CSID_PROPERTY = "objectCsid"; // FIXME: Get from external constant
49 private final static String SUBJECT_DOCTYPE_PROPERTY = "subjectDocumentType"; // FIXME: Get from external constant
50 private final static String OBJECT_DOCTYPE_PROPERTY = "objectDocumentType"; // FIXME: Get from external constant
51 protected final static String COLLECTIONOBJECTS_COMMON_SCHEMA = "collectionobjects_common"; // FIXME: Get from external constant
52 protected final static String COMPUTED_CURRENT_LOCATION_PROPERTY = "computedCurrentLocation"; // FIXME: Create and then get from external constant
53 private final static String CURRENT_LOCATION_ELEMENT_NAME = "currentLocation"; // From movement_commons schema. FIXME: Get from external constant that already exists
54 protected final static String MOVEMENTS_COMMON_SCHEMA = "movements_common"; // FIXME: Get from external constant
55 private final static String LOCATION_DATE_PROPERTY = "locationDate"; // FIXME: Get from external constant
56 protected final static String CURRENT_LOCATION_PROPERTY = "currentLocation"; // FIXME: Get from external constant
57 protected final static String COLLECTIONSPACE_CORE_SCHEMA = "collectionspace_core"; // FIXME: Get from external constant
58 protected final static String CREATED_AT_PROPERTY = "createdAt"; // FIXME: Get from external constant
59 protected final static String UPDATED_AT_PROPERTY = "updatedAt"; // FIXME: Get from external constant
61 // Use this meta URN/refname to mark computed locations that are indeterminate
62 private final static String INDETERMINATE_ID = "indeterminate";
63 protected final static String INDETERMINATE_LOCATION = RefName.buildAuthorityItem(INDETERMINATE_ID, LocationAuthorityClient.SERVICE_NAME, INDETERMINATE_ID,
64 INDETERMINATE_ID, "~Indeterminate Location~").toString();
67 private final static String NONVERSIONED_NONPROXY_DOCUMENT_WHERE_CLAUSE_FRAGMENT =
68 "AND ecm:isCheckedInVersion = 0"
69 + " AND ecm:isProxy = 0 ";
70 private final static String ACTIVE_DOCUMENT_WHERE_CLAUSE_FRAGMENT =
71 "AND (ecm:currentLifeCycleState <> 'deleted') "
72 + NONVERSIONED_NONPROXY_DOCUMENT_WHERE_CLAUSE_FRAGMENT;
74 // Used to set/get temp values in a DocumentModel instance
75 private static final String IGNORE_LOCATION_UPDATE_EVENT_LABEL = "IGNORE_LOCATION_UPDATE_EVENT";
77 public enum EventNotificationDocumentType {
78 // Document type about which we've received a notification
80 MOVEMENT, RELATION, COLLECTIONOBJECT;
83 private static void logEvent(Event event, String message) {
84 logEvent(event, message, false);
87 private static void logEvent(Event event, String message, boolean forceLogging) {
88 if (logger.isDebugEnabled() || forceLogging) {
89 DocumentEventContext docEventContext = (DocumentEventContext) event.getContext();
90 DocumentModel docModel = docEventContext.getSourceDocument();
91 String eventType = event.getName();
92 String csid = NuxeoUtils.getCsid(docModel);
94 logger.debug(String.format("### %s:", message != null ? message : "Unspecified"));
95 logger.debug(String.format("### \t-Event type: %s", eventType));
97 logger.debug("### \t-Target documment:");
98 logger.debug(String.format("### \t\tCSID=%s", csid));
99 logger.debug(String.format("### \t\tDocType=%s", docModel.getDocumentType().getName()));
101 if (documentMatchesType(docModel, RELATION_DOCTYPE)) {
102 String subjectDocType = (String) docModel.getProperty(RELATIONS_COMMON_SCHEMA, SUBJECT_DOCTYPE_PROPERTY);
103 String objectDocType = (String) docModel.getProperty(RELATIONS_COMMON_SCHEMA, OBJECT_DOCTYPE_PROPERTY);
104 String subjectCsid = (String) docModel.getProperty(RELATIONS_COMMON_SCHEMA, SUBJECT_CSID_PROPERTY);
105 String objectCsid = (String) docModel.getProperty(RELATIONS_COMMON_SCHEMA, OBJECT_CSID_PROPERTY);
106 logger.debug(String.format("\tRelation info subject=%s:%s\tobject=%s:%s",
107 subjectCsid, subjectDocType, objectCsid, objectDocType));
108 } else if (documentMatchesType(docModel, MOVEMENT_DOCTYPE)) {
109 String currentLocation = (String) docModel.getProperty(MOVEMENTS_COMMON_SCHEMA, CURRENT_LOCATION_ELEMENT_NAME);
110 GregorianCalendar locationDate = (GregorianCalendar) docModel.getProperty(MOVEMENTS_COMMON_SCHEMA, LOCATION_DATE_PROPERTY);
111 logger.debug("### \t-Movement Info:");
112 logger.debug(String.format("### \t\tCSID=%s", csid));
113 logger.debug(String.format("### \t\tlocation=%s", currentLocation != null ? currentLocation : "null"));
114 if (locationDate != null) {
115 logger.debug(String.format("### \t\tdate=%1$tm-%1$te-%1$tY", locationDate != null ? locationDate : ""));
117 logger.debug(String.format("### \t\tdate=<empty>"));
120 logger.debug(String.format("### Ignoring Update Location event: %s", eventType));
126 * Figure out if we should ignore this event.
128 private boolean shouldIgnoreEvent(DocumentEventContext docEventContext, String ignoreEventLabel) {
129 boolean result = false;
131 Boolean shouldIgnoreEvent = (Boolean) docEventContext.getProperties().get(ignoreEventLabel);
132 if (shouldIgnoreEvent != null && shouldIgnoreEvent) {
140 public void handleEvent(Event event) {
141 // Ensure we have all the event data we need to proceed.
142 if (isRegistered(event) == false || !(event.getContext() instanceof DocumentEventContext)) {
143 if (logger.isTraceEnabled() == true) {
144 logEvent(event, "Update Location", true);
149 Map<String, String> params = this.getParams(event); // Will be null if no params were configured.
150 logEvent(event, "Update Location");
152 DocumentEventContext docEventContext = (DocumentEventContext) event.getContext();
153 DocumentModel eventDocModel = docEventContext.getSourceDocument();
154 String eventType = event.getName();
155 boolean isAboutToBeRemovedEvent = eventType.equals(DocumentEventTypes.ABOUT_TO_REMOVE);
158 // This event handler itself sometimes triggers additional events. To prevent unnecessary cascading event handling, this event
159 // handler sets a flag in the document model indicating we should ignore cascading events. This method checks that flag and
160 // exits if it is set.
161 if (shouldIgnoreEvent(docEventContext, IGNORE_LOCATION_UPDATE_EVENT_LABEL) == true) {
166 // Ensure this event relates to a relationship record (between cataloging and movement records) or a movement record. If so, get the CSID
167 // of the corresponding movement record. Otherwise, exit.
169 String eventMovementCsid = null;
170 Enum<EventNotificationDocumentType> notificationDocumentType;
171 if (documentMatchesType(eventDocModel, RELATION_DOCTYPE)) {
172 notificationDocumentType = EventNotificationDocumentType.RELATION;
173 // Ensure this relationship record is a CollectionObject/Movement tuple.
174 eventMovementCsid = getCsidForDesiredDocTypeFromRelation(eventDocModel, MOVEMENT_DOCTYPE, COLLECTIONOBJECT_DOCTYPE);
175 if (Tools.isBlank(eventMovementCsid)) {
178 } else if (documentMatchesType(eventDocModel, MOVEMENT_DOCTYPE)) {
179 notificationDocumentType = EventNotificationDocumentType.MOVEMENT;
180 // Otherwise, get a Movement CSID directly from the Movement record.
181 eventMovementCsid = NuxeoUtils.getCsid(eventDocModel);
182 if (Tools.isBlank(eventMovementCsid)) {
183 logger.warn("Could not obtain CSID for Movement record from document event.");
184 logger.warn(NO_FURTHER_PROCESSING_MESSAGE);
187 } else if (documentMatchesType(eventDocModel, COLLECTIONOBJECT_DOCTYPE) &&
188 eventType.equals(DocumentEventTypes.DOCUMENT_UPDATED)) {
189 notificationDocumentType = EventNotificationDocumentType.COLLECTIONOBJECT;
191 // We don't need to handle this event.
195 // Note: currently, all Document lifecycle transitions on
196 // the relevant doctype(s) are handled by this event handler,
197 // not just transitions between 'soft deleted' and active states.
199 // We are assuming that we'll want to re-compute current locations
200 // for related CollectionObjects on all such transitions, as the
201 // semantics of such transitions are opaque to this event handler,
202 // because arbitrary workflows can be bound to those doctype(s).
204 // If we need to filter out some of those lifecycle transitions,
205 // such as excluding transitions to the 'locked' workflow state; or,
206 // alternately, if we want to restrict this event handler's
207 // scope to handle only transitions into the 'soft deleted' state,
208 // we can add additional checks for doing so at this point in the code.
211 // Get a list of all the CollectionObject records affected by this event.
213 CoreSessionInterface session = new CoreSessionWrapper(docEventContext.getCoreSession()); // NOTE: All Nuxeo sessions that get passed around to CollectionSpace code need to be wrapped inside of a CoreSessionWrapper
214 Set<String> collectionObjectCsids = new HashSet<>();
215 if (notificationDocumentType == EventNotificationDocumentType.RELATION) {
216 String relatedCollectionObjectCsid = getCsidForDesiredDocTypeFromRelation(eventDocModel, COLLECTIONOBJECT_DOCTYPE, MOVEMENT_DOCTYPE);
217 collectionObjectCsids.add(relatedCollectionObjectCsid);
218 } else if (notificationDocumentType == EventNotificationDocumentType.MOVEMENT) {
219 collectionObjectCsids.addAll(getCollectionObjectCsidsRelatedToMovement(eventMovementCsid, session));
220 } else if (notificationDocumentType == EventNotificationDocumentType.COLLECTIONOBJECT) {
221 collectionObjectCsids.add(NuxeoUtils.getCsid(eventDocModel));
223 // This event did not involve a document relevant to us.
228 // If we found no collectionobject records needing updating, then we're done.
230 if (collectionObjectCsids.isEmpty() == true) {
235 // Now iterate through the list of affected CollectionObjects found.
236 // For each CollectionObject, obtain its most recent, related Movement record,
237 // and update update the Computed Current Location field if needed.
239 DocumentModel collectionObjectDocModel;
240 DocumentModel mostRecentMovementDocModel;
241 for (String collectionObjectCsid : collectionObjectCsids) {
242 collectionObjectDocModel = getCurrentDocModelFromCsid(session, collectionObjectCsid);
243 if (isActiveDocument(collectionObjectDocModel) == true) {
244 DocumentModel movementDocModel = getCurrentDocModelFromCsid(session, eventMovementCsid);
246 // Get the CollectionObject's most recent, valid related Movement to use for computing the
247 // object's current location.
249 String mostRecentLocation = getMostRecentLocation(event, session, collectionObjectCsid,
250 isAboutToBeRemovedEvent, eventMovementCsid);
252 // Update the CollectionObject's Computed Current Location field with the Movement record's location
254 boolean didLocationChange = updateCollectionObjectLocation(collectionObjectDocModel, movementDocModel, mostRecentLocation);
257 // If the location changed, save/persist the change to the repository and log the change.
259 if (didLocationChange == true) {
260 persistLocationChange(session, collectionObjectDocModel);
262 // Log an INFO message if we've changed the cataloging record's location
264 if (logger.isInfoEnabled()) {
265 String computedCurrentLocationRefName =
266 (String) collectionObjectDocModel.getProperty(COLLECTIONOBJECTS_COMMON_SCHEMA, COMPUTED_CURRENT_LOCATION_PROPERTY);
267 logger.info(String.format("Updating cataloging record=%s current location to %s",
268 NuxeoUtils.getCsid(collectionObjectDocModel), computedCurrentLocationRefName));
276 // Disable update/documentModified events and persist the location change.
278 private void persistLocationChange(CoreSessionInterface session, DocumentModel collectionObjectDocModel) {
281 // Set a flag in the document model indicating that we want to ignore the update event that
282 // will be triggered by this save/persist request.
283 setDocModelContextProperty(collectionObjectDocModel, IGNORE_LOCATION_UPDATE_EVENT_LABEL, true);
286 // Save/Persist the document to the DB
287 session.saveDocument(collectionObjectDocModel);
290 // Clear the flag we set to ignore events triggered by our save request.
291 clearDocModelContextProperty(collectionObjectDocModel, IGNORE_LOCATION_UPDATE_EVENT_LABEL);
295 * Returns the CSIDs of active CollectionObject records related to a Movement record.
297 * @param movementCsid the CSID of a Movement record.
298 * @param coreSession a repository session.
299 * @throws ClientException
300 * @return the CSIDs of the CollectionObject records, if any, which are
301 * related to the Movement record.
303 private Set<String> getCollectionObjectCsidsRelatedToMovement(String movementCsid,
304 CoreSessionInterface coreSession) {
306 Set<String> csids = new HashSet<>();
308 // Via an NXQL query, get a list of active relation records where:
309 // * This movement record's CSID is the subject CSID of the relation,
310 // and its object document type is a CollectionObject doctype;
312 // * This movement record's CSID is the object CSID of the relation,
313 // and its subject document type is a CollectionObject doctype.
315 // Some values below are hard-coded for readability, rather than
316 // being obtained from constants.
317 String query = String.format(
318 "SELECT * FROM %1$s WHERE " // collectionspace_core:tenantId = 1 "
320 + " (%2$s:subjectCsid = '%3$s' "
321 + " AND %2$s:objectDocumentType = '%4$s') "
323 + " (%2$s:objectCsid = '%3$s' "
324 + " AND %2$s:subjectDocumentType = '%4$s') "
326 + ACTIVE_DOCUMENT_WHERE_CLAUSE_FRAGMENT,
327 RELATION_DOCTYPE, RELATIONS_COMMON_SCHEMA, movementCsid, COLLECTIONOBJECT_DOCTYPE);
329 DocumentModelList relationDocModels = coreSession.query(query);
330 if (relationDocModels == null || relationDocModels.isEmpty()) {
334 // Iterate through the list of Relation records found and build
335 // a list of CollectionObject CSIDs, by extracting the relevant CSIDs
336 // from those Relation records.
338 for (DocumentModel relationDocModel : relationDocModels) {
339 csid = getCsidForDesiredDocTypeFromRelation(relationDocModel, COLLECTIONOBJECT_DOCTYPE, MOVEMENT_DOCTYPE);
340 if (Tools.notBlank(csid)) {
348 // FIXME: Generic methods like many of those below might be split off from
349 // this specific event listener/handler, into an event handler utilities
350 // class, base classes, or otherwise.
352 // FIXME: Identify whether the equivalent of the documentMatchesType utility
353 // method is already implemented and substitute a call to the latter if so.
354 // This may well already exist.
356 * Identifies whether a document matches a supplied document type.
358 * @param docModel a document model.
359 * @param docType a document type string.
360 * @return true if the document matches the supplied document type; false if
363 protected static boolean documentMatchesType(DocumentModel docModel, String docType) {
364 if (docModel == null || Tools.isBlank(docType)) {
367 if (docModel.getType().startsWith(docType)) {
374 protected static boolean isActiveDocument(DocumentModel docModel) {
375 return isActiveDocument(docModel, false, null);
379 * Identifies whether a document is an active document; currently, whether
380 * it is not in a 'deleted' workflow state.
383 * @return true if the document is an active document; false if it is not.
385 protected static boolean isActiveDocument(DocumentModel docModel, boolean isAboutToBeRemovedEvent, String aboutToBeRemovedCsid) {
386 boolean isActiveDocument = false;
388 if (docModel != null) {
389 if (!docModel.getCurrentLifeCycleState().contains(WorkflowClient.WORKFLOWSTATE_DELETED)) {
390 isActiveDocument = true;
393 // If doc model is the target of the "aboutToBeRemoved" event, mark it as not active.
395 if (isAboutToBeRemovedEvent && Tools.notBlank(aboutToBeRemovedCsid)) {
396 if (NuxeoUtils.getCsid(docModel).equalsIgnoreCase(aboutToBeRemovedCsid)) {
397 isActiveDocument = false;
402 return isActiveDocument;
406 * Returns the current document model for a record identified by a CSID.
408 * Excludes documents which have been versioned (i.e. are a non-current
409 * version of a document), are a proxy for another document, or are
410 * un-retrievable via their CSIDs.
412 * @param session a repository session.
413 * @param csid a CollectionObject identifier (CSID)
414 * @return a document model for the document identified by the supplied
417 protected static DocumentModel getCurrentDocModelFromCsid(CoreSessionInterface session, String csid) {
418 DocumentModelList docModelList = null;
421 final String query = "SELECT * FROM "
422 + NuxeoUtils.BASE_DOCUMENT_TYPE
424 + NuxeoUtils.getByNameWhereClause(csid)
426 + NONVERSIONED_NONPROXY_DOCUMENT_WHERE_CLAUSE_FRAGMENT;
427 docModelList = session.query(query);
428 } catch (Exception e) {
429 logger.warn("Exception in query to get active document model for CSID: " + csid, e);
432 if (docModelList == null || docModelList.isEmpty()) {
433 logger.warn("Could not get active document models for CSID=" + csid);
435 } else if (docModelList.size() != 1) {
436 logger.error("Found more than 1 active document with CSID=" + csid);
440 return docModelList.get(0);
444 // Returns true if this event is for the creation of a new relationship record
446 private static boolean isCreatingNewRelationship(Event event) {
447 boolean result = false;
449 DocumentModel docModel = ((DocumentEventContext)event.getContext()).getSourceDocument();
450 if (event.getName().equals(DocumentEventTypes.DOCUMENT_CREATED) && documentMatchesType(docModel, RELATION_DOCTYPE)) {
457 // FIXME: A quick first pass, using an only partly query-based technique for
458 // getting the most recent Movement record related to a CollectionObject,
459 // augmented by procedural code.
461 // Could be replaced by a potentially more performant method, based on a query.
463 // E.g. the following is a sample CMIS query for retrieving Movement records
464 // related to a CollectionObject, which might serve as the basis for that query.
466 "SELECT DOC.nuxeo:pathSegment, DOC.dc:title, REL.dc:title,"
467 + "REL.relations_common:objectCsid, REL.relations_common:subjectCsid FROM Movement DOC "
468 + "JOIN Relation REL ON REL.relations_common:objectCsid = DOC.nuxeo:pathSegment "
469 + "WHERE REL.relations_common:subjectCsid = '5b4c617e-53a0-484b-804e' "
470 + "AND DOC.nuxeo:isVersion = false "
471 + "ORDER BY DOC.collectionspace_core:updatedAt DESC";
474 * Returns the most recent Movement record related to a CollectionObject.
476 * This method currently returns the related Movement record with the latest
477 * (i.e. most recent in time) Location Date field value.
479 * @param session a repository session.
480 * @param collectionObjectCsid a CollectionObject identifier (CSID)
481 * @param isAboutToBeRemovedEvent whether the current event involves a
482 * record that is slated for removal (hard deletion)
483 * @param movementCsidToFilter the CSID of a Movement record slated for
484 * deletion, or of a Movement record referenced by a Relation record slated
485 * for deletion. This record should be filtered out, prior to returning the
486 * most recent Movement record.
487 * @throws ClientException
488 * @return the most recent Movement record related to the CollectionObject
489 * identified by the supplied CSID.
491 protected String getMostRecentLocation(Event event,
492 CoreSessionInterface session, String collectionObjectCsid,
493 boolean isAboutToBeRemovedEvent, String eventMovementCsid) {
495 // Assume we can determine the most recent location by creating an indeterminate result
497 String result = INDETERMINATE_LOCATION;
500 // Get active Relation records involving Movement records related to this CollectionObject.
502 String query = String.format(
503 "SELECT * FROM %1$s WHERE " // collectionspace_core:tenantId = 1 "
505 + " (%2$s:subjectCsid = '%3$s' "
506 + " AND %2$s:objectDocumentType = '%4$s') "
508 + " (%2$s:objectCsid = '%3$s' "
509 + " AND %2$s:subjectDocumentType = '%4$s') "
511 + ACTIVE_DOCUMENT_WHERE_CLAUSE_FRAGMENT,
512 RELATION_DOCTYPE, RELATIONS_COMMON_SCHEMA, collectionObjectCsid, MOVEMENT_DOCTYPE);
513 logger.trace("query=" + query);
515 DocumentModelList relationDocModels = session.query(query);
516 if (isCreatingNewRelationship(event) == true) {
517 DocumentModel newRelation = ((DocumentEventContext)event.getContext()).getSourceDocument();
518 relationDocModels.add(newRelation);
522 // Remove redundant document models from the list.
524 relationDocModels = removeRedundantRelations(relationDocModels);
527 // Remove relationships that are with inactive movement records
529 relationDocModels = removeInactiveRelations(session, relationDocModels, isAboutToBeRemovedEvent, eventMovementCsid);
532 // If there are no candidate relationships after we removed the duplicates and inactive ones,
533 // throw an exception.
535 if (relationDocModels == null || relationDocModels.size() == 0) {
540 // If there is only one related movement record, then return it as the most recent
541 // movement record -but only if it's current location element is not empty.
543 if (relationDocModels.size() == 1) {
544 DocumentModel relationDocModel = relationDocModels.get(0);
545 DocumentModel movementDocModel = getMovementDocModelFromRelation(session, relationDocModel);
546 String location = (String) movementDocModel.getProperty(MOVEMENTS_COMMON_SCHEMA, CURRENT_LOCATION_ELEMENT_NAME);
548 if (Tools.isBlank(location) == false) {
550 } else { // currentLocation must be set
551 logger.error(String.format("Movement record=%s is missing its required location value and so is excluded from the computation of cataloging record=%s's current location.",
552 NuxeoUtils.getCsid(movementDocModel), collectionObjectCsid));
559 // Iterate through the list (>2) of related movement records, to find the related
560 // Movement record with the most recent location date.
562 GregorianCalendar mostRecentLocationDate = EARLIEST_COMPARISON_DATE;
563 GregorianCalendar mostRecentUpdatedDate = EARLIEST_COMPARISON_DATE;
565 for (DocumentModel relationDocModel : relationDocModels) {
566 String relatedMovementCsid;
567 DocumentModel movementDocModel;
569 // The movement record is either the subject or object of the relationship, but not both.
571 relatedMovementCsid = (String) relationDocModel.getProperty(RELATIONS_COMMON_SCHEMA, SUBJECT_CSID_PROPERTY);
572 if (relatedMovementCsid.equals(collectionObjectCsid)) {
573 relatedMovementCsid = (String) relationDocModel.getProperty(RELATIONS_COMMON_SCHEMA, OBJECT_CSID_PROPERTY);
575 movementDocModel = getCurrentDocModelFromCsid(session, relatedMovementCsid);
576 String location = (String) movementDocModel.getProperty(MOVEMENTS_COMMON_SCHEMA, CURRENT_LOCATION_ELEMENT_NAME);
579 // If the current Movement record lacks a location date, it cannot
580 // be established as the most recent Movement record; skip over it.
582 GregorianCalendar locationDate = (GregorianCalendar) movementDocModel.getProperty(MOVEMENTS_COMMON_SCHEMA, LOCATION_DATE_PROPERTY);
583 if (locationDate == null) {
584 logger.info(String.format("Movement record=%s has no location date and so is excluded from computation of cataloging record=%s current location.",
585 NuxeoUtils.getCsid(movementDocModel), collectionObjectCsid));
589 GregorianCalendar updatedDate = (GregorianCalendar) movementDocModel.getProperty(COLLECTIONSPACE_CORE_SCHEMA, UPDATED_AT_PROPERTY);
590 if (locationDate.after(mostRecentLocationDate)) {
591 mostRecentLocationDate = locationDate;
592 mostRecentUpdatedDate = updatedDate;
594 } else if (locationDate.compareTo(mostRecentLocationDate) == 0) {
595 // If the current Movement record's location date is identical
596 // to that of the (at this time) most recent Movement record, then
597 // instead compare the two records using their update date values
598 if (updatedDate.after(mostRecentUpdatedDate)) {
599 // The most recent location date value doesn't need to be
600 // updated here, as the two records' values are identical
601 mostRecentUpdatedDate = updatedDate;
611 // This method assumes that the relation passed into this method is between a Movement record
612 // and a CollectionObject (cataloging) record.
614 private static DocumentModel getMovementDocModelFromRelation(CoreSessionInterface session, DocumentModel relationDocModel) {
615 String movementCsid = null;
617 String subjectDocType = (String) relationDocModel.getProperty(RELATIONS_COMMON_SCHEMA, SUBJECT_DOCTYPE_PROPERTY);
618 if (subjectDocType.endsWith(MOVEMENT_DOCTYPE)) {
619 movementCsid = (String) relationDocModel.getProperty(RELATIONS_COMMON_SCHEMA, SUBJECT_CSID_PROPERTY);
621 movementCsid = (String) relationDocModel.getProperty(RELATIONS_COMMON_SCHEMA, OBJECT_CSID_PROPERTY);
624 return getCurrentDocModelFromCsid(session, movementCsid);
628 // Compares two Relation document models to see if they're either identical or
629 // reciprocal equivalents.
631 private static boolean compareRelationDocModels(DocumentModel r1, DocumentModel r2) {
632 boolean result = false;
634 String r1_subjectDocType = (String) r1.getProperty(RELATIONS_COMMON_SCHEMA, SUBJECT_DOCTYPE_PROPERTY);
635 String r1_objectDocType = (String) r1.getProperty(RELATIONS_COMMON_SCHEMA, OBJECT_DOCTYPE_PROPERTY);
636 String r1_subjectCsid = (String) r1.getProperty(RELATIONS_COMMON_SCHEMA, SUBJECT_CSID_PROPERTY);
637 String r1_objectCsid = (String) r1.getProperty(RELATIONS_COMMON_SCHEMA, OBJECT_CSID_PROPERTY);
639 String r2_subjectDocType = (String) r2.getProperty(RELATIONS_COMMON_SCHEMA, SUBJECT_DOCTYPE_PROPERTY);
640 String r2_objectDocType = (String) r2.getProperty(RELATIONS_COMMON_SCHEMA, OBJECT_DOCTYPE_PROPERTY);
641 String r2_subjectCsid = (String) r2.getProperty(RELATIONS_COMMON_SCHEMA, SUBJECT_CSID_PROPERTY);
642 String r2_objectCsid = (String) r2.getProperty(RELATIONS_COMMON_SCHEMA, OBJECT_CSID_PROPERTY);
644 // Check to see if they're identical
645 if (r1_subjectDocType.equalsIgnoreCase(r2_subjectDocType) && r1_objectDocType.equalsIgnoreCase(r2_objectDocType)
646 && r1_subjectCsid.equalsIgnoreCase(r2_subjectCsid) && r1_objectCsid.equalsIgnoreCase(r2_objectCsid)) {
650 // Check to see if they're reciprocal
651 if (r1_subjectDocType.equalsIgnoreCase(r2_objectDocType) && r1_objectDocType.equalsIgnoreCase(r2_subjectDocType)
652 && r1_subjectCsid.equalsIgnoreCase(r2_objectCsid) && r1_objectCsid.equalsIgnoreCase(r2_subjectCsid)) {
660 // Return a Relation document model list with redundant (either identical or reciprocal) relations removed.
662 private static DocumentModelList removeRedundantRelations(DocumentModelList relationDocModelList) {
663 DocumentModelList resultList = null;
665 if (relationDocModelList != null && relationDocModelList.size() > 0) {
666 resultList = new DocumentModelListImpl();
667 for (DocumentModel relationDocModel : relationDocModelList) {
668 if (existsInResultList(resultList, relationDocModel) == false) {
669 resultList.add(relationDocModel);
674 // TODO Auto-generated method stub
679 // Return just the list of active relationships with active Movement records. A value of 'true' for the 'isAboutToBeRemovedEvent'
680 // argument indicates that relationships with the 'movementCsid' record should be considered inactive.
682 private static DocumentModelList removeInactiveRelations(CoreSessionInterface session,
683 DocumentModelList relationDocModelList,
684 boolean isAboutToBeRemovedEvent,
685 String eventMovementCsid) {
686 DocumentModelList resultList = null;
688 if (relationDocModelList != null && relationDocModelList.size() > 0) {
689 resultList = new DocumentModelListImpl();
690 for (DocumentModel relationDocModel : relationDocModelList) {
691 String movementCsid = getCsidForDesiredDocTypeFromRelation(relationDocModel, MOVEMENT_DOCTYPE, COLLECTIONOBJECT_DOCTYPE);
692 DocumentModel movementDocModel = getCurrentDocModelFromCsid(session, movementCsid);
693 if (isActiveDocument(movementDocModel, isAboutToBeRemovedEvent, eventMovementCsid) == true) {
694 resultList.add(relationDocModel);
696 logger.debug(String.format("Disqualified relationship=%s with Movement record=%s from current location computation.",
697 NuxeoUtils.getCsid(relationDocModel), movementCsid));
707 // Check to see if the Relation (or its equivalent reciprocal) is already in the list.
709 private static boolean existsInResultList(DocumentModelList relationDocModelList, DocumentModel relationDocModel) {
710 boolean result = false;
712 for (DocumentModel target : relationDocModelList) {
713 if (compareRelationDocModels(relationDocModel, target) == true) {
723 * Returns the CSID for a desired document type from a Relation record,
724 * where the relationship involves two specified document types.
726 * @param relationDocModel a document model for a Relation record.
727 * @param desiredDocType a desired document type.
728 * @param relatedDocType a related document type.
729 * @throws ClientException
731 * @return the CSID from the desired document type in the relation. Returns
732 * null if the Relation record does not involve both the desired
733 * and related document types.
735 protected static String getCsidForDesiredDocTypeFromRelation(DocumentModel relationDocModel,
736 String desiredDocType, String relatedDocType) {
738 String subjectDocType = (String) relationDocModel.getProperty(RELATIONS_COMMON_SCHEMA, SUBJECT_DOCTYPE_PROPERTY);
739 String objectDocType = (String) relationDocModel.getProperty(RELATIONS_COMMON_SCHEMA, OBJECT_DOCTYPE_PROPERTY);
741 if (subjectDocType.startsWith(desiredDocType) && objectDocType.startsWith(relatedDocType)) { // Use startsWith() method, because customized tenant type names differ in their suffix.
742 csid = (String) relationDocModel.getProperty(RELATIONS_COMMON_SCHEMA, SUBJECT_CSID_PROPERTY);
743 } else if (subjectDocType.startsWith(relatedDocType) && objectDocType.startsWith(desiredDocType)) {
744 csid = (String) relationDocModel.getProperty(RELATIONS_COMMON_SCHEMA, OBJECT_CSID_PROPERTY);
750 // The following method can be extended by sub-classes to update
751 // different/multiple values; e.g. values for moveable locations ("crates").
753 * Updates a CollectionObject record with selected values from a Movement
756 * @param collectionObjectDocModel a document model for a CollectionObject
758 * @param movementDocModel a document model for a Movement record.
759 * @return a potentially updated document model for the CollectionObject
761 * @throws ClientException
763 protected abstract boolean updateCollectionObjectLocation(DocumentModel collectionObjectDocModel,
764 DocumentModel movmentDocModel,
765 String movementRecordsLocation);