]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
075c15624d515f3973c88cf26396c4ee722b9721
[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.NuxeoDocumentModelHandler;
47 import org.collectionspace.services.nuxeo.client.java.CoreSessionInterface;
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.vocabulary.VocabularyItemJAXBSchema;
52 import org.nuxeo.ecm.core.api.ClientException;
53 import org.nuxeo.ecm.core.api.DocumentModel;
54 import org.nuxeo.ecm.core.api.model.PropertyException;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57
58 import javax.ws.rs.core.MultivaluedMap;
59
60 import java.util.ArrayList;
61 import java.util.Collections;
62 import java.util.HashMap;
63 import java.util.List;
64 import java.util.Map;
65 import java.util.regex.Matcher;
66 import java.util.regex.Pattern;
67 import java.util.regex.PatternSyntaxException;
68
69 //import org.collectionspace.services.common.authority.AuthorityItemRelations;
70 /**
71  * AuthorityItemDocumentModelHandler
72  *
73  * $LastChangedRevision: $
74  * $LastChangedDate: $
75  */
76 public abstract class AuthorityItemDocumentModelHandler<AICommon>
77         extends NuxeoDocumentModelHandler<AICommon> {
78
79     private final Logger logger = LoggerFactory.getLogger(AuthorityItemDocumentModelHandler.class);
80     private String authorityItemCommonSchemaName;
81     private String authorityItemTermGroupXPathBase;
82     /**
83      * inVocabulary is the parent Authority for this context
84      */
85     protected String inAuthority = null;
86     protected boolean wildcardedAuthorityRequest = false;
87     protected String authorityRefNameBase = null;
88     // Used to determine when the displayName changes as part of the update.
89     protected String oldDisplayNameOnUpdate = null;
90     private final static String LIST_SUFFIX = "List";
91     private final static String ZERO_OR_MORE_ANY_CHAR_REGEX = ".*";
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<PoxPayloadIn, PoxPayloadOut> 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             CoreSessionInterface 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         CoreSessionInterface 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) NuxeoUtils.getProperyValue(docModel, AuthorityItemJAXBSchema.REF_NAME); //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     /**
560      * Returns the items in a list of term display names whose names contain
561      * a partial term (as might be submitted in a search query, for instance).
562      * @param termDisplayNameList a list of term display names.
563      * @param partialTerm a partial term display name; that is, a portion
564      * of a display name that might be expected to match 0-n terms in the list.
565      * @return a list of term display names that matches the partial term.
566      * Matches are case-insensitive. As well, before matching is performed, any
567      * special-purpose characters that may appear in the partial term (such as
568      * wildcards and anchor characters) are filtered out from both compared terms.
569      */
570     protected List<String> getPartialTermDisplayNameMatches(List<String> termDisplayNameList, String partialTerm) {
571         List<String> result = new ArrayList<>();
572         String partialTermMatchExpression = filterAnchorAndWildcardChars(partialTerm).toLowerCase();
573         try {
574             for (String termDisplayName : termDisplayNameList) {
575                 if (termDisplayName.toLowerCase()
576                         .matches(partialTermMatchExpression) == true) {
577                         result.add(termDisplayName);
578                 }
579             }
580         } catch (PatternSyntaxException pse) {
581             logger.warn("Error in regex match pattern '%s' for term display names: %s",
582                     partialTermMatchExpression, pse.getMessage());
583         }
584         return result;
585     }
586     
587     /**
588      * Filters user-supplied anchor and wildcard characters in a string,
589      * replacing them with equivalent regular expressions.
590      * @param term a term in which to filter anchor and wildcard characters.
591      * @return the term with those characters filtered.
592      */
593     protected String filterAnchorAndWildcardChars(String term) {
594         if (Tools.isBlank(term)) {
595             return term;
596         }
597         if (term.length() < 3) {
598             return term;
599         }
600         if (logger.isTraceEnabled()) {
601             logger.trace(String.format("Term = %s", term));
602         }
603         Boolean anchorAtStart = false;
604         Boolean anchorAtEnd = false;
605         String filteredTerm;
606         StringBuilder filteredTermBuilder = new StringBuilder(term);
607         // Term contains no anchor or wildcard characters.
608         if ( (! term.contains(RepositoryJavaClientImpl.USER_SUPPLIED_ANCHOR_CHAR))
609                 && (! term.contains(RepositoryJavaClientImpl.USER_SUPPLIED_WILDCARD)) ) {
610             filteredTerm = term;
611         } else {
612             // Term contains at least one such character.
613             try {
614                 // Filter the starting anchor or wildcard character, if any.
615                 String firstChar = filteredTermBuilder.substring(0,1);
616                 switch (firstChar) {
617                     case RepositoryJavaClientImpl.USER_SUPPLIED_ANCHOR_CHAR:
618                         anchorAtStart = true;
619                         break;
620                     case RepositoryJavaClientImpl.USER_SUPPLIED_WILDCARD:
621                         filteredTermBuilder.deleteCharAt(0);
622                         break;
623                 }
624                 if (logger.isTraceEnabled()) {
625                     logger.trace(String.format("After first char filtering = %s", filteredTermBuilder.toString()));
626                 }
627                 // Filter the ending anchor or wildcard character, if any.
628                 int lastPos = filteredTermBuilder.length() - 1;
629                 String lastChar = filteredTermBuilder.substring(lastPos);
630                 switch (lastChar) {
631                     case RepositoryJavaClientImpl.USER_SUPPLIED_ANCHOR_CHAR:
632                         filteredTermBuilder.deleteCharAt(lastPos);
633                         filteredTermBuilder.insert(filteredTermBuilder.length(), RepositoryJavaClientImpl.ENDING_ANCHOR_CHAR);
634                         anchorAtEnd = true;
635                         break;
636                     case RepositoryJavaClientImpl.USER_SUPPLIED_WILDCARD:
637                         filteredTermBuilder.deleteCharAt(lastPos);
638                         break;
639                 }
640                 if (logger.isTraceEnabled()) {
641                     logger.trace(String.format("After last char filtering = %s", filteredTermBuilder.toString()));
642                 }
643                 filteredTerm = filteredTermBuilder.toString();
644                 // Filter all other wildcards, if any.
645                 filteredTerm = filteredTerm.replaceAll(RepositoryJavaClientImpl.USER_SUPPLIED_WILDCARD_REGEX, ZERO_OR_MORE_ANY_CHAR_REGEX);
646                 if (logger.isTraceEnabled()) {
647                     logger.trace(String.format("After replacing user wildcards = %s", filteredTerm));
648                 }
649             } catch (Exception e) {
650                 logger.warn(String.format("Error filtering anchor and wildcard characters from string: %s", e.getMessage()));
651                 return term;
652             }
653         }
654         // Wrap the term in beginning and ending regex wildcards, unless a
655         // starting or ending anchor character was present.
656         return (anchorAtStart ? "" : ZERO_OR_MORE_ANY_CHAR_REGEX)
657                 + filteredTerm
658                 + (anchorAtEnd ? "" : ZERO_OR_MORE_ANY_CHAR_REGEX);
659     }
660     
661     @SuppressWarnings("unchecked")
662         private List<String> getPartialTermDisplayNameMatches(DocumentModel docModel, // REM - CSPACE-5133
663                         String schema, ListResultField field, String partialTerm) {
664         List<String> result = null;
665           
666         String xpath = field.getXpath(); // results in something like "persons_common:personTermGroupList/[0]/termDisplayName"
667         int endOfTermGroup = xpath.lastIndexOf("/[0]/");
668         String propertyName = endOfTermGroup != -1 ? xpath.substring(0, endOfTermGroup) : xpath; // it may not be multivalued so the xpath passed in would be the property name
669         Object value = null;
670         
671                 try {
672                         value = docModel.getProperty(schema, propertyName);
673                 } catch (Exception e) {
674                         logger.error("Could not extract term display name with property = "
675                                         + propertyName, e);
676                 }
677                 
678                 if (value != null && value instanceof ArrayList) {
679                         ArrayList<HashMap<String, Object>> termGroupList = (ArrayList<HashMap<String, Object>>)value;
680                         int arrayListSize = termGroupList.size();
681                         if (arrayListSize > 1) { // if there's only 1 element in the list then we've already matched the primary term's display name
682                                 List<String> displayNameList = new ArrayList<String>();
683                                 for (int i = 1; i < arrayListSize; i++) { // start at 1, skip the primary term's displayName since we will always return it
684                                         HashMap<String, Object> map = (HashMap<String, Object>)termGroupList.get(i);
685                                         String termDisplayName = (String) map.get(AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
686                                         displayNameList.add(i - 1, termDisplayName);
687                                 }
688                                 
689                                 result = getPartialTermDisplayNameMatches(displayNameList, partialTerm);
690                         }
691                 }
692
693         return result;
694     }
695
696     @Override
697         protected Object getListResultValue(DocumentModel docModel, // REM - CSPACE-5133
698                         String schema, ListResultField field) throws DocumentException {
699                 Object result = null;           
700
701                 result = NuxeoUtils.getXPathValue(docModel, schema, field.getXpath());
702                 
703                 //
704                 // Special handling of list item values for authority items (only)
705                 // takes place here:
706                 //
707                 // If the list result field is the termDisplayName element,
708                 // check whether a partial term matching query was made.
709                 // If it was, emit values for both the preferred (aka primary)
710                 // term and for all non-preferred terms, if any.
711                 //
712                 String elName = field.getElement();
713                 if (isTermDisplayName(elName) == true) {
714                         MultivaluedMap<String, String> queryParams = this.getServiceContext().getQueryParams();
715                 String partialTerm = queryParams != null ? queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM) : null;
716                 if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
717                                 String primaryTermDisplayName = (String)result;
718                         List<String> matches = getPartialTermDisplayNameMatches(docModel, schema, field, partialTerm);
719                         if (matches != null && matches.isEmpty() == false) {
720                                 matches.add(0, primaryTermDisplayName); // insert the primary term's display name at the beginning of the list
721                                 result = matches; // set the result to a list of matching term display names with the primary term's display name at the beginning
722                         }
723                 }
724                 }
725                 
726                 return result;
727         }
728     
729     @Override
730     public void extractAllParts(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
731         MultipartServiceContext ctx = (MultipartServiceContext) getServiceContext();
732         super.extractAllParts(wrapDoc);
733     }
734
735     @Override
736     public void fillAllParts(DocumentWrapper<DocumentModel> wrapDoc, Action action) throws Exception {
737         //
738         // We currently don't override this method with any AuthorityItemDocumentModelHandler specific functionality, so
739         // we could remove this method.
740         //
741         super.fillAllParts(wrapDoc, action);
742     }
743
744     protected List<RelationsCommonList.RelationListItem> cloneList(List<RelationsCommonList.RelationListItem> inboundList) {
745         List<RelationsCommonList.RelationListItem> result = newRelationsCommonList();
746         for (RelationsCommonList.RelationListItem item : inboundList) {
747             result.add(item);
748         }
749         return result;
750     }
751
752
753     /* don't even THINK of re-using this method.
754      * String example_uri = "/locationauthorities/7ec60f01-84ab-4908-9a6a/items/a5466530-713f-43b4-bc05";
755      */
756     @Deprecated
757     private String extractInAuthorityCSID(String uri) {
758         String IN_AUTHORITY_REGEX = "/(.*?)/(.*?)/(.*)";
759         Pattern p = Pattern.compile(IN_AUTHORITY_REGEX);
760         Matcher m = p.matcher(uri);
761         if (m.find()) {
762             if (m.groupCount() < 3) {
763                 logger.warn("REGEX-WRONG-GROUPCOUNT looking in " + uri);
764                 return "";
765             } else {
766                 //String service = m.group(1);
767                 String inauth = m.group(2);
768                 //String theRest = m.group(3);
769                 return inauth;
770                 //print("service:"+service+", inauth:"+inauth+", rest:"+rest);
771             }
772         } else {
773             logger.warn("REGEX-NOT-MATCHED looking in " + uri);
774             return "";
775         }
776     }
777
778     //ensures CSPACE-4042
779     protected void uriPointsToSameAuthority(String thisURI, String inboundItemURI) throws Exception {
780         String authorityCSID = extractInAuthorityCSID(thisURI);
781         String authorityCSIDForInbound = extractInAuthorityCSID(inboundItemURI);
782         if (Tools.isBlank(authorityCSID)
783                 || Tools.isBlank(authorityCSIDForInbound)
784                 || (!authorityCSID.equalsIgnoreCase(authorityCSIDForInbound))) {
785             throw new Exception("Item URI " + thisURI + " must point to same authority as related item: " + inboundItemURI);
786         }
787     }
788
789     public String getItemTermInfoGroupXPathBase() {
790         return authorityItemTermGroupXPathBase;
791     }
792         
793     public void setItemTermInfoGroupXPathBase(String itemTermInfoGroupXPathBase) {
794         authorityItemTermGroupXPathBase = itemTermInfoGroupXPathBase;
795     }
796     
797     protected String getAuthorityItemCommonSchemaName() {
798         return authorityItemCommonSchemaName;
799     }
800     
801     // @Override
802     public boolean isJDBCQuery() {
803         boolean result = false;
804         
805         MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams();
806         //
807         // Look the query params to see if we need to make a SQL query.
808         //
809         String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
810         if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
811                 result = true;
812         }
813         
814         return result;
815     }
816     
817     // By convention, the name of the database table that contains
818     // repeatable term information group records is derivable from
819     // an existing XPath base value, by removing a suffix and converting
820     // to lowercase
821     protected String getTermGroupTableName() {
822         String termInfoGroupListName = getItemTermInfoGroupXPathBase();
823         return termInfoGroupListName.substring(0, termInfoGroupListName.lastIndexOf(LIST_SUFFIX)).toLowerCase();
824     }
825     
826     protected String getInAuthorityValue() {
827         String inAuthorityValue = getInAuthority();
828         if (Tools.notBlank(inAuthorityValue)) {
829             return inAuthorityValue;
830         } else {
831             return AuthorityResource.PARENT_WILDCARD;
832         }
833     }
834     
835     @Override
836     public Map<String,String> getJDBCQueryParams() {
837         // FIXME: Get all of the following values from appropriate external constants.
838         // At present, these are duplicated in both RepositoryJavaClientImpl
839         // and in AuthorityItemDocumentModelHandler.
840         final String TERM_GROUP_LIST_NAME = "TERM_GROUP_LIST_NAME";
841         final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
842         final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
843         
844         Map<String,String> params = super.getJDBCQueryParams();
845         params.put(TERM_GROUP_LIST_NAME, getItemTermInfoGroupXPathBase());
846         params.put(TERM_GROUP_TABLE_NAME_PARAM, getTermGroupTableName());
847         params.put(IN_AUTHORITY_PARAM, getInAuthorityValue());
848         return params;
849     }
850     
851 }