]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
b4ea9c4e5c15ea0642d6733bf58ceec2025f6690
[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
13 import javax.ws.rs.core.PathSegment;
14 import javax.ws.rs.core.UriInfo;
15
16 import org.collectionspace.services.batch.AbstractBatchInvocable;
17 import org.collectionspace.services.batch.UriInfoImpl;
18 import org.collectionspace.services.client.AbstractCommonListUtils;
19 import org.collectionspace.services.client.CollectionObjectClient;
20 import org.collectionspace.services.client.IClientQueryParams;
21 import org.collectionspace.services.client.IQueryManager;
22 import org.collectionspace.services.client.MovementClient;
23 import org.collectionspace.services.client.PoxPayloadOut;
24 import org.collectionspace.services.client.workflow.WorkflowClient;
25 import org.collectionspace.services.common.NuxeoBasedResource;
26 import org.collectionspace.services.common.ResourceMap;
27 import org.collectionspace.services.common.api.RefNameUtils;
28 import org.collectionspace.services.common.api.Tools;
29 import org.collectionspace.services.common.invocable.InvocationResults;
30 import org.collectionspace.services.jaxb.AbstractCommonList;
31 import org.dom4j.DocumentException;
32 //import org.jboss.resteasy.specimpl.UriInfoImpl;
33 import org.jdom.Document;
34 import org.jdom.Element;
35 import org.jdom.Namespace;
36 import org.jdom.input.SAXBuilder;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 public class UpdateObjectLocationBatchJob extends AbstractBatchInvocable {
41
42     // FIXME: Where appropriate, get from existing constants rather than local declarations
43     private final static String COMPUTED_CURRENT_LOCATION_ELEMENT_NAME = "computedCurrentLocation";
44     private final static String CSID_ELEMENT_NAME = "csid";
45     private final static String CURRENT_LOCATION_ELEMENT_NAME = "currentLocation";
46     private final static String LIFECYCLE_STATE_ELEMENT_NAME = "currentLifeCycleState";
47     private final static String LOCATION_DATE_ELEMENT_NAME = "locationDate";
48     private final static String OBJECT_NUMBER_ELEMENT_NAME = "objectNumber";
49     private final static String UPDATE_DATE_ELEMENT_NAME = "updatedAt";
50     private final static String WORKFLOW_COMMON_SCHEMA_NAME = "workflow_common";
51     private final static String WORKFLOW_COMMON_NAMESPACE_PREFIX = "ns2";
52     private final static String WORKFLOW_COMMON_NAMESPACE_URI =
53             "http://collectionspace.org/services/workflow";
54     private final static Namespace WORKFLOW_COMMON_NAMESPACE =
55             Namespace.getNamespace(
56             WORKFLOW_COMMON_NAMESPACE_PREFIX,
57             WORKFLOW_COMMON_NAMESPACE_URI);
58     private final static String COLLECTIONOBJECTS_COMMON_SCHEMA_NAME = "collectionobjects_common";
59     private final static String COLLECTIONOBJECTS_COMMON_NAMESPACE_PREFIX = "ns2";
60     private final static String COLLECTIONOBJECTS_COMMON_NAMESPACE_URI =
61             "http://collectionspace.org/services/collectionobject";
62     private final static Namespace COLLECTIONOBJECTS_COMMON_NAMESPACE =
63             Namespace.getNamespace(
64             COLLECTIONOBJECTS_COMMON_NAMESPACE_PREFIX,
65             COLLECTIONOBJECTS_COMMON_NAMESPACE_URI);
66         private static final int DEFAULT_PAGE_SIZE = 1000;
67     private final boolean EXCLUDE_DELETED = true;
68     private final String CLASSNAME = this.getClass().getSimpleName();
69     private final Logger logger = LoggerFactory.getLogger(this.getClass());
70
71     // Initialization tasks
72     public UpdateObjectLocationBatchJob() {
73         setSupportedInvocationModes(Arrays.asList(INVOCATION_MODE_SINGLE, INVOCATION_MODE_LIST,
74                 INVOCATION_MODE_GROUP, INVOCATION_MODE_NO_CONTEXT));
75     }
76
77     /**
78      * The main work logic of the batch job. Will be called after setContext.
79      */
80     @Override
81     public void run() {
82
83         setCompletionStatus(STATUS_MIN_PROGRESS);
84
85         try {
86
87             List<String> csids = new ArrayList<String>();
88
89             // Build a list of CollectionObject records to process via this
90             // batch job, depending on the invocation mode requested.
91             if (requestIsForInvocationModeSingle()) {
92                 String singleCsid = getInvocationContext().getSingleCSID();
93                 if (Tools.isBlank(singleCsid)) {
94                     throw new Exception(CSID_VALUES_NOT_PROVIDED_IN_INVOCATION_CONTEXT);
95                 } else {
96                     csids.add(singleCsid);
97                 }
98             } else if (requestIsForInvocationModeList()) {
99                 List<String> listCsids = getListCsids();
100                 if (listCsids.isEmpty()) {
101                     throw new Exception(CSID_VALUES_NOT_PROVIDED_IN_INVOCATION_CONTEXT);
102                 }
103                 csids.addAll(listCsids);
104             } else if (requestIsForInvocationModeGroup()) {
105                 String groupCsid = getInvocationContext().getGroupCSID();
106                 if (Tools.isBlank(groupCsid)) {
107                     throw new Exception(CSID_VALUES_NOT_PROVIDED_IN_INVOCATION_CONTEXT);
108                 }
109                 List<String> groupMemberCsids = getMemberCsidsFromGroup(CollectionObjectClient.SERVICE_NAME, groupCsid);
110                 if (groupMemberCsids.isEmpty()) {
111                     throw new Exception(CSID_VALUES_NOT_PROVIDED_IN_INVOCATION_CONTEXT);
112                 }
113                 csids.addAll(groupMemberCsids);
114             } else if (requestIsForInvocationModeNoContext()) {
115                 List<String> noContextCsids = getNoContextCsids();
116                 if (noContextCsids.isEmpty()) {
117                     throw new Exception(CSID_VALUES_NOT_PROVIDED_IN_INVOCATION_CONTEXT);
118                 }
119                 csids.addAll(noContextCsids);
120             }
121             if (logger.isInfoEnabled()) {
122                 logger.info("Identified " + csids.size() + " total CollectionObject(s) to be processed via the " + CLASSNAME + " batch job");
123             }
124
125             // Update the value of the computed current location field for each CollectionObject
126             setResults(updateComputedCurrentLocations(csids));
127             setCompletionStatus(STATUS_COMPLETE);
128
129         } catch (Exception e) {
130             String errMsg = "Error encountered in " + CLASSNAME + ": " + e.getLocalizedMessage();
131             setErrorResult(errMsg);
132         }
133
134     }
135
136     private InvocationResults updateComputedCurrentLocations(List<String> csids) {
137         ResourceMap resourcemap = getResourceMap();
138         NuxeoBasedResource collectionObjectResource = (NuxeoBasedResource) resourcemap.get(CollectionObjectClient.SERVICE_NAME);
139         NuxeoBasedResource movementResource = (NuxeoBasedResource) resourcemap.get(MovementClient.SERVICE_NAME);
140         String computedCurrentLocation;
141         long numUpdated = 0;
142         long processed = 0;
143
144         long recordsToProcess = csids.size();
145         long logInterval = recordsToProcess / 10 + 2;
146         try {
147
148             // For each CollectionObject record
149             for (String collectionObjectCsid : csids) {
150                 
151                 // Log progress at INFO level
152                 if (processed % logInterval == 0) {
153                         logger.info(String.format("Recalculated computed location for %d of %d cataloging records.",
154                                         processed, recordsToProcess));
155                 }
156                 processed++;
157
158                 // Skip over soft-deleted CollectionObject records
159                 //
160                 // (Invocations using the 'no context' mode have already
161                 // filtered out soft-deleted records.)
162                 if (!requestIsForInvocationModeNoContext()) {
163                     if (isRecordDeleted(collectionObjectResource, collectionObjectCsid)) {
164                         if (logger.isTraceEnabled()) {
165                             logger.trace("Skipping soft-deleted CollectionObject record with CSID " + collectionObjectCsid);
166                         }
167                         continue;
168                     }
169                 }
170                 // Get the Movement records related to this CollectionObject record
171                 AbstractCommonList relatedMovements =
172                         getRelatedRecords(movementResource, collectionObjectCsid, EXCLUDE_DELETED);
173                 // Skip over CollectionObject records that have no related Movement records
174                 if (relatedMovements.getListItem().isEmpty()) {
175                     continue;
176                 }
177                 // Get the most recent 'suitable' Movement record, one which
178                 // contains both a location date and a current location value
179                 AbstractCommonList.ListItem mostRecentMovement = getMostRecentMovement(relatedMovements);
180                 // Skip over CollectionObject records where no suitable
181                 // most recent Movement record can be identified.
182                 //
183                 // FIXME: Clarify: it ever necessary to 'unset' a computed
184                 // current location value, by setting it to a null or empty value,
185                 // if that value is no longer obtainable from related Movement
186                 // records, if any?
187                 if (mostRecentMovement == null) {
188                     continue;
189                 }
190                 // Update the value of the computed current location field
191                 // (and, via subclasses, this and/or other relevant fields)
192                 // in the CollectionObject record
193                 numUpdated = updateCollectionObjectValues(collectionObjectResource,
194                         collectionObjectCsid, mostRecentMovement, resourcemap, numUpdated);
195             }
196
197         } catch (Exception e) {
198             String errMsg = "Error encountered in " + CLASSNAME + ": " + e.getLocalizedMessage() + " ";
199             errMsg = errMsg + "Successfully updated " + numUpdated + " CollectionObject record(s) prior to error.";
200             logger.error(errMsg);
201             setErrorResult(errMsg);
202             getResults().setNumAffected(numUpdated);
203             return getResults();
204         }
205
206         logger.info("Updated computedCurrentLocation values in " + numUpdated + " CollectionObject record(s).");
207         getResults().setNumAffected(numUpdated);
208         return getResults();
209     }
210     
211     //
212     // Returns the number of distinct/unique CSID values in the list
213     //
214     private int getNumberOfDistinceRecords(AbstractCommonList abstractCommonList) {
215         Set<String> resultSet = new HashSet<String>();
216         
217         for (AbstractCommonList.ListItem listItem : abstractCommonList.getListItem()) {
218                 String csid = AbstractCommonListUtils.ListItemGetElementValue(listItem, CSID_ELEMENT_NAME);
219                 if (!Tools.isBlank(csid)) {
220                     resultSet.add(csid);
221                 }
222         }
223         
224         return resultSet.size();
225     }
226
227     private AbstractCommonList.ListItem getMostRecentMovement(AbstractCommonList relatedMovements) {
228         Set<String> alreadyProcessedMovementCsids = new HashSet<String>();
229         AbstractCommonList.ListItem mostRecentMovement = null;
230         String movementCsid;
231         String currentLocation;
232         String locationDate;
233         String updateDate;
234         String mostRecentLocationDate = "";
235         String comparisonUpdateDate = "";
236         
237         //
238         // If there is only one related movement record, then return it as the most recent
239         // movement record -if it's current location element is not empty.
240         //
241         if (getNumberOfDistinceRecords(relatedMovements) == 1) {
242                 mostRecentMovement = relatedMovements.getListItem().get(0);
243             currentLocation = AbstractCommonListUtils.ListItemGetElementValue(mostRecentMovement, CURRENT_LOCATION_ELEMENT_NAME);
244             if (Tools.isBlank(currentLocation)) {
245                 mostRecentMovement = null;
246             }
247             return mostRecentMovement;
248         }
249         
250         for (AbstractCommonList.ListItem movementListItem : relatedMovements.getListItem()) {
251             movementCsid = AbstractCommonListUtils.ListItemGetElementValue(movementListItem, CSID_ELEMENT_NAME);
252             if (Tools.isBlank(movementCsid)) {
253                 continue;
254             }
255             // Skip over any duplicates in the list, such as records that might
256             // appear as the subject of one relation record and the object of
257             // its reciprocal relation record
258             if (alreadyProcessedMovementCsids.contains(movementCsid)) {
259                 continue;
260             } else {
261                 alreadyProcessedMovementCsids.add(movementCsid);
262             }
263             locationDate = AbstractCommonListUtils.ListItemGetElementValue(movementListItem, LOCATION_DATE_ELEMENT_NAME);
264             if (Tools.isBlank(locationDate)) {
265                 continue;
266             }
267             updateDate = AbstractCommonListUtils.ListItemGetElementValue(movementListItem, UPDATE_DATE_ELEMENT_NAME);
268             if (Tools.isBlank(updateDate)) {
269                 continue;
270             }
271             currentLocation = AbstractCommonListUtils.ListItemGetElementValue(movementListItem, CURRENT_LOCATION_ELEMENT_NAME);
272             if (Tools.isBlank(currentLocation)) {
273                 continue;
274             }
275             // Validate that this Movement record's currentLocation value parses
276             // successfully as an item refName, before identifying that record
277             // as the most recent Movement.
278             //
279             // TODO: Consider making this optional validation, in turn dependent on the
280             // value of a parameter passed in during batch job invocation.
281             if (RefNameUtils.parseAuthorityTermInfo(currentLocation) == null) {
282                 logger.warn(String.format("Could not parse current location refName '%s' in Movement record",
283                     currentLocation));
284                  continue;
285             }
286            
287             if (logger.isTraceEnabled()) {
288                 logger.trace("Location date value = " + locationDate);
289                 logger.trace("Update date value = " + updateDate);
290                 logger.trace("Current location value = " + currentLocation);
291             }
292             
293             // If this record's location date value is more recent than that of other
294             // Movement records processed so far, set the current Movement record
295             // as the most recent Movement.
296             //
297             // The following comparison assumes that all values for this element/field
298             // will be consistent ISO 8601 date/time representations, each of which can
299             // be ordered via string comparison.
300             //
301             // If this is *not* the case, we should instead parse and convert these values
302             // to date/time objects.
303             if (locationDate.compareTo(mostRecentLocationDate) > 0) {
304                 mostRecentLocationDate = locationDate;
305                 mostRecentMovement = movementListItem;
306                 comparisonUpdateDate = updateDate;
307             } else if (locationDate.compareTo(mostRecentLocationDate) == 0) {
308                 // If the two location dates match, then use a tiebreaker
309                 if (updateDate.compareTo(comparisonUpdateDate) > 0) {
310                     // The most recent location date value doesn't need to be
311                     // updated here, as the two records' values are identical
312                     mostRecentMovement = movementListItem;
313                     comparisonUpdateDate = updateDate;
314                 }
315             }
316
317         }
318         
319         return mostRecentMovement;
320     }
321
322     // This method can be overridden and extended to update a custom set of
323     // values in the CollectionObject record by pulling in values from its
324     // most recent related Movement record.
325     //
326     // Note: any such values must first be exposed in Movement list items,
327     // in turn via configuration in Services tenant bindings ("listResultsField").
328     protected long updateCollectionObjectValues(NuxeoBasedResource collectionObjectResource,
329             String collectionObjectCsid,
330             AbstractCommonList.ListItem mostRecentMovement,
331             ResourceMap resourcemap, long numUpdated)
332             throws DocumentException, URISyntaxException {
333         PoxPayloadOut collectionObjectPayload;
334         String computedCurrentLocation;
335         String objectNumber;
336         String previousComputedCurrentLocation;
337
338         collectionObjectPayload = findByCsid(collectionObjectResource, collectionObjectCsid);
339         if (Tools.isBlank(collectionObjectPayload.toXML())) {
340             return numUpdated;
341         } else {
342             if (logger.isTraceEnabled()) {
343                 logger.trace("Payload: " + "\n" + collectionObjectPayload);
344             }
345         }
346         // Perform the update only if the computed current location value will change
347         // as a result of the update
348         computedCurrentLocation =
349                 AbstractCommonListUtils.ListItemGetElementValue(mostRecentMovement, CURRENT_LOCATION_ELEMENT_NAME);
350         previousComputedCurrentLocation = getFieldElementValue(collectionObjectPayload,
351                 COLLECTIONOBJECTS_COMMON_SCHEMA_NAME, COLLECTIONOBJECTS_COMMON_NAMESPACE,
352                 COMPUTED_CURRENT_LOCATION_ELEMENT_NAME);
353         if (!shouldUpdateLocation(previousComputedCurrentLocation, computedCurrentLocation)) {
354             return numUpdated;
355         }
356     
357         // Perform the update only if there is a non-blank object number available.
358         //
359         // In the default CollectionObject validation handler, the object number
360         // is a required field and its (non-blank) value must be present in update
361         // payloads to successfully perform an update.
362         objectNumber = getFieldElementValue(collectionObjectPayload,
363                 COLLECTIONOBJECTS_COMMON_SCHEMA_NAME, COLLECTIONOBJECTS_COMMON_NAMESPACE,
364                 OBJECT_NUMBER_ELEMENT_NAME);
365         if (logger.isTraceEnabled()) {
366             logger.trace("Object number: " + objectNumber);
367         }
368         // FIXME: Consider making the requirement that a non-blank object number
369         // be present dependent on the value of a parameter passed in during
370         // batch job invocation, as some implementations may have turned off that
371         // validation requirement.
372         if (Tools.isBlank(objectNumber)) {
373             return numUpdated;
374         }
375
376         // At this point in the code, the most recent related Movement record
377         // should not have a null current location, as such records are
378         // excluded from consideration altogether in getMostRecentMovement().
379         // This is a redundant fallback check, in case that code somehow fails
380         // or is modified or deleted.
381         if (computedCurrentLocation == null) {
382             return numUpdated;
383         }
384
385         // Update the location.
386         String collectionObjectUpdatePayload =
387                 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
388                 + "<document name=\"collectionobject\">"
389                 + "  <ns2:collectionobjects_common "
390                 + "      xmlns:ns2=\"http://collectionspace.org/services/collectionobject\">"
391                 + "    <objectNumber>" + objectNumber + "</objectNumber>"
392                 + "    <computedCurrentLocation>" + computedCurrentLocation + "</computedCurrentLocation>"
393                 + "  </ns2:collectionobjects_common>"
394                 + "</document>";
395         if (logger.isTraceEnabled()) {
396             logger.trace("Update payload: " + "\n" + collectionObjectUpdatePayload);
397         }
398         
399         UriInfo uriInfo = this.setupQueryParamForUpdateRecords(); // Determines if we'll updated the updateAt and updatedBy core values
400         byte[] response = collectionObjectResource.update(resourcemap, uriInfo, collectionObjectCsid,
401                 collectionObjectUpdatePayload);
402         numUpdated++;
403         
404         if (logger.isTraceEnabled()) {
405             logger.trace("Computed current location value for CollectionObject " + collectionObjectCsid
406                     + " was set to " + computedCurrentLocation);
407
408         }
409         return numUpdated;
410     }
411     
412     protected boolean shouldUpdateLocation(String previousLocation, String currentLocation) {
413         boolean shouldUpdate = true;
414         if (Tools.isBlank(previousLocation) && Tools.isBlank(currentLocation)) {
415             shouldUpdate = false;
416         } else if (Tools.notBlank(previousLocation) && previousLocation.equals(currentLocation)) {
417             shouldUpdate = false;
418         }
419         return shouldUpdate;
420     }
421
422     // #################################################################
423     // Ray Lee's convenience methods from his AbstractBatchJob class for the
424     // UC Berkeley Botanical Garden v2.4 implementation.
425     // #################################################################
426     protected PoxPayloadOut findByCsid(String serviceName, String csid) throws URISyntaxException, DocumentException {
427         NuxeoBasedResource resource = (NuxeoBasedResource) getResourceMap().get(serviceName);
428         return findByCsid(resource, csid);
429     }
430
431     protected PoxPayloadOut findByCsid(NuxeoBasedResource resource, String csid) throws URISyntaxException, DocumentException {
432         PoxPayloadOut result = null;
433         
434         try {
435                         result = resource.getResourceFromCsid(null, createUriInfo(), csid);
436                 } catch (Exception e) {
437                         String msg = String.format("UpdateObjectLocation batch job could find/get resource CSID='%s' of type '%s'",
438                                         csid, resource.getServiceName());
439                         if (logger.isDebugEnabled()) {
440                                 logger.debug(msg, e);
441                         } else {
442                                 logger.error(msg);
443                         }
444                 }
445         
446         return result;
447     }
448
449     protected UriInfo createUriInfo() throws URISyntaxException {
450         return createUriInfo("");
451     }
452
453     private UriInfo createUriInfo(String queryString) throws URISyntaxException {
454         URI absolutePath = new URI("");
455         URI baseUri = new URI("");
456         return new UriInfoImpl(absolutePath, baseUri, "", queryString, Collections.<PathSegment>emptyList());
457     }
458
459     // #################################################################
460     // Other convenience methods
461     // #################################################################
462     protected UriInfo createRelatedRecordsUriInfo(String queryString) throws URISyntaxException {
463         URI uri = new URI(null, null, null, queryString, null);
464         return createUriInfo(uri.getRawQuery());
465     }
466     
467     protected UriInfo setupQueryParamForUpdateRecords() throws URISyntaxException {
468         UriInfo result = null;
469         
470         //
471         // Check first to see if we've got a query param.  It will override any invocation context value
472         //
473         String updateCoreValues = (String) getServiceContext().getQueryParams().getFirst(IClientQueryParams.UPDATE_CORE_VALUES);
474         if (Tools.isBlank(updateCoreValues)) {
475                 //
476                 // Since there is no query param, let's check the invocation context
477                 //
478                 updateCoreValues = getInvocationContext().getUpdateCoreValues();                
479         }
480         
481         //
482         // If we found a value, then use it to create a query parameter
483         //
484         if (Tools.notBlank(updateCoreValues)) {
485                 result = createUriInfo(IClientQueryParams.UPDATE_CORE_VALUES + "=" + updateCoreValues);
486         }
487         
488         return result;
489     }
490
491     protected String getFieldElementValue(PoxPayloadOut payload, String partLabel, Namespace partNamespace, String fieldPath) {
492         String value = null;
493         SAXBuilder builder = new SAXBuilder();
494         try {
495             Document document = builder.build(new StringReader(payload.toXML()));
496             Element root = document.getRootElement();
497             // The part element is always expected to have an explicit namespace.
498             Element part = root.getChild(partLabel, partNamespace);
499             // Try getting the field element both with and without a namespace.
500             // Even though a field element that lacks a namespace prefix
501             // may yet inherit its namespace from a parent, JDOM may require that
502             // the getChild() call be made without a namespace.
503             Element field = part.getChild(fieldPath, partNamespace);
504             if (field == null) {
505                 field = part.getChild(fieldPath);
506             }
507             if (field != null) {
508                 value = field.getText();
509             }
510         } catch (Exception e) {
511             logger.error("Error getting value from field path " + fieldPath
512                     + " in schema part " + partLabel);
513             return null;
514         }
515         return value;
516     }
517
518     private boolean isRecordDeleted(NuxeoBasedResource resource, String collectionObjectCsid)
519             throws URISyntaxException, DocumentException {
520         boolean isDeleted = false;
521         
522         byte[] workflowResponse = resource.getWorkflow(createUriInfo(), collectionObjectCsid);
523         if (workflowResponse != null) {
524             PoxPayloadOut payloadOut = new PoxPayloadOut(workflowResponse);
525             String workflowState =
526                     getFieldElementValue(payloadOut, WORKFLOW_COMMON_SCHEMA_NAME,
527                     WORKFLOW_COMMON_NAMESPACE, LIFECYCLE_STATE_ELEMENT_NAME);
528             if (Tools.notBlank(workflowState) && workflowState.contains(WorkflowClient.WORKFLOWSTATE_DELETED)) {
529                 isDeleted = true;
530             }
531         }
532         
533         return isDeleted;
534     }
535
536     private UriInfo addFilterToExcludeSoftDeletedRecords(UriInfo uriInfo) throws URISyntaxException {
537         if (uriInfo == null) {
538             uriInfo = createUriInfo();
539         }
540         uriInfo.getQueryParameters().add(WorkflowClient.WORKFLOW_QUERY_NONDELETED, Boolean.FALSE.toString());
541         return uriInfo;
542     }
543     
544     private UriInfo addFilterForPageSize(UriInfo uriInfo, long startPage, long pageSize) throws URISyntaxException {
545         if (uriInfo == null) {
546             uriInfo = createUriInfo();
547         }
548         uriInfo.getQueryParameters().addFirst(IClientQueryParams.START_PAGE_PARAM, Long.toString(startPage));
549         uriInfo.getQueryParameters().addFirst(IClientQueryParams.PAGE_SIZE_PARAM, Long.toString(pageSize));
550
551         return uriInfo;
552     }
553
554     private AbstractCommonList getRecordsRelatedToCsid(NuxeoBasedResource resource, String csid,
555             String relationshipDirection, boolean excludeDeletedRecords) throws URISyntaxException {
556         UriInfo uriInfo = createUriInfo();
557         uriInfo.getQueryParameters().add(relationshipDirection, csid);
558         if (excludeDeletedRecords) {
559             uriInfo = addFilterToExcludeSoftDeletedRecords(uriInfo);
560         }
561         // The 'resource' type used here identifies the record type of the
562         // related records to be retrieved
563         AbstractCommonList relatedRecords = resource.getList(uriInfo);
564         if (logger.isTraceEnabled()) {
565             logger.trace("Identified " + relatedRecords.getTotalItems()
566                     + " record(s) related to the object record via direction " + relationshipDirection + " with CSID " + csid);
567         }
568         return relatedRecords;
569     }
570
571     /**
572      * Returns the records of a specified type that are related to a specified
573      * record, where that record is the object of the relation.
574      *
575      * @param resource a resource. The type of this resource determines the type
576      * of related records that are returned.
577      * @param csid a CSID identifying a record
578      * @param excludeDeletedRecords true if 'soft-deleted' records should be
579      * excluded from results; false if those records should be included
580      * @return a list of records of a specified type, related to a specified
581      * record
582      * @throws URISyntaxException
583      */
584     private AbstractCommonList getRecordsRelatedToObjectCsid(NuxeoBasedResource resource, String csid, boolean excludeDeletedRecords) throws URISyntaxException {
585         return getRecordsRelatedToCsid(resource, csid, IQueryManager.SEARCH_RELATED_TO_CSID_AS_OBJECT, excludeDeletedRecords);
586     }
587
588     /**
589      * Returns the records of a specified type that are related to a specified
590      * record, where that record is the subject of the relation.
591      *
592      * @param resource a resource. The type of this resource determines the type
593      * of related records that are returned.
594      * @param csid a CSID identifying a record
595      * @param excludeDeletedRecords true if 'soft-deleted' records should be
596      * excluded from results; false if those records should be included
597      * @return a list of records of a specified type, related to a specified
598      * record
599      * @throws URISyntaxException
600      */
601     private AbstractCommonList getRecordsRelatedToSubjectCsid(NuxeoBasedResource resource, String csid, boolean excludeDeletedRecords) throws URISyntaxException {
602         return getRecordsRelatedToCsid(resource, csid, IQueryManager.SEARCH_RELATED_TO_CSID_AS_SUBJECT, excludeDeletedRecords);
603     }
604
605     private AbstractCommonList getRelatedRecords(NuxeoBasedResource resource, String csid, boolean excludeDeletedRecords)
606             throws URISyntaxException, DocumentException {
607         AbstractCommonList relatedRecords = new AbstractCommonList();
608         AbstractCommonList recordsRelatedToObjectCSID = getRecordsRelatedToObjectCsid(resource, csid, excludeDeletedRecords);
609         AbstractCommonList recordsRelatedToSubjectCSID = getRecordsRelatedToSubjectCsid(resource, csid, excludeDeletedRecords);
610         // If either list contains any related records, merge in its items
611         if (recordsRelatedToObjectCSID.getListItem().size() > 0) {
612             relatedRecords.getListItem().addAll(recordsRelatedToObjectCSID.getListItem());
613         }
614         if (recordsRelatedToSubjectCSID.getListItem().size() > 0) {
615             relatedRecords.getListItem().addAll(recordsRelatedToSubjectCSID.getListItem());
616         }
617         if (logger.isTraceEnabled()) {
618             logger.trace("Identified a total of " + relatedRecords.getListItem().size()
619                     + " record(s) related to the record with CSID " + csid);
620         }
621         return relatedRecords;
622     }
623
624     private List<String> getCsidsList(AbstractCommonList list) {
625         List<String> csids = new ArrayList<String>();
626         for (AbstractCommonList.ListItem listitem : list.getListItem()) {
627             csids.add(AbstractCommonListUtils.ListItemGetCSID(listitem));
628         }
629         return csids;
630     }
631     
632     private void appendItemsToCsidsList(List<String> existingList, AbstractCommonList abstractCommonList) {
633         for (AbstractCommonList.ListItem listitem : abstractCommonList.getListItem()) {
634                 existingList.add(AbstractCommonListUtils.ListItemGetCSID(listitem));
635         }
636     }
637     
638
639     private List<String> getMemberCsidsFromGroup(String serviceName, String groupCsid) throws URISyntaxException, DocumentException {
640         ResourceMap resourcemap = getResourceMap();
641         NuxeoBasedResource resource = (NuxeoBasedResource) resourcemap.get(serviceName);
642         return getMemberCsidsFromGroup(resource, groupCsid);
643     }
644
645     private List<String> getMemberCsidsFromGroup(NuxeoBasedResource resource, String groupCsid) throws URISyntaxException, DocumentException {
646         // The 'resource' type used here identifies the record type of the
647         // related records to be retrieved
648         AbstractCommonList relatedRecords =
649                 getRelatedRecords(resource, groupCsid, EXCLUDE_DELETED);
650         List<String> memberCsids = getCsidsList(relatedRecords);
651         return memberCsids;
652     }
653
654     private List<String> getNoContextCsids() throws URISyntaxException {
655         ResourceMap resourcemap = getResourceMap();
656         NuxeoBasedResource collectionObjectResource = (NuxeoBasedResource) resourcemap.get(CollectionObjectClient.SERVICE_NAME);
657         UriInfo uriInfo = createUriInfo();
658         uriInfo = addFilterToExcludeSoftDeletedRecords(uriInfo);
659
660         boolean morePages = true;
661         long currentPage = 0;
662         long totalItems = 0;
663         long pageSize = DEFAULT_PAGE_SIZE;
664         List<String> noContextCsids = new ArrayList<String>();
665         
666         while (morePages == true) {
667                 uriInfo = addFilterForPageSize(uriInfo, currentPage, pageSize);
668                 AbstractCommonList collectionObjects = collectionObjectResource.getList(uriInfo);
669                 appendItemsToCsidsList(noContextCsids, collectionObjects);
670                 
671                 if (collectionObjects.getItemsInPage() == pageSize) { // We know we're at the last page when the number of items returned in the last request is less than the page size.
672                         currentPage++;
673                 } else {
674                         morePages = false;                      
675                 }
676         }
677         
678         return noContextCsids;
679     }
680 }