1 package org.collectionspace.services.listener;
3 import java.util.ArrayList;
4 import java.util.GregorianCalendar;
5 import java.util.HashMap;
8 import org.apache.commons.logging.Log;
9 import org.apache.commons.logging.LogFactory;
10 import org.collectionspace.services.client.workflow.WorkflowClient;
11 import org.collectionspace.services.common.api.RefNameUtils;
12 import org.collectionspace.services.common.api.Tools;
13 import org.collectionspace.services.movement.nuxeo.MovementConstants;
14 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
15 import org.nuxeo.ecm.core.api.ClientException;
16 import org.nuxeo.ecm.core.api.CoreSession;
17 import org.nuxeo.ecm.core.api.DocumentModel;
18 import org.nuxeo.ecm.core.api.DocumentModelList;
19 import org.nuxeo.ecm.core.event.Event;
20 import org.nuxeo.ecm.core.event.EventContext;
21 import org.nuxeo.ecm.core.event.EventListener;
22 import org.nuxeo.ecm.core.event.impl.DocumentEventContext;
24 public class UpdateObjectLocationOnMove implements EventListener {
26 // FIXME: We might experiment here with using log4j instead of Apache Commons Logging;
27 // am using the latter to follow Ray's pattern for now
28 private final Log logger = LogFactory.getLog(UpdateObjectLocationOnMove.class);
29 // FIXME: Make the following message, or its equivalent, a constant usable by all event listeners
30 private final String NO_FURTHER_PROCESSING_MESSAGE =
31 "This event listener will not continue processing this event ...";
32 private final List<String> relevantDocTypesList = new ArrayList<String>();
33 GregorianCalendar EARLIEST_COMPARISON_DATE = new GregorianCalendar(1600, 1, 1);
34 private final static String RELATIONS_COMMON_SCHEMA = "relations_common"; // FIXME: Get from external constant
35 private final static String RELATION_DOCTYPE = "Relation"; // FIXME: Get from external constant
36 private final static String SUBJECT_CSID_PROPERTY = "subjectCsid"; // FIXME: Get from external constant
37 private final static String OBJECT_CSID_PROPERTY = "objectCsid"; // FIXME: Get from external constant
38 private final static String COLLECTIONOBJECTS_COMMON_SCHEMA = "collectionobjects_common"; // FIXME: Get from external constant
39 private final static String COLLECTIONOBJECT_DOCTYPE = "CollectionObject"; // FIXME: Get from external constant
40 private final static String COMPUTED_CURRENT_LOCATION_PROPERTY = "computedCurrentLocation"; // FIXME: Create and then get from external constant
41 private final static String MOVEMENTS_COMMON_SCHEMA = "movements_common"; // FIXME: Get from external constant
42 private final static String MOVEMENT_DOCTYPE = MovementConstants.NUXEO_DOCTYPE;
43 private final static String LOCATION_DATE_PROPERTY = "locationDate"; // FIXME: Get from external constant
44 private final static String CURRENT_LOCATION_PROPERTY = "currentLocation"; // FIXME: Get from external constant
45 private final static String ACTIVE_DOCUMENT_WHERE_CLAUSE_FRAGMENT =
46 "AND (ecm:currentLifeCycleState <> 'deleted') "
47 + "AND ecm:isProxy = 0 "
48 + "AND ecm:isCheckedInVersion = 0";
50 // FIXME: Per Rick, what happens if a relation record is created,
51 // updated, deleted, or transitioned to a different workflow state,
52 // that effectively either adds or removes a relation between a Movement
53 // record and a CollectionObject record? Do we need to listen
54 // for that event as well and update the CollectionObject record's
55 // computedCurrentLocation accordingly?
57 // The following code is currently only handling events affecting
58 // Movement records. One possible approach is to add a companion
59 // event handler for Relation records, also registered as an event listener
60 // via configuration in the same document bundle as this event handler.
62 // FIXME: The following code handles the computation of current locations
63 // for CollectionObject records on creation, update, and soft deletion
64 // (workflow transition to 'deleted' state) of related Movement records.
65 // It does not yet been configured or tested to also handle outright
66 // deletion of related Movement records.
68 public void handleEvent(Event event) throws ClientException {
70 logger.trace("In handleEvent in UpdateObjectLocationOnMove ...");
72 EventContext eventContext = event.getContext();
73 if (eventContext == null) {
77 if (!(eventContext instanceof DocumentEventContext)) {
80 DocumentEventContext docEventContext = (DocumentEventContext) eventContext;
81 DocumentModel docModel = docEventContext.getSourceDocument();
83 // If this event does not involve one of the relevant doctypes
84 // designated as being handled by this event listener, return
85 // without further handling the event.
87 // FIXME: We will likely need to add the Relation doctype here,
88 // along with additional code to handle such changes. (See comment above.)
89 // As an alternative, we could create a second event handler for
90 // doing so, also registered as an event listener via configuration
91 // in the same document bundle as this event handler. If so, the
92 // code below could be simplified to be a single check, rather than
93 // iterating through a list.
94 boolean involvesRelevantDocType = false;
95 relevantDocTypesList.add(MovementConstants.NUXEO_DOCTYPE);
96 for (String docType : relevantDocTypesList) {
97 if (documentMatchesType(docModel, docType)) {
98 involvesRelevantDocType = true;
102 if (!involvesRelevantDocType) {
106 if (logger.isTraceEnabled()) {
107 logger.trace("An event involving a document of the relevant type(s) was received by UpdateObjectLocationOnMove ...");
110 // Note: currently, all Document lifecycle transitions on
111 // the relevant doctype(s) are handled by this event handler,
112 // not just transitions between 'soft deleted' and active states.
113 // We are assuming that we'll want to re-compute current locations
114 // for related CollectionObjects on any such transitions.
116 // If we need to filter out some of those lifecycle transitions,
117 // we can add additional checks for doing so at this point.
120 // Find CollectionObject records that are related to this Movement record:
122 // Via an NXQL query, get a list of active relation records where:
123 // * This movement record's CSID is the subject CSID of the relation,
124 // and its object document type is a CollectionObject doctype;
126 // * This movement record's CSID is the object CSID of the relation,
127 // and its subject document type is a CollectionObject doctype.
128 String movementCsid = NuxeoUtils.getCsid(docModel);
129 CoreSession coreSession = docEventContext.getCoreSession();
130 // Some values below are hard-coded for readability, rather than
131 // being obtained from constants.
132 String query = String.format(
133 "SELECT * FROM %1$s WHERE " // collectionspace_core:tenantId = 1 "
135 + " (%2$s:subjectCsid = '%3$s' "
136 + " AND %2$s:objectDocumentType = '%4$s') "
138 + " (%2$s:objectCsid = '%3$s' "
139 + " AND %2$s:subjectDocumentType = '%4$s') "
141 + ACTIVE_DOCUMENT_WHERE_CLAUSE_FRAGMENT,
142 RELATION_DOCTYPE, RELATIONS_COMMON_SCHEMA, movementCsid, COLLECTIONOBJECT_DOCTYPE);
143 DocumentModelList relatedDocModels = coreSession.query(query);
144 if (relatedDocModels == null || relatedDocModels.isEmpty()) {
148 // Iterate through the list of Relation records found and build
149 // a list of CollectionObject CSIDs, by extracting the object CSIDs
150 // from those Relation records.
152 // FIXME: The following code might be refactored into a generic 'get
153 // values of a single property from a list of document models' method,
154 // if this doesn't already exist.
156 List<String> collectionObjectCsids = new ArrayList<String>();
157 for (DocumentModel relatedDocModel : relatedDocModels) {
158 csid = (String) relatedDocModel.getProperty(RELATIONS_COMMON_SCHEMA, OBJECT_CSID_PROPERTY);
159 if (Tools.notBlank(csid)) {
160 collectionObjectCsids.add(csid);
163 if (collectionObjectCsids == null || collectionObjectCsids.isEmpty()) {
164 logger.warn("Could not obtain any CSIDs of related CollectionObject records.");
165 logger.warn(NO_FURTHER_PROCESSING_MESSAGE);
168 if (logger.isTraceEnabled()) {
169 logger.trace("Found " + collectionObjectCsids.size() + " CSIDs of related CollectionObject records.");
173 // Iterate through the list of CollectionObject CSIDs found.
174 DocumentModel collectionObjectDocModel = null;
175 String computedCurrentLocationRefName = "";
176 Map<DocumentModel, String> docModelsToUpdate = new HashMap<DocumentModel, String>();
177 for (String collectionObjectCsid : collectionObjectCsids) {
179 collectionObjectDocModel = getDocModelFromCsid(coreSession, collectionObjectCsid);
180 // Verify that the CollectionObject record is active.
181 if (!isActiveDocument(collectionObjectDocModel)) {
184 // Obtain the computed current location of that CollectionObject.
185 computedCurrentLocationRefName = computeCurrentLocation(coreSession, collectionObjectCsid);
186 if (logger.isTraceEnabled()) {
187 logger.trace("computedCurrentLocation refName=" + computedCurrentLocationRefName);
190 // Check that the value returned, which is expected to be a
191 // reference (refName) to a storage location authority term,
193 // * Non-null and non-blank. (We need to verify this assumption; can a
194 // CollectionObject's computed current location meaningfully be 'un-set'?)
195 // * Capable of being successfully parsed by an authority item parser;
196 // that is, returning a non-null parse result.
197 if ((Tools.notBlank(computedCurrentLocationRefName)
198 && (RefNameUtils.parseAuthorityTermInfo(computedCurrentLocationRefName) != null))) {
199 if (logger.isTraceEnabled()) {
200 logger.trace("refName passes basic validation tests.");
203 // If the value returned from the function passes validation,
204 // compare it to the value in the computedCurrentLocation
205 // field of that CollectionObject.
207 // If the CollectionObject does not already have a
208 // computedCurrentLocation value, or if the two values differ ...
209 String existingComputedCurrentLocationRefName =
210 (String) collectionObjectDocModel.getProperty(COLLECTIONOBJECTS_COMMON_SCHEMA, COMPUTED_CURRENT_LOCATION_PROPERTY);
211 if (Tools.isBlank(existingComputedCurrentLocationRefName)
212 || !computedCurrentLocationRefName.equals(existingComputedCurrentLocationRefName)) {
213 if (logger.isTraceEnabled()) {
214 logger.trace("Existing computedCurrentLocation refName=" + existingComputedCurrentLocationRefName);
215 logger.trace("computedCurrentLocation refName requires updating.");
217 // ... set aside this CollectionObject's docModel and its new
218 // computed current location value for subsequent updating
219 docModelsToUpdate.put(collectionObjectDocModel, computedCurrentLocationRefName);
222 if (logger.isTraceEnabled()) {
223 logger.trace("computedCurrentLocation refName does NOT require updating.");
229 // For each CollectionObject docModel that has been set aside for updating,
230 // update the value of its computedCurrentLocation field with its new,
231 // computed current location.
232 int collectionObjectsUpdated = 0;
233 for (Map.Entry<DocumentModel, String> entry : docModelsToUpdate.entrySet()) {
234 DocumentModel dmodel = entry.getKey();
235 String newCurrentLocationValue = entry.getValue();
236 dmodel.setProperty(COLLECTIONOBJECTS_COMMON_SCHEMA, COMPUTED_CURRENT_LOCATION_PROPERTY, newCurrentLocationValue);
237 coreSession.saveDocument(dmodel);
238 collectionObjectsUpdated++;
239 if (logger.isTraceEnabled()) {
240 String afterUpdateComputedCurrentLocationRefName =
241 (String) dmodel.getProperty(COLLECTIONOBJECTS_COMMON_SCHEMA, COMPUTED_CURRENT_LOCATION_PROPERTY);
242 logger.trace("Following update, new computedCurrentLocation refName value=" + afterUpdateComputedCurrentLocationRefName);
246 logger.info("Updated " + collectionObjectsUpdated + " CollectionObject record(s) with new computed current location(s).");
249 // FIXME: Generic methods like many of those below might be split off,
250 // into an event utilities class, base classes, or otherwise. - ADR 2012-12-05
252 // FIXME: Identify whether the equivalent of the documentMatchesType utility
253 // method is already implemented and substitute a call to the latter if so.
254 // This may well already exist.
256 * Identifies whether a document matches a supplied document type.
258 * @param docModel a document model.
259 * @param docType a document type string.
260 * @return true if the document matches the supplied document type; false if
263 private boolean documentMatchesType(DocumentModel docModel, String docType) {
264 if (docModel == null || Tools.isBlank(docType)) {
267 if (docModel.getType().startsWith(docType)) {
275 * Identifies whether a document is an active document; that is, if it is
276 * not a versioned record; not a proxy (symbolic link to an actual record);
277 * and not in the 'deleted' workflow state.
279 * (A note relating the latter: Nuxeo appears to send 'documentModified'
280 * events even on workflow transitions, such when records are 'soft deleted'
281 * by being transitioned to the 'deleted' workflow state.)
284 * @return true if the document is an active document; false if it is not.
286 private boolean isActiveDocument(DocumentModel docModel) {
287 if (docModel == null) {
290 boolean isActiveDocument = false;
292 if (!docModel.isVersion()
293 && !docModel.isProxy()
294 && !docModel.getCurrentLifeCycleState().equals(WorkflowClient.WORKFLOWSTATE_DELETED)) {
295 isActiveDocument = true;
297 } catch (ClientException ce) {
298 logger.warn("Error while identifying whether document is an active document: ", ce);
300 return isActiveDocument;
304 * Returns a document model for a record identified by a CSID.
306 * @param session a repository session.
307 * @param collectionObjectCsid a CollectionObject identifier (CSID)
308 * @return a document model for the record identified by the supplied CSID.
310 private DocumentModel getDocModelFromCsid(CoreSession session, String collectionObjectCsid) {
311 DocumentModelList collectionObjectDocModels = null;
313 final String query = "SELECT * FROM "
314 + NuxeoUtils.BASE_DOCUMENT_TYPE
316 + NuxeoUtils.getByNameWhereClause(collectionObjectCsid);
317 collectionObjectDocModels = session.query(query);
318 } catch (Exception e) {
319 logger.warn("Exception in query to get document model for CollectionObject: ", e);
321 if (collectionObjectDocModels == null || collectionObjectDocModels.isEmpty()) {
322 logger.warn("Could not get document models for CollectionObject(s).");
323 } else if (collectionObjectDocModels.size() != 1) {
324 logger.debug("Found more than 1 document with CSID=" + collectionObjectCsid);
326 return collectionObjectDocModels.get(0);
329 // FIXME: A quick first pass, using an only partly query-based technique for
330 // getting the current location, augmented by procedural code.
332 // Should be replaced by a more performant method, based entirely, or nearly so,
335 // E.g. the following is a sample CMIS query for retrieving Movement records
336 // related to a CollectionObject, which might serve as the basis for that query.
338 "SELECT DOC.nuxeo:pathSegment, DOC.dc:title, REL.dc:title,"
339 + "REL.relations_common:objectCsid, REL.relations_common:subjectCsid FROM Movement DOC "
340 + "JOIN Relation REL ON REL.relations_common:objectCsid = DOC.nuxeo:pathSegment "
341 + "WHERE REL.relations_common:subjectCsid = '5b4c617e-53a0-484b-804e' "
342 + "AND DOC.nuxeo:isVersion = false "
343 + "ORDER BY DOC.collectionspace_core:updatedAt DESC";
346 * Returns the computed current location for a CollectionObject.
348 * @param session a repository session.
349 * @param collectionObjectCsid a CollectionObject identifier (CSID)
350 * @throws ClientException
351 * @return the computed current location for the CollectionObject identified
352 * by the supplied CSID.
354 private String computeCurrentLocation(CoreSession session, String collectionObjectCsid)
355 throws ClientException {
356 String computedCurrentLocation = "";
357 // Get Relation records for Movements related to this CollectionObject.
359 // Some values below are hard-coded for readability, rather than
360 // being obtained from constants.
361 String query = String.format(
362 "SELECT * FROM %1$s WHERE " // collectionspace_core:tenantId = 1 "
364 + " (%2$s:subjectCsid = '%3$s' "
365 + " AND %2$s:objectDocumentType = '%4$s') "
367 + " (%2$s:objectCsid = '%3$s' "
368 + " AND %2$s:subjectDocumentType = '%4$s') "
370 + ACTIVE_DOCUMENT_WHERE_CLAUSE_FRAGMENT,
371 RELATION_DOCTYPE, RELATIONS_COMMON_SCHEMA, collectionObjectCsid, MOVEMENT_DOCTYPE);
372 DocumentModelList relatedDocModels = session.query(query);
373 if (relatedDocModels == null || relatedDocModels.isEmpty()) {
374 return computedCurrentLocation;
377 // Iterate through related movement records, to get the CollectionObject's
378 // computed current location from the related Movement record with the
379 // most recent location date.
380 GregorianCalendar mostRecentLocationDate = EARLIEST_COMPARISON_DATE;
381 DocumentModel movementDocModel = null;
383 String location = "";
384 for (DocumentModel relatedDocModel : relatedDocModels) {
385 // Due to the 'OR' operator in the query above, related Movement
386 // record CSIDs may reside in either the subject or object CSID fields
387 // of the relation record. Whichever CSID value doesn't match the
388 // CollectionObject's CSID is inferred to be the related Movement record's CSID.
389 csid = (String) relatedDocModel.getProperty(RELATIONS_COMMON_SCHEMA, SUBJECT_CSID_PROPERTY);
390 if (csid.equals(collectionObjectCsid)) {
391 csid = (String) relatedDocModel.getProperty(RELATIONS_COMMON_SCHEMA, OBJECT_CSID_PROPERTY);
393 movementDocModel = getDocModelFromCsid(session, csid);
394 // Verify that the Movement record is active. This will also exclude
395 // versioned Movement records from the computation of the current
396 // location, for tenants that are versioning such records.
397 if (!isActiveDocument(movementDocModel)) {
400 GregorianCalendar locationDate =
401 (GregorianCalendar) movementDocModel.getProperty(MOVEMENTS_COMMON_SCHEMA, LOCATION_DATE_PROPERTY);
402 if (locationDate == null) {
405 if (locationDate.after(mostRecentLocationDate)) {
406 mostRecentLocationDate = locationDate;
407 location = (String) movementDocModel.getProperty(MOVEMENTS_COMMON_SCHEMA, CURRENT_LOCATION_PROPERTY);
409 if (Tools.notBlank(location)) {
410 computedCurrentLocation = location;
413 return computedCurrentLocation;