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