]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
dd501d5ca611397c39dae2ed46cc04345dd42ded
[tmp/jakarta-migration.git] /
1 package org.collectionspace.services.listener;
2
3 import java.util.ArrayList;
4 import java.util.GregorianCalendar;
5 import java.util.HashMap;
6 import java.util.List;
7 import java.util.Map;
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;
23
24 public class UpdateObjectLocationOnMove implements EventListener {
25
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";
49
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?
56     //
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.
61     
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.
67     @Override
68     public void handleEvent(Event event) throws ClientException {
69
70         logger.trace("In handleEvent in UpdateObjectLocationOnMove ...");
71
72         EventContext eventContext = event.getContext();
73         if (eventContext == null) {
74             return;
75         }
76
77         if (!(eventContext instanceof DocumentEventContext)) {
78             return;
79         }
80         DocumentEventContext docEventContext = (DocumentEventContext) eventContext;
81         DocumentModel docModel = docEventContext.getSourceDocument();
82
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.
86         //
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;
99                 break;
100             }
101         }
102         if (!involvesRelevantDocType) {
103             return;
104         }
105         
106         if (logger.isTraceEnabled()) {
107             logger.trace("An event involving a document of the relevant type(s) was received by UpdateObjectLocationOnMove ...");
108         }
109         
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.
115         //
116         // If we need to filter out some of those lifecycle transitions,
117         // we can add additional checks for doing so at this point.
118
119
120         // Find CollectionObject records that are related to this Movement record:
121         //
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;
125         // or
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 "
134                 + "("
135                 + "  (%2$s:subjectCsid = '%3$s' "
136                 + "  AND %2$s:objectDocumentType = '%4$s') "
137                 + " OR "
138                 + "  (%2$s:objectCsid = '%3$s' "
139                 + "  AND %2$s:subjectDocumentType = '%4$s') "
140                 + ")"
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()) {
145             return;
146         }
147
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.
151
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.
155         String csid = "";
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);
161             }
162         }
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);
166             return;
167         } else {
168             if (logger.isTraceEnabled()) {
169                 logger.trace("Found " + collectionObjectCsids.size() + " CSIDs of related CollectionObject records.");
170             }
171         }
172
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) {
178
179             collectionObjectDocModel = getDocModelFromCsid(coreSession, collectionObjectCsid);
180             // Verify that the CollectionObject record is active.
181             if (!isActiveDocument(collectionObjectDocModel)) {
182                 continue;
183             }
184             // Obtain the computed current location of that CollectionObject.
185             computedCurrentLocationRefName = computeCurrentLocation(coreSession, collectionObjectCsid);
186             if (logger.isTraceEnabled()) {
187                 logger.trace("computedCurrentLocation refName=" + computedCurrentLocationRefName);
188             }
189
190             // Check that the value returned, which is expected to be a
191             // reference (refName) to a storage location authority term,
192             // is, at a minimum:
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.");
201                 }
202
203                 // If the value returned from the function passes validation,
204                 // compare it to the value in the computedCurrentLocation
205                 // field of that CollectionObject.
206                 //
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.");
216                     }
217                     // ... set aside this CollectionObject's docModel and its new
218                     // computed current location value for subsequent updating
219                     docModelsToUpdate.put(collectionObjectDocModel, computedCurrentLocationRefName);
220                 }
221             } else {
222                 if (logger.isTraceEnabled()) {
223                     logger.trace("computedCurrentLocation refName does NOT require updating.");
224                 }
225             }
226
227         }
228
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);
243
244             }
245         }
246         logger.info("Updated " + collectionObjectsUpdated + " CollectionObject record(s) with new computed current location(s).");
247     }
248
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
251     //
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.
255     /**
256      * Identifies whether a document matches a supplied document type.
257      *
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
261      * it does not.
262      */
263     private boolean documentMatchesType(DocumentModel docModel, String docType) {
264         if (docModel == null || Tools.isBlank(docType)) {
265             return false;
266         }
267         if (docModel.getType().startsWith(docType)) {
268             return true;
269         } else {
270             return false;
271         }
272     }
273
274     /**
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.
278      *
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.)
282      *
283      * @param docModel
284      * @return true if the document is an active document; false if it is not.
285      */
286     private boolean isActiveDocument(DocumentModel docModel) {
287         if (docModel == null) {
288             return false;
289         }
290         boolean isActiveDocument = false;
291         try {
292             if (!docModel.isVersion()
293                     && !docModel.isProxy()
294                     && !docModel.getCurrentLifeCycleState().equals(WorkflowClient.WORKFLOWSTATE_DELETED)) {
295                 isActiveDocument = true;
296             }
297         } catch (ClientException ce) {
298             logger.warn("Error while identifying whether document is an active document: ", ce);
299         }
300         return isActiveDocument;
301     }
302
303     /**
304      * Returns a document model for a record identified by a CSID.
305      *
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.
309      */
310     private DocumentModel getDocModelFromCsid(CoreSession session, String collectionObjectCsid) {
311         DocumentModelList collectionObjectDocModels = null;
312         try {
313             final String query = "SELECT * FROM "
314                     + NuxeoUtils.BASE_DOCUMENT_TYPE
315                     + " WHERE "
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);
320         }
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);
325         }
326         return collectionObjectDocModels.get(0);
327     }
328
329     // FIXME: A quick first pass, using an only partly query-based technique for
330     // getting the current location, augmented by procedural code.
331     //
332     // Should be replaced by a more performant method, based entirely, or nearly so,
333     // on a query.
334     //
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.
337     /*
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";
344      */
345     /**
346      * Returns the computed current location for a CollectionObject.
347      *
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.
353      */
354     private String computeCurrentLocation(CoreSession session, String collectionObjectCsid)
355             throws ClientException {
356         String computedCurrentLocation = "";
357         // Get Relation records for Movements related to this CollectionObject.
358         //
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 "
363                 + "("
364                 + "  (%2$s:subjectCsid = '%3$s' "
365                 + "  AND %2$s:objectDocumentType = '%4$s') "
366                 + " OR "
367                 + "  (%2$s:objectCsid = '%3$s' "
368                 + "  AND %2$s:subjectDocumentType = '%4$s') "
369                 + ")"
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;
375         } else {
376         }
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;
382         String csid = "";
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);
392             }
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)) {
398                 continue;
399             }
400             GregorianCalendar locationDate =
401                     (GregorianCalendar) movementDocModel.getProperty(MOVEMENTS_COMMON_SCHEMA, LOCATION_DATE_PROPERTY);
402             if (locationDate == null) {
403                 continue;
404             }
405             if (locationDate.after(mostRecentLocationDate)) {
406                 mostRecentLocationDate = locationDate;
407                 location = (String) movementDocModel.getProperty(MOVEMENTS_COMMON_SCHEMA, CURRENT_LOCATION_PROPERTY);
408             }
409             if (Tools.notBlank(location)) {
410                 computedCurrentLocation = location;
411             }
412         }
413         return computedCurrentLocation;
414     }
415 }