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