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