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