]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
99b6865b633f3354f1aa99bc752586a5eae8dc72
[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.document.DocumentHandler.Action;
40 import org.collectionspace.services.common.repository.RepositoryClient;
41 import org.collectionspace.services.common.vocabulary.AuthorityJAXBSchema;
42 import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema;
43 import org.collectionspace.services.common.vocabulary.AuthorityResource;
44 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils;
45 import org.collectionspace.services.config.service.ListResultField;
46 import org.collectionspace.services.config.service.ObjectPartType;
47 import org.collectionspace.services.nuxeo.client.java.NuxeoDocumentModelHandler;
48 import org.collectionspace.services.nuxeo.client.java.CoreSessionInterface;
49 import org.collectionspace.services.nuxeo.client.java.RepositoryClientImpl;
50 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
51 import org.collectionspace.services.relation.RelationsCommonList;
52 import org.collectionspace.services.vocabulary.VocabularyItemJAXBSchema;
53 import org.nuxeo.ecm.core.api.ClientException;
54 import org.nuxeo.ecm.core.api.DocumentModel;
55 import org.nuxeo.ecm.core.api.model.PropertyException;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 import javax.ws.rs.core.MultivaluedMap;
60
61 import java.util.ArrayList;
62 import java.util.Collections;
63 import java.util.HashMap;
64 import java.util.List;
65 import java.util.Map;
66 import java.util.regex.Matcher;
67 import java.util.regex.Pattern;
68 import java.util.regex.PatternSyntaxException;
69
70 //import org.collectionspace.services.common.authority.AuthorityItemRelations;
71 /**
72  * AuthorityItemDocumentModelHandler
73  *
74  * $LastChangedRevision: $
75  * $LastChangedDate: $
76  */
77 public abstract class AuthorityItemDocumentModelHandler<AICommon>
78         extends NuxeoDocumentModelHandler<AICommon> {
79
80     private final Logger logger = LoggerFactory.getLogger(AuthorityItemDocumentModelHandler.class);
81     private String authorityItemCommonSchemaName;
82     private String authorityItemTermGroupXPathBase;
83     /**
84      * inVocabulary is the parent Authority for this context
85      */
86     protected String inAuthority = null;
87     protected boolean wildcardedAuthorityRequest = false;
88     protected String authorityRefNameBase = null;
89     // Used to determine when the displayName changes as part of the update.
90     protected String oldDisplayNameOnUpdate = null;
91     private final static String LIST_SUFFIX = "List";
92     private final static String ZERO_OR_MORE_ANY_CHAR_REGEX = ".*";
93
94     public AuthorityItemDocumentModelHandler(String authorityItemCommonSchemaName) {
95         this.authorityItemCommonSchemaName = authorityItemCommonSchemaName;
96     }
97     
98     abstract public String getParentCommonSchemaName();
99
100     @Override
101     protected String getRefnameDisplayName(DocumentWrapper<DocumentModel> docWrapper) {
102         String result = null;
103         
104         DocumentModel docModel = docWrapper.getWrappedObject();
105         ServiceContext<PoxPayloadIn, PoxPayloadOut> 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             CoreSessionInterface 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     public void fillAllParts(DocumentWrapper<DocumentModel> wrapDoc, Action action) throws Exception {
402         super.fillAllParts(wrapDoc, action);
403         //
404         // Update the record's revision number on both CREATE and UPDATE actions
405         //
406         updateRevNumbers(wrapDoc);
407     }
408     
409     protected void updateRevNumbers(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
410         DocumentModel documentModel = wrapDoc.getWrappedObject();
411         Long rev = (Long)documentModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REV);
412         if (rev == null) {
413                 rev = (long)0;
414         } else {
415                 rev++;
416         }
417         documentModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REV, rev);
418         //
419         // Next, update the inAuthority (the parent's) rev number
420         //
421         DocumentModel inAuthorityDocModel = NuxeoUtils.getDocFromCsid(getServiceContext(), getRepositorySession(), getInAuthority());
422         Long parentRev = (Long)inAuthorityDocModel.getProperty(getParentCommonSchemaName(), AuthorityJAXBSchema.REV);
423                 parentRev++;
424                 inAuthorityDocModel.setProperty(getParentCommonSchemaName(), AuthorityJAXBSchema.REV, parentRev);
425                 getRepositorySession().saveDocument(inAuthorityDocModel);
426     }    
427     
428     /**
429      * If no short identifier was provided in the input payload, generate a
430      * short identifier from the preferred term display name or term name.
431      */
432         private String handleDisplayNameAsShortIdentifier(DocumentModel docModel) throws Exception {
433                 String result = (String) docModel.getProperty(authorityItemCommonSchemaName,
434                                 AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
435
436                 if (Tools.isEmpty(result)) {
437                         String termDisplayName = getPrimaryDisplayName(
438                                         docModel, authorityItemCommonSchemaName,
439                                         getItemTermInfoGroupXPathBase(),
440                                         AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
441
442                         String termName = getPrimaryDisplayName(
443                                         docModel, authorityItemCommonSchemaName,
444                                         getItemTermInfoGroupXPathBase(),
445                                         AuthorityItemJAXBSchema.TERM_NAME);
446
447                         String generatedShortIdentifier = AuthorityIdentifierUtils.generateShortIdentifierFromDisplayName(termDisplayName,
448                                                         termName);
449                         docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER,
450                                         generatedShortIdentifier);
451                         result = generatedShortIdentifier;
452                 }
453                 
454                 return result;
455         }
456
457     /**
458      * Generate a refName for the authority item from the short identifier
459      * and display name.
460      * 
461      * All refNames for authority items are generated.  If a client supplies
462      * a refName, it will be overwritten during create (per this method) 
463      * or discarded during update (per filterReadOnlyPropertiesForPart).
464      * 
465      * @see #filterReadOnlyPropertiesForPart(Map<String, Object>, org.collectionspace.services.common.service.ObjectPartType)
466      * 
467      */
468     protected String updateRefnameForAuthorityItem(DocumentModel docModel,
469             String schemaName) throws Exception {
470         String result = null;
471         
472         RefName.RefNameInterface refname = getRefName(getServiceContext(), docModel);
473         String refNameStr = refname.toString();
474         docModel.setProperty(schemaName, AuthorityItemJAXBSchema.REF_NAME, refNameStr);
475         result = refNameStr;
476         
477         return result;
478     }
479
480     /**
481      * Check the logic around the parent pointer. Note that we only need do this on
482      * create, since we have logic to make this read-only on update. 
483      * 
484      * @param docModel
485      * 
486      * @throws Exception the exception
487      */
488     private void handleInAuthority(DocumentModel docModel) throws Exception {
489         if(inAuthority==null) { // Only happens on queries to wildcarded authorities
490                 throw new IllegalStateException("Trying to Create an object with no inAuthority value!");
491         }
492         docModel.setProperty(authorityItemCommonSchemaName,
493                 AuthorityItemJAXBSchema.IN_AUTHORITY, inAuthority);
494     }
495     
496     public AuthorityRefDocList getReferencingObjects(
497                 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
498                 UriTemplateRegistry uriTemplateRegistry, 
499                 List<String> serviceTypes,
500                 String propertyName,
501             String itemcsid) throws Exception {
502         AuthorityRefDocList authRefDocList = null;
503         CoreSessionInterface repoSession = null;
504         boolean releaseRepoSession = false;
505         
506         try {
507                 RepositoryClientImpl repoClient = (RepositoryClientImpl)this.getRepositoryClient(ctx);
508                 repoSession = this.getRepositorySession();
509                 if (repoSession == null) {
510                         repoSession = repoClient.getRepositorySession(ctx);
511                         releaseRepoSession = true;
512                 }
513             DocumentFilter myFilter = getDocumentFilter();
514
515                 try {
516                         DocumentWrapper<DocumentModel> wrapper = repoClient.getDoc(repoSession, ctx, itemcsid);
517                         DocumentModel docModel = wrapper.getWrappedObject();
518                         String refName = (String) NuxeoUtils.getProperyValue(docModel, AuthorityItemJAXBSchema.REF_NAME); //docModel.getPropertyValue(AuthorityItemJAXBSchema.REF_NAME);
519                 authRefDocList = RefNameServiceUtils.getAuthorityRefDocs(
520                                 repoSession, ctx, uriTemplateRegistry, repoClient,
521                         serviceTypes,
522                         refName,
523                         propertyName,
524                         myFilter, true /*computeTotal*/);
525                 } catch (PropertyException pe) {
526                         throw pe;
527                 } catch (DocumentException de) {
528                         throw de;
529                 } catch (Exception e) {
530                         if (logger.isDebugEnabled()) {
531                                 logger.debug("Caught exception ", e);
532                         }
533                         throw new DocumentException(e);
534                 } finally {
535                         // If we got/aquired a new seesion then we're responsible for releasing it.
536                         if (releaseRepoSession && repoSession != null) {
537                                 repoClient.releaseRepositorySession(ctx, repoSession);
538                         }
539                 }
540         } catch (Exception e) {
541                 if (logger.isDebugEnabled()) {
542                         logger.debug("Caught exception ", e);
543                 }
544                 throw new DocumentException(e);
545         }
546         
547         return authRefDocList;
548     }
549
550     /* (non-Javadoc)
551      * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#extractPart(org.nuxeo.ecm.core.api.DocumentModel, java.lang.String, org.collectionspace.services.common.service.ObjectPartType)
552      */
553     @Override
554     protected Map<String, Object> extractPart(DocumentModel docModel, String schema, ObjectPartType partMeta)
555             throws Exception {
556         Map<String, Object> unQObjectProperties = super.extractPart(docModel, schema, partMeta);
557
558         // Add the CSID to the common part, since they may have fetched via the shortId.
559         if (partMeta.getLabel().equalsIgnoreCase(authorityItemCommonSchemaName)) {
560             String csid = getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
561             unQObjectProperties.put("csid", csid);
562         }
563
564         return unQObjectProperties;
565     }
566
567     /**
568      * Filters out selected values supplied in an update request.
569      * 
570      * For example, filters out AuthorityItemJAXBSchema.IN_AUTHORITY, to ensure
571      * that the link to the item's parent remains untouched.
572      * 
573      * @param objectProps the properties filtered out from the update payload
574      * @param partMeta metadata for the object to fill
575      */
576     @Override
577     public void filterReadOnlyPropertiesForPart(
578             Map<String, Object> objectProps, ObjectPartType partMeta) {
579         super.filterReadOnlyPropertiesForPart(objectProps, partMeta);
580         String commonPartLabel = getServiceContext().getCommonPartLabel();
581         if (partMeta.getLabel().equalsIgnoreCase(commonPartLabel)) {
582             objectProps.remove(AuthorityItemJAXBSchema.IN_AUTHORITY);
583             objectProps.remove(AuthorityItemJAXBSchema.CSID);
584             objectProps.remove(AuthorityJAXBSchema.SHORT_IDENTIFIER);
585             objectProps.remove(AuthorityItemJAXBSchema.REF_NAME);
586         }
587     }
588     
589     /**
590      * Returns the items in a list of term display names whose names contain
591      * a partial term (as might be submitted in a search query, for instance).
592      * @param termDisplayNameList a list of term display names.
593      * @param partialTerm a partial term display name; that is, a portion
594      * of a display name that might be expected to match 0-n terms in the list.
595      * @return a list of term display names that matches the partial term.
596      * Matches are case-insensitive. As well, before matching is performed, any
597      * special-purpose characters that may appear in the partial term (such as
598      * wildcards and anchor characters) are filtered out from both compared terms.
599      */
600     protected List<String> getPartialTermDisplayNameMatches(List<String> termDisplayNameList, String partialTerm) {
601         List<String> result = new ArrayList<>();
602         String partialTermMatchExpression = filterAnchorAndWildcardChars(partialTerm).toLowerCase();
603         try {
604             for (String termDisplayName : termDisplayNameList) {
605                 if (termDisplayName.toLowerCase()
606                         .matches(partialTermMatchExpression) == true) {
607                         result.add(termDisplayName);
608                 }
609             }
610         } catch (PatternSyntaxException pse) {
611             logger.warn("Error in regex match pattern '%s' for term display names: %s",
612                     partialTermMatchExpression, pse.getMessage());
613         }
614         return result;
615     }
616     
617     /**
618      * Filters user-supplied anchor and wildcard characters in a string,
619      * replacing them with equivalent regular expressions.
620      * @param term a term in which to filter anchor and wildcard characters.
621      * @return the term with those characters filtered.
622      */
623     protected String filterAnchorAndWildcardChars(String term) {
624         if (Tools.isBlank(term)) {
625             return term;
626         }
627         if (term.length() < 3) {
628             return term;
629         }
630         if (logger.isTraceEnabled()) {
631             logger.trace(String.format("Term = %s", term));
632         }
633         Boolean anchorAtStart = false;
634         Boolean anchorAtEnd = false;
635         String filteredTerm;
636         StringBuilder filteredTermBuilder = new StringBuilder(term);
637         // Term contains no anchor or wildcard characters.
638         if ( (! term.contains(RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR))
639                 && (! term.contains(RepositoryClientImpl.USER_SUPPLIED_WILDCARD)) ) {
640             filteredTerm = term;
641         } else {
642             // Term contains at least one such character.
643             try {
644                 // Filter the starting anchor or wildcard character, if any.
645                 String firstChar = filteredTermBuilder.substring(0,1);
646                 switch (firstChar) {
647                     case RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR:
648                         anchorAtStart = true;
649                         break;
650                     case RepositoryClientImpl.USER_SUPPLIED_WILDCARD:
651                         filteredTermBuilder.deleteCharAt(0);
652                         break;
653                 }
654                 if (logger.isTraceEnabled()) {
655                     logger.trace(String.format("After first char filtering = %s", filteredTermBuilder.toString()));
656                 }
657                 // Filter the ending anchor or wildcard character, if any.
658                 int lastPos = filteredTermBuilder.length() - 1;
659                 String lastChar = filteredTermBuilder.substring(lastPos);
660                 switch (lastChar) {
661                     case RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR:
662                         filteredTermBuilder.deleteCharAt(lastPos);
663                         filteredTermBuilder.insert(filteredTermBuilder.length(), RepositoryClientImpl.ENDING_ANCHOR_CHAR);
664                         anchorAtEnd = true;
665                         break;
666                     case RepositoryClientImpl.USER_SUPPLIED_WILDCARD:
667                         filteredTermBuilder.deleteCharAt(lastPos);
668                         break;
669                 }
670                 if (logger.isTraceEnabled()) {
671                     logger.trace(String.format("After last char filtering = %s", filteredTermBuilder.toString()));
672                 }
673                 filteredTerm = filteredTermBuilder.toString();
674                 // Filter all other wildcards, if any.
675                 filteredTerm = filteredTerm.replaceAll(RepositoryClientImpl.USER_SUPPLIED_WILDCARD_REGEX, ZERO_OR_MORE_ANY_CHAR_REGEX);
676                 if (logger.isTraceEnabled()) {
677                     logger.trace(String.format("After replacing user wildcards = %s", filteredTerm));
678                 }
679             } catch (Exception e) {
680                 logger.warn(String.format("Error filtering anchor and wildcard characters from string: %s", e.getMessage()));
681                 return term;
682             }
683         }
684         // Wrap the term in beginning and ending regex wildcards, unless a
685         // starting or ending anchor character was present.
686         return (anchorAtStart ? "" : ZERO_OR_MORE_ANY_CHAR_REGEX)
687                 + filteredTerm
688                 + (anchorAtEnd ? "" : ZERO_OR_MORE_ANY_CHAR_REGEX);
689     }
690     
691     @SuppressWarnings("unchecked")
692         private List<String> getPartialTermDisplayNameMatches(DocumentModel docModel, // REM - CSPACE-5133
693                         String schema, ListResultField field, String partialTerm) {
694         List<String> result = null;
695           
696         String xpath = field.getXpath(); // results in something like "persons_common:personTermGroupList/[0]/termDisplayName"
697         int endOfTermGroup = xpath.lastIndexOf("/[0]/");
698         String propertyName = endOfTermGroup != -1 ? xpath.substring(0, endOfTermGroup) : xpath; // it may not be multivalued so the xpath passed in would be the property name
699         Object value = null;
700         
701                 try {
702                         value = docModel.getProperty(schema, propertyName);
703                 } catch (Exception e) {
704                         logger.error("Could not extract term display name with property = "
705                                         + propertyName, e);
706                 }
707                 
708                 if (value != null && value instanceof ArrayList) {
709                         ArrayList<HashMap<String, Object>> termGroupList = (ArrayList<HashMap<String, Object>>)value;
710                         int arrayListSize = termGroupList.size();
711                         if (arrayListSize > 1) { // if there's only 1 element in the list then we've already matched the primary term's display name
712                                 List<String> displayNameList = new ArrayList<String>();
713                                 for (int i = 1; i < arrayListSize; i++) { // start at 1, skip the primary term's displayName since we will always return it
714                                         HashMap<String, Object> map = (HashMap<String, Object>)termGroupList.get(i);
715                                         String termDisplayName = (String) map.get(AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
716                                         displayNameList.add(i - 1, termDisplayName);
717                                 }
718                                 
719                                 result = getPartialTermDisplayNameMatches(displayNameList, partialTerm);
720                         }
721                 }
722
723         return result;
724     }
725
726     @Override
727         protected Object getListResultValue(DocumentModel docModel, // REM - CSPACE-5133
728                         String schema, ListResultField field) throws DocumentException {
729                 Object result = null;           
730
731                 result = NuxeoUtils.getXPathValue(docModel, schema, field.getXpath());
732                 
733                 //
734                 // Special handling of list item values for authority items (only)
735                 // takes place here:
736                 //
737                 // If the list result field is the termDisplayName element,
738                 // check whether a partial term matching query was made.
739                 // If it was, emit values for both the preferred (aka primary)
740                 // term and for all non-preferred terms, if any.
741                 //
742                 String elName = field.getElement();
743                 if (isTermDisplayName(elName) == true) {
744                         MultivaluedMap<String, String> queryParams = this.getServiceContext().getQueryParams();
745                 String partialTerm = queryParams != null ? queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM) : null;
746                 if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
747                                 String primaryTermDisplayName = (String)result;
748                         List<String> matches = getPartialTermDisplayNameMatches(docModel, schema, field, partialTerm);
749                         if (matches != null && matches.isEmpty() == false) {
750                                 matches.add(0, primaryTermDisplayName); // insert the primary term's display name at the beginning of the list
751                                 result = matches; // set the result to a list of matching term display names with the primary term's display name at the beginning
752                         }
753                 }
754                 }
755                 
756                 return result;
757         }
758     
759     @Override
760     public void extractAllParts(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
761         MultipartServiceContext ctx = (MultipartServiceContext) getServiceContext();
762         super.extractAllParts(wrapDoc);
763     }
764
765     protected List<RelationsCommonList.RelationListItem> cloneList(List<RelationsCommonList.RelationListItem> inboundList) {
766         List<RelationsCommonList.RelationListItem> result = newRelationsCommonList();
767         for (RelationsCommonList.RelationListItem item : inboundList) {
768             result.add(item);
769         }
770         return result;
771     }
772
773
774     /* don't even THINK of re-using this method.
775      * String example_uri = "/locationauthorities/7ec60f01-84ab-4908-9a6a/items/a5466530-713f-43b4-bc05";
776      */
777     @Deprecated
778     private String extractInAuthorityCSID(String uri) {
779         String IN_AUTHORITY_REGEX = "/(.*?)/(.*?)/(.*)";
780         Pattern p = Pattern.compile(IN_AUTHORITY_REGEX);
781         Matcher m = p.matcher(uri);
782         if (m.find()) {
783             if (m.groupCount() < 3) {
784                 logger.warn("REGEX-WRONG-GROUPCOUNT looking in " + uri);
785                 return "";
786             } else {
787                 //String service = m.group(1);
788                 String inauth = m.group(2);
789                 //String theRest = m.group(3);
790                 return inauth;
791                 //print("service:"+service+", inauth:"+inauth+", rest:"+rest);
792             }
793         } else {
794             logger.warn("REGEX-NOT-MATCHED looking in " + uri);
795             return "";
796         }
797     }
798
799     //ensures CSPACE-4042
800     protected void uriPointsToSameAuthority(String thisURI, String inboundItemURI) throws Exception {
801         String authorityCSID = extractInAuthorityCSID(thisURI);
802         String authorityCSIDForInbound = extractInAuthorityCSID(inboundItemURI);
803         if (Tools.isBlank(authorityCSID)
804                 || Tools.isBlank(authorityCSIDForInbound)
805                 || (!authorityCSID.equalsIgnoreCase(authorityCSIDForInbound))) {
806             throw new Exception("Item URI " + thisURI + " must point to same authority as related item: " + inboundItemURI);
807         }
808     }
809
810     public String getItemTermInfoGroupXPathBase() {
811         return authorityItemTermGroupXPathBase;
812     }
813         
814     public void setItemTermInfoGroupXPathBase(String itemTermInfoGroupXPathBase) {
815         authorityItemTermGroupXPathBase = itemTermInfoGroupXPathBase;
816     }
817     
818     protected String getAuthorityItemCommonSchemaName() {
819         return authorityItemCommonSchemaName;
820     }
821     
822     // @Override
823     public boolean isJDBCQuery() {
824         boolean result = false;
825         
826         MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams();
827         //
828         // Look the query params to see if we need to make a SQL query.
829         //
830         String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
831         if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
832                 result = true;
833         }
834         
835         return result;
836     }
837     
838     // By convention, the name of the database table that contains
839     // repeatable term information group records is derivable from
840     // an existing XPath base value, by removing a suffix and converting
841     // to lowercase
842     protected String getTermGroupTableName() {
843         String termInfoGroupListName = getItemTermInfoGroupXPathBase();
844         return termInfoGroupListName.substring(0, termInfoGroupListName.lastIndexOf(LIST_SUFFIX)).toLowerCase();
845     }
846     
847     protected String getInAuthorityValue() {
848         String inAuthorityValue = getInAuthority();
849         if (Tools.notBlank(inAuthorityValue)) {
850             return inAuthorityValue;
851         } else {
852             return AuthorityResource.PARENT_WILDCARD;
853         }
854     }
855     
856     @Override
857     public Map<String,String> getJDBCQueryParams() {
858         // FIXME: Get all of the following values from appropriate external constants.
859         // At present, these are duplicated in both RepositoryClientImpl
860         // and in AuthorityItemDocumentModelHandler.
861         final String TERM_GROUP_LIST_NAME = "TERM_GROUP_LIST_NAME";
862         final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
863         final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
864         
865         Map<String,String> params = super.getJDBCQueryParams();
866         params.put(TERM_GROUP_LIST_NAME, getItemTermInfoGroupXPathBase());
867         params.put(TERM_GROUP_TABLE_NAME_PARAM, getTermGroupTableName());
868         params.put(IN_AUTHORITY_PARAM, getInAuthorityValue());
869         return params;
870     }
871     
872 }