]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
95804a67b7b78da8dbcfe275e5852d6c197d3126
[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.CollectionSpaceClient;
28 import org.collectionspace.services.client.IQueryManager;
29 import org.collectionspace.services.client.PoxPayloadIn;
30 import org.collectionspace.services.client.PoxPayloadOut;
31 import org.collectionspace.services.client.workflow.WorkflowClient;
32 import org.collectionspace.services.common.ResourceMap;
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.RefNameUtils;
37 import org.collectionspace.services.common.api.Tools;
38 import org.collectionspace.services.common.api.RefNameUtils.AuthorityInfo;
39 import org.collectionspace.services.common.authorityref.AuthorityRefDocList;
40 import org.collectionspace.services.common.context.MultipartServiceContext;
41 import org.collectionspace.services.common.context.ServiceContext;
42 import org.collectionspace.services.common.document.DocumentException;
43 import org.collectionspace.services.common.document.DocumentFilter;
44 import org.collectionspace.services.common.document.DocumentNotFoundException;
45 import org.collectionspace.services.common.document.DocumentReferenceException;
46 import org.collectionspace.services.common.document.DocumentWrapper;
47 import org.collectionspace.services.common.repository.RepositoryClient;
48 import org.collectionspace.services.common.vocabulary.AuthorityJAXBSchema;
49 import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema;
50 import org.collectionspace.services.common.vocabulary.AuthorityResource;
51 import org.collectionspace.services.common.vocabulary.AuthorityServiceUtils;
52 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils;
53 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.AuthorityItemSpecifier;
54 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.Specifier;
55 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.SpecifierForm;
56 import org.collectionspace.services.config.service.ListResultField;
57 import org.collectionspace.services.config.service.ObjectPartType;
58 import org.collectionspace.services.lifecycle.TransitionDef;
59 import org.collectionspace.services.nuxeo.client.java.NuxeoDocumentModelHandler;
60 import org.collectionspace.services.nuxeo.client.java.CoreSessionInterface;
61 import org.collectionspace.services.nuxeo.client.java.RepositoryClientImpl;
62 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
63 import org.collectionspace.services.relation.RelationsCommonList;
64 import org.collectionspace.services.vocabulary.VocabularyItemJAXBSchema;
65 import org.nuxeo.ecm.core.api.ClientException;
66 import org.nuxeo.ecm.core.api.DocumentModel;
67 import org.nuxeo.ecm.core.api.model.PropertyException;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
70
71 import javax.ws.rs.core.MultivaluedMap;
72
73 import java.util.ArrayList;
74 import java.util.Collection;
75 import java.util.Collections;
76 import java.util.HashMap;
77 import java.util.List;
78 import java.util.Map;
79 import java.util.regex.Matcher;
80 import java.util.regex.Pattern;
81 import java.util.regex.PatternSyntaxException;
82
83 //import org.collectionspace.services.common.authority.AuthorityItemRelations;
84 /**
85  * AuthorityItemDocumentModelHandler
86  *
87  * $LastChangedRevision: $
88  * $LastChangedDate: $
89  */
90 public abstract class AuthorityItemDocumentModelHandler<AICommon>
91         extends NuxeoDocumentModelHandler<AICommon> {
92
93     private final Logger logger = LoggerFactory.getLogger(AuthorityItemDocumentModelHandler.class);
94     
95     protected String authorityCommonSchemaName;
96     protected String authorityItemCommonSchemaName;
97     private String authorityItemTermGroupXPathBase;
98     
99     private boolean isProposed = false; // used by local authority to propose a new shared item. Allows local deployments to use new terms until they become official
100     private boolean shouldUpdateRevNumber = true; // by default we should update the revision number -not true on synchronization with SAS
101     /**
102      * inVocabulary is the parent Authority for this context
103      */
104     protected String inAuthority = null;
105     protected boolean wildcardedAuthorityRequest = false;
106     protected String authorityRefNameBase = null;
107     // Used to determine when the displayName changes as part of the update.
108     protected String oldDisplayNameOnUpdate = null;
109     private final static String LIST_SUFFIX = "List";
110     private final static String ZERO_OR_MORE_ANY_CHAR_REGEX = ".*";
111
112     public AuthorityItemDocumentModelHandler(String authorityCommonSchemaName, String authorityItemCommonSchemaName) {
113         this.authorityItemCommonSchemaName = authorityItemCommonSchemaName;
114     }
115     
116     abstract public String getParentCommonSchemaName();
117     
118     //
119     // Getter and Setter for 'proposed'
120     //
121     public boolean getIsProposed() {
122         return this.isProposed;
123     }
124     
125     public void setIsProposed(boolean flag) {
126         this.isProposed = flag;
127     }
128     
129     //
130     // Getter and Setter for 'shouldUpdateRevNumber'
131     //
132     public boolean getShouldUpdateRevNumber() {
133         return this.shouldUpdateRevNumber;
134     }
135     
136     public void setShouldUpdateRevNumber(boolean flag) {
137         this.shouldUpdateRevNumber = flag;
138     }
139
140     @Override
141     public void prepareSync() throws Exception {
142         this.setShouldUpdateRevNumber(AuthorityServiceUtils.DONT_UPDATE_REV);  // Never update rev nums on sync operations
143     }
144
145     @Override
146     protected String getRefnameDisplayName(DocumentWrapper<DocumentModel> docWrapper) {
147         String result = null;
148         
149         DocumentModel docModel = docWrapper.getWrappedObject();
150         ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = this.getServiceContext();
151         RefName.AuthorityItem refname = (RefName.AuthorityItem)getRefName(ctx, docModel);
152         result = refname.getDisplayName();
153         
154         return result;
155     }
156     
157     /*
158      * After calling this method successfully, the document model will contain an updated refname and short ID
159      * (non-Javadoc)
160      * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#getRefName(org.collectionspace.services.common.context.ServiceContext, org.nuxeo.ecm.core.api.DocumentModel)
161      */
162     @Override
163     public RefName.RefNameInterface getRefName(ServiceContext ctx,
164                 DocumentModel docModel) {
165         RefName.RefNameInterface refname = null;
166         
167         try {
168                 String displayName = getPrimaryDisplayName(docModel, authorityItemCommonSchemaName,
169                     getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
170                 if (Tools.isEmpty(displayName)) {
171                     throw new Exception("The displayName for this authority term was empty or not set.");
172                 }
173         
174                 String shortIdentifier = (String) docModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
175                 if (Tools.isEmpty(shortIdentifier)) {
176                         // We didn't find a short ID in the payload request, so we need to synthesize one.
177                         shortIdentifier = handleDisplayNameAsShortIdentifier(docModel); // updates the document model with the new short ID as a side-effect
178                 }
179                 
180                 String authorityRefBaseName = getAuthorityRefNameBase();
181                 if (Tools.isEmpty(authorityRefBaseName)) {
182                     throw new Exception("Could not create the refName for this authority term, because the refName for its authority parent was empty.");
183                 }
184                 
185                 // Create the items refname using the parent's as a base
186                 RefName.Authority parentsRefName = RefName.Authority.parse(authorityRefBaseName);
187                 refname = RefName.buildAuthorityItem(parentsRefName, shortIdentifier, displayName);
188                 // Now update the document model with the refname value
189                 String refNameStr = refname.toString();
190                 docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REF_NAME, refNameStr); // REM - This field is deprecated now that the refName is part of the collection_space core schema
191
192         } catch (Exception e) {
193                 logger.error(e.getMessage(), e);
194         }
195
196         return refname;
197     }
198     
199     public void setInAuthority(String inAuthority) {
200         this.inAuthority = inAuthority;
201     }
202     
203    public String getInAuthorityCsid() {
204         return this.inAuthority;
205     }
206
207     /** Subclasses may override this to customize the URI segment. */
208     public String getAuthorityServicePath() {
209         return getServiceContext().getServiceName().toLowerCase();    // Laramie20110510 CSPACE-3932
210     }
211
212     @Override
213     public String getUri(DocumentModel docModel) {
214         // Laramie20110510 CSPACE-3932
215         String authorityServicePath = getAuthorityServicePath();
216         if(inAuthority==null) { // Only true with the first document model received, on queries to wildcarded authorities
217             wildcardedAuthorityRequest = true;
218         }
219         // If this search crosses multiple authorities, get the inAuthority value
220         // from each record, rather than using the cached value from the first record
221         if(wildcardedAuthorityRequest) {
222                 try {
223                         inAuthority = (String) docModel.getProperty(authorityItemCommonSchemaName,
224                         AuthorityItemJAXBSchema.IN_AUTHORITY);
225                 } catch (ClientException pe) {
226                         throw new RuntimeException("Could not get parent specifier for item!");
227                 }
228         }
229         return "/" + authorityServicePath + '/' + inAuthority + '/' + AuthorityClient.ITEMS + '/' + getCsid(docModel);
230     }
231
232     protected String getAuthorityRefNameBase() {
233         return this.authorityRefNameBase;
234     }
235
236     public void setAuthorityRefNameBase(String value) {
237         this.authorityRefNameBase = value;
238     }
239
240     /*
241      * Note: the Vocabulary service's VocabularyItemDocumentModelHandler class overrides this method.
242      */
243     protected ListResultField getListResultsDisplayNameField() {
244         ListResultField result = new ListResultField();
245         // Per CSPACE-5132, the name of this element remains 'displayName'
246         // for backwards compatibility, although its value is obtained
247         // from the termDisplayName field.
248         //
249         // Update: this name is now being changed to 'termDisplayName', both
250         // because this is the actual field name and because the app layer
251         // work to convert over to this field is underway. Per Patrick, the
252         // app layer treats lists, in at least some context(s), as sparse record
253         // payloads, and thus fields in list results must all be present in
254         // (i.e. represent a strict subset of the fields in) record schemas.
255         // - ADR 2012-05-11
256         // 
257         //
258         // In CSPACE-5134, these list results will change substantially
259         // to return display names for both the preferred term and for
260         // each non-preferred term (if any).
261         result.setElement(AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
262         result.setXpath(NuxeoUtils.getPrimaryXPathPropertyName(
263                 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_DISPLAY_NAME));
264         
265         return result;
266     }
267     
268     /*
269      * Note: the Vocabulary service's VocabularyItemDocumentModelHandler class overrides this method.
270      */    
271     protected ListResultField getListResultsTermStatusField() {
272         ListResultField result = new ListResultField();
273         
274         result.setElement(AuthorityItemJAXBSchema.TERM_STATUS);
275         result.setXpath(NuxeoUtils.getPrimaryXPathPropertyName(
276                 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_STATUS));
277
278         return result;
279     }    
280     
281     private boolean isTermDisplayName(String elName) {
282         return AuthorityItemJAXBSchema.TERM_DISPLAY_NAME.equals(elName) || VocabularyItemJAXBSchema.DISPLAY_NAME.equals(elName);
283     }
284     
285     /*
286      * (non-Javadoc)
287      * @see org.collectionspace.services.nuxeo.client.java.DocHandlerBase#getListItemsArray()
288      * 
289      * Note: We're updating the "global" service and tenant bindings instance here -the list instance here is
290      * a reference to the tenant bindings instance in the singleton ServiceMain.
291      */
292     @Override
293     public List<ListResultField> getListItemsArray() throws DocumentException {
294         List<ListResultField> list = super.getListItemsArray();
295         
296         // One-time initialization for each authority item service.
297         if (isListItemArrayExtended() == false) {
298                 synchronized(AuthorityItemDocumentModelHandler.class) {
299                         if (isListItemArrayExtended() == false) {                               
300                         int nFields = list.size();
301                         // Ensure that each item in a list of Authority items includes
302                         // a set of common fields, so we do not depend upon configuration
303                         // for general logic.
304                         List<Integer> termDisplayNamePositionsInList = new ArrayList<>();
305                         boolean hasShortId = false;
306                         boolean hasTermStatus = false;
307                         for (int i = 0; i < nFields; i++) {
308                             ListResultField field = list.get(i);
309                             String elName = field.getElement();
310                             if (isTermDisplayName(elName) == true) {
311                                 termDisplayNamePositionsInList.add(i);
312                             } else if (AuthorityItemJAXBSchema.SHORT_IDENTIFIER.equals(elName)) {
313                                 hasShortId = true;
314                             } else if (AuthorityItemJAXBSchema.TERM_STATUS.equals(elName)) {
315                                 hasTermStatus = true;
316                             }
317                         }
318                                 
319                         ListResultField field;
320                         
321                         // Certain fields in authority item list results
322                         // are handled specially here
323                         
324                         // Term display name
325                         //
326                         // Ignore (throw out) any configuration entries that
327                         // specify how the termDisplayName field should be
328                         // emitted in authority item lists. This field will
329                         // be handled in a standardized manner (see block below).
330                         if (termDisplayNamePositionsInList.isEmpty() == false) {
331                             // Remove matching items starting at the end of the list
332                             // and moving towards the start, so that reshuffling of
333                             // list order doesn't alter the positions of earlier items
334                             Collections.sort(termDisplayNamePositionsInList, Collections.reverseOrder());
335                             for (int i : termDisplayNamePositionsInList) {
336                                 list.remove(i);
337                             }
338                         }
339                         // termDisplayName values in authority item lists
340                         // will be handled via code that emits display names
341                         // for both the preferred term and all non-preferred
342                         // terms (if any). The following is a placeholder
343                         // entry that will trigger this code. See the
344                         // getListResultValue() method in this class.
345                         field = getListResultsDisplayNameField();
346                         list.add(field);
347                         
348                         // Short identifier
349                         if (!hasShortId) {
350                             field = new ListResultField();
351                             field.setElement(AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
352                             field.setXpath(AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
353                             list.add(field);
354                         }
355                         
356                         // Term status
357                         if (!hasTermStatus) {
358                             field = getListResultsTermStatusField();
359                             list.add(field);
360                         }
361                         
362                         }
363      
364                         setListItemArrayExtended(true);
365                 } // end of synchronized block
366         }
367
368         return list;
369     }
370     
371     /**
372      * We consider workflow state changes as a change that should bump the revision number.
373      * Warning: This method might change the transitionDef's transtionName value
374      */
375     @Override
376     public void handleWorkflowTransition(DocumentWrapper<DocumentModel> wrapDoc, TransitionDef transitionDef) throws Exception {
377         // Decide whether or not to update the revision number
378         if (this.getShouldUpdateRevNumber() == true) { // We don't update the rev number of synchronization requests
379                 updateRevNumbers(wrapDoc);
380         }
381         
382         DocumentModel docModel = wrapDoc.getWrappedObject();
383         if (this.hasReferencingObjects(this.getServiceContext(), docModel) == true) {
384                 
385         }
386     }
387         
388     /**
389      * This method synchronizes/updates a single authority item resource.
390      * for the handleSync method, the wrapDoc argument contains a authority item specifier.
391      */
392     @Override
393     public boolean handleSync(DocumentWrapper<Object> wrapDoc) throws Exception {
394         boolean result = false;
395         ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
396         
397         //
398         // Get information about the local authority item so we can compare with corresponding item on the shared authority server
399         //
400         AuthorityItemSpecifier authorityItemSpecifier = (AuthorityItemSpecifier) wrapDoc.getWrappedObject();
401         DocumentModel itemDocModel = NuxeoUtils.getDocFromSpecifier(ctx, getRepositorySession(), getAuthorityItemCommonSchemaName(), 
402                         authorityItemSpecifier);
403         if (itemDocModel == null) {
404                 throw new DocumentNotFoundException(String.format("Could not find authority item resource with CSID='%s'",
405                                 authorityItemSpecifier.getItemSpecifier().value));
406         }
407         Long localItemRev = (Long) NuxeoUtils.getProperyValue(itemDocModel, AuthorityItemJAXBSchema.REV);
408         Boolean localIsProposed = (Boolean) NuxeoUtils.getProperyValue(itemDocModel, AuthorityItemJAXBSchema.PROPOSED);
409         String localItemCsid = itemDocModel.getName();
410         String localItemWorkflowState = itemDocModel.getCurrentLifeCycleState();
411         String itemShortId = (String) NuxeoUtils.getProperyValue(itemDocModel, AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
412         
413         //
414         // Now get the item's Authority (the parent) information
415         //
416         DocumentModel authorityDocModel = NuxeoUtils.getDocFromSpecifier(ctx, getRepositorySession(), authorityCommonSchemaName,
417                         authorityItemSpecifier.getParentSpecifier());
418         String authorityShortId = (String) NuxeoUtils.getProperyValue(authorityDocModel, AuthorityJAXBSchema.SHORT_IDENTIFIER);
419         String localParentCsid = authorityDocModel.getName();
420         //
421         // Using the short IDs of the local authority and item, create URN specifiers to retrieve the SAS authority item
422         //
423         AuthorityItemSpecifier sasAuthorityItemSpecifier = new AuthorityItemSpecifier(SpecifierForm.URN_NAME, authorityShortId, itemShortId);
424         // Get the shared authority server's copy
425         PoxPayloadIn sasPayloadIn = AuthorityServiceUtils.requestPayloadIn(sasAuthorityItemSpecifier, 
426                         getAuthorityServicePath(), getEntityResponseType());
427         Long sasRev = getRevision(sasPayloadIn);
428         String sasWorkflowState = getWorkflowState(sasPayloadIn);
429         //
430         // If the shared authority item is newer, update our local copy
431         //
432         if (sasRev > localItemRev || localIsProposed) {
433                 AuthorityResource authorityResource = (AuthorityResource) ctx.getResource(getAuthorityServicePath());
434                 PoxPayloadOut payloadOut = authorityResource.updateAuthorityItem(ctx, 
435                                 ctx.getResourceMap(),                                   
436                                 ctx.getUriInfo(),
437                                 localParentCsid,                                // parent's CSID
438                                 localItemCsid,                                  // item's CSID
439                                 sasPayloadIn,                                   // the payload from the remote SAS
440                                 AuthorityServiceUtils.DONT_UPDATE_REV,  // don't update the parent's revision number
441                                 AuthorityServiceUtils.NOT_PROPOSED);    // The items is not proposed, make it a real SAS item now
442                 if (payloadOut != null) {
443                         ctx.setOutput(payloadOut);
444                         result = true;
445                 }
446         }
447         //
448         // If the workflow states are different, we need to update the local's to reflects the remote's
449         //
450         if (localItemWorkflowState.equalsIgnoreCase(sasWorkflowState) == false) {
451                 AuthorityResource authorityResource = (AuthorityResource) ctx.getResource(getAuthorityServicePath()); // Get the authority (parent) client not the item client
452                 //
453                 // We need to move the local item to the SAS workflow state.  This might involve multiple transitions.
454                 //
455                 List<String> transitionList = getTransitionList(sasWorkflowState, localItemWorkflowState);
456                 for (String transition:transitionList) {
457                         if (transition.equalsIgnoreCase(WorkflowClient.WORKFLOWTRANSITION_DELETE) == true) {
458                                 if (hasReferencingObjects(ctx, itemDocModel)) {
459                                         throw new DocumentReferenceException(String.format("Cannot soft-delete authority item '%s' because it still has records in the system that are referencing it.  See the service layer log file for details.",
460                                                         itemDocModel.getName()));
461                                 }
462                         }
463                         authorityResource.updateItemWorkflowWithTransition(ctx, localParentCsid, localItemCsid, transition, AuthorityServiceUtils.DONT_UPDATE_REV);
464                 }
465                 result = true;
466         }
467         
468         return result;
469     }
470     
471     /**
472      * We need to move the local item to the SAS workflow state.  This might involve multiple transitions.
473      */
474     private List<String> getTransitionList(String sasWorkflowState, String localItemWorkflowState) {
475         List<String> result = new ArrayList<String>();
476         
477         //
478         // If the SAS authority items is soft-deleted, we need to mark the local item as soft-deleted
479         //
480         if (sasWorkflowState.contains(WorkflowClient.WORKFLOWSTATE_DELETED)) {
481                 result.add(WorkflowClient.WORKFLOWTRANSITION_DELETE);
482         } else if (sasWorkflowState.equalsIgnoreCase(WorkflowClient.WORKFLOWSTATE_PROJECT)) {
483                 result.add(WorkflowClient.WORKFLOWTRANSITION_UNDELETE);
484         }
485         
486         //
487         // Ensure the local item is always in a "locked" state.  Items sync'd with a SAS should always be locked
488         //
489         if (localItemWorkflowState.contains(WorkflowClient.WORKFLOWSTATE_LOCKED) != true) { // REM - This may be a bad assumption to make.
490                 result.add(WorkflowClient.WORKFLOWTRANSITION_LOCK);
491         }
492
493         return result;
494     }
495     
496     /* (non-Javadoc)
497      * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#handleCreate(org.collectionspace.services.common.document.DocumentWrapper)
498      */
499     @Override
500     public void handleCreate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
501         // first fill all the parts of the document, refname and short ID get set as well
502         super.handleCreate(wrapDoc);
503         // Ensure we have required fields set properly
504         handleInAuthority(wrapDoc.getWrappedObject());        
505     }
506
507     /*
508      * This method gets called after the primary update to an authority item has happened.  If the authority item's refName
509      * has changed, then we need to updated all the records that use that refname with the new/updated version
510      * 
511      * (non-Javadoc)
512      */
513     @Override
514     public void handleDelete(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
515         ServiceContext ctx = getServiceContext();
516         DocumentModel docModel = wrapDoc.getWrappedObject();
517         
518         if (hasReferencingObjects(ctx, docModel) == true) {
519                 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.",
520                                 docModel.getName()));
521         }
522     }
523     
524     /**
525      * Checks to see if an authority item has referencing objects.
526      * 
527      * @param ctx
528      * @param docModel
529      * @return
530      * @throws Exception
531      */
532     private boolean hasReferencingObjects(ServiceContext ctx, DocumentModel docModel) throws Exception {
533         boolean result = false;
534         
535         String inAuthorityCsid = (String) docModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.IN_AUTHORITY);
536         AuthorityResource authorityResource = (AuthorityResource)ctx.getResource(getAuthorityServicePath());
537         String itemCsid = docModel.getName();
538         UriTemplateRegistry uriTemplateRegistry = ServiceMain.getInstance().getUriTemplateRegistry();
539         AuthorityRefDocList refObjs = authorityResource.getReferencingObjects(ctx, inAuthorityCsid, itemCsid, 
540                         uriTemplateRegistry, ctx.getUriInfo());
541         
542         if (refObjs.getTotalItems() > 0) {
543                 result = true;
544                 logger.error(String.format("Cannot delete authority item '%s' because it still has %d records in the system that are referencing it.",
545                                 itemCsid, refObjs.getTotalItems()));
546                 logReferencingObjects(docModel, refObjs);
547         }
548         
549         return result;
550     }
551     
552     private void logReferencingObjects(DocumentModel docModel, AuthorityRefDocList refObjs) {
553         List<AuthorityRefDocList.AuthorityRefDocItem> items = refObjs.getAuthorityRefDocItem();
554         int i = 0;
555         for (AuthorityRefDocList.AuthorityRefDocItem item : items) {
556             logger.debug(docModel.getName() + ": list-item[" + i + "] "
557                     + item.getDocType() + "("
558                     + item.getDocId() + ") Name:["
559                     + item.getDocName() + "] Number:["
560                     + item.getDocNumber() + "] in field:["
561                     + item.getSourceField() + "]");
562         }
563     }
564
565     /*
566      * This method gets called after the primary update to an authority item has happened.  If the authority item's refName
567      * has changed, then we need to updated all the records that use that refname with the new/updated version
568      * 
569      * (non-Javadoc)
570      * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#completeUpdate(org.collectionspace.services.common.document.DocumentWrapper)
571      */
572     public void completeUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
573         // Must call our super class' version first
574         super.completeUpdate(wrapDoc);
575         
576         //
577         // Look for and update authority references with the updated refName
578         //
579         if (hasRefNameUpdate() == true) {
580             // We have work to do.
581             if (logger.isDebugEnabled()) {
582                 final String EOL = System.getProperty("line.separator");
583                 logger.debug("Need to find and update references to authority item." + EOL
584                         + "   Old refName" + oldRefNameOnUpdate + EOL
585                         + "   New refName" + newRefNameOnUpdate);
586             }
587             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
588             RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient = getRepositoryClient(ctx);
589             CoreSessionInterface repoSession = this.getRepositorySession();
590             
591             // Update all the existing records that have a field with the old refName in it
592             int nUpdated = RefNameServiceUtils.updateAuthorityRefDocs(ctx, repoClient, repoSession,
593                     oldRefNameOnUpdate, newRefNameOnUpdate, getRefPropName());
594             
595             // Finished so log a message.
596             if (logger.isDebugEnabled()) {
597                 logger.debug("Updated " + nUpdated + " instances of oldRefName to newRefName");
598             }
599         }
600     }
601     
602     /*
603      * Note that the Vocabulary service's document-model for items overrides this method.
604      */
605         protected String getPrimaryDisplayName(DocumentModel docModel, String schema,
606                         String complexPropertyName, String fieldName) {
607                 String result = null;
608
609                 result = getStringValueInPrimaryRepeatingComplexProperty(docModel, schema, complexPropertyName, fieldName);
610                 
611                 return result;
612         }
613     
614     /* (non-Javadoc)
615      * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#handleUpdate(org.collectionspace.services.common.document.DocumentWrapper)
616      */
617     @Override
618     // 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.
619     @Deprecated
620     public void handleUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
621         // Must call our super's version first, this updates the core schema and the relationship records to deal with possible refName changes/update
622         super.handleUpdate(wrapDoc);
623         if (this.hasRefNameUpdate() == true) {
624                 DocumentModel docModel = wrapDoc.getWrappedObject();
625             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                
626         }
627     }
628     
629     //
630     // Handles both update calls (PUTS) AND create calls (POSTS)
631     //
632     public void fillAllParts(DocumentWrapper<DocumentModel> wrapDoc, Action action) throws Exception {
633         super.fillAllParts(wrapDoc, action);
634         //
635         // Update the record's revision number on both CREATE and UPDATE actions
636         //
637         if (this.getShouldUpdateRevNumber() == true) { // We won't update rev numbers on synchronization with SAS
638                 updateRevNumbers(wrapDoc);
639         }
640         //
641         // If this is a proposed item (not part of the SAS), mark it as such
642         //
643         DocumentModel documentModel = wrapDoc.getWrappedObject();
644         documentModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.PROPOSED,
645                         new Boolean(this.getIsProposed()));
646     }
647     
648     /**
649      * Update the revision number of both the item and the item's parent.
650      * @param wrapDoc
651      * @throws Exception
652      */
653     protected void updateRevNumbers(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
654         DocumentModel documentModel = wrapDoc.getWrappedObject();
655         Long rev = (Long)documentModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REV);
656         if (rev == null) {
657                 rev = (long)0;
658         } else {
659                 rev++;
660         }
661         documentModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REV, rev);
662         //
663         // Next, update the inAuthority (the parent's) rev number
664         //
665         String inAuthorityCsid = this.getInAuthorityCsid();
666         if (inAuthorityCsid == null) {
667                 // When inAuthorityCsid is null, it usually means we're performing and update or synch with the SAS
668                 inAuthorityCsid = (String)documentModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.IN_AUTHORITY);
669         }
670         DocumentModel inAuthorityDocModel = NuxeoUtils.getDocFromCsid(getServiceContext(), getRepositorySession(), inAuthorityCsid);
671         Long parentRev = (Long)inAuthorityDocModel.getProperty(getParentCommonSchemaName(), AuthorityJAXBSchema.REV);
672         if (parentRev == null) {
673                 parentRev = new Long(0);
674         }
675                 parentRev++;
676                 inAuthorityDocModel.setProperty(getParentCommonSchemaName(), AuthorityJAXBSchema.REV, parentRev);
677                 getRepositorySession().saveDocument(inAuthorityDocModel);
678     }    
679     
680     /**
681      * If no short identifier was provided in the input payload, generate a
682      * short identifier from the preferred term display name or term name.
683      */
684         private String handleDisplayNameAsShortIdentifier(DocumentModel docModel) throws Exception {
685                 String result = (String) docModel.getProperty(authorityItemCommonSchemaName,
686                                 AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
687
688                 if (Tools.isEmpty(result)) {
689                         String termDisplayName = getPrimaryDisplayName(
690                                         docModel, authorityItemCommonSchemaName,
691                                         getItemTermInfoGroupXPathBase(),
692                                         AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
693
694                         String termName = getPrimaryDisplayName(
695                                         docModel, authorityItemCommonSchemaName,
696                                         getItemTermInfoGroupXPathBase(),
697                                         AuthorityItemJAXBSchema.TERM_NAME);
698
699                         String generatedShortIdentifier = AuthorityIdentifierUtils.generateShortIdentifierFromDisplayName(termDisplayName,
700                                                         termName);
701                         docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER,
702                                         generatedShortIdentifier);
703                         result = generatedShortIdentifier;
704                 }
705                 
706                 return result;
707         }
708
709     /**
710      * Generate a refName for the authority item from the short identifier
711      * and display name.
712      * 
713      * All refNames for authority items are generated.  If a client supplies
714      * a refName, it will be overwritten during create (per this method) 
715      * or discarded during update (per filterReadOnlyPropertiesForPart).
716      * 
717      * @see #filterReadOnlyPropertiesForPart(Map<String, Object>, org.collectionspace.services.common.service.ObjectPartType)
718      * 
719      */
720     protected String updateRefnameForAuthorityItem(DocumentModel docModel,
721             String schemaName) throws Exception {
722         String result = null;
723         
724         RefName.RefNameInterface refname = getRefName(getServiceContext(), docModel);
725         String refNameStr = refname.toString();
726         docModel.setProperty(schemaName, AuthorityItemJAXBSchema.REF_NAME, refNameStr);
727         result = refNameStr;
728         
729         return result;
730     }
731
732     /**
733      * Check the logic around the parent pointer. Note that we only need do this on
734      * create, since we have logic to make this read-only on update. 
735      * 
736      * @param docModel
737      * 
738      * @throws Exception the exception
739      */
740     private void handleInAuthority(DocumentModel docModel) throws Exception {
741         if(inAuthority==null) { // Only happens on queries to wildcarded authorities
742                 throw new IllegalStateException("Trying to Create an object with no inAuthority value!");
743         }
744         docModel.setProperty(authorityItemCommonSchemaName,
745                 AuthorityItemJAXBSchema.IN_AUTHORITY, inAuthority);
746     }
747     
748     /**
749      * Returns a list of records that reference this authority item
750      * 
751      * @param ctx
752      * @param uriTemplateRegistry
753      * @param serviceTypes
754      * @param propertyName
755      * @param itemcsid
756      * @return
757      * @throws Exception
758      */
759     public AuthorityRefDocList getReferencingObjects(
760                 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
761                 UriTemplateRegistry uriTemplateRegistry, 
762                 List<String> serviceTypes,
763                 String propertyName,
764             String itemcsid) throws Exception {
765         AuthorityRefDocList authRefDocList = null;
766         CoreSessionInterface repoSession = null;
767         boolean releaseRepoSession = false;
768         
769         try {
770                 RepositoryClientImpl repoClient = (RepositoryClientImpl)this.getRepositoryClient(ctx);
771                 repoSession = this.getRepositorySession();
772                 if (repoSession == null) {
773                         repoSession = repoClient.getRepositorySession(ctx);
774                         releaseRepoSession = true;
775                 }
776             DocumentFilter myFilter = getDocumentFilter();
777
778                 try {
779                         DocumentWrapper<DocumentModel> wrapper = repoClient.getDoc(repoSession, ctx, itemcsid);
780                         DocumentModel docModel = wrapper.getWrappedObject();
781                         String refName = (String) NuxeoUtils.getProperyValue(docModel, AuthorityItemJAXBSchema.REF_NAME); //docModel.getPropertyValue(AuthorityItemJAXBSchema.REF_NAME);
782                 authRefDocList = RefNameServiceUtils.getAuthorityRefDocs(
783                                 repoSession, ctx, uriTemplateRegistry, repoClient,
784                         serviceTypes,
785                         refName,
786                         propertyName,
787                         myFilter, true /*computeTotal*/);
788                 } catch (PropertyException pe) {
789                         throw pe;
790                 } catch (DocumentException de) {
791                         throw de;
792                 } catch (Exception e) {
793                         if (logger.isDebugEnabled()) {
794                                 logger.debug("Caught exception ", e);
795                         }
796                         throw new DocumentException(e);
797                 } finally {
798                         // If we got/aquired a new seesion then we're responsible for releasing it.
799                         if (releaseRepoSession && repoSession != null) {
800                                 repoClient.releaseRepositorySession(ctx, repoSession);
801                         }
802                 }
803         } catch (Exception e) {
804                 if (logger.isDebugEnabled()) {
805                         logger.debug("Caught exception ", e);
806                 }
807                 throw new DocumentException(e);
808         }
809         
810         return authRefDocList;
811     }
812
813     /* (non-Javadoc)
814      * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#extractPart(org.nuxeo.ecm.core.api.DocumentModel, java.lang.String, org.collectionspace.services.common.service.ObjectPartType)
815      */
816     @Override
817     protected Map<String, Object> extractPart(DocumentModel docModel, String schema, ObjectPartType partMeta)
818             throws Exception {
819         Map<String, Object> unQObjectProperties = super.extractPart(docModel, schema, partMeta);
820
821         // Add the CSID to the common part, since they may have fetched via the shortId.
822         if (partMeta.getLabel().equalsIgnoreCase(authorityItemCommonSchemaName)) {
823             String csid = getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
824             unQObjectProperties.put("csid", csid);
825         }
826
827         return unQObjectProperties;
828     }
829
830     /**
831      * Filters out selected values supplied in an update request.
832      * 
833      * For example, filters out AuthorityItemJAXBSchema.IN_AUTHORITY, to ensure
834      * that the link to the item's parent remains untouched.
835      * 
836      * @param objectProps the properties filtered out from the update payload
837      * @param partMeta metadata for the object to fill
838      */
839     @Override
840     public void filterReadOnlyPropertiesForPart(
841             Map<String, Object> objectProps, ObjectPartType partMeta) {
842         super.filterReadOnlyPropertiesForPart(objectProps, partMeta);
843         String commonPartLabel = getServiceContext().getCommonPartLabel();
844         if (partMeta.getLabel().equalsIgnoreCase(commonPartLabel)) {
845             objectProps.remove(AuthorityItemJAXBSchema.IN_AUTHORITY);
846             objectProps.remove(AuthorityItemJAXBSchema.CSID);
847             objectProps.remove(AuthorityJAXBSchema.SHORT_IDENTIFIER);
848             objectProps.remove(AuthorityItemJAXBSchema.REF_NAME);
849         }
850     }
851     
852     /**
853      * Returns the items in a list of term display names whose names contain
854      * a partial term (as might be submitted in a search query, for instance).
855      * @param termDisplayNameList a list of term display names.
856      * @param partialTerm a partial term display name; that is, a portion
857      * of a display name that might be expected to match 0-n terms in the list.
858      * @return a list of term display names that matches the partial term.
859      * Matches are case-insensitive. As well, before matching is performed, any
860      * special-purpose characters that may appear in the partial term (such as
861      * wildcards and anchor characters) are filtered out from both compared terms.
862      */
863     protected List<String> getPartialTermDisplayNameMatches(List<String> termDisplayNameList, String partialTerm) {
864         List<String> result = new ArrayList<>();
865         String partialTermMatchExpression = filterAnchorAndWildcardChars(partialTerm).toLowerCase();
866         try {
867             for (String termDisplayName : termDisplayNameList) {
868                 if (termDisplayName.toLowerCase()
869                         .matches(partialTermMatchExpression) == true) {
870                         result.add(termDisplayName);
871                 }
872             }
873         } catch (PatternSyntaxException pse) {
874             logger.warn("Error in regex match pattern '%s' for term display names: %s",
875                     partialTermMatchExpression, pse.getMessage());
876         }
877         return result;
878     }
879     
880     /**
881      * Filters user-supplied anchor and wildcard characters in a string,
882      * replacing them with equivalent regular expressions.
883      * @param term a term in which to filter anchor and wildcard characters.
884      * @return the term with those characters filtered.
885      */
886     protected String filterAnchorAndWildcardChars(String term) {
887         if (Tools.isBlank(term)) {
888             return term;
889         }
890         if (term.length() < 3) {
891             return term;
892         }
893         if (logger.isTraceEnabled()) {
894             logger.trace(String.format("Term = %s", term));
895         }
896         Boolean anchorAtStart = false;
897         Boolean anchorAtEnd = false;
898         String filteredTerm;
899         StringBuilder filteredTermBuilder = new StringBuilder(term);
900         // Term contains no anchor or wildcard characters.
901         if ( (! term.contains(RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR))
902                 && (! term.contains(RepositoryClientImpl.USER_SUPPLIED_WILDCARD)) ) {
903             filteredTerm = term;
904         } else {
905             // Term contains at least one such character.
906             try {
907                 // Filter the starting anchor or wildcard character, if any.
908                 String firstChar = filteredTermBuilder.substring(0,1);
909                 switch (firstChar) {
910                     case RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR:
911                         anchorAtStart = true;
912                         break;
913                     case RepositoryClientImpl.USER_SUPPLIED_WILDCARD:
914                         filteredTermBuilder.deleteCharAt(0);
915                         break;
916                 }
917                 if (logger.isTraceEnabled()) {
918                     logger.trace(String.format("After first char filtering = %s", filteredTermBuilder.toString()));
919                 }
920                 // Filter the ending anchor or wildcard character, if any.
921                 int lastPos = filteredTermBuilder.length() - 1;
922                 String lastChar = filteredTermBuilder.substring(lastPos);
923                 switch (lastChar) {
924                     case RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR:
925                         filteredTermBuilder.deleteCharAt(lastPos);
926                         filteredTermBuilder.insert(filteredTermBuilder.length(), RepositoryClientImpl.ENDING_ANCHOR_CHAR);
927                         anchorAtEnd = true;
928                         break;
929                     case RepositoryClientImpl.USER_SUPPLIED_WILDCARD:
930                         filteredTermBuilder.deleteCharAt(lastPos);
931                         break;
932                 }
933                 if (logger.isTraceEnabled()) {
934                     logger.trace(String.format("After last char filtering = %s", filteredTermBuilder.toString()));
935                 }
936                 filteredTerm = filteredTermBuilder.toString();
937                 // Filter all other wildcards, if any.
938                 filteredTerm = filteredTerm.replaceAll(RepositoryClientImpl.USER_SUPPLIED_WILDCARD_REGEX, ZERO_OR_MORE_ANY_CHAR_REGEX);
939                 if (logger.isTraceEnabled()) {
940                     logger.trace(String.format("After replacing user wildcards = %s", filteredTerm));
941                 }
942             } catch (Exception e) {
943                 logger.warn(String.format("Error filtering anchor and wildcard characters from string: %s", e.getMessage()));
944                 return term;
945             }
946         }
947         // Wrap the term in beginning and ending regex wildcards, unless a
948         // starting or ending anchor character was present.
949         return (anchorAtStart ? "" : ZERO_OR_MORE_ANY_CHAR_REGEX)
950                 + filteredTerm
951                 + (anchorAtEnd ? "" : ZERO_OR_MORE_ANY_CHAR_REGEX);
952     }
953     
954     @SuppressWarnings("unchecked")
955         private List<String> getPartialTermDisplayNameMatches(DocumentModel docModel, // REM - CSPACE-5133
956                         String schema, ListResultField field, String partialTerm) {
957         List<String> result = null;
958           
959         String xpath = field.getXpath(); // results in something like "persons_common:personTermGroupList/[0]/termDisplayName"
960         int endOfTermGroup = xpath.lastIndexOf("/[0]/");
961         String propertyName = endOfTermGroup != -1 ? xpath.substring(0, endOfTermGroup) : xpath; // it may not be multivalued so the xpath passed in would be the property name
962         Object value = null;
963         
964                 try {
965                         value = docModel.getProperty(schema, propertyName);
966                 } catch (Exception e) {
967                         logger.error("Could not extract term display name with property = "
968                                         + propertyName, e);
969                 }
970                 
971                 if (value != null && value instanceof ArrayList) {
972                         ArrayList<HashMap<String, Object>> termGroupList = (ArrayList<HashMap<String, Object>>)value;
973                         int arrayListSize = termGroupList.size();
974                         if (arrayListSize > 1) { // if there's only 1 element in the list then we've already matched the primary term's display name
975                                 List<String> displayNameList = new ArrayList<String>();
976                                 for (int i = 1; i < arrayListSize; i++) { // start at 1, skip the primary term's displayName since we will always return it
977                                         HashMap<String, Object> map = (HashMap<String, Object>)termGroupList.get(i);
978                                         String termDisplayName = (String) map.get(AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
979                                         displayNameList.add(i - 1, termDisplayName);
980                                 }
981                                 
982                                 result = getPartialTermDisplayNameMatches(displayNameList, partialTerm);
983                         }
984                 }
985
986         return result;
987     }
988
989     @Override
990         protected Object getListResultValue(DocumentModel docModel, // REM - CSPACE-5133
991                         String schema, ListResultField field) throws DocumentException {
992                 Object result = null;           
993
994                 result = NuxeoUtils.getXPathValue(docModel, schema, field.getXpath());
995                 
996                 //
997                 // Special handling of list item values for authority items (only)
998                 // takes place here:
999                 //
1000                 // If the list result field is the termDisplayName element,
1001                 // check whether a partial term matching query was made.
1002                 // If it was, emit values for both the preferred (aka primary)
1003                 // term and for all non-preferred terms, if any.
1004                 //
1005                 String elName = field.getElement();
1006                 if (isTermDisplayName(elName) == true) {
1007                         MultivaluedMap<String, String> queryParams = this.getServiceContext().getQueryParams();
1008                 String partialTerm = queryParams != null ? queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM) : null;
1009                 if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
1010                                 String primaryTermDisplayName = (String)result;
1011                         List<String> matches = getPartialTermDisplayNameMatches(docModel, schema, field, partialTerm);
1012                         if (matches != null && matches.isEmpty() == false) {
1013                                 matches.add(0, primaryTermDisplayName); // insert the primary term's display name at the beginning of the list
1014                                 result = matches; // set the result to a list of matching term display names with the primary term's display name at the beginning
1015                         }
1016                 }
1017                 }
1018                 
1019                 return result;
1020         }
1021     
1022     @Override
1023     public void extractAllParts(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
1024         MultipartServiceContext ctx = (MultipartServiceContext) getServiceContext();
1025         super.extractAllParts(wrapDoc);
1026     }
1027
1028     protected List<RelationsCommonList.RelationListItem> cloneList(List<RelationsCommonList.RelationListItem> inboundList) {
1029         List<RelationsCommonList.RelationListItem> result = newRelationsCommonList();
1030         for (RelationsCommonList.RelationListItem item : inboundList) {
1031             result.add(item);
1032         }
1033         return result;
1034     }
1035
1036
1037     /* don't even THINK of re-using this method.
1038      * String example_uri = "/locationauthorities/7ec60f01-84ab-4908-9a6a/items/a5466530-713f-43b4-bc05";
1039      */
1040     @Deprecated
1041     private String extractInAuthorityCSID(String uri) {
1042         String IN_AUTHORITY_REGEX = "/(.*?)/(.*?)/(.*)";
1043         Pattern p = Pattern.compile(IN_AUTHORITY_REGEX);
1044         Matcher m = p.matcher(uri);
1045         if (m.find()) {
1046             if (m.groupCount() < 3) {
1047                 logger.warn("REGEX-WRONG-GROUPCOUNT looking in " + uri);
1048                 return "";
1049             } else {
1050                 //String service = m.group(1);
1051                 String inauth = m.group(2);
1052                 //String theRest = m.group(3);
1053                 return inauth;
1054                 //print("service:"+service+", inauth:"+inauth+", rest:"+rest);
1055             }
1056         } else {
1057             logger.warn("REGEX-NOT-MATCHED looking in " + uri);
1058             return "";
1059         }
1060     }
1061
1062     //ensures CSPACE-4042
1063     protected void uriPointsToSameAuthority(String thisURI, String inboundItemURI) throws Exception {
1064         String authorityCSID = extractInAuthorityCSID(thisURI);
1065         String authorityCSIDForInbound = extractInAuthorityCSID(inboundItemURI);
1066         if (Tools.isBlank(authorityCSID)
1067                 || Tools.isBlank(authorityCSIDForInbound)
1068                 || (!authorityCSID.equalsIgnoreCase(authorityCSIDForInbound))) {
1069             throw new Exception("Item URI " + thisURI + " must point to same authority as related item: " + inboundItemURI);
1070         }
1071     }
1072
1073     public String getItemTermInfoGroupXPathBase() {
1074         return authorityItemTermGroupXPathBase;
1075     }
1076         
1077     public void setItemTermInfoGroupXPathBase(String itemTermInfoGroupXPathBase) {
1078         authorityItemTermGroupXPathBase = itemTermInfoGroupXPathBase;
1079     }
1080     
1081     protected String getAuthorityItemCommonSchemaName() {
1082         return authorityItemCommonSchemaName;
1083     }
1084     
1085     // @Override
1086     public boolean isJDBCQuery() {
1087         boolean result = false;
1088         
1089         MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams();
1090         //
1091         // Look the query params to see if we need to make a SQL query.
1092         //
1093         String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
1094         if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
1095                 result = true;
1096         }
1097         
1098         return result;
1099     }
1100     
1101     // By convention, the name of the database table that contains
1102     // repeatable term information group records is derivable from
1103     // an existing XPath base value, by removing a suffix and converting
1104     // to lowercase
1105     protected String getTermGroupTableName() {
1106         String termInfoGroupListName = getItemTermInfoGroupXPathBase();
1107         return termInfoGroupListName.substring(0, termInfoGroupListName.lastIndexOf(LIST_SUFFIX)).toLowerCase();
1108     }
1109     
1110     protected String getInAuthorityValue() {
1111         String inAuthorityValue = getInAuthorityCsid();
1112         if (Tools.notBlank(inAuthorityValue)) {
1113             return inAuthorityValue;
1114         } else {
1115             return AuthorityResource.PARENT_WILDCARD;
1116         }
1117     }
1118     
1119     @Override
1120     public Map<String,String> getJDBCQueryParams() {
1121         // FIXME: Get all of the following values from appropriate external constants.
1122         // At present, these are duplicated in both RepositoryClientImpl
1123         // and in AuthorityItemDocumentModelHandler.
1124         final String TERM_GROUP_LIST_NAME = "TERM_GROUP_LIST_NAME";
1125         final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
1126         final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
1127         
1128         Map<String,String> params = super.getJDBCQueryParams();
1129         params.put(TERM_GROUP_LIST_NAME, getItemTermInfoGroupXPathBase());
1130         params.put(TERM_GROUP_TABLE_NAME_PARAM, getTermGroupTableName());
1131         params.put(IN_AUTHORITY_PARAM, getInAuthorityValue());
1132         return params;
1133     }
1134     
1135 }