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