]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
3c4bc12d43df45e2eb1f3baa4187a9ac50107b0b
[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.PoxPayloadIn;
29 import org.collectionspace.services.client.PoxPayloadOut;
30
31 import org.collectionspace.services.common.UriTemplateRegistry;
32 import org.collectionspace.services.common.api.RefName;
33 import org.collectionspace.services.common.api.Tools;
34 import org.collectionspace.services.common.authorityref.AuthorityRefDocList;
35 import org.collectionspace.services.common.context.MultipartServiceContext;
36 import org.collectionspace.services.common.context.ServiceContext;
37 import org.collectionspace.services.common.document.DocumentException;
38 import org.collectionspace.services.common.document.DocumentFilter;
39 import org.collectionspace.services.common.document.DocumentWrapper;
40 import org.collectionspace.services.common.repository.RepositoryClient;
41 import org.collectionspace.services.common.vocabulary.AuthorityJAXBSchema;
42 import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema;
43 import org.collectionspace.services.common.vocabulary.AuthorityResource;
44 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils;
45
46 import org.collectionspace.services.config.service.ListResultField;
47 import org.collectionspace.services.config.service.ObjectPartType;
48
49 import org.collectionspace.services.nuxeo.client.java.DocHandlerBase;
50 import org.collectionspace.services.nuxeo.client.java.RepositoryJavaClientImpl;
51 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
52
53 import org.collectionspace.services.relation.RelationsCommonList;
54 import org.collectionspace.services.relation.RelationsDocListItem;
55
56 import org.collectionspace.services.vocabulary.VocabularyItemJAXBSchema;
57
58 import org.nuxeo.ecm.core.api.ClientException;
59 import org.nuxeo.ecm.core.api.DocumentModel;
60 import org.nuxeo.ecm.core.api.model.PropertyException;
61 import org.nuxeo.ecm.core.api.repository.RepositoryInstance;
62
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
65
66 import javax.ws.rs.core.MultivaluedMap;
67
68 import java.util.ArrayList;
69 import java.util.Collections;
70 import java.util.HashMap;
71 import java.util.List;
72 import java.util.Map;
73 import java.util.regex.Matcher;
74 import java.util.regex.Pattern;
75
76 //import org.collectionspace.services.common.authority.AuthorityItemRelations;
77 /**
78  * AuthorityItemDocumentModelHandler
79  *
80  * $LastChangedRevision: $
81  * $LastChangedDate: $
82  */
83 public abstract class AuthorityItemDocumentModelHandler<AICommon>
84         extends DocHandlerBase<AICommon> {
85
86     private final Logger logger = LoggerFactory.getLogger(AuthorityItemDocumentModelHandler.class);
87     private String authorityItemCommonSchemaName;
88     private String authorityItemTermGroupXPathBase;
89     /**
90      * inVocabulary is the parent Authority for this context
91      */
92     protected String inAuthority = null;
93     protected boolean wildcardedAuthorityRequest = false;
94     protected String authorityRefNameBase = null;
95     // Used to determine when the displayName changes as part of the update.
96     protected String oldDisplayNameOnUpdate = null;
97     private final static String LIST_SUFFIX = "List";
98
99     public AuthorityItemDocumentModelHandler(String authorityItemCommonSchemaName) {
100         this.authorityItemCommonSchemaName = authorityItemCommonSchemaName;
101     }
102
103     @Override
104     protected String getRefnameDisplayName(DocumentWrapper<DocumentModel> docWrapper) {
105         String result = null;
106         
107         DocumentModel docModel = docWrapper.getWrappedObject();
108         ServiceContext ctx = this.getServiceContext();
109         RefName.AuthorityItem refname = (RefName.AuthorityItem)getRefName(ctx, docModel);
110         result = refname.getDisplayName();
111         
112         return result;
113     }
114     
115     /*
116      * After calling this method successfully, the document model will contain an updated refname and short ID
117      * (non-Javadoc)
118      * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#getRefName(org.collectionspace.services.common.context.ServiceContext, org.nuxeo.ecm.core.api.DocumentModel)
119      */
120     @Override
121     public RefName.RefNameInterface getRefName(ServiceContext ctx,
122                 DocumentModel docModel) {
123         RefName.RefNameInterface refname = null;
124         
125         try {
126                 String displayName = getPrimaryDisplayName(docModel, authorityItemCommonSchemaName,
127                     getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
128                 if (Tools.isEmpty(displayName)) {
129                     throw new Exception("The displayName for this authority term was empty or not set.");
130                 }
131         
132                 String shortIdentifier = (String) docModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
133                 if (Tools.isEmpty(shortIdentifier)) {
134                         // We didn't find a short ID in the payload request, so we need to synthesize one.
135                         shortIdentifier = handleDisplayNameAsShortIdentifier(docModel); // updates the document model with the new short ID as a side-effect
136                 }
137                 
138                 String authorityRefBaseName = getAuthorityRefNameBase();
139                 if (Tools.isEmpty(authorityRefBaseName)) {
140                     throw new Exception("Could not create the refName for this authority term, because the refName for its authority parent was empty.");
141                 }
142                 
143                 // Create the items refname using the parent's as a base
144                 RefName.Authority parentsRefName = RefName.Authority.parse(authorityRefBaseName);
145                 refname = RefName.buildAuthorityItem(parentsRefName, shortIdentifier, displayName);
146                 // Now update the document model with the refname value
147                 String refNameStr = refname.toString();
148                 docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REF_NAME, refNameStr); // REM - This field is deprecated now that the refName is part of the collection_space core schema
149
150         } catch (Exception e) {
151                 logger.error(e.getMessage(), e);
152         }
153
154         return refname;
155     }
156     
157     public void setInAuthority(String inAuthority) {
158         this.inAuthority = inAuthority;
159     }
160     
161    public String getInAuthority() {
162         return this.inAuthority;
163     }
164
165     /** Subclasses may override this to customize the URI segment. */
166     public String getAuthorityServicePath() {
167         return getServiceContext().getServiceName().toLowerCase();    // Laramie20110510 CSPACE-3932
168     }
169
170     @Override
171     public String getUri(DocumentModel docModel) {
172         // Laramie20110510 CSPACE-3932
173         String authorityServicePath = getAuthorityServicePath();
174         if(inAuthority==null) { // Only true with the first document model received, on queries to wildcarded authorities
175             wildcardedAuthorityRequest = true;
176         }
177         // If this search crosses multiple authorities, get the inAuthority value
178         // from each record, rather than using the cached value from the first record
179         if(wildcardedAuthorityRequest) {
180                 try {
181                         inAuthority = (String) docModel.getProperty(authorityItemCommonSchemaName,
182                         AuthorityItemJAXBSchema.IN_AUTHORITY);
183                 } catch (ClientException pe) {
184                         throw new RuntimeException("Could not get parent specifier for item!");
185                 }
186         }
187         return "/" + authorityServicePath + '/' + inAuthority + '/' + AuthorityClient.ITEMS + '/' + getCsid(docModel);
188     }
189
190     protected String getAuthorityRefNameBase() {
191         return this.authorityRefNameBase;
192     }
193
194     public void setAuthorityRefNameBase(String value) {
195         this.authorityRefNameBase = value;
196     }
197
198     /*
199      * Note: the Vocabulary service's VocabularyItemDocumentModelHandler class overrides this method.
200      */
201     protected ListResultField getListResultsDisplayNameField() {
202         ListResultField result = new ListResultField();
203         // Per CSPACE-5132, the name of this element remains 'displayName'
204         // for backwards compatibility, although its value is obtained
205         // from the termDisplayName field.
206         //
207         // Update: this name is now being changed to 'termDisplayName', both
208         // because this is the actual field name and because the app layer
209         // work to convert over to this field is underway. Per Patrick, the
210         // app layer treats lists, in at least some context(s), as sparse record
211         // payloads, and thus fields in list results must all be present in
212         // (i.e. represent a strict subset of the fields in) record schemas.
213         // - ADR 2012-05-11
214         // 
215         //
216         // In CSPACE-5134, these list results will change substantially
217         // to return display names for both the preferred term and for
218         // each non-preferred term (if any).
219         result.setElement(AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
220         result.setXpath(NuxeoUtils.getPrimaryXPathPropertyName(
221                 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_DISPLAY_NAME));
222         
223         return result;
224     }
225     
226     /*
227      * Note: the Vocabulary service's VocabularyItemDocumentModelHandler class overrides this method.
228      */    
229     protected ListResultField getListResultsTermStatusField() {
230         ListResultField result = new ListResultField();
231         
232         result.setElement(AuthorityItemJAXBSchema.TERM_STATUS);
233         result.setXpath(NuxeoUtils.getPrimaryXPathPropertyName(
234                 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_STATUS));
235
236         return result;
237     }    
238     
239     private boolean isTermDisplayName(String elName) {
240         return AuthorityItemJAXBSchema.TERM_DISPLAY_NAME.equals(elName) || VocabularyItemJAXBSchema.DISPLAY_NAME.equals(elName);
241     }
242     
243     /*
244      * (non-Javadoc)
245      * @see org.collectionspace.services.nuxeo.client.java.DocHandlerBase#getListItemsArray()
246      * 
247      * Note: We're updating the "global" service and tenant bindings instance here -the list instance here is
248      * a reference to the tenant bindings instance in the singleton ServiceMain.
249      */
250     @Override
251     public List<ListResultField> getListItemsArray() throws DocumentException {
252         List<ListResultField> list = super.getListItemsArray();
253         
254         // One-time initialization for each authority item service.
255         if (isListItemArrayExtended() == false) {
256                 synchronized(AuthorityItemDocumentModelHandler.class) {
257                         if (isListItemArrayExtended() == false) {                               
258                         int nFields = list.size();
259                         // Ensure that each item in a list of Authority items includes
260                         // a set of common fields, so we do not depend upon configuration
261                         // for general logic.
262                         List<Integer> termDisplayNamePositionsInList = new ArrayList<>();;
263                         boolean hasShortId = false;
264                         boolean hasTermStatus = false;
265                         for (int i = 0; i < nFields; i++) {
266                             ListResultField field = list.get(i);
267                             String elName = field.getElement();
268                             if (isTermDisplayName(elName) == true) {
269                                 termDisplayNamePositionsInList.add(i);
270                             } else if (AuthorityItemJAXBSchema.SHORT_IDENTIFIER.equals(elName)) {
271                                 hasShortId = true;
272                             } else if (AuthorityItemJAXBSchema.TERM_STATUS.equals(elName)) {
273                                 hasTermStatus = true;
274                             }
275                         }
276                                 
277                         ListResultField field;
278                         // Ignore (throw out) any configuration entries that
279                         // specify how the termDisplayName field should be
280                         // emitted in authority item lists. This field will
281                         // be handled specially (see block below).
282                         if (termDisplayNamePositionsInList.isEmpty() == false) {
283                             // Remove matching items starting at the end of the list
284                             // and moving towards the start, so that reshuffling of
285                             // list order doesn't alter the positions of earlier items
286                             Collections.sort(termDisplayNamePositionsInList, Collections.reverseOrder());
287                             for (int i : termDisplayNamePositionsInList) {
288                                 list.remove(i);
289                             }
290                         }
291                         // Specially handle termDisplayName values in authority
292                         // item lists, by invoking code that emits display names
293                         // for both preferred and non-preferred terms
294                         field = getListResultsDisplayNameField();
295                         list.add(field);
296                         if (!hasShortId) {
297                             field = new ListResultField();
298                             field.setElement(AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
299                             field.setXpath(AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
300                             list.add(field);
301                         }
302                         if (!hasTermStatus) {
303                             field = getListResultsTermStatusField();
304                             list.add(field);
305                         }
306                         }
307                         
308                         setListItemArrayExtended(true);
309                 } // end of synchronized block
310         }
311
312         return list;
313     }
314     
315     /* (non-Javadoc)
316      * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#handleCreate(org.collectionspace.services.common.document.DocumentWrapper)
317      */
318     @Override
319     public void handleCreate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
320         // first fill all the parts of the document, refname and short ID get set as well
321         super.handleCreate(wrapDoc);
322         // Ensure we have required fields set properly
323         handleInAuthority(wrapDoc.getWrappedObject());        
324     }
325
326     /*
327      * This method gets called after the primary update to an authority item has happened.  If the authority item's refName
328      * has changed, then we need to updated all the records that use that refname with the new/updated version
329      * 
330      * (non-Javadoc)
331      * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#completeUpdate(org.collectionspace.services.common.document.DocumentWrapper)
332      */
333     public void completeUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
334         // Must call our super class' version first
335         super.completeUpdate(wrapDoc);
336         
337         //
338         // Look for and update authority references with the updated refName
339         //
340         if (hasRefNameUpdate() == true) {
341             // We have work to do.
342             if (logger.isDebugEnabled()) {
343                 final String EOL = System.getProperty("line.separator");
344                 logger.debug("Need to find and update references to authority item." + EOL
345                         + "   Old refName" + oldRefNameOnUpdate + EOL
346                         + "   New refName" + newRefNameOnUpdate);
347             }
348             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
349             RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient = getRepositoryClient(ctx);
350             RepositoryInstance repoSession = this.getRepositorySession();
351             
352             // Update all the existing records that have a field with the old refName in it
353             int nUpdated = RefNameServiceUtils.updateAuthorityRefDocs(ctx, repoClient, repoSession,
354                     oldRefNameOnUpdate, newRefNameOnUpdate, getRefPropName());
355             
356             // Finished so log a message.
357             if (logger.isDebugEnabled()) {
358                 logger.debug("Updated " + nUpdated + " instances of oldRefName to newRefName");
359             }
360         }
361     }
362     
363     /*
364      * Note that the Vocabulary service's document-model for items overrides this method.
365      */
366         protected String getPrimaryDisplayName(DocumentModel docModel, String schema,
367                         String complexPropertyName, String fieldName) {
368                 String result = null;
369
370                 result = getStringValueInPrimaryRepeatingComplexProperty(docModel, schema, complexPropertyName, fieldName);
371                 
372                 return result;
373         }
374     
375     /* (non-Javadoc)
376      * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#handleUpdate(org.collectionspace.services.common.document.DocumentWrapper)
377      */
378     @Override
379     // 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.
380     @Deprecated
381     public void handleUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
382         // Must call our super's version first, this updates the core schema and the relationship records to deal with possible refName changes/update
383         super.handleUpdate(wrapDoc);
384         if (this.hasRefNameUpdate() == true) {
385                 DocumentModel docModel = wrapDoc.getWrappedObject();
386             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                
387         }
388     }
389     
390     /**
391      * If no short identifier was provided in the input payload, generate a
392      * short identifier from the preferred term display name or term name.
393      */
394         private String handleDisplayNameAsShortIdentifier(DocumentModel docModel) throws Exception {
395                 String result = (String) docModel.getProperty(authorityItemCommonSchemaName,
396                                 AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
397
398                 if (Tools.isEmpty(result)) {
399                         String termDisplayName = getPrimaryDisplayName(
400                                         docModel, authorityItemCommonSchemaName,
401                                         getItemTermInfoGroupXPathBase(),
402                                         AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
403
404                         String termName = getPrimaryDisplayName(
405                                         docModel, authorityItemCommonSchemaName,
406                                         getItemTermInfoGroupXPathBase(),
407                                         AuthorityItemJAXBSchema.TERM_NAME);
408
409                         String generatedShortIdentifier = AuthorityIdentifierUtils.generateShortIdentifierFromDisplayName(termDisplayName,
410                                                         termName);
411                         docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER,
412                                         generatedShortIdentifier);
413                         result = generatedShortIdentifier;
414                 }
415                 
416                 return result;
417         }
418
419     /**
420      * Generate a refName for the authority item from the short identifier
421      * and display name.
422      * 
423      * All refNames for authority items are generated.  If a client supplies
424      * a refName, it will be overwritten during create (per this method) 
425      * or discarded during update (per filterReadOnlyPropertiesForPart).
426      * 
427      * @see #filterReadOnlyPropertiesForPart(Map<String, Object>, org.collectionspace.services.common.service.ObjectPartType)
428      * 
429      */
430     protected String updateRefnameForAuthorityItem(DocumentModel docModel,
431             String schemaName) throws Exception {
432         String result = null;
433         
434         RefName.RefNameInterface refname = getRefName(getServiceContext(), docModel);
435         String refNameStr = refname.toString();
436         docModel.setProperty(schemaName, AuthorityItemJAXBSchema.REF_NAME, refNameStr);
437         result = refNameStr;
438         
439         return result;
440     }
441
442     /**
443      * Check the logic around the parent pointer. Note that we only need do this on
444      * create, since we have logic to make this read-only on update. 
445      * 
446      * @param docModel
447      * 
448      * @throws Exception the exception
449      */
450     private void handleInAuthority(DocumentModel docModel) throws Exception {
451         if(inAuthority==null) { // Only happens on queries to wildcarded authorities
452                 throw new IllegalStateException("Trying to Create an object with no inAuthority value!");
453         }
454         docModel.setProperty(authorityItemCommonSchemaName,
455                 AuthorityItemJAXBSchema.IN_AUTHORITY, inAuthority);
456     }
457     
458     public AuthorityRefDocList getReferencingObjects(
459                 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
460                 UriTemplateRegistry uriTemplateRegistry, 
461                 List<String> serviceTypes,
462                 String propertyName,
463             String itemcsid) throws Exception {
464         AuthorityRefDocList authRefDocList = null;
465         RepositoryInstance repoSession = null;
466         boolean releaseRepoSession = false;
467         
468         try {
469                 RepositoryJavaClientImpl repoClient = (RepositoryJavaClientImpl)this.getRepositoryClient(ctx);
470                 repoSession = this.getRepositorySession();
471                 if (repoSession == null) {
472                         repoSession = repoClient.getRepositorySession(ctx);
473                         releaseRepoSession = true;
474                 }
475             DocumentFilter myFilter = getDocumentFilter();
476
477                 try {
478                         DocumentWrapper<DocumentModel> wrapper = repoClient.getDoc(repoSession, ctx, itemcsid);
479                         DocumentModel docModel = wrapper.getWrappedObject();
480                         String refName = (String) docModel.getPropertyValue(AuthorityItemJAXBSchema.REF_NAME);
481                 authRefDocList = RefNameServiceUtils.getAuthorityRefDocs(
482                                 repoSession, ctx, uriTemplateRegistry, repoClient,
483                         serviceTypes,
484                         refName,
485                         propertyName,
486                         myFilter, true /*computeTotal*/);
487                 } catch (PropertyException pe) {
488                         throw pe;
489                 } catch (DocumentException de) {
490                         throw de;
491                 } catch (Exception e) {
492                         if (logger.isDebugEnabled()) {
493                                 logger.debug("Caught exception ", e);
494                         }
495                         throw new DocumentException(e);
496                 } finally {
497                         // If we got/aquired a new seesion then we're responsible for releasing it.
498                         if (releaseRepoSession && repoSession != null) {
499                                 repoClient.releaseRepositorySession(ctx, repoSession);
500                         }
501                 }
502         } catch (Exception e) {
503                 if (logger.isDebugEnabled()) {
504                         logger.debug("Caught exception ", e);
505                 }
506                 throw new DocumentException(e);
507         }
508         
509         return authRefDocList;
510     }
511
512     /* (non-Javadoc)
513      * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#extractPart(org.nuxeo.ecm.core.api.DocumentModel, java.lang.String, org.collectionspace.services.common.service.ObjectPartType)
514      */
515     @Override
516     protected Map<String, Object> extractPart(DocumentModel docModel, String schema, ObjectPartType partMeta)
517             throws Exception {
518         Map<String, Object> unQObjectProperties = super.extractPart(docModel, schema, partMeta);
519
520         // Add the CSID to the common part, since they may have fetched via the shortId.
521         if (partMeta.getLabel().equalsIgnoreCase(authorityItemCommonSchemaName)) {
522             String csid = getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
523             unQObjectProperties.put("csid", csid);
524         }
525
526         return unQObjectProperties;
527     }
528
529     /**
530      * Filters out selected values supplied in an update request.
531      * 
532      * For example, filters out AuthorityItemJAXBSchema.IN_AUTHORITY, to ensure
533      * that the link to the item's parent remains untouched.
534      * 
535      * @param objectProps the properties filtered out from the update payload
536      * @param partMeta metadata for the object to fill
537      */
538     @Override
539     public void filterReadOnlyPropertiesForPart(
540             Map<String, Object> objectProps, ObjectPartType partMeta) {
541         super.filterReadOnlyPropertiesForPart(objectProps, partMeta);
542         String commonPartLabel = getServiceContext().getCommonPartLabel();
543         if (partMeta.getLabel().equalsIgnoreCase(commonPartLabel)) {
544             objectProps.remove(AuthorityItemJAXBSchema.IN_AUTHORITY);
545             objectProps.remove(AuthorityItemJAXBSchema.CSID);
546             objectProps.remove(AuthorityJAXBSchema.SHORT_IDENTIFIER);
547             objectProps.remove(AuthorityItemJAXBSchema.REF_NAME);
548         }
549     }
550     
551     protected List<String> getPartialTermDisplayNameMatches(List<String> termDisplayNameList, String partialTerm) {
552         List<String> result = new ArrayList<String>();
553         
554         for (String termDisplayName : termDisplayNameList) {
555                 if (termDisplayName.toLowerCase().contains(partialTerm.toLowerCase()) == true) {
556                         result.add(termDisplayName);
557                 }
558         }
559         
560         return result;
561     }
562     
563     @SuppressWarnings("unchecked")
564         private List<String> getPartialTermDisplayNameMatches(DocumentModel docModel, // REM - CSPACE-5133
565                         String schema, ListResultField field, String partialTerm) {
566         List<String> result = null;
567           
568         String xpath = field.getXpath(); // results in something like "persons_common:personTermGroupList/[0]/termDisplayName"
569         int endOfTermGroup = xpath.lastIndexOf("/[0]/");
570         String propertyName = endOfTermGroup != -1 ? xpath.substring(0, endOfTermGroup) : xpath; // it may not be multivalued so the xpath passed in would be the property name
571         Object value = null;
572         
573                 try {
574                         value = docModel.getProperty(schema, propertyName);
575                 } catch (Exception e) {
576                         logger.error("Could not extract term display name with property = "
577                                         + propertyName, e);
578                 }
579                 
580                 if (value != null && value instanceof ArrayList) {
581                         ArrayList<HashMap<String, Object>> termGroupList = (ArrayList<HashMap<String, Object>>)value;
582                         int arrayListSize = termGroupList.size();
583                         if (arrayListSize > 1) { // if there's only 1 element in the list then we've already matched the primary term's display name
584                                 List<String> displayNameList = new ArrayList<String>();
585                                 for (int i = 1; i < arrayListSize; i++) { // start at 1, skip the primary term's displayName since we will always return it
586                                         HashMap<String, Object> map = (HashMap<String, Object>)termGroupList.get(i);
587                                         String termDisplayName = (String) map.get(AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
588                                         displayNameList.add(i - 1, termDisplayName);
589                                 }
590                                 
591                                 result = getPartialTermDisplayNameMatches(displayNameList, partialTerm);
592                         }
593                 }
594
595         return result;
596     }
597
598     @Override
599         protected Object getListResultValue(DocumentModel docModel, // REM - CSPACE-5133
600                         String schema, ListResultField field) {
601                 Object result = null;           
602
603                 result = NuxeoUtils.getXPathValue(docModel, schema, field.getXpath());
604                 
605                 //
606                 // Special handling of list item values for authority items (only)
607                 // takes place here:
608                 //
609                 // If the list result field is the termDisplayName element,
610                 // check whether a partial term matching query was made.
611                 // If it was, emit values for both the preferred (aka primary)
612                 // term and for all non-preferred terms, if any.
613                 //
614                 String elName = field.getElement();
615                 if (isTermDisplayName(elName) == true) {
616                         MultivaluedMap<String, String> queryParams = this.getServiceContext().getQueryParams();
617                 String partialTerm = queryParams != null ? queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM) : null;
618                 if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
619                                 String primaryTermDisplayName = (String)result;
620                         List<String> matches = getPartialTermDisplayNameMatches(docModel, schema, field, partialTerm);
621                         if (matches != null && matches.isEmpty() == false) {
622                                 matches.add(0, primaryTermDisplayName); // insert the primary term's display name at the beginning of the list
623                                 result = matches; // set the result to a list of matching term display names with the primary term's display name at the beginning
624                         }
625                 }
626                 }
627                 
628                 return result;
629         }
630     
631     @Override
632     public void extractAllParts(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
633         MultipartServiceContext ctx = (MultipartServiceContext) getServiceContext();
634         super.extractAllParts(wrapDoc);
635     }
636
637     @Override
638     public void fillAllParts(DocumentWrapper<DocumentModel> wrapDoc, Action action) throws Exception {
639         //
640         // We currently don't override this method with any AuthorityItemDocumentModelHandler specific functionality, so
641         // we could remove this method.
642         //
643         super.fillAllParts(wrapDoc, action);
644     }
645
646     protected List<RelationsCommonList.RelationListItem> cloneList(List<RelationsCommonList.RelationListItem> inboundList) {
647         List<RelationsCommonList.RelationListItem> result = newRelationsCommonList();
648         for (RelationsCommonList.RelationListItem item : inboundList) {
649             result.add(item);
650         }
651         return result;
652     }
653
654
655     /* don't even THINK of re-using this method.
656      * String example_uri = "/locationauthorities/7ec60f01-84ab-4908-9a6a/items/a5466530-713f-43b4-bc05";
657      */
658     @Deprecated
659     private String extractInAuthorityCSID(String uri) {
660         String IN_AUTHORITY_REGEX = "/(.*?)/(.*?)/(.*)";
661         Pattern p = Pattern.compile(IN_AUTHORITY_REGEX);
662         Matcher m = p.matcher(uri);
663         if (m.find()) {
664             if (m.groupCount() < 3) {
665                 logger.warn("REGEX-WRONG-GROUPCOUNT looking in " + uri);
666                 return "";
667             } else {
668                 //String service = m.group(1);
669                 String inauth = m.group(2);
670                 //String theRest = m.group(3);
671                 return inauth;
672                 //print("service:"+service+", inauth:"+inauth+", rest:"+rest);
673             }
674         } else {
675             logger.warn("REGEX-NOT-MATCHED looking in " + uri);
676             return "";
677         }
678     }
679
680     //ensures CSPACE-4042
681     protected void uriPointsToSameAuthority(String thisURI, String inboundItemURI) throws Exception {
682         String authorityCSID = extractInAuthorityCSID(thisURI);
683         String authorityCSIDForInbound = extractInAuthorityCSID(inboundItemURI);
684         if (Tools.isBlank(authorityCSID)
685                 || Tools.isBlank(authorityCSIDForInbound)
686                 || (!authorityCSID.equalsIgnoreCase(authorityCSIDForInbound))) {
687             throw new Exception("Item URI " + thisURI + " must point to same authority as related item: " + inboundItemURI);
688         }
689     }
690
691     public String getItemTermInfoGroupXPathBase() {
692         return authorityItemTermGroupXPathBase;
693     }
694         
695     public void setItemTermInfoGroupXPathBase(String itemTermInfoGroupXPathBase) {
696         authorityItemTermGroupXPathBase = itemTermInfoGroupXPathBase;
697     }
698     
699     protected String getAuthorityItemCommonSchemaName() {
700         return authorityItemCommonSchemaName;
701     }
702     
703     // @Override
704     public boolean isJDBCQuery() {
705         boolean result = false;
706         
707         MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams();
708         //
709         // Look the query params to see if we need to make a SQL query.
710         //
711         String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
712         if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
713                 result = true;
714         }
715         
716         return result;
717     }
718     
719     // By convention, the name of the database table that contains
720     // repeatable term information group records is derivable from
721     // an existing XPath base value, by removing a suffix and converting
722     // to lowercase
723     protected String getTermGroupTableName() {
724         String termInfoGroupListName = getItemTermInfoGroupXPathBase();
725         return termInfoGroupListName.substring(0, termInfoGroupListName.lastIndexOf(LIST_SUFFIX)).toLowerCase();
726     }
727     
728     protected String getInAuthorityValue() {
729         String inAuthorityValue = getInAuthority();
730         if (Tools.notBlank(inAuthorityValue)) {
731             return inAuthorityValue;
732         } else {
733             return AuthorityResource.PARENT_WILDCARD;
734         }
735     }
736     
737     @Override
738     public Map<String,String> getJDBCQueryParams() {
739         // FIXME: Get all of the following values from appropriate external constants.
740         // At present, these are duplicated in both RepositoryJavaClientImpl
741         // and in AuthorityItemDocumentModelHandler.
742         final String TERM_GROUP_LIST_NAME = "TERM_GROUP_LIST_NAME";
743         final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
744         final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
745         
746         Map<String,String> params = super.getJDBCQueryParams();
747         params.put(TERM_GROUP_LIST_NAME, getItemTermInfoGroupXPathBase());
748         params.put(TERM_GROUP_TABLE_NAME_PARAM, getTermGroupTableName());
749         params.put(IN_AUTHORITY_PARAM, getInAuthorityValue());
750         return params;
751     }
752     
753 }