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 // ####################################################################
51 // FIXME: Per Rick, what happens if a relation record is updated,
52 // that 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 create and
58 // update events affecting Movement records.
59 // ####################################################################
60 // FIXME: We'll likely also need to handle workflow state transition and
61 // deletion events, where the soft or hard deletion of a Movement or
62 // Relation record effectively changes the current location for a CollectionObject.
64 public void handleEvent(Event event) throws ClientException {
66 logger.trace("In handleEvent in UpdateObjectLocationOnMove ...");
68 EventContext eventContext = event.getContext();
69 if (eventContext == null) {
73 if (!(eventContext instanceof DocumentEventContext)) {
76 DocumentEventContext docEventContext = (DocumentEventContext) eventContext;
77 DocumentModel docModel = docEventContext.getSourceDocument();
79 // If this event does not involve one of the relevant doctypes
80 // designated as being handled by this event listener, return
81 // without further handling the event.
83 // FIXME: We will likely need to add the Relation doctype here,
84 // along with additional code to handle such changes. (See comment above.)
85 // As an alternative, we could create a second event handler for
86 // doing so, also registered as an event listener via configuration
87 // in the same document bundle as this event handler. If so, the
88 // code below could be simplified to be a single check, rather than
89 // iterating through a list.
90 boolean involvesRelevantDocType = false;
91 relevantDocTypesList.add(MovementConstants.NUXEO_DOCTYPE);
92 for (String docType : relevantDocTypesList) {
93 if (documentMatchesType(docModel, docType)) {
94 involvesRelevantDocType = true;
98 if (!involvesRelevantDocType) {
101 if (!isActiveDocument(docModel)) {
105 if (logger.isDebugEnabled()) {
106 logger.debug("An event involving an active document of the relevant type(s) was received by UpdateObjectLocationOnMove ...");
109 // Find CollectionObject records that are related to this Movement record:
111 // Via an NXQL query, get a list of active relation records where:
112 // * This movement record's CSID is the subject CSID of the relation,
113 // and its object document type is a CollectionObject doctype;
115 // * This movement record's CSID is the object CSID of the relation,
116 // and its subject document type is a CollectionObject doctype.
117 String movementCsid = NuxeoUtils.getCsid(docModel);
118 CoreSession coreSession = docEventContext.getCoreSession();
119 // Some values below are hard-coded for readability, rather than
120 // being obtained from constants.
121 String query = String.format(
122 "SELECT * FROM %1$s WHERE " // collectionspace_core:tenantId = 1 "
124 + " (%2$s:subjectCsid = '%3$s' "
125 + " AND %2$s:objectDocumentType = '%4$s') "
127 + " (%2$s:objectCsid = '%3$s' "
128 + " AND %2$s:subjectDocumentType = '%4$s') "
130 + ACTIVE_DOCUMENT_WHERE_CLAUSE_FRAGMENT,
131 RELATION_DOCTYPE, RELATIONS_COMMON_SCHEMA, movementCsid, COLLECTIONOBJECT_DOCTYPE);
132 DocumentModelList relatedDocModels = coreSession.query(query);
133 if (relatedDocModels == null || relatedDocModels.isEmpty()) {
137 // Iterate through the list of Relation records found and build
138 // a list of CollectionObject CSIDs, by extracting the object CSIDs
139 // from those Relation records.
141 // FIXME: The following code might be refactored into a generic 'get
142 // values of a single property from a list of document models' method,
143 // if this doesn't already exist.
145 List<String> collectionObjectCsids = new ArrayList<String>();
146 for (DocumentModel relatedDocModel : relatedDocModels) {
147 csid = (String) relatedDocModel.getProperty(RELATIONS_COMMON_SCHEMA, OBJECT_CSID_PROPERTY);
148 if (Tools.notBlank(csid)) {
149 collectionObjectCsids.add(csid);
152 if (collectionObjectCsids == null || collectionObjectCsids.isEmpty()) {
153 logger.warn("Could not obtain any CSIDs of related CollectionObject records.");
154 logger.warn(NO_FURTHER_PROCESSING_MESSAGE);
157 if (logger.isTraceEnabled()) {
158 logger.trace("Found " + collectionObjectCsids.size() + " CSIDs of related CollectionObject records.");
162 // Iterate through the list of CollectionObject CSIDs found.
163 DocumentModel collectionObjectDocModel = null;
164 String computedCurrentLocationRefName = "";
165 Map<DocumentModel, String> docModelsToUpdate = new HashMap<DocumentModel, String>();
166 for (String collectionObjectCsid : collectionObjectCsids) {
168 collectionObjectDocModel = getDocModelFromCsid(coreSession, collectionObjectCsid);
169 // Verify that the CollectionObject record is active.
170 if (!isActiveDocument(collectionObjectDocModel)) {
173 // Obtain the computed current location of that CollectionObject.
174 computedCurrentLocationRefName = computeCurrentLocation(coreSession, collectionObjectCsid);
175 if (logger.isTraceEnabled()) {
176 logger.trace("computedCurrentLocation refName=" + computedCurrentLocationRefName);
179 // Check that the value returned, which is expected to be a
180 // reference (refName) to a storage location authority term,
182 // * Non-null and non-blank. (We need to verify this assumption; can a
183 // CollectionObject's computed current location meaningfully be 'un-set'?)
184 // * Capable of being successfully parsed by an authority item parser;
185 // that is, returning a non-null parse result.
186 if ((Tools.notBlank(computedCurrentLocationRefName)
187 && (RefNameUtils.parseAuthorityTermInfo(computedCurrentLocationRefName) != null))) {
188 if (logger.isTraceEnabled()) {
189 logger.trace("refName passes basic validation tests.");
192 // If the value returned from the function passes validation,
193 // compare it to the value in the computedCurrentLocation
194 // field of that CollectionObject.
196 // If the CollectionObject does not already have a
197 // computedCurrentLocation value, or if the two values differ ...
198 String existingComputedCurrentLocationRefName =
199 (String) collectionObjectDocModel.getProperty(COLLECTIONOBJECTS_COMMON_SCHEMA, COMPUTED_CURRENT_LOCATION_PROPERTY);
200 if (Tools.isBlank(existingComputedCurrentLocationRefName)
201 || !computedCurrentLocationRefName.equals(existingComputedCurrentLocationRefName)) {
202 if (logger.isTraceEnabled()) {
203 logger.trace("Existing computedCurrentLocation refName=" + existingComputedCurrentLocationRefName);
204 logger.trace("computedCurrentLocation refName requires updating.");
206 // ... set aside this CollectionObject's docModel and its new
207 // computed current location value for subsequent updating
208 docModelsToUpdate.put(collectionObjectDocModel, computedCurrentLocationRefName);
211 if (logger.isTraceEnabled()) {
212 logger.trace("computedCurrentLocation refName does NOT require updating.");
218 // For each CollectionObject docModel that has been set aside for updating,
219 // update the value of its computedCurrentLocation field with its new,
220 // computed current location.
221 int collectionObjectsUpdated = 0;
222 for (Map.Entry<DocumentModel, String> entry : docModelsToUpdate.entrySet()) {
223 DocumentModel dmodel = entry.getKey();
224 String newCurrentLocationValue = entry.getValue();
225 dmodel.setProperty(COLLECTIONOBJECTS_COMMON_SCHEMA, COMPUTED_CURRENT_LOCATION_PROPERTY, newCurrentLocationValue);
226 coreSession.saveDocument(dmodel);
227 collectionObjectsUpdated++;
228 if (logger.isTraceEnabled()) {
229 String afterUpdateComputedCurrentLocationRefName =
230 (String) dmodel.getProperty(COLLECTIONOBJECTS_COMMON_SCHEMA, COMPUTED_CURRENT_LOCATION_PROPERTY);
231 logger.trace("Following update, new computedCurrentLocation refName value=" + afterUpdateComputedCurrentLocationRefName);
235 logger.info("Updated " + collectionObjectsUpdated + " CollectionObject record(s) with a new computed current location.");
238 // FIXME: Generic methods like many of those below might be split off,
239 // into an event utilities class, base classes, or otherwise. - ADR 2012-12-05
241 // FIXME: Identify whether the equivalent of the documentMatchesType utility
242 // method is already implemented and substitute a call to the latter if so.
243 // This may well already exist.
245 * Identifies whether a document matches a supplied document type.
247 * @param docModel a document model.
248 * @param docType a document type string.
249 * @return true if the document matches the supplied document type; false if
252 private boolean documentMatchesType(DocumentModel docModel, String docType) {
253 if (docModel == null || Tools.isBlank(docType)) {
256 if (docModel.getType().startsWith(docType)) {
264 * Identifies whether a document is an active document; that is, if it is
265 * not a versioned record; not a proxy (symbolic link to an actual record);
266 * and not in the 'deleted' workflow state.
268 * (A note relating the latter: Nuxeo appears to send 'documentModified'
269 * events even on workflow transitions, such when records are 'soft deleted'
270 * by being transitioned to the 'deleted' workflow state.)
273 * @return true if the document is an active document; false if it is not.
275 private boolean isActiveDocument(DocumentModel docModel) {
276 if (docModel == null) {
279 boolean isActiveDocument = false;
281 if (!docModel.isVersion()
282 && !docModel.isProxy()
283 && !docModel.getCurrentLifeCycleState().equals(WorkflowClient.WORKFLOWSTATE_DELETED)) {
284 isActiveDocument = true;
286 } catch (ClientException ce) {
287 logger.warn("Error while identifying whether document is an active document: ", ce);
289 return isActiveDocument;
293 * Returns a document model for a record identified by a CSID.
295 * @param session a repository session.
296 * @param collectionObjectCsid a CollectionObject identifier (CSID)
297 * @return a document model for the record identified by the supplied CSID.
299 private DocumentModel getDocModelFromCsid(CoreSession session, String collectionObjectCsid) {
300 DocumentModelList collectionObjectDocModels = null;
302 final String query = "SELECT * FROM "
303 + NuxeoUtils.BASE_DOCUMENT_TYPE
305 + NuxeoUtils.getByNameWhereClause(collectionObjectCsid);
306 collectionObjectDocModels = session.query(query);
307 } catch (Exception e) {
308 logger.warn("Exception in query to get document model for CollectionObject: ", e);
310 if (collectionObjectDocModels == null || collectionObjectDocModels.isEmpty()) {
311 logger.warn("Could not get document models for CollectionObject(s).");
312 } else if (collectionObjectDocModels.size() != 1) {
313 logger.debug("Found more than 1 document with CSID=" + collectionObjectCsid);
315 return collectionObjectDocModels.get(0);
318 // FIXME: A quick first pass, using an only partly query-based technique for
319 // getting the current location, augmented by procedural code.
321 // Should be replaced by a more performant method, based entirely, or nearly so,
324 // E.g. the following is a sample CMIS query for retrieving Movement records
325 // related to a CollectionObject, which might serve as the basis for that query.
327 "SELECT DOC.nuxeo:pathSegment, DOC.dc:title, REL.dc:title,"
328 + "REL.relations_common:objectCsid, REL.relations_common:subjectCsid FROM Movement DOC "
329 + "JOIN Relation REL ON REL.relations_common:objectCsid = DOC.nuxeo:pathSegment "
330 + "WHERE REL.relations_common:subjectCsid = '5b4c617e-53a0-484b-804e' "
331 + "AND DOC.nuxeo:isVersion = false "
332 + "ORDER BY DOC.collectionspace_core:updatedAt DESC";
335 * Returns the computed current location for a CollectionObject.
337 * @param session a repository session.
338 * @param collectionObjectCsid a CollectionObject identifier (CSID)
339 * @throws ClientException
340 * @return the computed current location for the CollectionObject identified
341 * by the supplied CSID.
343 private String computeCurrentLocation(CoreSession session, String collectionObjectCsid)
344 throws ClientException {
345 String computedCurrentLocation = "";
346 // Get Relation records for Movements related to this CollectionObject.
348 // Some values below are hard-coded for readability, rather than
349 // being obtained from constants.
350 String query = String.format(
351 "SELECT * FROM %1$s WHERE " // collectionspace_core:tenantId = 1 "
353 + " (%2$s:subjectCsid = '%3$s' "
354 + " AND %2$s:objectDocumentType = '%4$s') "
356 + " (%2$s:objectCsid = '%3$s' "
357 + " AND %2$s:subjectDocumentType = '%4$s') "
359 + ACTIVE_DOCUMENT_WHERE_CLAUSE_FRAGMENT,
360 RELATION_DOCTYPE, RELATIONS_COMMON_SCHEMA, collectionObjectCsid, MOVEMENT_DOCTYPE);
361 DocumentModelList relatedDocModels = session.query(query);
362 if (relatedDocModels == null || relatedDocModels.isEmpty()) {
363 return computedCurrentLocation;
366 // Iterate through related movement records, to get the CollectionObject's
367 // computed current location from the related Movement record with the
368 // most recent location date.
369 GregorianCalendar mostRecentLocationDate = EARLIEST_COMPARISON_DATE;
370 DocumentModel movementDocModel = null;
372 String location = "";
373 for (DocumentModel relatedDocModel : relatedDocModels) {
374 // Due to the 'OR' operator in the query above, related Movement
375 // record CSIDs may reside in either the subject or object CSID fields
376 // of the relation record. Whichever CSID value doesn't match the
377 // CollectionObject's CSID is inferred to be the related Movement record's CSID.
378 csid = (String) relatedDocModel.getProperty(RELATIONS_COMMON_SCHEMA, SUBJECT_CSID_PROPERTY);
379 if (csid.equals(collectionObjectCsid)) {
380 csid = (String) relatedDocModel.getProperty(RELATIONS_COMMON_SCHEMA, OBJECT_CSID_PROPERTY);
382 movementDocModel = getDocModelFromCsid(session, csid);
383 // Verify that the Movement record is active. This will also exclude
384 // versioned Movement records from the computation of the current
385 // location, for tenants that are versioning such records.
386 if (!isActiveDocument(movementDocModel)) {
389 GregorianCalendar locationDate =
390 (GregorianCalendar) movementDocModel.getProperty(MOVEMENTS_COMMON_SCHEMA, LOCATION_DATE_PROPERTY);
391 if (locationDate == null) {
394 if (locationDate.after(mostRecentLocationDate)) {
395 mostRecentLocationDate = locationDate;
396 location = (String) movementDocModel.getProperty(MOVEMENTS_COMMON_SCHEMA, CURRENT_LOCATION_PROPERTY);
398 if (Tools.notBlank(location)) {
399 computedCurrentLocation = location;
402 return computedCurrentLocation;