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