]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
d3c8b2c3eb138af3ff4760fddf6d4374765af7b5
[tmp/jakarta-migration.git] /
1 /**
2  *  This document is a part of the source code and related artifacts
3  *  for CollectionSpace, an open source collections management system
4  *  for museums and related institutions:
5
6  *  http://www.collectionspace.org
7  *  http://wiki.collectionspace.org
8
9  *  Copyright 2009 University of California at Berkeley
10
11  *  Licensed under the Educational Community License (ECL), Version 2.0.
12  *  You may not use this file except in compliance with this License.
13
14  *  You may obtain a copy of the ECL 2.0 License at
15
16  *  https://source.collectionspace.org/collection-space/LICENSE.txt
17
18  *  Unless required by applicable law or agreed to in writing, software
19  *  distributed under the License is distributed on an "AS IS" BASIS,
20  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21  *  See the License for the specific language governing permissions and
22  *  limitations under the License.
23  */
24 package org.collectionspace.services.common.vocabulary.nuxeo;
25
26 import org.collectionspace.services.client.AuthorityClient;
27 import org.collectionspace.services.client.IQueryManager;
28 import org.collectionspace.services.client.PayloadInputPart;
29 import org.collectionspace.services.client.PoxPayloadIn;
30 import org.collectionspace.services.client.PoxPayloadOut;
31 import org.collectionspace.services.client.RelationClient;
32 import org.collectionspace.services.client.workflow.WorkflowClient;
33 import org.collectionspace.services.common.ServiceMain;
34 import org.collectionspace.services.common.UriTemplateRegistry;
35 import org.collectionspace.services.common.api.RefName;
36 import org.collectionspace.services.common.api.Tools;
37 import org.collectionspace.services.common.authorityref.AuthorityRefDocList;
38 import org.collectionspace.services.common.context.MultipartServiceContext;
39 import org.collectionspace.services.common.context.ServiceContext;
40 import org.collectionspace.services.common.document.DocumentException;
41 import org.collectionspace.services.common.document.DocumentFilter;
42 import org.collectionspace.services.common.document.DocumentNotFoundException;
43 import org.collectionspace.services.common.document.DocumentReferenceException;
44 import org.collectionspace.services.common.document.DocumentWrapper;
45 import org.collectionspace.services.common.repository.RepositoryClient;
46 import org.collectionspace.services.common.vocabulary.AuthorityJAXBSchema;
47 import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema;
48 import org.collectionspace.services.common.vocabulary.AuthorityResource;
49 import org.collectionspace.services.common.vocabulary.AuthorityServiceUtils;
50 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils;
51 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.AuthorityItemSpecifier;
52 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.SpecifierForm;
53 import org.collectionspace.services.config.service.ListResultField;
54 import org.collectionspace.services.config.service.ObjectPartType;
55 import org.collectionspace.services.lifecycle.TransitionDef;
56 import org.collectionspace.services.nuxeo.client.java.NuxeoDocumentModelHandler;
57 import org.collectionspace.services.nuxeo.client.java.CoreSessionInterface;
58 import org.collectionspace.services.nuxeo.client.java.NuxeoRepositoryClientImpl;
59 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
60 import org.collectionspace.services.relation.RelationsCommonList;
61 import org.collectionspace.services.vocabulary.VocabularyItemJAXBSchema;
62
63 import org.nuxeo.ecm.core.api.ClientException;
64 import org.nuxeo.ecm.core.api.DocumentModel;
65 import org.nuxeo.ecm.core.api.model.PropertyException;
66
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
69
70 import javax.ws.rs.core.MultivaluedMap;
71
72 import java.util.ArrayList;
73 import java.util.Collections;
74 import java.util.HashMap;
75 import java.util.List;
76 import java.util.Map;
77 import java.util.regex.Matcher;
78 import java.util.regex.Pattern;
79 import java.util.regex.PatternSyntaxException;
80
81 //import org.collectionspace.services.common.authority.AuthorityItemRelations;
82 /**
83  * AuthorityItemDocumentModelHandler
84  *
85  * $LastChangedRevision: $
86  * $LastChangedDate: $
87  */
88 public abstract class AuthorityItemDocumentModelHandler<AICommon>
89         extends NuxeoDocumentModelHandler<AICommon> {
90
91     private final Logger logger = LoggerFactory.getLogger(AuthorityItemDocumentModelHandler.class);
92     
93     protected String authorityCommonSchemaName;
94     protected String authorityItemCommonSchemaName;
95     private String authorityItemTermGroupXPathBase;
96     
97     private boolean shouldUpdateSASFields = true;
98     private boolean syncHierarchicalRelationships = false;
99     private boolean isProposed = false; // used by local authority to propose a new shared item. Allows local deployments to use new terms until they become official
100     private boolean isSAS = false; // used to indicate if the authority item originated as a SAS item
101     private boolean shouldUpdateRevNumber = true; // by default we should update the revision number -not true on synchronization with SAS
102     /**
103      * inVocabulary is the parent Authority for this context
104      */
105     protected String inAuthority = null;
106     protected boolean wildcardedAuthorityRequest = false;
107     protected String authorityRefNameBase = null;
108     // Used to determine when the displayName changes as part of the update.
109     protected String oldDisplayNameOnUpdate = null;
110     private final static String LIST_SUFFIX = "List";
111     private final static String ZERO_OR_MORE_ANY_CHAR_REGEX = ".*";
112
113     public AuthorityItemDocumentModelHandler(String authorityCommonSchemaName, String authorityItemCommonSchemaName) {
114         this.authorityItemCommonSchemaName = authorityItemCommonSchemaName;
115     }
116     
117     abstract public String getParentCommonSchemaName();
118     
119     //
120     // Getter and Setter for 'shouldUpdateSASFields'
121     //
122     public boolean getShouldUpdateSASFields() {
123         return shouldUpdateSASFields;
124     }
125     
126     public void setshouldUpdateSASFields(boolean flag) {
127         shouldUpdateSASFields = flag;
128     }
129     
130     //
131     // Getter and Setter for 'proposed'
132     //
133     public boolean getIsProposed() {
134         return this.isProposed;
135     }
136     
137     public void setIsProposed(boolean flag) {
138         this.isProposed = flag;
139     }
140     
141     //
142     // Getter and Setter for 'isSAS'
143     //
144     public boolean getIsSASItem() {
145         return this.isSAS;
146     }
147
148     public void setIsSASItem(boolean flag) {
149         this.isSAS = flag;
150     }
151     
152     //
153     // Getter and Setter for 'shouldUpdateRevNumber'
154     //
155     public boolean getShouldUpdateRevNumber() {
156         return this.shouldUpdateRevNumber;
157     }
158     
159     public void setShouldUpdateRevNumber(boolean flag) {
160         this.shouldUpdateRevNumber = flag;
161     }
162
163     //
164     // Getter and Setter for deciding if we need to synch hierarchical relationships
165     //
166     public boolean getShouldSyncHierarchicalRelationships() {
167         return this.syncHierarchicalRelationships;
168     }
169     
170     public void setShouldSyncHierarchicalRelationships(boolean flag) {
171         this.syncHierarchicalRelationships = flag;
172     }
173
174     @Override
175     public void prepareSync() throws Exception {
176         this.setShouldUpdateRevNumber(AuthorityServiceUtils.DONT_UPDATE_REV);  // Never update rev nums on sync operations
177     }
178
179     @Override
180     protected String getRefnameDisplayName(DocumentWrapper<DocumentModel> docWrapper) {
181         String result = null;
182         
183         DocumentModel docModel = docWrapper.getWrappedObject();
184         ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = this.getServiceContext();
185         RefName.AuthorityItem refname = (RefName.AuthorityItem)getRefName(ctx, docModel);
186         result = refname.getDisplayName();
187         
188         return result;
189     }
190     
191     /*
192      * After calling this method successfully, the document model will contain an updated refname and short ID
193      * (non-Javadoc)
194      * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#getRefName(org.collectionspace.services.common.context.ServiceContext, org.nuxeo.ecm.core.api.DocumentModel)
195      */
196     @Override
197     public RefName.RefNameInterface getRefName(ServiceContext ctx,
198             DocumentModel docModel) {
199         RefName.RefNameInterface refname = null;
200         
201         try {
202             String displayName = getPrimaryDisplayName(docModel, authorityItemCommonSchemaName,
203                     getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
204             if (Tools.isEmpty(displayName)) {
205                 throw new Exception("The displayName for this authority term was empty or not set.");
206             }
207         
208             String shortIdentifier = (String) docModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
209             if (Tools.isEmpty(shortIdentifier)) {
210                 // We didn't find a short ID in the payload request, so we need to synthesize one.
211                 shortIdentifier = handleDisplayNameAsShortIdentifier(docModel); // updates the document model with the new short ID as a side-effect
212             }
213             
214             String authorityRefBaseName = getAuthorityRefNameBase();
215             if (Tools.isEmpty(authorityRefBaseName)) {
216                 throw new Exception("Could not create the refName for this authority term, because the refName for its authority parent was empty.");
217             }
218             
219             // Create the items refname using the parent's as a base
220             RefName.Authority parentsRefName = RefName.Authority.parse(authorityRefBaseName);
221             refname = RefName.buildAuthorityItem(parentsRefName, shortIdentifier, displayName);
222             // Now update the document model with the refname value
223             String refNameStr = refname.toString();
224             docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REF_NAME, refNameStr); // REM - This field is deprecated now that the refName is part of the collection_space core schema
225
226         } catch (Exception e) {
227             logger.error(e.getMessage(), e);
228         }
229
230         return refname;
231     }
232     
233     public void setInAuthority(String inAuthority) {
234         this.inAuthority = inAuthority;
235     }
236     
237    public String getInAuthorityCsid() {
238         return this.inAuthority;
239     }
240
241     /** Subclasses may override this to customize the URI segment. */
242     public String getAuthorityServicePath() {
243         return getServiceContext().getServiceName().toLowerCase();    // Laramie20110510 CSPACE-3932
244     }
245
246     @Override
247     public String getUri(DocumentModel docModel) {
248         // Laramie20110510 CSPACE-3932
249         String authorityServicePath = getAuthorityServicePath();
250         if(inAuthority==null) {    // Only true with the first document model received, on queries to wildcarded authorities
251             wildcardedAuthorityRequest = true;
252         }
253         // If this search crosses multiple authorities, get the inAuthority value
254         // from each record, rather than using the cached value from the first record
255         if(wildcardedAuthorityRequest) {
256             try {
257                 inAuthority = (String) docModel.getProperty(authorityItemCommonSchemaName,
258                     AuthorityItemJAXBSchema.IN_AUTHORITY);
259             } catch (ClientException pe) {
260                 throw new RuntimeException("Could not get parent specifier for item!");
261             }
262         }
263         return "/" + authorityServicePath + '/' + inAuthority + '/' + AuthorityClient.ITEMS + '/' + getCsid(docModel);
264     }
265
266     protected String getAuthorityRefNameBase() {
267         return this.authorityRefNameBase;
268     }
269
270     public void setAuthorityRefNameBase(String value) {
271         this.authorityRefNameBase = value;
272     }
273
274     /*
275      * Note: the Vocabulary service's VocabularyItemDocumentModelHandler class overrides this method.
276      */
277     protected ListResultField getListResultsDisplayNameField() {
278         ListResultField result = new ListResultField();
279         // Per CSPACE-5132, the name of this element remains 'displayName'
280         // for backwards compatibility, although its value is obtained
281         // from the termDisplayName field.
282         //
283         // Update: this name is now being changed to 'termDisplayName', both
284         // because this is the actual field name and because the app layer
285         // work to convert over to this field is underway. Per Patrick, the
286         // app layer treats lists, in at least some context(s), as sparse record
287         // payloads, and thus fields in list results must all be present in
288         // (i.e. represent a strict subset of the fields in) record schemas.
289         // - ADR 2012-05-11
290         // 
291         //
292         // In CSPACE-5134, these list results will change substantially
293         // to return display names for both the preferred term and for
294         // each non-preferred term (if any).
295         result.setElement(AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
296         result.setXpath(NuxeoUtils.getPrimaryXPathPropertyName(
297                 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_DISPLAY_NAME));
298         
299         return result;
300     }
301     
302     /*
303      * Note: the Vocabulary service's VocabularyItemDocumentModelHandler class overrides this method.
304      */    
305     protected ListResultField getListResultsTermStatusField() {
306         ListResultField result = new ListResultField();
307         
308         result.setElement(AuthorityItemJAXBSchema.TERM_STATUS);
309         result.setXpath(NuxeoUtils.getPrimaryXPathPropertyName(
310                 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_STATUS));
311
312         return result;
313     }    
314     
315     private boolean isTermDisplayName(String elName) {
316         return AuthorityItemJAXBSchema.TERM_DISPLAY_NAME.equals(elName) || VocabularyItemJAXBSchema.DISPLAY_NAME.equals(elName);
317     }
318     
319     /*
320      * (non-Javadoc)
321      * @see org.collectionspace.services.nuxeo.client.java.DocHandlerBase#getListItemsArray()
322      * 
323      * Note: We're updating the "global" service and tenant bindings instance here -the list instance here is
324      * a reference to the tenant bindings instance in the singleton ServiceMain.
325      */
326     @Override
327     public List<ListResultField> getListItemsArray() throws DocumentException {
328         List<ListResultField> list = super.getListItemsArray();
329         
330         // One-time initialization for each authority item service.
331         if (isListItemArrayExtended() == false) {
332             synchronized(AuthorityItemDocumentModelHandler.class) {
333                 if (isListItemArrayExtended() == false) {                    
334                     int nFields = list.size();
335                     // Ensure that each item in a list of Authority items includes
336                     // a set of common fields, so we do not depend upon configuration
337                     // for general logic.
338                      List<Integer> termDisplayNamePositionsInList = new ArrayList<>();
339                            boolean hasShortId = false;
340                     boolean hasTermStatus = false;
341                     for (int i = 0; i < nFields; i++) {
342                         ListResultField field = list.get(i);
343                         String elName = field.getElement();
344                         if (isTermDisplayName(elName) == true) {
345                             termDisplayNamePositionsInList.add(i);
346                         } else if (AuthorityItemJAXBSchema.SHORT_IDENTIFIER.equals(elName)) {
347                             hasShortId = true;
348                         } else if (AuthorityItemJAXBSchema.TERM_STATUS.equals(elName)) {
349                             hasTermStatus = true;
350                         }
351                     }
352                     
353                     ListResultField field;
354                         
355                         // Certain fields in authority item list results
356                         // are handled specially here
357                         
358                         // Term display name
359                         //
360                         // Ignore (throw out) any configuration entries that
361                         // specify how the termDisplayName field should be
362                         // emitted in authority item lists. This field will
363                         // be handled in a standardized manner (see block below).
364                         if (termDisplayNamePositionsInList.isEmpty() == false) {
365                             // Remove matching items starting at the end of the list
366                             // and moving towards the start, so that reshuffling of
367                             // list order doesn't alter the positions of earlier items
368                             Collections.sort(termDisplayNamePositionsInList, Collections.reverseOrder());
369                             for (int i : termDisplayNamePositionsInList) {
370                                 list.remove(i);
371                             }
372                         }
373                         // termDisplayName values in authority item lists
374                         // will be handled via code that emits display names
375                         // for both the preferred term and all non-preferred
376                         // terms (if any). The following is a placeholder
377                         // entry that will trigger this code. See the
378                         // getListResultValue() method in this class.
379                     field = getListResultsDisplayNameField();
380                     list.add(field);
381                         
382                         // Short identifier
383                     if (!hasShortId) {
384                         field = new ListResultField();
385                         field.setElement(AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
386                         field.setXpath(AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
387                         list.add(field);
388                     }
389                         
390                         // Term status
391                     if (!hasTermStatus) {
392                         field = getListResultsTermStatusField();
393                         list.add(field);
394                     }
395                         
396                 }
397      
398                 setListItemArrayExtended(true);
399             } // end of synchronized block
400         }
401
402         return list;
403     }
404     
405     /**
406      * We consider workflow state changes as a change that should bump the revision number.
407      * Warning: This method might change the transitionDef's transtionName value
408      */
409     @Override
410     public void handleWorkflowTransition(ServiceContext ctx, DocumentWrapper<DocumentModel> wrapDoc, TransitionDef transitionDef) throws Exception {
411         // Decide whether or not to update the revision number
412         if (this.getShouldUpdateRevNumber() == true) { // We don't update the rev number of synchronization requests
413             updateRevNumbers(wrapDoc);
414         }
415         //
416         // We can't delete an authority item that has referencing records.
417         //
418         DocumentModel docModel = wrapDoc.getWrappedObject();
419         if (transitionDef.getName().equalsIgnoreCase(WorkflowClient.WORKFLOWTRANSITION_DELETE)) {
420             AuthorityRefDocList refsToAllObjects = getReferencingObjects(ctx, docModel, RefObjsSearchType.ALL);
421             AuthorityRefDocList refsToSoftDeletedObjects = getReferencingObjects(ctx, docModel, RefObjsSearchType.DELETED_ONLY);
422             if (refsToAllObjects.getTotalItems() > 0) {
423                 if (refsToAllObjects.getTotalItems() > refsToSoftDeletedObjects.getTotalItems()) {
424                     //
425                     // If the number of refs to active objects is greater than the number of refs to
426                     // soft deleted objects then we can't delete the item.
427                     //
428                     logger.error(String.format("Cannot delete authority item CSID='%s' because it still has records in the system that are referencing it.",
429                             docModel.getName()));
430                     if (logger.isWarnEnabled() == true) {
431                         logReferencingObjects(docModel, refsToAllObjects);
432                     }
433
434                     throw new DocumentReferenceException(String.format("Cannot delete authority item '%s' because it still has records in the system that are referencing it.  See the service layer log file for details.",
435                             docModel.getName()));
436                 }
437             }
438         }
439     }
440     
441     /**
442      * 
443      * @param wrapDoc
444      * @return
445      * @throws Exception
446      */
447     protected boolean handleRelationsSync(DocumentWrapper<Object> wrapDoc) throws Exception {
448         boolean result = false;
449         ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
450
451         //
452         // Get information about the local authority item so we can compare with corresponding item on the shared authority server
453         //
454         AuthorityItemSpecifier authorityItemSpecifier = (AuthorityItemSpecifier) wrapDoc.getWrappedObject();
455         DocumentModel itemDocModel = NuxeoUtils.getDocFromSpecifier(ctx, getRepositorySession(), getAuthorityItemCommonSchemaName(), 
456                 authorityItemSpecifier);
457         if (itemDocModel == null) {
458             throw new DocumentNotFoundException(String.format("Could not find authority item resource with CSID='%s'",
459                     authorityItemSpecifier.getItemSpecifier().value));
460         }
461         Long localItemRev = (Long) NuxeoUtils.getProperyValue(itemDocModel, AuthorityItemJAXBSchema.REV);
462         Boolean localIsProposed = (Boolean) NuxeoUtils.getProperyValue(itemDocModel, AuthorityItemJAXBSchema.PROPOSED);
463         String localItemCsid = itemDocModel.getName();
464         String localItemWorkflowState = itemDocModel.getCurrentLifeCycleState();
465         String itemShortId = (String) NuxeoUtils.getProperyValue(itemDocModel, AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
466         
467         //
468         // Now get the item's Authority (the parent) information
469         //
470         DocumentModel authorityDocModel = NuxeoUtils.getDocFromSpecifier(ctx, getRepositorySession(), authorityCommonSchemaName,
471                 authorityItemSpecifier.getParentSpecifier());
472         String authorityShortId = (String)NuxeoUtils.getProperyValue(authorityDocModel, AuthorityJAXBSchema.SHORT_IDENTIFIER);
473         String localParentCsid = authorityDocModel.getName();
474         String remoteClientConfigName = (String)NuxeoUtils.getProperyValue(authorityDocModel, AuthorityJAXBSchema.REMOTECLIENT_CONFIG_NAME);
475         //
476         // Using the short IDs of the local authority and item, create URN specifiers and retrieve the SAS authority item
477         //
478         AuthorityItemSpecifier sasAuthorityItemSpecifier = new AuthorityItemSpecifier(SpecifierForm.URN_NAME, authorityShortId, itemShortId);
479         // Get the shared authority server's copy
480         PoxPayloadIn sasPayloadIn = AuthorityServiceUtils.requestPayloadInFromRemoteServer(sasAuthorityItemSpecifier, 
481                 remoteClientConfigName, getAuthorityServicePath(), getEntityResponseType(), AuthorityClient.INCLUDE_RELATIONS);
482         
483         //
484         // Get the RelationsCommonList and remove the CSIDs since they are for remote items only. We'll use
485         // the refnames in the payload instead to find the local CSIDs
486         //
487         PayloadInputPart relationsCommonListPart = sasPayloadIn.getPart(RelationClient.SERVICE_COMMON_LIST_NAME);
488         relationsCommonListPart.clearElementBody(); // clear the existing DOM element that was created from the incoming XML payload
489         RelationsCommonList rcl = (RelationsCommonList) relationsCommonListPart.getBody();  // Get the JAX-B object and clear the CSID values
490         for (RelationsCommonList.RelationListItem listItem : rcl.getRelationListItem()) {
491             // clear the remote relation item's CSID
492             listItem.setCsid(null);
493             // clear the remote subject's CSID
494             listItem.setSubjectCsid(null);
495             listItem.getSubject().setCsid(null);
496             listItem.getSubject().setUri(null);
497             // clear the remote object's CSID
498             listItem.setObjectCsid(null);
499             listItem.getObject().setCsid(null);
500             listItem.getObject().setUri(null);
501         }
502         
503         //
504         // Remove all the payload parts except the relations part since we only want to sync the relationships
505         //
506         ArrayList<PayloadInputPart> newPartList = new ArrayList<PayloadInputPart>();
507         newPartList.add(relationsCommonListPart); // add our CSID filtered RelationsCommonList part
508         sasPayloadIn.setParts(newPartList);
509         sasPayloadIn = new PoxPayloadIn(sasPayloadIn.toXML()); // Builds a new payload using the current set of parts -i.e., just the relations part
510         
511         sasPayloadIn = AuthorityServiceUtils.filterRefnameDomains(ctx, sasPayloadIn); // We need to filter the domain name part of any and all refnames in the payload
512         AuthorityResource authorityResource = (AuthorityResource) ctx.getResource(getAuthorityServicePath());
513         PoxPayloadOut payloadOut = authorityResource.updateAuthorityItem(ctx, 
514                 ctx.getResourceMap(),                     
515                 ctx.getUriInfo(),
516                 localParentCsid,                         // parent's CSID
517                 localItemCsid,                             // item's CSID
518                 sasPayloadIn,                            // the payload from the remote SAS
519                 AuthorityServiceUtils.DONT_UPDATE_REV,    // don't update the parent's revision number
520                 AuthorityServiceUtils.NOT_PROPOSED,        // The items is not proposed, make it a real SAS item now
521                 AuthorityServiceUtils.SAS_ITEM);        // Since we're sync'ing, this must be a SAS item
522         if (payloadOut != null) {    
523             ctx.setOutput(payloadOut);
524             result = true;
525         }        
526         
527         return result;
528     }
529         
530     @Override
531     public boolean handleSync(DocumentWrapper<Object> wrapDoc) throws Exception {
532         boolean result = false;
533
534         if (this.getShouldSyncHierarchicalRelationships() == true) {
535             result = handleRelationsSync(wrapDoc);
536         } else {
537             result = handlePayloadSync(wrapDoc);
538         }
539         
540         return result;
541     }
542     
543     /**
544      * 
545      * @param wrapDoc
546      * @return
547      * @throws Exception
548      */
549     protected boolean handlePayloadSync(DocumentWrapper<Object> wrapDoc) throws Exception {
550         boolean result = false;
551         ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
552         
553         //
554         // Get information about the local authority item so we can compare with corresponding item on the shared authority server
555         //
556         AuthorityItemSpecifier authorityItemSpecifier = (AuthorityItemSpecifier) wrapDoc.getWrappedObject();
557         DocumentModel itemDocModel = NuxeoUtils.getDocFromSpecifier(ctx, getRepositorySession(), getAuthorityItemCommonSchemaName(), 
558                 authorityItemSpecifier);
559         if (itemDocModel == null) {
560             throw new DocumentNotFoundException(String.format("Could not find authority item resource with CSID='%s'",
561                     authorityItemSpecifier.getItemSpecifier().value));
562         }
563         Long localItemRev = (Long) NuxeoUtils.getProperyValue(itemDocModel, AuthorityItemJAXBSchema.REV);
564         Boolean localIsProposed = (Boolean) NuxeoUtils.getProperyValue(itemDocModel, AuthorityItemJAXBSchema.PROPOSED);
565         String localItemCsid = itemDocModel.getName();
566         String localItemWorkflowState = itemDocModel.getCurrentLifeCycleState();
567         String itemShortId = (String) NuxeoUtils.getProperyValue(itemDocModel, AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
568         
569         //
570         // Now get the item's Authority (the parent) information
571         //
572         DocumentModel authorityDocModel = NuxeoUtils.getDocFromSpecifier(ctx, getRepositorySession(), authorityCommonSchemaName,
573                 authorityItemSpecifier.getParentSpecifier());
574         String authorityShortId = (String) NuxeoUtils.getProperyValue(authorityDocModel, AuthorityJAXBSchema.SHORT_IDENTIFIER);
575         String localParentCsid = authorityDocModel.getName();
576         String remoteClientConfigName = (String)NuxeoUtils.getProperyValue(authorityDocModel, AuthorityJAXBSchema.REMOTECLIENT_CONFIG_NAME);
577
578         //
579         // Using the short IDs of the local authority and item, create URN specifiers and retrieve the SAS authority item
580         //
581         AuthorityItemSpecifier sasAuthorityItemSpecifier = new AuthorityItemSpecifier(SpecifierForm.URN_NAME, authorityShortId, itemShortId);
582         // Get the shared authority server's copy
583         PoxPayloadIn sasPayloadIn = AuthorityServiceUtils.requestPayloadInFromRemoteServer(sasAuthorityItemSpecifier, 
584                 remoteClientConfigName, getAuthorityServicePath(), getEntityResponseType(), AuthorityClient.DONT_INCLUDE_RELATIONS);
585         Long sasRev = getRevision(sasPayloadIn);
586         String sasWorkflowState = getWorkflowState(sasPayloadIn);
587         //
588         // If the shared authority item is newer, update our local copy
589         //
590         if (sasRev > localItemRev || localIsProposed || ctx.shouldForceSync()) {
591             sasPayloadIn = AuthorityServiceUtils.filterRefnameDomains(ctx, sasPayloadIn); // We need to filter the domain name part of any and all refnames in the payload
592             AuthorityResource authorityResource = (AuthorityResource) ctx.getResource(getAuthorityServicePath());
593             PoxPayloadOut payloadOut = authorityResource.updateAuthorityItem(ctx, 
594                     ctx.getResourceMap(),                     
595                     ctx.getUriInfo(),
596                     localParentCsid,                         // parent's CSID
597                     localItemCsid,                             // item's CSID
598                     sasPayloadIn,                            // the payload from the remote SAS
599                     AuthorityServiceUtils.DONT_UPDATE_REV,    // don't update the parent's revision number
600                     AuthorityServiceUtils.NOT_PROPOSED,        // The items is not proposed, make it a real SAS item now
601                     AuthorityServiceUtils.SAS_ITEM);        // Since we're sync'ing, this must be a SAS item
602             if (payloadOut != null) {    
603                 ctx.setOutput(payloadOut);
604                 result = true;
605             }
606         }
607         //
608         // Check to see if we need to update the local items's workflow state to reflect that of the remote's
609         //
610         List<String> transitionList = getTransitionList(sasWorkflowState, localItemWorkflowState);
611         if (transitionList.isEmpty() == false) {
612             AuthorityResource authorityResource = (AuthorityResource) ctx.getResource(getAuthorityServicePath()); // Get the authority (parent) client not the item client
613             //
614             // We need to move the local item to the SAS workflow state.  This might involve multiple transitions.
615             //
616             for (String transition:transitionList) {
617                 try {
618                     authorityResource.updateItemWorkflowWithTransition(ctx, localParentCsid, localItemCsid, transition, AuthorityServiceUtils.DONT_UPDATE_REV);
619                 } catch (DocumentReferenceException de) {
620                     //
621                     // This exception means we tried unsuccessfully to soft-delete (workflow transition 'delete') an item that still has references to it from other records.
622                     //
623                     AuthorityServiceUtils.setAuthorityItemDeprecated(ctx, itemDocModel, authorityItemCommonSchemaName, AuthorityServiceUtils.DEPRECATED);  // Since we can't sof-delete it, we need to mark it as deprecated since it is soft-deleted on the SAS
624                     logger.warn(String.format("Could not transition item CSID='%s' from workflow state '%s' to '%s'.  Check the services log file for details.",
625                             localItemCsid, localItemWorkflowState, sasWorkflowState));
626                 }
627             }
628             result = true;
629         }
630         
631         return result;
632     }
633     
634     /**
635      * We need to change the local item's state to one that maps to the replication server's workflow
636      * state.  This might involve making multiple transitions.
637      * 
638      * WIKI:
639      *     See table at https://wiki.collectionspace.org/pages/viewpage.action?pageId=162496564
640      * 
641      */
642     private List<String> getTransitionList(String sasWorkflowState, String localItemWorkflowState) throws DocumentException {
643         List<String> result = new ArrayList<String>();        
644         //
645         // The first set of conditions maps a replication-server "project" state to a local client state of "replicated"
646         //
647         if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT)) {
648             result.add(WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
649         } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED)) {
650             result.add(WorkflowClient.WORKFLOWTRANSITION_UNDELETE);
651             result.add(WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
652         } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED)) {
653             // Do nothing.  We're good with this state
654         } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED)) {
655             result.add(WorkflowClient.WORKFLOWTRANSITION_UNDELETE);
656         //
657         // The second set of conditions maps a replication-server "deleted" state to a local client state of "deleted"
658         //
659         } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT)) {
660             result.add(WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
661             result.add(WorkflowClient.WORKFLOWTRANSITION_DELETE);
662         } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED)) {
663             result.add(WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
664         } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED)) {
665             result.add(WorkflowClient.WORKFLOWTRANSITION_DELETE);
666         } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED)) {
667             // Do nothing.  We're good with this state
668         //
669         // The third set of conditions maps a replication-server "replicated" state to a local state of "replicated"
670         //
671         } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT)) {
672             result.add(WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
673         } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED)) {
674             result.add(WorkflowClient.WORKFLOWTRANSITION_UNDELETE);
675             result.add(WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
676         } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED)) {
677             // Do nothing.  We're good with this state
678         } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED)) {
679             result.add(WorkflowClient.WORKFLOWTRANSITION_UNDELETE);
680         //
681         // The last set of conditions maps a replication-server "replicated_deleted" state to a local client state of "deleted"
682         //
683         } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT)) {
684             result.add(WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
685             result.add(WorkflowClient.WORKFLOWTRANSITION_DELETE);
686         } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED)) {
687             result.add(WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
688         } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED)) {
689             result.add(WorkflowClient.WORKFLOWTRANSITION_DELETE);
690         } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED)) {
691             // Do nothing.  We're good with this state            
692         } else {
693             //
694             // If we get here, we've encountered a SAS workflow state that we don't recognize.
695             //
696             throw new DocumentException(String.format("Encountered an invalid workflow state of '%s' on a SAS authority item.", sasWorkflowState));
697         }
698         
699         return result;
700     }
701     
702     /* (non-Javadoc)
703      * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#handleCreate(org.collectionspace.services.common.document.DocumentWrapper)
704      */
705     @Override
706     public void handleCreate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
707         // first fill all the parts of the document, refname and short ID get set as well
708         super.handleCreate(wrapDoc);
709         // Ensure we have required fields set properly
710         handleInAuthority(wrapDoc.getWrappedObject());        
711     }
712
713     enum RefObjsSearchType {
714         ALL, NON_DELETED, DELETED_ONLY
715     }
716     
717     /*
718      * This method gets called after the primary update to an authority item has happened.  If the authority item's refName
719      * has changed, then we need to updated all the records that use that refname with the new/updated version
720      * 
721      * (non-Javadoc)
722      */
723     @SuppressWarnings({ "rawtypes", "unchecked" })
724     @Override
725     public boolean handleDelete(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
726         boolean result = true;
727         
728         ServiceContext ctx = getServiceContext();
729         DocumentModel docModel = wrapDoc.getWrappedObject();
730         
731         AuthorityRefDocList refsToAllObjects = getReferencingObjects(ctx, docModel, RefObjsSearchType.ALL);
732         AuthorityRefDocList refsToSoftDeletedObjects = getReferencingObjects(ctx, docModel, RefObjsSearchType.DELETED_ONLY);
733         if (refsToAllObjects.getTotalItems() > 0) {
734             if (refsToAllObjects.getTotalItems() > refsToSoftDeletedObjects.getTotalItems()) {
735                 //
736                 // If the number of refs to active objects is greater than the number of refs to
737                 // soft deleted objects then we can't delete the item.
738                 //
739                 logger.error(String.format("Cannot delete authority item CSID='%s' because it still has %d records in the system that are referencing it.",
740                         docModel.getName(), refsToSoftDeletedObjects.getTotalItems()));
741                 if (logger.isWarnEnabled() == true) {
742                     logReferencingObjects(docModel, refsToAllObjects);
743                 }
744
745                 throw new DocumentReferenceException(String.format("Cannot delete authority item '%s' because it still has records in the system that are referencing it.  See the service layer log file for details.",
746                         docModel.getName()));
747             } else {
748                 //
749                 // If all the refs are to soft-deleted objects, we should soft-delete this authority item instead of hard-deleting it and instead of failing.
750                 //
751                 String parentCsid = (String) NuxeoUtils.getProperyValue(docModel, AuthorityItemJAXBSchema.IN_AUTHORITY);
752                 String itemCsid = docModel.getName();
753                 AuthorityResource authorityResource = (AuthorityResource) ctx.getResource(getAuthorityServicePath());
754                 authorityResource.updateItemWorkflowWithTransition(ctx, parentCsid, itemCsid, WorkflowClient.WORKFLOWTRANSITION_DELETE, 
755                         this.getShouldUpdateRevNumber());
756                 result = false; // Don't delete since we just soft-deleted it.                
757             }
758         }
759         
760         //
761         // Since we've changed the state of the parent by deleting (or soft-deleting) one of its items, we might need to update the parent rev number
762         //
763         if (getShouldUpdateRevNumber() == true) {
764             updateRevNumbers(wrapDoc);
765         }
766         
767         return result;
768     }
769     
770     /**
771      * Checks to see if an authority item has referencing objects.
772      * 
773      * @param ctx
774      * @param docModel
775      * @return
776      * @throws Exception
777      */
778     @SuppressWarnings("rawtypes")
779     private AuthorityRefDocList getReferencingObjects(ServiceContext ctx, DocumentModel docModel, RefObjsSearchType searchType) throws Exception {
780         AuthorityRefDocList result = null;
781         
782         if (ctx.getUriInfo() == null) {
783             //
784             // We need a UriInfo object so we can pass "query" params to the AuthorityResource's getReferencingObjects() method
785             //
786             ctx.setUriInfo(this.getServiceContext().getUriInfo()); // try to get a UriInfo instance from the handler's context
787         }
788         
789         //
790         // Since the call to get referencing objects might indirectly use the WorkflowClient.WORKFLOW_QUERY_NONDELETED query param, we need to
791         // temporarily remove that query param if it is set.  If set, we'll save the value and reset once we're finished.
792         //
793         boolean doesContainValue = ctx.getUriInfo().getQueryParameters().containsKey(WorkflowClient.WORKFLOW_QUERY_DELETED_QP);
794         String previousValue = ctx.getUriInfo().getQueryParameters().getFirst(WorkflowClient.WORKFLOW_QUERY_DELETED_QP);
795         try {
796             if (doesContainValue) {
797                 ctx.getUriInfo().getQueryParameters().remove(WorkflowClient.WORKFLOW_QUERY_DELETED_QP);
798             }
799             AuthorityResource authorityResource = (AuthorityResource)ctx.getResource(getAuthorityServicePath());
800             result = getReferencingObjects(authorityResource, ctx, docModel, searchType);
801         } finally {
802             if (doesContainValue) {
803                 ctx.getUriInfo().getQueryParameters().addFirst(WorkflowClient.WORKFLOW_QUERY_DELETED_QP, previousValue);
804             }
805         }
806         
807         return result;
808     }
809     
810     @SuppressWarnings({ "rawtypes", "unchecked" })
811     private AuthorityRefDocList getReferencingObjects(AuthorityResource authorityResource, ServiceContext ctx, DocumentModel docModel, RefObjsSearchType searchType) throws Exception {
812         AuthorityRefDocList result = null;
813         
814         String inAuthorityCsid = (String) docModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.IN_AUTHORITY);
815         String itemCsid = docModel.getName();
816         
817         try {
818             switch (searchType) {
819                 case ALL:
820                     // By default, get get everything
821                     break;
822                 case NON_DELETED:
823                     // Get only non-deleted objects
824                     ctx.getUriInfo().getQueryParameters().addFirst(WorkflowClient.WORKFLOW_QUERY_DELETED_QP, Boolean.FALSE.toString());  // Add the wf_deleted=false query param to exclude soft-deleted items
825                     break;
826                 case DELETED_ONLY:
827                     // Get only deleted objects
828                     ctx.getUriInfo().getQueryParameters().addFirst(WorkflowClient.WORKFLOW_QUERY_ONLY_DELETED_QP, Boolean.TRUE.toString());  // Add the wf_only_deleted query param to get only soft-deleted items
829                     break;
830             }
831             result = authorityResource.getReferencingObjects(ctx, inAuthorityCsid, itemCsid, ctx.getUriInfo());
832
833         } finally {
834             //
835             // Cleanup query params
836             //
837             switch (searchType) {
838                 case ALL:
839                     break;
840                 case NON_DELETED:
841                     ctx.getUriInfo().getQueryParameters().remove(WorkflowClient.WORKFLOWSTATE_DELETED);
842                     break;
843                 case DELETED_ONLY:
844                     ctx.getUriInfo().getQueryParameters().remove(WorkflowClient.WORKFLOW_QUERY_ONLY_DELETED_QP);
845                     break;
846             }
847         }
848
849         return result;
850     }    
851     
852     private void logReferencingObjects(DocumentModel docModel, AuthorityRefDocList refObjs) {
853         List<AuthorityRefDocList.AuthorityRefDocItem> items = refObjs.getAuthorityRefDocItem();
854         logger.warn(String.format("The authority item CSID='%s' has the following references:", docModel.getName()));
855         int i = 0;
856         for (AuthorityRefDocList.AuthorityRefDocItem item : items) {
857             if (item.getWorkflowState().contains(WorkflowClient.WORKFLOWSTATE_DELETED) == false) {
858                 logger.warn(docModel.getName() + " referenced by : list-item[" + i + "] "
859                         + item.getDocType() + "("
860                         + item.getDocId() + ") Name:["
861                         + item.getDocName() + "] Number:["
862                         + item.getDocNumber() + "] in field:["
863                         + item.getSourceField() + "]");
864                 i++;
865             }
866         }
867     }
868
869     /*
870      * This method gets called after the primary update to an authority item has happened.  If the authority item's refName
871      * has changed, then we need to updated all the records that use that refname with the new/updated version
872      * 
873      * (non-Javadoc)
874      * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#completeUpdate(org.collectionspace.services.common.document.DocumentWrapper)
875      */
876     public void completeUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
877         // Must call our super class' version first
878         super.completeUpdate(wrapDoc);
879         
880         //
881         // Look for and update authority references with the updated refName
882         //
883         if (hasRefNameUpdate() == true) {
884             // We have work to do.
885             if (logger.isDebugEnabled()) {
886                 final String EOL = System.getProperty("line.separator");
887                 logger.debug("Need to find and update references to authority item." + EOL
888                         + "   Old refName" + oldRefNameOnUpdate + EOL
889                         + "   New refName" + newRefNameOnUpdate);
890             }
891             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
892             RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient = getRepositoryClient(ctx);
893             CoreSessionInterface repoSession = this.getRepositorySession();
894             
895             // Update all the existing records that have a field with the old refName in it
896             int nUpdated = RefNameServiceUtils.updateAuthorityRefDocs(ctx, repoClient, repoSession,
897                     oldRefNameOnUpdate, newRefNameOnUpdate, getRefPropName());
898             
899             // Finished so log a message.
900             if (logger.isDebugEnabled()) {
901                 logger.debug("Updated " + nUpdated + " instances of oldRefName to newRefName");
902             }
903         }
904     }
905     
906     /*
907      * Note that the Vocabulary service's document-model for items overrides this method.
908      */
909     protected String getPrimaryDisplayName(DocumentModel docModel, String schema,
910             String complexPropertyName, String fieldName) {
911         String result = null;
912
913         result = getStringValueInPrimaryRepeatingComplexProperty(docModel, schema, complexPropertyName, fieldName);
914         
915         return result;
916     }
917     
918     /* (non-Javadoc)
919      * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#handleUpdate(org.collectionspace.services.common.document.DocumentWrapper)
920      */
921     @Override
922     // FIXME: Once we remove the refName field from the authority item schemas, we can remove this override method since our super does everthing for us now.
923     @Deprecated
924     public void handleUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
925         // Must call our super's version first, this updates the core schema and the relationship records to deal with possible refName changes/update
926         super.handleUpdate(wrapDoc);
927         if (this.hasRefNameUpdate() == true) {
928             DocumentModel docModel = wrapDoc.getWrappedObject();
929             docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REF_NAME, this.newRefNameOnUpdate); // This field is deprecated since it is now a duplicate of what is in the collectionspace_core:refName field            
930         }
931     }
932     
933     //
934     // Handles both update calls (PUTS) AND create calls (POSTS)
935     //
936     public void fillAllParts(DocumentWrapper<DocumentModel> wrapDoc, Action action) throws Exception {
937         super.fillAllParts(wrapDoc, action);
938         DocumentModel documentModel = wrapDoc.getWrappedObject();
939
940         //
941         // Update the record's revision number on both CREATE and UPDATE actions (as long as it is NOT a SAS authority item)
942         //
943         Boolean propertyValue = (Boolean) documentModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SAS);
944         boolean isMarkedAsSASItem = propertyValue != null ? propertyValue : false;
945         if (this.getShouldUpdateRevNumber() == true && !isMarkedAsSASItem) { // We won't update rev numbers on synchronization with SAS items and on local changes to SAS items
946             updateRevNumbers(wrapDoc);
947         }
948         
949         if (getShouldUpdateSASFields() == true) {
950             //
951             // If this is a proposed item (not part of the SAS), mark it as such
952             //
953             documentModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.PROPOSED,
954                     new Boolean(this.getIsProposed()));
955             //
956             // If it is a SAS authority item, mark it as such
957             //
958             documentModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SAS,
959                     new Boolean(this.getIsSASItem()));
960         }
961     }
962     
963     /**
964      * Update the revision number of both the item and the item's parent.
965      * @param wrapDoc
966      * @throws Exception
967      */
968     protected void updateRevNumbers(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
969         DocumentModel documentModel = wrapDoc.getWrappedObject();
970         Long rev = (Long)documentModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REV);
971         if (rev == null) {
972             rev = (long)0;
973         } else {
974             rev++;
975         }
976         documentModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REV, rev);
977         //
978         // Next, update the inAuthority (the parent's) rev number
979         //
980         String inAuthorityCsid = this.getInAuthorityCsid();
981         if (inAuthorityCsid == null) {
982             // When inAuthorityCsid is null, it usually means we're performing and update or synch with the SAS
983             inAuthorityCsid = (String)documentModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.IN_AUTHORITY);
984         }
985         DocumentModel inAuthorityDocModel = NuxeoUtils.getDocFromCsid(getServiceContext(), getRepositorySession(), inAuthorityCsid);
986         if (inAuthorityDocModel != null) {
987             Long parentRev = (Long)inAuthorityDocModel.getProperty(getParentCommonSchemaName(), AuthorityJAXBSchema.REV);
988             if (parentRev == null) {
989                 parentRev = new Long(0);
990             }
991                parentRev++;
992                inAuthorityDocModel.setProperty(getParentCommonSchemaName(), AuthorityJAXBSchema.REV, parentRev);
993                getRepositorySession().saveDocument(inAuthorityDocModel);
994         } else {
995             logger.warn(String.format("Containing authority '%s' for item '%s' has been deleted.  Item is orphaned, so revision numbers can't be updated.",
996                     inAuthorityCsid, documentModel.getName()));
997         }
998     }    
999     
1000     /**
1001      * If no short identifier was provided in the input payload, generate a
1002      * short identifier from the preferred term display name or term name.
1003      */
1004     private String handleDisplayNameAsShortIdentifier(DocumentModel docModel) throws Exception {
1005         String result = (String) docModel.getProperty(authorityItemCommonSchemaName,
1006                 AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
1007
1008         if (Tools.isEmpty(result)) {
1009             String termDisplayName = getPrimaryDisplayName(
1010                     docModel, authorityItemCommonSchemaName,
1011                     getItemTermInfoGroupXPathBase(),
1012                     AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
1013
1014             String termName = getPrimaryDisplayName(
1015                     docModel, authorityItemCommonSchemaName,
1016                     getItemTermInfoGroupXPathBase(),
1017                     AuthorityItemJAXBSchema.TERM_NAME);
1018
1019             String generatedShortIdentifier = AuthorityIdentifierUtils.generateShortIdentifierFromDisplayName(termDisplayName,
1020                             termName);
1021             docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER,
1022                     generatedShortIdentifier);
1023             result = generatedShortIdentifier;
1024         }
1025         
1026         return result;
1027     }
1028
1029     /**
1030      * Generate a refName for the authority item from the short identifier
1031      * and display name.
1032      * 
1033      * All refNames for authority items are generated.  If a client supplies
1034      * a refName, it will be overwritten during create (per this method) 
1035      * or discarded during update (per filterReadOnlyPropertiesForPart).
1036      * 
1037      * @see #filterReadOnlyPropertiesForPart(Map<String, Object>, org.collectionspace.services.common.service.ObjectPartType)
1038      * 
1039      */
1040     protected String updateRefnameForAuthorityItem(DocumentModel docModel,
1041             String schemaName) throws Exception {
1042         String result = null;
1043         
1044         RefName.RefNameInterface refname = getRefName(getServiceContext(), docModel);
1045         String refNameStr = refname.toString();
1046         docModel.setProperty(schemaName, AuthorityItemJAXBSchema.REF_NAME, refNameStr);
1047         result = refNameStr;
1048         
1049         return result;
1050     }
1051
1052     /**
1053      * Check the logic around the parent pointer. Note that we only need do this on
1054      * create, since we have logic to make this read-only on update. 
1055      * 
1056      * @param docModel
1057      * 
1058      * @throws Exception the exception
1059      */
1060     private void handleInAuthority(DocumentModel docModel) throws Exception {
1061         if (inAuthority == null) { // Only happens on queries to wildcarded authorities
1062             throw new IllegalStateException("Trying to Create an object with no inAuthority value!");
1063         }
1064         docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.IN_AUTHORITY, inAuthority);
1065     }
1066     
1067     /**
1068      * Returns a list of records that reference this authority item
1069      * 
1070      * @param ctx
1071      * @param uriTemplateRegistry
1072      * @param serviceTypes
1073      * @param propertyName
1074      * @param itemcsid
1075      * @return
1076      * @throws Exception
1077      */
1078     public AuthorityRefDocList getReferencingObjects(
1079             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
1080             List<String> serviceTypes,
1081             String propertyName,
1082             String itemcsid) throws Exception {
1083         AuthorityRefDocList authRefDocList = null;
1084         CoreSessionInterface repoSession = (CoreSessionInterface) ctx.getCurrentRepositorySession();
1085         boolean releaseRepoSession = false;
1086         
1087         try {
1088             NuxeoRepositoryClientImpl repoClient = (NuxeoRepositoryClientImpl)this.getRepositoryClient(ctx);
1089             repoSession = this.getRepositorySession();
1090             if (repoSession == null) {
1091                 repoSession = repoClient.getRepositorySession(ctx);
1092                 releaseRepoSession = true;
1093             }
1094             DocumentFilter myFilter = getDocumentFilter();
1095
1096             try {
1097                 DocumentWrapper<DocumentModel> wrapper = repoClient.getDoc(repoSession, ctx, itemcsid);
1098                 DocumentModel docModel = wrapper.getWrappedObject();
1099                 String refName = (String) NuxeoUtils.getProperyValue(docModel, AuthorityItemJAXBSchema.REF_NAME); //docModel.getPropertyValue(AuthorityItemJAXBSchema.REF_NAME);
1100                 authRefDocList = RefNameServiceUtils.getAuthorityRefDocs(
1101                         repoSession, ctx, repoClient,
1102                         serviceTypes,
1103                         refName,
1104                         propertyName,
1105                         myFilter, true /*computeTotal*/);
1106             } catch (PropertyException pe) {
1107                 throw pe;
1108             } catch (DocumentException de) {
1109                 throw de;
1110             } catch (Exception e) {
1111                 if (logger.isDebugEnabled()) {
1112                     logger.debug("Caught exception ", e);
1113                 }
1114                 throw new DocumentException(e);
1115             } finally {
1116                 // If we got/aquired a new seesion then we're responsible for releasing it.
1117                 if (releaseRepoSession && repoSession != null) {
1118                     repoClient.releaseRepositorySession(ctx, repoSession);
1119                 }
1120             }
1121         } catch (Exception e) {
1122             if (logger.isDebugEnabled()) {
1123                 logger.debug("Caught exception ", e);
1124             }
1125             throw new DocumentException(e);
1126         }
1127         
1128         return authRefDocList;
1129     }
1130
1131     /* (non-Javadoc)
1132      * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#extractPart(org.nuxeo.ecm.core.api.DocumentModel, java.lang.String, org.collectionspace.services.common.service.ObjectPartType)
1133      */
1134     @Override
1135     protected Map<String, Object> extractPart(DocumentModel docModel, String schema, ObjectPartType partMeta)
1136             throws Exception {
1137         Map<String, Object> unQObjectProperties = super.extractPart(docModel, schema, partMeta);
1138
1139         // Add the CSID to the common part, since they may have fetched via the shortId.
1140         if (partMeta.getLabel().equalsIgnoreCase(authorityItemCommonSchemaName)) {
1141             String csid = getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
1142             unQObjectProperties.put("csid", csid);
1143         }
1144
1145         return unQObjectProperties;
1146     }
1147
1148     /**
1149      * Filters out selected values supplied in an update request.
1150      * 
1151      * For example, filters out AuthorityItemJAXBSchema.IN_AUTHORITY, to ensure
1152      * that the link to the item's parent remains untouched.
1153      * 
1154      * @param objectProps the properties filtered out from the update payload
1155      * @param partMeta metadata for the object to fill
1156      */
1157     @Override
1158     public void filterReadOnlyPropertiesForPart(
1159             Map<String, Object> objectProps, ObjectPartType partMeta) {
1160         super.filterReadOnlyPropertiesForPart(objectProps, partMeta);
1161         String commonPartLabel = getServiceContext().getCommonPartLabel();
1162         if (partMeta.getLabel().equalsIgnoreCase(commonPartLabel)) {
1163             objectProps.remove(AuthorityItemJAXBSchema.IN_AUTHORITY);
1164             objectProps.remove(AuthorityItemJAXBSchema.CSID);
1165             objectProps.remove(AuthorityJAXBSchema.SHORT_IDENTIFIER);
1166             objectProps.remove(AuthorityItemJAXBSchema.REF_NAME);
1167         }
1168     }
1169     
1170     /**
1171      * Returns the items in a list of term display names whose names contain
1172      * a partial term (as might be submitted in a search query, for instance).
1173      * @param termDisplayNameList a list of term display names.
1174      * @param partialTerm a partial term display name; that is, a portion
1175      * of a display name that might be expected to match 0-n terms in the list.
1176      * @return a list of term display names that matches the partial term.
1177      * Matches are case-insensitive. As well, before matching is performed, any
1178      * special-purpose characters that may appear in the partial term (such as
1179      * wildcards and anchor characters) are filtered out from both compared terms.
1180      */
1181     protected List<String> getPartialTermDisplayNameMatches(List<String> termDisplayNameList, String partialTerm) {
1182         List<String> result = new ArrayList<>();
1183         String partialTermMatchExpression = filterAnchorAndWildcardChars(partialTerm).toLowerCase();
1184         try {
1185             for (String termDisplayName : termDisplayNameList) {
1186                 if (termDisplayName.toLowerCase()
1187                         .matches(partialTermMatchExpression) == true) {
1188                         result.add(termDisplayName);
1189                 }
1190             }
1191         } catch (PatternSyntaxException pse) {
1192             logger.warn("Error in regex match pattern '%s' for term display names: %s",
1193                     partialTermMatchExpression, pse.getMessage());
1194         }
1195         return result;
1196     }
1197     
1198     /**
1199      * Filters user-supplied anchor and wildcard characters in a string,
1200      * replacing them with equivalent regular expressions.
1201      * @param term a term in which to filter anchor and wildcard characters.
1202      * @return the term with those characters filtered.
1203      */
1204     protected String filterAnchorAndWildcardChars(String term) {
1205         if (Tools.isBlank(term)) {
1206             return term;
1207         }
1208         if (term.length() < 3) {
1209             return term;
1210         }
1211         if (logger.isTraceEnabled()) {
1212             logger.trace(String.format("Term = %s", term));
1213         }
1214         Boolean anchorAtStart = false;
1215         Boolean anchorAtEnd = false;
1216         String filteredTerm;
1217         StringBuilder filteredTermBuilder = new StringBuilder(term);
1218         // Term contains no anchor or wildcard characters.
1219         if ( (! term.contains(NuxeoRepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR))
1220                 && (! term.contains(NuxeoRepositoryClientImpl.USER_SUPPLIED_WILDCARD)) ) {
1221             filteredTerm = term;
1222         } else {
1223             // Term contains at least one such character.
1224             try {
1225                 // Filter the starting anchor or wildcard character, if any.
1226                 String firstChar = filteredTermBuilder.substring(0,1);
1227                 switch (firstChar) {
1228                     case NuxeoRepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR:
1229                         anchorAtStart = true;
1230                         break;
1231                     case NuxeoRepositoryClientImpl.USER_SUPPLIED_WILDCARD:
1232                         filteredTermBuilder.deleteCharAt(0);
1233                         break;
1234                 }
1235                 if (logger.isTraceEnabled()) {
1236                     logger.trace(String.format("After first char filtering = %s", filteredTermBuilder.toString()));
1237                 }
1238                 // Filter the ending anchor or wildcard character, if any.
1239                 int lastPos = filteredTermBuilder.length() - 1;
1240                 String lastChar = filteredTermBuilder.substring(lastPos);
1241                 switch (lastChar) {
1242                     case NuxeoRepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR:
1243                         filteredTermBuilder.deleteCharAt(lastPos);
1244                         filteredTermBuilder.insert(filteredTermBuilder.length(), NuxeoRepositoryClientImpl.ENDING_ANCHOR_CHAR);
1245                         anchorAtEnd = true;
1246                         break;
1247                     case NuxeoRepositoryClientImpl.USER_SUPPLIED_WILDCARD:
1248                         filteredTermBuilder.deleteCharAt(lastPos);
1249                         break;
1250                 }
1251                 if (logger.isTraceEnabled()) {
1252                     logger.trace(String.format("After last char filtering = %s", filteredTermBuilder.toString()));
1253                 }
1254                 filteredTerm = filteredTermBuilder.toString();
1255                 // Filter all other wildcards, if any.
1256                 filteredTerm = filteredTerm.replaceAll(NuxeoRepositoryClientImpl.USER_SUPPLIED_WILDCARD_REGEX, ZERO_OR_MORE_ANY_CHAR_REGEX);
1257                 if (logger.isTraceEnabled()) {
1258                     logger.trace(String.format("After replacing user wildcards = %s", filteredTerm));
1259                 }
1260             } catch (Exception e) {
1261                 logger.warn(String.format("Error filtering anchor and wildcard characters from string: %s", e.getMessage()));
1262                 return term;
1263             }
1264         }
1265         // Wrap the term in beginning and ending regex wildcards, unless a
1266         // starting or ending anchor character was present.
1267         return (anchorAtStart ? "" : ZERO_OR_MORE_ANY_CHAR_REGEX)
1268                 + filteredTerm
1269                 + (anchorAtEnd ? "" : ZERO_OR_MORE_ANY_CHAR_REGEX);
1270     }
1271     
1272     @SuppressWarnings("unchecked")
1273     private List<String> getPartialTermDisplayNameMatches(DocumentModel docModel, // REM - CSPACE-5133
1274             String schema, ListResultField field, String partialTerm) {
1275         List<String> result = null;
1276           
1277         String xpath = field.getXpath(); // results in something like "persons_common:personTermGroupList/[0]/termDisplayName"
1278         int endOfTermGroup = xpath.lastIndexOf("/[0]/");
1279         String propertyName = endOfTermGroup != -1 ? xpath.substring(0, endOfTermGroup) : xpath; // it may not be multivalued so the xpath passed in would be the property name
1280         Object value = null;
1281         
1282         try {
1283             value = docModel.getProperty(schema, propertyName);
1284         } catch (Exception e) {
1285             logger.error("Could not extract term display name with property = "
1286                     + propertyName, e);
1287         }
1288         
1289         if (value != null && value instanceof ArrayList) {
1290             ArrayList<HashMap<String, Object>> termGroupList = (ArrayList<HashMap<String, Object>>)value;
1291             int arrayListSize = termGroupList.size();
1292             if (arrayListSize > 1) { // if there's only 1 element in the list then we've already matched the primary term's display name
1293                 List<String> displayNameList = new ArrayList<String>();
1294                 for (int i = 1; i < arrayListSize; i++) { // start at 1, skip the primary term's displayName since we will always return it
1295                     HashMap<String, Object> map = (HashMap<String, Object>)termGroupList.get(i);
1296                     String termDisplayName = (String) map.get(AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
1297                     displayNameList.add(i - 1, termDisplayName);
1298                 }
1299                 
1300                 result = getPartialTermDisplayNameMatches(displayNameList, partialTerm);
1301             }
1302         }
1303
1304         return result;
1305     }
1306
1307     @Override
1308     protected Object getListResultValue(DocumentModel docModel, // REM - CSPACE-5133
1309             String schema, ListResultField field) throws DocumentException {
1310         Object result = null;        
1311         String fieldXPath = field.getXpath();
1312         
1313         if (fieldXPath.equalsIgnoreCase(AuthorityClient.REFERENCED) == false) {
1314             result = NuxeoUtils.getXPathValue(docModel, schema, field.getXpath());
1315         } else {
1316             //
1317             // Special case for the 'referenced' list result field.
1318             //
1319             // Set result value of field 'referenced' to 'true' if item is being referenced; otherwise, 'false'
1320             //
1321             try {
1322                 result = Boolean.FALSE.toString();
1323                 AuthorityRefDocList referenceList = null;
1324
1325                 String wf_deletedStr = (String) getServiceContext().getQueryParams().getFirst(WorkflowClient.WORKFLOW_QUERY_DELETED_QP);
1326                 if (wf_deletedStr != null && Tools.isFalse(wf_deletedStr)) {
1327                     //
1328                     // if query param 'wf_deleted=false', we won't count references to soft-deleted records
1329                     //
1330                     referenceList = getReferencingObjects(getServiceContext(), docModel, RefObjsSearchType.NON_DELETED);
1331                 } else {
1332                     //
1333                     // if query param 'wf_deleted=true' or missing, we count references to soft-deleted and active records
1334                     //
1335                     referenceList = getReferencingObjects(getServiceContext(), docModel, RefObjsSearchType.ALL);
1336                 }
1337                 
1338                 if (referenceList.getTotalItems() > 0) {
1339                     result = Boolean.TRUE.toString();
1340                 }
1341                 
1342                 return result;
1343             } catch (Exception e) {
1344                 String msg = String.format("Failed while trying to find records referencing term CSID='%s'.", docModel.getName());
1345                 throw new DocumentException(msg, e);
1346             }
1347         }
1348                 
1349         //
1350         // Special handling of list item values for authority items (only)
1351         // takes place here:
1352         //
1353         // If the list result field is the termDisplayName element,
1354         // check whether a partial term matching query was made.
1355         // If it was, emit values for both the preferred (aka primary)
1356         // term and for all non-preferred terms, if any.
1357         //
1358         String elName = field.getElement();
1359         if (isTermDisplayName(elName) == true) {
1360             MultivaluedMap<String, String> queryParams = this.getServiceContext().getQueryParams();
1361             String partialTerm = queryParams != null ? queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM) : null;
1362             if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
1363                 String primaryTermDisplayName = (String)result;
1364                 List<String> matches = getPartialTermDisplayNameMatches(docModel, schema, field, partialTerm);
1365                 if (matches != null && matches.isEmpty() == false) {
1366                     matches.add(0, primaryTermDisplayName); // insert the primary term's display name at the beginning of the list
1367                     result = matches; // set the result to a list of matching term display names with the primary term's display name at the beginning
1368                 }
1369             }
1370         }
1371         
1372         return result;
1373     }
1374     
1375     @Override
1376     public void extractAllParts(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
1377         MultipartServiceContext ctx = (MultipartServiceContext) getServiceContext();
1378         super.extractAllParts(wrapDoc);
1379     }
1380
1381     protected List<RelationsCommonList.RelationListItem> cloneList(List<RelationsCommonList.RelationListItem> inboundList) {
1382         List<RelationsCommonList.RelationListItem> result = newRelationsCommonList();
1383         for (RelationsCommonList.RelationListItem item : inboundList) {
1384             result.add(item);
1385         }
1386         return result;
1387     }
1388
1389
1390     /* don't even THINK of re-using this method.
1391      * String example_uri = "/locationauthorities/7ec60f01-84ab-4908-9a6a/items/a5466530-713f-43b4-bc05";
1392      */
1393     @Deprecated
1394     private String extractInAuthorityCSID(String uri) {
1395         String IN_AUTHORITY_REGEX = "/(.*?)/(.*?)/(.*)";
1396         Pattern p = Pattern.compile(IN_AUTHORITY_REGEX);
1397         Matcher m = p.matcher(uri);
1398         if (m.find()) {
1399             if (m.groupCount() < 3) {
1400                 logger.warn("REGEX-WRONG-GROUPCOUNT looking in " + uri);
1401                 return "";
1402             } else {
1403                 //String service = m.group(1);
1404                 String inauth = m.group(2);
1405                 //String theRest = m.group(3);
1406                 return inauth;
1407                 //print("service:"+service+", inauth:"+inauth+", rest:"+rest);
1408             }
1409         } else {
1410             logger.warn("REGEX-NOT-MATCHED looking in " + uri);
1411             return "";
1412         }
1413     }
1414
1415     //ensures CSPACE-4042
1416     protected void uriPointsToSameAuthority(String thisURI, String inboundItemURI) throws Exception {
1417         String authorityCSID = extractInAuthorityCSID(thisURI);
1418         String authorityCSIDForInbound = extractInAuthorityCSID(inboundItemURI);
1419         if (Tools.isBlank(authorityCSID)
1420                 || Tools.isBlank(authorityCSIDForInbound)
1421                 || (!authorityCSID.equalsIgnoreCase(authorityCSIDForInbound))) {
1422             throw new Exception("Item URI " + thisURI + " must point to same authority as related item: " + inboundItemURI);
1423         }
1424     }
1425
1426     public String getItemTermInfoGroupXPathBase() {
1427         return authorityItemTermGroupXPathBase;
1428     }
1429         
1430     public void setItemTermInfoGroupXPathBase(String itemTermInfoGroupXPathBase) {
1431         authorityItemTermGroupXPathBase = itemTermInfoGroupXPathBase;
1432     }
1433     
1434     protected String getAuthorityItemCommonSchemaName() {
1435         return authorityItemCommonSchemaName;
1436     }
1437     
1438     // @Override
1439     public boolean isJDBCQuery() {
1440         boolean result = false;
1441         
1442         MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams();
1443         //
1444         // Look the query params to see if we need to make a SQL query.
1445         //
1446         String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
1447         if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
1448             result = true;
1449         }
1450         
1451         return result;
1452     }
1453     
1454     // By convention, the name of the database table that contains
1455     // repeatable term information group records is derivable from
1456     // an existing XPath base value, by removing a suffix and converting
1457     // to lowercase
1458     protected String getTermGroupTableName() {
1459         String termInfoGroupListName = getItemTermInfoGroupXPathBase();
1460         return termInfoGroupListName.substring(0, termInfoGroupListName.lastIndexOf(LIST_SUFFIX)).toLowerCase();
1461     }
1462     
1463     protected String getInAuthorityValue() {
1464         String inAuthorityValue = getInAuthorityCsid();
1465         if (Tools.notBlank(inAuthorityValue)) {
1466             return inAuthorityValue;
1467         } else {
1468             return AuthorityResource.PARENT_WILDCARD;
1469         }
1470     }
1471     
1472     @Override
1473     public Map<String,String> getJDBCQueryParams() {
1474         // FIXME: Get all of the following values from appropriate external constants.
1475         // At present, these are duplicated in both RepositoryClientImpl
1476         // and in AuthorityItemDocumentModelHandler.
1477         final String TERM_GROUP_LIST_NAME = "TERM_GROUP_LIST_NAME";
1478         final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
1479         final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
1480         
1481         Map<String,String> params = super.getJDBCQueryParams();
1482         params.put(TERM_GROUP_LIST_NAME, getItemTermInfoGroupXPathBase());
1483         params.put(TERM_GROUP_TABLE_NAME_PARAM, getTermGroupTableName());
1484         params.put(IN_AUTHORITY_PARAM, getInAuthorityValue());
1485         return params;
1486     }
1487     
1488 }