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