]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
e6a71b397a61e052a5f8b13e1f3434d506f94cdd
[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.CommonAPI;
33 import org.collectionspace.services.common.api.RefName;
34 import org.collectionspace.services.common.api.Tools;
35 import org.collectionspace.services.common.authorityref.AuthorityRefDocList;
36 import org.collectionspace.services.common.context.MultipartServiceContext;
37 import org.collectionspace.services.common.context.ServiceContext;
38 import org.collectionspace.services.common.document.DocumentException;
39 import org.collectionspace.services.common.document.DocumentFilter;
40 import org.collectionspace.services.common.document.DocumentWrapper;
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);
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      * Note that the Vocabulary service's document-model for items overrides this method.
301      */
302         protected String getPrimaryDisplayName(DocumentModel docModel, String schema,
303                         String complexPropertyName, String fieldName) {
304                 String result = null;
305
306                 result = getStringValueInPrimaryRepeatingComplexProperty(docModel, schema, complexPropertyName, fieldName);
307                 
308                 return result;
309         }
310     
311     /* (non-Javadoc)
312      * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#handleUpdate(org.collectionspace.services.common.document.DocumentWrapper)
313      */
314     @Override
315     public void handleUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
316         // First, get a copy of the old displayName
317         // oldDisplayNameOnUpdate = (String) wrapDoc.getWrappedObject().getProperty(authorityItemCommonSchemaName,
318         //        AuthorityItemJAXBSchema.DISPLAY_NAME);
319         oldDisplayNameOnUpdate = getPrimaryDisplayName(wrapDoc.getWrappedObject(), authorityItemCommonSchemaName,
320                 getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
321         oldRefNameOnUpdate = (String) wrapDoc.getWrappedObject().getProperty(authorityItemCommonSchemaName,
322                 AuthorityItemJAXBSchema.REF_NAME);
323         super.handleUpdate(wrapDoc);
324
325         // Now, check the new display and handle the refname update.
326         String newDisplayName = (String) getPrimaryDisplayName(wrapDoc.getWrappedObject(), authorityItemCommonSchemaName,
327                 authorityItemTermGroupXPathBase,
328                 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
329         if (newDisplayName != null && !newDisplayName.equals(oldDisplayNameOnUpdate)) {
330             // Need to update the refName, and then fix all references.
331             newRefNameOnUpdate = handleItemRefNameUpdateForDisplayName(wrapDoc.getWrappedObject(), newDisplayName);
332         } else {
333             // Mark as not needing attention in completeUpdate phase.
334             newRefNameOnUpdate = null;
335             oldRefNameOnUpdate = null;
336         }
337     }
338
339     /**
340      * Handle refName updates for changes to display name.
341      * Assumes refName is already correct. Just ensures it is right.
342      *
343      * @param docModel the doc model
344      * @param newDisplayName the new display name
345      * @throws Exception the exception
346      */
347     protected String handleItemRefNameUpdateForDisplayName(DocumentModel docModel,
348             String newDisplayName) throws Exception {
349         RefName.AuthorityItem authItem = RefName.AuthorityItem.parse(oldRefNameOnUpdate);
350         if (authItem == null) {
351             String err = "Authority Item has illegal refName: " + oldRefNameOnUpdate;
352             logger.debug(err);
353             throw new IllegalArgumentException(err);
354         }
355         authItem.displayName = newDisplayName;
356         String updatedRefName = authItem.toString();
357         docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REF_NAME, updatedRefName);
358         return updatedRefName;
359     }
360     
361     /**
362      * If no short identifier was provided in the input payload, generate a
363      * short identifier from the preferred term display name or term name.
364      */
365         private String handleDisplayNameAsShortIdentifier(DocumentModel docModel) throws Exception {
366                 String result = (String) docModel.getProperty(authorityItemCommonSchemaName,
367                                 AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
368
369                 if (Tools.isEmpty(result)) {
370                         String termDisplayName = getPrimaryDisplayName(
371                                         docModel, authorityItemCommonSchemaName,
372                                         getItemTermInfoGroupXPathBase(),
373                                         AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
374
375                         String termName = getPrimaryDisplayName(
376                                         docModel, authorityItemCommonSchemaName,
377                                         getItemTermInfoGroupXPathBase(),
378                                         AuthorityItemJAXBSchema.TERM_NAME);
379
380                         String generatedShortIdentifier = AuthorityIdentifierUtils.generateShortIdentifierFromDisplayName(termDisplayName,
381                                                         termName);
382                         docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER,
383                                         generatedShortIdentifier);
384                         result = generatedShortIdentifier;
385                 }
386                 
387                 return result;
388         }
389
390     /**
391      * Generate a refName for the authority item from the short identifier
392      * and display name.
393      * 
394      * All refNames for authority items are generated.  If a client supplies
395      * a refName, it will be overwritten during create (per this method) 
396      * or discarded during update (per filterReadOnlyPropertiesForPart).
397      * 
398      * @see #filterReadOnlyPropertiesForPart(Map<String, Object>, org.collectionspace.services.common.service.ObjectPartType)
399      * 
400      */
401     protected String updateRefnameForAuthorityItem(DocumentModel docModel,
402             String schemaName) throws Exception {
403         String result = null;
404         
405         RefName.RefNameInterface refname = getRefName(getServiceContext(), docModel);
406         String refNameStr = refname.toString();
407         docModel.setProperty(schemaName, AuthorityItemJAXBSchema.REF_NAME, refNameStr);
408         result = refNameStr;
409         
410         return result;
411     }
412
413     /**
414      * Check the logic around the parent pointer. Note that we only need do this on
415      * create, since we have logic to make this read-only on update. 
416      * 
417      * @param docModel
418      * 
419      * @throws Exception the exception
420      */
421     private void handleInAuthority(DocumentModel docModel) throws Exception {
422         if(inAuthority==null) { // Only happens on queries to wildcarded authorities
423                 throw new IllegalStateException("Trying to Create an object with no inAuthority value!");
424         }
425         docModel.setProperty(authorityItemCommonSchemaName,
426                 AuthorityItemJAXBSchema.IN_AUTHORITY, inAuthority);
427     }
428     
429     public AuthorityRefDocList getReferencingObjects(
430                 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
431                 UriTemplateRegistry uriTemplateRegistry, 
432                 List<String> serviceTypes,
433                 String propertyName,
434             String itemcsid) throws Exception {
435         AuthorityRefDocList authRefDocList = null;
436         RepositoryInstance repoSession = null;
437         boolean releaseRepoSession = false;
438         
439         try {
440                 RepositoryJavaClientImpl repoClient = (RepositoryJavaClientImpl)this.getRepositoryClient(ctx);
441                 repoSession = this.getRepositorySession();
442                 if (repoSession == null) {
443                         repoSession = repoClient.getRepositorySession(ctx);
444                         releaseRepoSession = true;
445                 }
446             DocumentFilter myFilter = getDocumentFilter();
447
448                 try {
449                         DocumentWrapper<DocumentModel> wrapper = repoClient.getDoc(repoSession, ctx, itemcsid);
450                         DocumentModel docModel = wrapper.getWrappedObject();
451                         String refName = (String) docModel.getPropertyValue(AuthorityItemJAXBSchema.REF_NAME);
452                 authRefDocList = RefNameServiceUtils.getAuthorityRefDocs(
453                                 repoSession, ctx, uriTemplateRegistry, repoClient,
454                         serviceTypes,
455                         refName,
456                         propertyName,
457                         myFilter, true /*computeTotal*/);
458                 } catch (PropertyException pe) {
459                         throw pe;
460                 } catch (DocumentException de) {
461                         throw de;
462                 } catch (Exception e) {
463                         if (logger.isDebugEnabled()) {
464                                 logger.debug("Caught exception ", e);
465                         }
466                         throw new DocumentException(e);
467                 } finally {
468                         // If we got/aquired a new seesion then we're responsible for releasing it.
469                         if (releaseRepoSession && repoSession != null) {
470                                 repoClient.releaseRepositorySession(ctx, repoSession);
471                         }
472                 }
473         } catch (Exception e) {
474                 if (logger.isDebugEnabled()) {
475                         logger.debug("Caught exception ", e);
476                 }
477                 throw new DocumentException(e);
478         }
479         
480         return authRefDocList;
481     }
482
483     /* (non-Javadoc)
484      * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#extractPart(org.nuxeo.ecm.core.api.DocumentModel, java.lang.String, org.collectionspace.services.common.service.ObjectPartType)
485      */
486     @Override
487     protected Map<String, Object> extractPart(DocumentModel docModel, String schema, ObjectPartType partMeta)
488             throws Exception {
489         Map<String, Object> unQObjectProperties = super.extractPart(docModel, schema, partMeta);
490
491         // Add the CSID to the common part, since they may have fetched via the shortId.
492         if (partMeta.getLabel().equalsIgnoreCase(authorityItemCommonSchemaName)) {
493             String csid = getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
494             unQObjectProperties.put("csid", csid);
495         }
496
497         return unQObjectProperties;
498     }
499
500     /**
501      * Filters out selected values supplied in an update request.
502      * 
503      * For example, filters out AuthorityItemJAXBSchema.IN_AUTHORITY, to ensure
504      * that the link to the item's parent remains untouched.
505      * 
506      * @param objectProps the properties filtered out from the update payload
507      * @param partMeta metadata for the object to fill
508      */
509     @Override
510     public void filterReadOnlyPropertiesForPart(
511             Map<String, Object> objectProps, ObjectPartType partMeta) {
512         super.filterReadOnlyPropertiesForPart(objectProps, partMeta);
513         String commonPartLabel = getServiceContext().getCommonPartLabel();
514         if (partMeta.getLabel().equalsIgnoreCase(commonPartLabel)) {
515             objectProps.remove(AuthorityItemJAXBSchema.IN_AUTHORITY);
516             objectProps.remove(AuthorityItemJAXBSchema.CSID);
517             objectProps.remove(AuthorityJAXBSchema.SHORT_IDENTIFIER);
518             objectProps.remove(AuthorityItemJAXBSchema.REF_NAME);
519         }
520     }
521     
522     protected List<String> getPartialTermDisplayNameMatches(List<String> termDisplayNameList, String partialTerm) {
523         List<String> result = new ArrayList<String>();
524         
525         for (String termDisplayName : termDisplayNameList) {
526                 if (termDisplayName.toLowerCase().contains(partialTerm.toLowerCase()) == true) {
527                         result.add(termDisplayName);
528                 }
529         }
530         
531         return result;
532     }
533     
534     @SuppressWarnings("unchecked")
535         private List<String> getPartialTermDisplayNameMatches(DocumentModel docModel, // REM - CSPACE-5133
536                         String schema, ListResultField field, String partialTerm) {
537         List<String> result = null;
538           
539         String xpath = field.getXpath(); // results in something like "persons_common:personTermGroupList/[0]/termDisplayName"
540         int endOfTermGroup = xpath.lastIndexOf("/[0]/");
541         String propertyName = endOfTermGroup != -1 ? xpath.substring(0, endOfTermGroup) : xpath; // it may not be multivalued so the xpath passed in would be the property name
542         Object value = null;
543         
544                 try {
545                         value = docModel.getProperty(schema, propertyName);
546                 } catch (Exception e) {
547                         logger.error("Could not extract term display name with property = "
548                                         + propertyName, e);
549                 }
550                 
551                 if (value != null && value instanceof ArrayList) {
552                         ArrayList<HashMap<String, Object>> termGroupList = (ArrayList<HashMap<String, Object>>)value;
553                         int arrayListSize = termGroupList.size();
554                         if (arrayListSize > 1) { // if there's only 1 element in the list then we've already matched the primary term's display name
555                                 List<String> displayNameList = new ArrayList<String>();
556                                 for (int i = 1; i < arrayListSize; i++) { // start at 1, skip the primary term's displayName since we will always return it
557                                         HashMap<String, Object> map = (HashMap<String, Object>)termGroupList.get(i);
558                                         String termDisplayName = (String) map.get(AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
559                                         displayNameList.add(i - 1, termDisplayName);
560                                 }
561                                 
562                                 result = getPartialTermDisplayNameMatches(displayNameList, partialTerm);
563                         }
564                 }
565
566         return result;
567     }
568
569     @Override
570         protected Object getListResultValue(DocumentModel docModel, // REM - CSPACE-5133
571                         String schema, ListResultField field) {
572                 Object result = null;           
573
574                 result = NuxeoUtils.getXPathValue(docModel, schema, field.getXpath());
575                 String elName = field.getElement();
576                 //
577                 // If the list result value is the termDisplayName element, we need to check to see if a partial term query was made.
578                 //
579                 if (isTermDisplayName(elName) == true) {
580                         MultivaluedMap<String, String> queryParams = this.getServiceContext().getQueryParams();
581                 String partialTerm = queryParams != null ? queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM) : null;
582                 if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
583                                 String primaryTermDisplayName = (String)result;
584                         List<String> matches = getPartialTermDisplayNameMatches(docModel, schema, field, partialTerm);
585                         if (matches != null && matches.isEmpty() == false) {
586                                 matches.add(0, primaryTermDisplayName); // insert the primary term's display name at the beginning of the list
587                                 result = matches; // set the result to a list of matching term display names with the primary term's display name at the beginning
588                         }
589                 }
590                 }
591                 
592                 return result;
593         }
594     
595     @Override
596     public void extractAllParts(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
597         MultipartServiceContext ctx = (MultipartServiceContext) getServiceContext();
598         super.extractAllParts(wrapDoc);
599     }
600
601     @Override
602     public void fillAllParts(DocumentWrapper<DocumentModel> wrapDoc, Action action) throws Exception {
603         //
604         // We currently don't override this method with any AuthorityItemDocumentModelHandler specific functionality, so
605         // we could remove this method.
606         //
607         super.fillAllParts(wrapDoc, action);
608     }
609
610     protected List<RelationsCommonList.RelationListItem> cloneList(List<RelationsCommonList.RelationListItem> inboundList) {
611         List<RelationsCommonList.RelationListItem> result = newRelationsCommonList();
612         for (RelationsCommonList.RelationListItem item : inboundList) {
613             result.add(item);
614         }
615         return result;
616     }
617
618     // Note that item2 may be sparse (only refName, no CSID for subject or object)
619     // But item1 must not be sparse 
620     private boolean itemsEqual(RelationsCommonList.RelationListItem item1, RelationsCommonList.RelationListItem item2) {
621         if (item1 == null || item2 == null) {
622             return false;
623         }
624         RelationsDocListItem subj1 = item1.getSubject();
625         RelationsDocListItem subj2 = item2.getSubject();
626         RelationsDocListItem obj1 = item1.getObject();
627         RelationsDocListItem obj2 = item2.getObject();
628         String subj1Csid = subj1.getCsid();
629         String subj2Csid = subj2.getCsid();
630         String subj1RefName = subj1.getRefName();
631         String subj2RefName = subj2.getRefName();
632
633         String obj1Csid = obj1.getCsid();
634         String obj2Csid = obj2.getCsid();
635         String obj1RefName = obj1.getRefName();
636         String obj2RefName = obj2.getRefName();
637
638         boolean isEqual = 
639                            (subj1Csid.equals(subj2Csid) || ((subj2Csid==null)  && subj1RefName.equals(subj2RefName)))
640                 && (obj1Csid.equals(obj1Csid)   || ((obj2Csid==null)   && obj1RefName.equals(obj2RefName)))
641                 // predicate is proper, but still allow relationshipType
642                 && (item1.getPredicate().equals(item2.getPredicate())
643                         ||  ((item2.getPredicate()==null)  && item1.getRelationshipType().equals(item2.getRelationshipType())))
644                 // Allow missing docTypes, so long as they do not conflict
645                 && (obj1.getDocumentType().equals(obj2.getDocumentType()) || obj2.getDocumentType()==null)
646                 && (subj1.getDocumentType().equals(subj2.getDocumentType()) || subj2.getDocumentType()==null);
647         return isEqual;
648     }
649
650
651     /* don't even THINK of re-using this method.
652      * String example_uri = "/locationauthorities/7ec60f01-84ab-4908-9a6a/items/a5466530-713f-43b4-bc05";
653      */
654     private String extractInAuthorityCSID(String uri) {
655         String IN_AUTHORITY_REGEX = "/(.*?)/(.*?)/(.*)";
656         Pattern p = Pattern.compile(IN_AUTHORITY_REGEX);
657         Matcher m = p.matcher(uri);
658         if (m.find()) {
659             if (m.groupCount() < 3) {
660                 logger.warn("REGEX-WRONG-GROUPCOUNT looking in " + uri);
661                 return "";
662             } else {
663                 //String service = m.group(1);
664                 String inauth = m.group(2);
665                 //String theRest = m.group(3);
666                 return inauth;
667                 //print("service:"+service+", inauth:"+inauth+", rest:"+rest);
668             }
669         } else {
670             logger.warn("REGEX-NOT-MATCHED looking in " + uri);
671             return "";
672         }
673     }
674
675     //ensures CSPACE-4042
676     protected void uriPointsToSameAuthority(String thisURI, String inboundItemURI) throws Exception {
677         String authorityCSID = extractInAuthorityCSID(thisURI);
678         String authorityCSIDForInbound = extractInAuthorityCSID(inboundItemURI);
679         if (Tools.isBlank(authorityCSID)
680                 || Tools.isBlank(authorityCSIDForInbound)
681                 || (!authorityCSID.equalsIgnoreCase(authorityCSIDForInbound))) {
682             throw new Exception("Item URI " + thisURI + " must point to same authority as related item: " + inboundItemURI);
683         }
684     }
685
686     public String getItemTermInfoGroupXPathBase() {
687         return authorityItemTermGroupXPathBase;
688     }
689         
690     public void setItemTermInfoGroupXPathBase(String itemTermInfoGroupXPathBase) {
691         authorityItemTermGroupXPathBase = itemTermInfoGroupXPathBase;
692     }
693     
694     protected String getAuthorityItemCommonSchemaName() {
695         return authorityItemCommonSchemaName;
696     }
697 }