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