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