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