]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
8604fb7f02e59e3137df2c7baae9ae975c42e9f1
[tmp/jakarta-migration.git] /
1 package org.collectionspace.services.batch.nuxeo;
2
3 import java.io.StringReader;
4 import java.net.URI;
5 import java.net.URISyntaxException;
6 import java.util.ArrayList;
7 import java.util.Arrays;
8 import java.util.Collections;
9 import java.util.HashSet;
10 import java.util.List;
11 import java.util.Set;
12 import javax.ws.rs.core.PathSegment;
13 import javax.ws.rs.core.UriInfo;
14 import org.collectionspace.services.batch.AbstractBatchInvocable;
15 import org.collectionspace.services.client.AbstractCommonListUtils;
16 import org.collectionspace.services.client.CollectionObjectClient;
17 import org.collectionspace.services.client.MovementClient;
18 import org.collectionspace.services.client.PoxPayloadOut;
19 import org.collectionspace.services.client.workflow.WorkflowClient;
20 import org.collectionspace.services.common.ResourceBase;
21 import org.collectionspace.services.common.ResourceMap;
22 import org.collectionspace.services.common.api.Tools;
23 import org.collectionspace.services.common.invocable.InvocationResults;
24 import org.collectionspace.services.jaxb.AbstractCommonList;
25 import org.dom4j.DocumentException;
26 import org.jboss.resteasy.specimpl.UriInfoImpl;
27 import org.jdom.Document;
28 import org.jdom.Element;
29 import org.jdom.Namespace;
30 import org.jdom.input.SAXBuilder;
31 import org.slf4j.Logger;
32 import org.slf4j.LoggerFactory;
33
34 public class UpdateObjectLocationBatchJob extends AbstractBatchInvocable {
35
36     // FIXME: Where appropriate, get from existing constants rather than local declarations
37     private final static String COMPUTED_CURRENT_LOCATION_ELEMENT_NAME = "computedCurrentLocation";
38     private final static String CSID_ELEMENT_NAME = "csid";
39     private final static String CURRENT_LOCATION_ELEMENT_NAME = "currentLocation";
40     private final static String LIFECYCLE_STATE_ELEMENT_NAME = "currentLifeCycleState";
41     private final static String LOCATION_DATE_ELEMENT_NAME = "locationDate";
42     private final static String OBJECT_NUMBER_ELEMENT_NAME = "objectNumber";
43     private final static String WORKFLOW_COMMON_SCHEMA_NAME = "workflow_common";
44     private final static String WORKFLOW_COMMON_NAMESPACE_PREFIX = "ns2";
45     private final static String WORKFLOW_COMMON_NAMESPACE_URI =
46             "http://collectionspace.org/services/workflow";
47     private final static Namespace WORKFLOW_COMMON_NAMESPACE =
48             Namespace.getNamespace(
49             WORKFLOW_COMMON_NAMESPACE_PREFIX,
50             WORKFLOW_COMMON_NAMESPACE_URI);
51     private final static String COLLECTIONOBJECTS_COMMON_SCHEMA_NAME = "collectionobjects_common";
52     private final static String COLLECTIONOBJECTS_COMMON_NAMESPACE_PREFIX = "ns2";
53     private final static String COLLECTIONOBJECTS_COMMON_NAMESPACE_URI =
54             "http://collectionspace.org/services/collectionobject";
55     private final static Namespace COLLECTIONOBJECTS_COMMON_NAMESPACE =
56             Namespace.getNamespace(
57             COLLECTIONOBJECTS_COMMON_NAMESPACE_PREFIX,
58             COLLECTIONOBJECTS_COMMON_NAMESPACE_URI);
59     private final String CLASSNAME = this.getClass().getSimpleName();
60     private final Logger logger = LoggerFactory.getLogger(this.getClass());
61
62     // Initialization tasks
63     public UpdateObjectLocationBatchJob() {
64         setSupportedInvocationModes(Arrays.asList(INVOCATION_MODE_SINGLE, INVOCATION_MODE_LIST, INVOCATION_MODE_NO_CONTEXT));
65     }
66
67     /**
68      * The main work logic of the batch job. Will be called after setContext.
69      */
70     @Override
71     public void run() {
72
73         setCompletionStatus(STATUS_MIN_PROGRESS);
74
75         try {
76
77             List<String> csids = new ArrayList<String>();
78
79             // Build a list of CollectionObject records to process via this
80             // batch job, depending on the invocation mode requested.
81             if (requestIsForInvocationModeSingle()) {
82                 String singleCsid = getInvocationContext().getSingleCSID();
83                 if (Tools.isBlank(singleCsid)) {
84                     throw new Exception(CSID_VALUES_NOT_PROVIDED_IN_INVOCATION_CONTEXT);
85                 } else {
86                     csids.add(singleCsid);
87                 }
88             } else if (requestIsForInvocationModeList()) {
89                 List<String> listCsids = getListCsids();
90                 if (listCsids.isEmpty()) {
91                     throw new Exception(CSID_VALUES_NOT_PROVIDED_IN_INVOCATION_CONTEXT);
92                 }
93                 csids.addAll(listCsids);
94             } else if (requestIsForInvocationModeGroup()) {
95                 // This invocation mode is currently not yet supported.
96                 // FIXME: Add code to getMemberCsidsFromGroup() to support this mode.
97                 String groupCsid = getInvocationContext().getGroupCSID();
98                 List<String> groupMemberCsids = getMemberCsidsFromGroup(groupCsid);
99                 if (groupMemberCsids.isEmpty()) {
100                     throw new Exception(CSID_VALUES_NOT_PROVIDED_IN_INVOCATION_CONTEXT);
101                 }
102                 csids.addAll(groupMemberCsids);
103             } else if (requestIsForInvocationModeNoContext()) {
104                 List<String> noContextCsids = getNoContextCsids();
105                 if (noContextCsids.isEmpty()) {
106                     throw new Exception(CSID_VALUES_NOT_PROVIDED_IN_INVOCATION_CONTEXT);
107                 }
108                 csids.addAll(noContextCsids);
109             }
110
111             // Update the value of the computed current location field for each CollectionObject
112             setResults(updateComputedCurrentLocations(csids));
113             setCompletionStatus(STATUS_COMPLETE);
114
115         } catch (Exception e) {
116             String errMsg = "Error encountered in " + CLASSNAME + ": " + e.getLocalizedMessage();
117             setErrorResult(errMsg);
118         }
119
120     }
121
122     private InvocationResults updateComputedCurrentLocations(List<String> csids) {
123
124         ResourceMap resourcemap = getResourceMap();
125         ResourceBase collectionObjectResource = resourcemap.get(CollectionObjectClient.SERVICE_NAME);
126         ResourceBase movementResource = resourcemap.get(MovementClient.SERVICE_NAME);
127         String computedCurrentLocation;
128         int numUpdated = 0;
129
130         try {
131
132             // For each CollectionObject record
133             for (String collectionObjectCsid : csids) {
134
135                 // Skip over soft-deleted CollectionObject records
136                 if (isRecordDeleted(collectionObjectResource, collectionObjectCsid)) {
137                     if (logger.isTraceEnabled()) {
138                         logger.trace("Skipping soft-deleted CollectionObject record with CSID " + collectionObjectCsid);
139                     }
140                     continue;
141                 }
142                 // Get the Movement records related to this CollectionObject record
143                 AbstractCommonList relatedMovements =
144                         getRelatedRecords(movementResource, collectionObjectCsid, true /* exclude deleted records */);
145                 // Skip over CollectionObject records that have no related Movement records
146                 if (relatedMovements.getListItem().isEmpty()) {
147                     continue;
148                 }
149                 // Compute the current location of this CollectionObject,
150                 // based on data in its related Movement records
151                 computedCurrentLocation = computeCurrentLocation(relatedMovements);
152                 // Skip over CollectionObject records where no current location
153                 // value can be computed from related Movement records
154                 //
155                 // FIXME: Clarify: it ever necessary to 'unset' a computed
156                 // current location value, by setting it to a null or empty value,
157                 // if that value is no longer obtainable from related Movement records?
158                 if (Tools.isBlank(computedCurrentLocation)) {
159                     continue;
160                 }
161                 // Update the value of the computed current location field
162                 // in the CollectionObject record
163                 numUpdated = updateComputedCurrentLocationValue(collectionObjectResource,
164                         collectionObjectCsid, computedCurrentLocation, resourcemap, numUpdated);
165             }
166
167         } catch (Exception e) {
168             String errMsg = "Error encountered in " + CLASSNAME + ": " + e.getLocalizedMessage() + " ";
169             errMsg = errMsg + "Successfully updated " + numUpdated + " CollectionObject record(s) prior to error.";
170             logger.error(errMsg);
171             setErrorResult(errMsg);
172             getResults().setNumAffected(numUpdated);
173             return getResults();
174         }
175
176         logger.info("Updated computedCurrentLocation values in " + numUpdated + " CollectionObject record(s).");
177         getResults().setNumAffected(numUpdated);
178         return getResults();
179     }
180
181     private String computeCurrentLocation(AbstractCommonList relatedMovements) {
182         String computedCurrentLocation;
183         String movementCsid;
184         Set<String> alreadyProcessedMovementCsids = new HashSet<String>();
185         computedCurrentLocation = "";
186         String currentLocation;
187         String locationDate;
188         String mostRecentLocationDate = "";
189         for (AbstractCommonList.ListItem movementRecord : relatedMovements.getListItem()) {
190             movementCsid = AbstractCommonListUtils.ListItemGetElementValue(movementRecord, CSID_ELEMENT_NAME);
191             if (Tools.isBlank(movementCsid)) {
192                 continue;
193             }
194             // Avoid processing any related Movement record more than once,
195             // regardless of the directionality of its relation(s) to this
196             // CollectionObject record.
197             if (alreadyProcessedMovementCsids.contains(movementCsid)) {
198                 continue;
199             } else {
200                 alreadyProcessedMovementCsids.add(movementCsid);
201             }
202             locationDate = AbstractCommonListUtils.ListItemGetElementValue(movementRecord, LOCATION_DATE_ELEMENT_NAME);
203             if (Tools.isBlank(locationDate)) {
204                 continue;
205             }
206             currentLocation = AbstractCommonListUtils.ListItemGetElementValue(movementRecord, CURRENT_LOCATION_ELEMENT_NAME);
207             if (Tools.isBlank(currentLocation)) {
208                 continue;
209             }
210             if (logger.isTraceEnabled()) {
211                 logger.trace("Location date value = " + locationDate);
212                 logger.trace("Current location value = " + currentLocation);
213             }
214             // If this record's location date value is more recent than that of other
215             // Movement records processed so far, set the computed current location
216             // to its current location value.
217             //
218             // Assumes that all values for this element/field will be consistent ISO 8601
219             // date/time representations, each of which can be ordered via string comparison.
220             //
221             // If this is *not* the case, we can instead parse and convert these values
222             // to date/time objects.
223             if (locationDate.compareTo(mostRecentLocationDate) > 0) {
224                 mostRecentLocationDate = locationDate;
225                 // FIXME: Add optional validation here that the currentLocation value
226                 // parses successfully as an item refName.
227                 // Consider making this optional validation, in turn dependent on the
228                 // value of a parameter passed in during batch job invocation.
229                 computedCurrentLocation = currentLocation;
230             }
231
232         }
233         return computedCurrentLocation;
234     }
235
236     private int updateComputedCurrentLocationValue(ResourceBase collectionObjectResource,
237             String collectionObjectCsid, String computedCurrentLocation, ResourceMap resourcemap, int numUpdated)
238             throws DocumentException, URISyntaxException {
239         PoxPayloadOut collectionObjectPayload;
240         String objectNumber;
241         String previousComputedCurrentLocation;
242
243         collectionObjectPayload = findByCsid(collectionObjectResource, collectionObjectCsid);
244         if (Tools.isBlank(collectionObjectPayload.toXML())) {
245             return numUpdated;
246         } else {
247             if (logger.isTraceEnabled()) {
248                 logger.trace("Payload: " + "\n" + collectionObjectPayload);
249             }
250         }
251         // Perform the update only if the computed current location value will change
252         previousComputedCurrentLocation = getFieldElementValue(collectionObjectPayload,
253                 COLLECTIONOBJECTS_COMMON_SCHEMA_NAME, COLLECTIONOBJECTS_COMMON_NAMESPACE,
254                 COMPUTED_CURRENT_LOCATION_ELEMENT_NAME);
255         if (Tools.notBlank(previousComputedCurrentLocation)
256                 && computedCurrentLocation.equals(previousComputedCurrentLocation)) {
257             return numUpdated;
258         }
259         // In the default CollectionObject validation handler, the object number
260         // is a required field and its (non-blank) value must be present in update
261         // payloads to successfully perform an update.
262         //
263         // FIXME: Consider making this check for an object number dependent on the
264         // value of a parameter passed in during batch job invocation.
265         objectNumber = getFieldElementValue(collectionObjectPayload,
266                 COLLECTIONOBJECTS_COMMON_SCHEMA_NAME, COLLECTIONOBJECTS_COMMON_NAMESPACE,
267                 OBJECT_NUMBER_ELEMENT_NAME);
268         if (logger.isTraceEnabled()) {
269             logger.trace("Object number: " + objectNumber);
270         }
271         if (Tools.isBlank(objectNumber)) {
272             return numUpdated;
273         }
274
275         String collectionObjectUpdatePayload =
276                 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
277                 + "<document name=\"collectionobject\">"
278                 + "  <ns2:collectionobjects_common "
279                 + "      xmlns:ns2=\"http://collectionspace.org/services/collectionobject\">"
280                 + "    <objectNumber>" + objectNumber + "</objectNumber>"
281                 + "    <computedCurrentLocation>" + computedCurrentLocation + "</computedCurrentLocation>"
282                 + "  </ns2:collectionobjects_common>"
283                 + "</document>";
284         if (logger.isTraceEnabled()) {
285             logger.trace("Update payload: " + "\n" + collectionObjectUpdatePayload);
286         }
287         byte[] response = collectionObjectResource.update(resourcemap, null, collectionObjectCsid,
288                 collectionObjectUpdatePayload);
289         numUpdated++;
290         if (logger.isTraceEnabled()) {
291             logger.trace("Computed current location value for CollectionObject " + collectionObjectCsid
292                     + " was set to " + computedCurrentLocation);
293
294         }
295         return numUpdated;
296     }
297
298     // #################################################################
299     // Ray Lee's convenience methods from his AbstractBatchJob class for the
300     // UC Berkeley Botanical Garden v2.4 implementation.
301     // #################################################################
302     protected PoxPayloadOut findByCsid(String serviceName, String csid) throws URISyntaxException, DocumentException {
303         ResourceBase resource = getResourceMap().get(serviceName);
304         return findByCsid(resource, csid);
305     }
306
307     protected PoxPayloadOut findByCsid(ResourceBase resource, String csid) throws URISyntaxException, DocumentException {
308         byte[] response = resource.get(null, createUriInfo(), csid);
309         PoxPayloadOut payload = new PoxPayloadOut(response);
310         return payload;
311     }
312
313     protected UriInfo createUriInfo() throws URISyntaxException {
314         return createUriInfo("");
315     }
316
317     protected UriInfo createUriInfo(String queryString) throws URISyntaxException {
318         URI absolutePath = new URI("");
319         URI baseUri = new URI("");
320         return new UriInfoImpl(absolutePath, baseUri, "", queryString, Collections.<PathSegment>emptyList());
321     }
322
323     // #################################################################
324     // Other convenience methods
325     // #################################################################
326     protected UriInfo createRelatedRecordsUriInfo(String queryString) throws URISyntaxException {
327         URI uri = new URI(null, null, null, queryString, null);
328         return createUriInfo(uri.getRawQuery());
329     }
330
331     protected String getFieldElementValue(PoxPayloadOut payload, String partLabel, Namespace partNamespace, String fieldPath) {
332         String value = null;
333         SAXBuilder builder = new SAXBuilder();
334         try {
335             Document document = builder.build(new StringReader(payload.toXML()));
336             Element root = document.getRootElement();
337             // The part element is always expected to have an explicit namespace.
338             Element part = root.getChild(partLabel, partNamespace);
339             // Try getting the field element both with and without a namespace.
340             // Even though a field element that lacks a namespace prefix
341             // may yet inherit its namespace from a parent, JDOM may require that
342             // the getChild() call be made without a namespace.
343             Element field = part.getChild(fieldPath, partNamespace);
344             if (field == null) {
345                 field = part.getChild(fieldPath);
346             }
347             if (field != null) {
348                 value = field.getText();
349             }
350         } catch (Exception e) {
351             logger.error("Error getting value from field path " + fieldPath
352                     + " in schema part " + partLabel);
353             return null;
354         }
355         return value;
356     }
357
358     private boolean isRecordDeleted(ResourceBase resource, String collectionObjectCsid)
359             throws URISyntaxException, DocumentException {
360         boolean isDeleted = false;
361         byte[] workflowResponse = resource.getWorkflow(createUriInfo(), collectionObjectCsid);
362         if (workflowResponse != null) {
363             PoxPayloadOut payloadOut = new PoxPayloadOut(workflowResponse);
364             String workflowState =
365                     getFieldElementValue(payloadOut, WORKFLOW_COMMON_SCHEMA_NAME,
366                     WORKFLOW_COMMON_NAMESPACE, LIFECYCLE_STATE_ELEMENT_NAME);
367             if (Tools.notBlank(workflowState) && workflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED)) {
368                 isDeleted = true;
369             }
370         }
371         return isDeleted;
372     }
373
374     private AbstractCommonList getRelatedRecords(ResourceBase resource, String csid, boolean excludeDeletedRecords)
375             throws URISyntaxException, DocumentException {
376
377         // Get records related to a record, specified by its CSID,
378         // where the record is the object of the relation
379         UriInfo uriInfo = createUriInfo();
380         // FIXME: Get this from constant(s), where appropriate
381         uriInfo.getQueryParameters().add("rtObj", csid);
382         if (excludeDeletedRecords) {
383             uriInfo.getQueryParameters().add(WorkflowClient.WORKFLOW_QUERY_NONDELETED, "false");
384         }
385
386         AbstractCommonList relatedRecords = resource.getList(uriInfo);
387         if (logger.isTraceEnabled()) {
388             logger.trace("Identified " + relatedRecords.getTotalItems()
389                     + " record(s) related to the object record with CSID " + csid);
390         }
391
392         // Get records related to a record, specified by its CSID,
393         // where the record is the subject of the relation
394         // FIXME: Get query string(s) from constant(s), where appropriate
395         uriInfo = createUriInfo();
396         uriInfo.getQueryParameters().add("rtSbj", csid);
397         if (excludeDeletedRecords) {
398             uriInfo.getQueryParameters().add(WorkflowClient.WORKFLOW_QUERY_NONDELETED, "false");
399         }
400         AbstractCommonList reverseRelatedRecords = resource.getList(uriInfo);
401         if (logger.isTraceEnabled()) {
402             logger.trace("Identified " + reverseRelatedRecords.getTotalItems()
403                     + " record(s) related to the subject record with CSID " + csid);
404         }
405
406         // If the second list contains any related records,
407         // merge it into the first list
408         if (reverseRelatedRecords.getListItem().size() > 0) {
409             relatedRecords.getListItem().addAll(reverseRelatedRecords.getListItem());
410         }
411
412         if (logger.isTraceEnabled()) {
413             logger.trace("Identified a total of " + relatedRecords.getListItem().size()
414                     + " record(s) related to the record with CSID " + csid);
415         }
416
417         return relatedRecords;
418     }
419
420     // Stub method, as this invocation mode is not currently supported
421     private List<String> getMemberCsidsFromGroup(String groupCsid) throws URISyntaxException {
422         List<String> memberCsids = Collections.emptyList();
423         return memberCsids;
424     }
425
426     private List<String> getNoContextCsids() throws URISyntaxException {
427         List<String> noContextCsids = new ArrayList<String>();
428         ResourceMap resourcemap = getResourceMap();
429         ResourceBase collectionObjectResource = resourcemap.get(CollectionObjectClient.SERVICE_NAME);
430         UriInfo uriInfo = createUriInfo();
431         uriInfo.getQueryParameters().add(WorkflowClient.WORKFLOW_QUERY_NONDELETED, "false");
432         AbstractCommonList collectionObjects = collectionObjectResource.getList(uriInfo);
433         for (AbstractCommonList.ListItem collectionObjectRecord : collectionObjects.getListItem()) {
434             noContextCsids.add(AbstractCommonListUtils.ListItemGetCSID(collectionObjectRecord));
435         }
436         if (logger.isInfoEnabled()) {
437             logger.info("Identified " + noContextCsids.size()
438                     + " total active CollectionObjects to process in the 'no context' invocation mode.");
439         }
440         return noContextCsids;
441     }
442 }