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