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 private final static String ACTIVE_DOCUMENT_WHERE_CLAUSE_FRAGMENT =
44 "AND (ecm:currentLifeCycleState <> 'deleted') "
45 + "AND ecm:isProxy = 0 "
46 + "AND ecm:isCheckedInVersion = 0";
49 public void handleEvent(Event event) throws ClientException {
51 logger.trace("In handleEvent in UpdateObjectLocationOnMove ...");
53 EventContext eventContext = event.getContext();
54 if (eventContext == null) {
58 if (!(eventContext instanceof DocumentEventContext)) {
61 DocumentEventContext docEventContext = (DocumentEventContext) eventContext;
62 DocumentModel docModel = docEventContext.getSourceDocument();
64 // If this document event involves a Relation record, does this pertain to
65 // a relationship between a Movement record and a CollectionObject record?
67 // If not, we're not interested in processing this document event
68 // in this event handler, as it will have no bearing on updating a
69 // computed current location for a CollectionObject.
72 // (The rest of the code flow below is then identical to that which
73 // is followed when this document event involves a Movement record.)
74 String movementCsid = "";
75 if (documentMatchesType(docModel, RELATION_DOCTYPE)) {
76 if (logger.isTraceEnabled()) {
77 logger.trace("An event involving a Relation document was received by UpdateObjectLocationOnMove ...");
79 // Get a Movement CSID from the Relation record. (If we can't
80 // get it, then we don't have a pertinent relation record.)
81 movementCsid = getCsidForDesiredDocType(docModel, MOVEMENT_DOCTYPE, COLLECTIONOBJECT_DOCTYPE);
82 if (Tools.isBlank(movementCsid)) {
83 logger.warn("Could not obtain CSID for Movement record from document event.");
84 logger.warn(NO_FURTHER_PROCESSING_MESSAGE);
87 } else if (documentMatchesType(docModel, MOVEMENT_DOCTYPE)) {
88 if (logger.isTraceEnabled()) {
89 logger.trace("An event involving a Movement document was received by UpdateObjectLocationOnMove ...");
91 // Otherwise, get a Movement CSID directly from the Movement record.
92 movementCsid = NuxeoUtils.getCsid(docModel);
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);
99 if (logger.isTraceEnabled()) {
100 logger.trace("This event did not involve a document relevant to UpdateObjectLocationOnMove ...");
105 // Note: currently, all Document lifecycle transitions on
106 // the relevant doctype(s) are handled by this event handler,
107 // not just transitions between 'soft deleted' and active states.
109 // We are assuming that we'll want to re-compute current locations
110 // for related CollectionObjects on all such transitions, as the
111 // semantics of such transitions are opaque to this event handler,
112 // because arbitrary workflows can be bound to those doctype(s).
114 // If we need to filter out some of those lifecycle transitions,
115 // such as excluding transitions to the 'locked' workflow state; or,
116 // alternately, if we want to restrict this event handler's
117 // scope to handle only transitions into the 'soft deleted' state,
118 // we can add additional checks for doing so at this point in the code.
120 if (logger.isTraceEnabled()) {
121 logger.trace("Movement CSID=" + movementCsid);
124 // Find CollectionObject records that are related to this Movement record:
126 // Via an NXQL query, get a list of active relation records where:
127 // * This movement record's CSID is the subject CSID of the relation,
128 // and its object document type is a CollectionObject doctype;
130 // * This movement record's CSID is the object CSID of the relation,
131 // and its subject document type is a CollectionObject doctype.
132 CoreSession coreSession = docEventContext.getCoreSession();
133 // Some values below are hard-coded for readability, rather than
134 // being obtained from constants.
135 String query = String.format(
136 "SELECT * FROM %1$s WHERE " // collectionspace_core:tenantId = 1 "
138 + " (%2$s:subjectCsid = '%3$s' "
139 + " AND %2$s:objectDocumentType = '%4$s') "
141 + " (%2$s:objectCsid = '%3$s' "
142 + " AND %2$s:subjectDocumentType = '%4$s') "
144 + ACTIVE_DOCUMENT_WHERE_CLAUSE_FRAGMENT,
145 RELATION_DOCTYPE, RELATIONS_COMMON_SCHEMA, movementCsid, COLLECTIONOBJECT_DOCTYPE);
146 DocumentModelList relationDocModels = coreSession.query(query);
147 if (relationDocModels == null || relationDocModels.isEmpty()) {
148 // Encountering a Movement record that is not related to any
149 // CollectionObject is potentially a normal occurrence, so no
150 // error messages are logged here when we stop handling this event.
154 // Iterate through the list of Relation records found and build
155 // a list of CollectionObject CSIDs, by extracting the relevant CSIDs
156 // from those Relation records.
158 // FIXME: The following code might be refactored into a generic 'get
159 // values of a single property from a list of document models' method,
160 // if this doesn't already exist.
162 Set<String> collectionObjectCsids = new HashSet<String>(); // Prevents/removes duplicates on add
163 for (DocumentModel relationDocModel : relationDocModels) {
164 csid = getCsidForDesiredDocType(relationDocModel, COLLECTIONOBJECT_DOCTYPE, MOVEMENT_DOCTYPE);
165 if (Tools.notBlank(csid)) {
166 collectionObjectCsids.add(csid);
169 if (collectionObjectCsids == null || collectionObjectCsids.isEmpty()) {
170 logger.warn("Could not obtain any CSIDs of related CollectionObject records.");
171 logger.warn(NO_FURTHER_PROCESSING_MESSAGE);
174 if (logger.isTraceEnabled()) {
175 logger.trace("Found " + collectionObjectCsids.size() + " CSIDs of related CollectionObject records.");
179 // Iterate through the list of CollectionObject CSIDs found,
180 // obtain their most recently associated Movement, and update
181 // their relevant field value(s) accordingly.
182 DocumentModel collectionObjectDocModel;
183 DocumentModel mostRecentMovementDocModel;
184 for (String collectionObjectCsid : collectionObjectCsids) {
185 if (logger.isTraceEnabled()) {
186 logger.trace("CollectionObject CSID=" + collectionObjectCsid);
188 // Verify that the CollectionObject is retrievable.
189 collectionObjectDocModel = getDocModelFromCsid(coreSession, collectionObjectCsid);
190 if (collectionObjectDocModel == null) {
193 // Verify that the CollectionObject record is active.
194 if (!isActiveDocument(collectionObjectDocModel)) {
197 mostRecentMovementDocModel = getMostRecentMovement(coreSession, collectionObjectCsid);
198 if (mostRecentMovementDocModel == null) {
201 collectionObjectDocModel =
202 updateCollectionObjectValuesFromMovement(collectionObjectDocModel, mostRecentMovementDocModel);
203 coreSession.saveDocument(collectionObjectDocModel);
208 // FIXME: Generic methods like many of those below might be split off,
209 // into an event utilities class, base classes, or otherwise. - ADR 2012-12-05
211 // FIXME: Identify whether the equivalent of the documentMatchesType utility
212 // method is already implemented and substitute a call to the latter if so.
213 // This may well already exist.
215 * Identifies whether a document matches a supplied document type.
217 * @param docModel a document model.
218 * @param docType a document type string.
219 * @return true if the document matches the supplied document type; false if
222 protected static boolean documentMatchesType(DocumentModel docModel, String docType) {
223 if (docModel == null || Tools.isBlank(docType)) {
226 if (docModel.getType().startsWith(docType)) {
234 * Identifies whether a document is an active document; that is, if it is
235 * not a versioned record; not a proxy (symbolic link to an actual record);
236 * and not in the 'deleted' workflow state.
238 * (A note relating the latter: Nuxeo appears to send 'documentModified'
239 * events even on workflow transitions, such when records are 'soft deleted'
240 * by being transitioned to the 'deleted' workflow state.)
243 * @return true if the document is an active document; false if it is not.
245 protected static boolean isActiveDocument(DocumentModel docModel) {
246 if (docModel == null) {
249 boolean isActiveDocument = false;
251 if (!docModel.isVersion()
252 && !docModel.isProxy()
253 && !docModel.getCurrentLifeCycleState().equals(WorkflowClient.WORKFLOWSTATE_DELETED)) {
254 isActiveDocument = true;
256 } catch (ClientException ce) {
257 logger.warn("Error while identifying whether document is an active document: ", ce);
259 return isActiveDocument;
263 * Returns a document model for a record identified by a CSID.
265 * @param session a repository session.
266 * @param collectionObjectCsid a CollectionObject identifier (CSID)
267 * @return a document model for the record identified by the supplied CSID.
269 protected static DocumentModel getDocModelFromCsid(CoreSession session, String collectionObjectCsid) {
270 DocumentModelList collectionObjectDocModels = null;
272 final String query = "SELECT * FROM "
273 + NuxeoUtils.BASE_DOCUMENT_TYPE
275 + NuxeoUtils.getByNameWhereClause(collectionObjectCsid);
276 collectionObjectDocModels = session.query(query);
277 } catch (Exception e) {
278 logger.warn("Exception in query to get document model for CollectionObject: ", e);
280 if (collectionObjectDocModels == null || collectionObjectDocModels.isEmpty()) {
281 logger.warn("Could not get document models for CollectionObject(s).");
283 } else if (collectionObjectDocModels.size() != 1) {
284 logger.debug("Found more than 1 document with CSID=" + collectionObjectCsid);
287 return collectionObjectDocModels.get(0);
290 // FIXME: A quick first pass, using an only partly query-based technique for
291 // getting the most recent Movement record related to a CollectionObject,
292 // augmented by procedural code.
294 // Should be replaced by a more performant method, based entirely, or nearly so,
297 // E.g. the following is a sample CMIS query for retrieving Movement records
298 // related to a CollectionObject, which might serve as the basis for that query.
300 "SELECT DOC.nuxeo:pathSegment, DOC.dc:title, REL.dc:title,"
301 + "REL.relations_common:objectCsid, REL.relations_common:subjectCsid FROM Movement DOC "
302 + "JOIN Relation REL ON REL.relations_common:objectCsid = DOC.nuxeo:pathSegment "
303 + "WHERE REL.relations_common:subjectCsid = '5b4c617e-53a0-484b-804e' "
304 + "AND DOC.nuxeo:isVersion = false "
305 + "ORDER BY DOC.collectionspace_core:updatedAt DESC";
308 * Returns the most recent Movement record related to a CollectionObject.
310 * This method currently returns the related Movement record with the latest
311 * (i.e. most recent in time) Location Date field value.
313 * @param session a repository session.
314 * @param collectionObjectCsid a CollectionObject identifier (CSID)
315 * @throws ClientException
316 * @return the most recent Movement record related to the CollectionObject
317 * identified by the supplied CSID.
319 protected static DocumentModel getMostRecentMovement(CoreSession session, String collectionObjectCsid)
320 throws ClientException {
321 DocumentModel mostRecentMovementDocModel = null;
322 // Get Relation records for Movements related to this CollectionObject.
324 // Some values below are hard-coded for readability, rather than
325 // being obtained from constants.
326 String query = String.format(
327 "SELECT * FROM %1$s WHERE " // collectionspace_core:tenantId = 1 "
329 + " (%2$s:subjectCsid = '%3$s' "
330 + " AND %2$s:objectDocumentType = '%4$s') "
332 + " (%2$s:objectCsid = '%3$s' "
333 + " AND %2$s:subjectDocumentType = '%4$s') "
335 + ACTIVE_DOCUMENT_WHERE_CLAUSE_FRAGMENT,
336 RELATION_DOCTYPE, RELATIONS_COMMON_SCHEMA, collectionObjectCsid, MOVEMENT_DOCTYPE);
337 if (logger.isTraceEnabled()) {
338 logger.trace("query=" + query);
340 DocumentModelList relationDocModels = session.query(query);
341 if (relationDocModels == null || relationDocModels.isEmpty()) {
342 logger.warn("Unexpectedly found no relations to Movement records to/from to this CollectionObject record.");
343 return mostRecentMovementDocModel;
345 if (logger.isTraceEnabled()) {
346 logger.trace("Found " + relationDocModels.size() + " relations to Movement records to/from this CollectionObject record.");
349 // Iterate through related movement records, to find the related
350 // Movement record with the most recent location date.
351 GregorianCalendar mostRecentLocationDate = EARLIEST_COMPARISON_DATE;
352 DocumentModel movementDocModel = null;
353 Set<String> alreadyProcessedMovementCsids = new HashSet<String>();
354 String relatedMovementCsid = "";
355 for (DocumentModel relationDocModel : relationDocModels) {
356 // Due to the 'OR' operator in the query above, related Movement
357 // record CSIDs may reside in either the subject or object CSID fields
358 // of the relation record. Whichever CSID value doesn't match the
359 // CollectionObject's CSID is inferred to be the related Movement record's CSID.
360 relatedMovementCsid = (String) relationDocModel.getProperty(RELATIONS_COMMON_SCHEMA, SUBJECT_CSID_PROPERTY);
361 if (relatedMovementCsid.equals(collectionObjectCsid)) {
362 relatedMovementCsid = (String) relationDocModel.getProperty(RELATIONS_COMMON_SCHEMA, OBJECT_CSID_PROPERTY);
364 if (Tools.isBlank(relatedMovementCsid)) {
367 // Because of the OR clause used in the query above, there may be
368 // two or more Relation records returned in the query results that
369 // reference the same Movement record, as either the subject
370 // or object of a relation to the same CollectionObject record;
371 // we need to filter out those duplicates.
372 if (alreadyProcessedMovementCsids.contains(relatedMovementCsid)) {
375 alreadyProcessedMovementCsids.add(relatedMovementCsid);
377 if (logger.isTraceEnabled()) {
378 logger.trace("Movement CSID=" + relatedMovementCsid);
380 movementDocModel = getDocModelFromCsid(session, relatedMovementCsid);
381 if (movementDocModel == null) {
385 // Verify that the Movement record is active. This will also exclude
386 // versioned Movement records from the computation of the current
387 // location, for tenants that are versioning such records.
388 if (!isActiveDocument(movementDocModel)) {
389 if (logger.isTraceEnabled()) {
390 logger.trace("Skipping this inactive Movement record ...");
394 GregorianCalendar locationDate =
395 (GregorianCalendar) movementDocModel.getProperty(MOVEMENTS_COMMON_SCHEMA, LOCATION_DATE_PROPERTY);
396 if (locationDate == null) {
399 if (locationDate.after(mostRecentLocationDate)) {
400 mostRecentLocationDate = locationDate;
401 mostRecentMovementDocModel = movementDocModel;
404 return mostRecentMovementDocModel;
408 * Returns the CSID for a desired document type from a Relation record,
409 * where the relationship involves two specified, different document types.
411 * @param relationDocModel a document model for a Relation record.
412 * @param desiredDocType a desired document type.
413 * @param relatedDocType a related document type.
414 * @throws ClientException
415 * @return the CSID from the desired document type in the relation. Returns
416 * an empty string if the Relation record does not involve both the desired
417 * and related document types, or if the desired document type is at both
418 * ends of the relation.
420 protected static String getCsidForDesiredDocType(DocumentModel relationDocModel,
421 String desiredDocType, String relatedDocType) throws ClientException {
423 String subjectDocType = (String) relationDocModel.getProperty(RELATIONS_COMMON_SCHEMA, SUBJECT_DOCTYPE_PROPERTY);
424 String objectDocType = (String) relationDocModel.getProperty(RELATIONS_COMMON_SCHEMA, OBJECT_DOCTYPE_PROPERTY);
425 if (subjectDocType.startsWith(desiredDocType) && objectDocType.startsWith(desiredDocType)) {
428 if (subjectDocType.startsWith(desiredDocType) && objectDocType.startsWith(relatedDocType)) {
429 csid = (String) relationDocModel.getProperty(RELATIONS_COMMON_SCHEMA, SUBJECT_CSID_PROPERTY);
430 } else if (subjectDocType.startsWith(relatedDocType) && objectDocType.startsWith(desiredDocType)) {
431 csid = (String) relationDocModel.getProperty(RELATIONS_COMMON_SCHEMA, OBJECT_CSID_PROPERTY);
436 // Can be extended by sub-classes to update different/multiple values;
437 // e.g. values for moveable locations ("crates").
439 * Updates a CollectionObject record with selected values from a Movement record.
441 * @param collectionObjectDocModel a document model for a CollectionObject record.
442 * @param movementDocModel a document model for a Movement record.
443 * @throws ClientException
445 protected abstract DocumentModel updateCollectionObjectValuesFromMovement(DocumentModel collectionObjectDocModel,
446 DocumentModel movementDocModel)
447 throws ClientException;