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