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