]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
4acf9b25e8e706f3e4b05531269e4acf904cddf9
[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 shouldUpdateParentRevNumber = 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 getShouldUpdateParentRevNumber() {
114         return this.shouldUpdateParentRevNumber;
115     }
116     
117     public void setShouldUpdateParentRevNumber(boolean flag) {
118         this.shouldUpdateParentRevNumber = 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.getItemSpecifier());
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                                 null, 
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         updateRevNumbers(wrapDoc);
508     }
509     
510     protected void updateRevNumbers(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
511         DocumentModel documentModel = wrapDoc.getWrappedObject();
512         Long rev = (Long)documentModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REV);
513         if (rev == null) {
514                 rev = (long)0;
515         } else {
516                 rev++;
517         }
518         documentModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REV, rev);
519         //
520         // Next, update the inAuthority (the parent's) rev number
521         //
522         if (this.shouldUpdateParentRevNumber == true) {
523                 DocumentModel inAuthorityDocModel = NuxeoUtils.getDocFromCsid(getServiceContext(), getRepositorySession(), getInAuthority());
524                 Long parentRev = (Long)inAuthorityDocModel.getProperty(getParentCommonSchemaName(), AuthorityJAXBSchema.REV);
525                 if (parentRev == null) {
526                         parentRev = new Long(0);
527                 }
528                         parentRev++;
529                         inAuthorityDocModel.setProperty(getParentCommonSchemaName(), AuthorityJAXBSchema.REV, parentRev);
530                         getRepositorySession().saveDocument(inAuthorityDocModel);
531         }
532     }    
533     
534     /**
535      * If no short identifier was provided in the input payload, generate a
536      * short identifier from the preferred term display name or term name.
537      */
538         private String handleDisplayNameAsShortIdentifier(DocumentModel docModel) throws Exception {
539                 String result = (String) docModel.getProperty(authorityItemCommonSchemaName,
540                                 AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
541
542                 if (Tools.isEmpty(result)) {
543                         String termDisplayName = getPrimaryDisplayName(
544                                         docModel, authorityItemCommonSchemaName,
545                                         getItemTermInfoGroupXPathBase(),
546                                         AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
547
548                         String termName = getPrimaryDisplayName(
549                                         docModel, authorityItemCommonSchemaName,
550                                         getItemTermInfoGroupXPathBase(),
551                                         AuthorityItemJAXBSchema.TERM_NAME);
552
553                         String generatedShortIdentifier = AuthorityIdentifierUtils.generateShortIdentifierFromDisplayName(termDisplayName,
554                                                         termName);
555                         docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER,
556                                         generatedShortIdentifier);
557                         result = generatedShortIdentifier;
558                 }
559                 
560                 return result;
561         }
562
563     /**
564      * Generate a refName for the authority item from the short identifier
565      * and display name.
566      * 
567      * All refNames for authority items are generated.  If a client supplies
568      * a refName, it will be overwritten during create (per this method) 
569      * or discarded during update (per filterReadOnlyPropertiesForPart).
570      * 
571      * @see #filterReadOnlyPropertiesForPart(Map<String, Object>, org.collectionspace.services.common.service.ObjectPartType)
572      * 
573      */
574     protected String updateRefnameForAuthorityItem(DocumentModel docModel,
575             String schemaName) throws Exception {
576         String result = null;
577         
578         RefName.RefNameInterface refname = getRefName(getServiceContext(), docModel);
579         String refNameStr = refname.toString();
580         docModel.setProperty(schemaName, AuthorityItemJAXBSchema.REF_NAME, refNameStr);
581         result = refNameStr;
582         
583         return result;
584     }
585
586     /**
587      * Check the logic around the parent pointer. Note that we only need do this on
588      * create, since we have logic to make this read-only on update. 
589      * 
590      * @param docModel
591      * 
592      * @throws Exception the exception
593      */
594     private void handleInAuthority(DocumentModel docModel) throws Exception {
595         if(inAuthority==null) { // Only happens on queries to wildcarded authorities
596                 throw new IllegalStateException("Trying to Create an object with no inAuthority value!");
597         }
598         docModel.setProperty(authorityItemCommonSchemaName,
599                 AuthorityItemJAXBSchema.IN_AUTHORITY, inAuthority);
600     }
601     
602     public AuthorityRefDocList getReferencingObjects(
603                 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
604                 UriTemplateRegistry uriTemplateRegistry, 
605                 List<String> serviceTypes,
606                 String propertyName,
607             String itemcsid) throws Exception {
608         AuthorityRefDocList authRefDocList = null;
609         CoreSessionInterface repoSession = null;
610         boolean releaseRepoSession = false;
611         
612         try {
613                 RepositoryClientImpl repoClient = (RepositoryClientImpl)this.getRepositoryClient(ctx);
614                 repoSession = this.getRepositorySession();
615                 if (repoSession == null) {
616                         repoSession = repoClient.getRepositorySession(ctx);
617                         releaseRepoSession = true;
618                 }
619             DocumentFilter myFilter = getDocumentFilter();
620
621                 try {
622                         DocumentWrapper<DocumentModel> wrapper = repoClient.getDoc(repoSession, ctx, itemcsid);
623                         DocumentModel docModel = wrapper.getWrappedObject();
624                         String refName = (String) NuxeoUtils.getProperyValue(docModel, AuthorityItemJAXBSchema.REF_NAME); //docModel.getPropertyValue(AuthorityItemJAXBSchema.REF_NAME);
625                 authRefDocList = RefNameServiceUtils.getAuthorityRefDocs(
626                                 repoSession, ctx, uriTemplateRegistry, repoClient,
627                         serviceTypes,
628                         refName,
629                         propertyName,
630                         myFilter, true /*computeTotal*/);
631                 } catch (PropertyException pe) {
632                         throw pe;
633                 } catch (DocumentException de) {
634                         throw de;
635                 } catch (Exception e) {
636                         if (logger.isDebugEnabled()) {
637                                 logger.debug("Caught exception ", e);
638                         }
639                         throw new DocumentException(e);
640                 } finally {
641                         // If we got/aquired a new seesion then we're responsible for releasing it.
642                         if (releaseRepoSession && repoSession != null) {
643                                 repoClient.releaseRepositorySession(ctx, repoSession);
644                         }
645                 }
646         } catch (Exception e) {
647                 if (logger.isDebugEnabled()) {
648                         logger.debug("Caught exception ", e);
649                 }
650                 throw new DocumentException(e);
651         }
652         
653         return authRefDocList;
654     }
655
656     /* (non-Javadoc)
657      * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#extractPart(org.nuxeo.ecm.core.api.DocumentModel, java.lang.String, org.collectionspace.services.common.service.ObjectPartType)
658      */
659     @Override
660     protected Map<String, Object> extractPart(DocumentModel docModel, String schema, ObjectPartType partMeta)
661             throws Exception {
662         Map<String, Object> unQObjectProperties = super.extractPart(docModel, schema, partMeta);
663
664         // Add the CSID to the common part, since they may have fetched via the shortId.
665         if (partMeta.getLabel().equalsIgnoreCase(authorityItemCommonSchemaName)) {
666             String csid = getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
667             unQObjectProperties.put("csid", csid);
668         }
669
670         return unQObjectProperties;
671     }
672
673     /**
674      * Filters out selected values supplied in an update request.
675      * 
676      * For example, filters out AuthorityItemJAXBSchema.IN_AUTHORITY, to ensure
677      * that the link to the item's parent remains untouched.
678      * 
679      * @param objectProps the properties filtered out from the update payload
680      * @param partMeta metadata for the object to fill
681      */
682     @Override
683     public void filterReadOnlyPropertiesForPart(
684             Map<String, Object> objectProps, ObjectPartType partMeta) {
685         super.filterReadOnlyPropertiesForPart(objectProps, partMeta);
686         String commonPartLabel = getServiceContext().getCommonPartLabel();
687         if (partMeta.getLabel().equalsIgnoreCase(commonPartLabel)) {
688             objectProps.remove(AuthorityItemJAXBSchema.IN_AUTHORITY);
689             objectProps.remove(AuthorityItemJAXBSchema.CSID);
690             objectProps.remove(AuthorityJAXBSchema.SHORT_IDENTIFIER);
691             objectProps.remove(AuthorityItemJAXBSchema.REF_NAME);
692         }
693     }
694     
695     /**
696      * Returns the items in a list of term display names whose names contain
697      * a partial term (as might be submitted in a search query, for instance).
698      * @param termDisplayNameList a list of term display names.
699      * @param partialTerm a partial term display name; that is, a portion
700      * of a display name that might be expected to match 0-n terms in the list.
701      * @return a list of term display names that matches the partial term.
702      * Matches are case-insensitive. As well, before matching is performed, any
703      * special-purpose characters that may appear in the partial term (such as
704      * wildcards and anchor characters) are filtered out from both compared terms.
705      */
706     protected List<String> getPartialTermDisplayNameMatches(List<String> termDisplayNameList, String partialTerm) {
707         List<String> result = new ArrayList<>();
708         String partialTermMatchExpression = filterAnchorAndWildcardChars(partialTerm).toLowerCase();
709         try {
710             for (String termDisplayName : termDisplayNameList) {
711                 if (termDisplayName.toLowerCase()
712                         .matches(partialTermMatchExpression) == true) {
713                         result.add(termDisplayName);
714                 }
715             }
716         } catch (PatternSyntaxException pse) {
717             logger.warn("Error in regex match pattern '%s' for term display names: %s",
718                     partialTermMatchExpression, pse.getMessage());
719         }
720         return result;
721     }
722     
723     /**
724      * Filters user-supplied anchor and wildcard characters in a string,
725      * replacing them with equivalent regular expressions.
726      * @param term a term in which to filter anchor and wildcard characters.
727      * @return the term with those characters filtered.
728      */
729     protected String filterAnchorAndWildcardChars(String term) {
730         if (Tools.isBlank(term)) {
731             return term;
732         }
733         if (term.length() < 3) {
734             return term;
735         }
736         if (logger.isTraceEnabled()) {
737             logger.trace(String.format("Term = %s", term));
738         }
739         Boolean anchorAtStart = false;
740         Boolean anchorAtEnd = false;
741         String filteredTerm;
742         StringBuilder filteredTermBuilder = new StringBuilder(term);
743         // Term contains no anchor or wildcard characters.
744         if ( (! term.contains(RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR))
745                 && (! term.contains(RepositoryClientImpl.USER_SUPPLIED_WILDCARD)) ) {
746             filteredTerm = term;
747         } else {
748             // Term contains at least one such character.
749             try {
750                 // Filter the starting anchor or wildcard character, if any.
751                 String firstChar = filteredTermBuilder.substring(0,1);
752                 switch (firstChar) {
753                     case RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR:
754                         anchorAtStart = true;
755                         break;
756                     case RepositoryClientImpl.USER_SUPPLIED_WILDCARD:
757                         filteredTermBuilder.deleteCharAt(0);
758                         break;
759                 }
760                 if (logger.isTraceEnabled()) {
761                     logger.trace(String.format("After first char filtering = %s", filteredTermBuilder.toString()));
762                 }
763                 // Filter the ending anchor or wildcard character, if any.
764                 int lastPos = filteredTermBuilder.length() - 1;
765                 String lastChar = filteredTermBuilder.substring(lastPos);
766                 switch (lastChar) {
767                     case RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR:
768                         filteredTermBuilder.deleteCharAt(lastPos);
769                         filteredTermBuilder.insert(filteredTermBuilder.length(), RepositoryClientImpl.ENDING_ANCHOR_CHAR);
770                         anchorAtEnd = true;
771                         break;
772                     case RepositoryClientImpl.USER_SUPPLIED_WILDCARD:
773                         filteredTermBuilder.deleteCharAt(lastPos);
774                         break;
775                 }
776                 if (logger.isTraceEnabled()) {
777                     logger.trace(String.format("After last char filtering = %s", filteredTermBuilder.toString()));
778                 }
779                 filteredTerm = filteredTermBuilder.toString();
780                 // Filter all other wildcards, if any.
781                 filteredTerm = filteredTerm.replaceAll(RepositoryClientImpl.USER_SUPPLIED_WILDCARD_REGEX, ZERO_OR_MORE_ANY_CHAR_REGEX);
782                 if (logger.isTraceEnabled()) {
783                     logger.trace(String.format("After replacing user wildcards = %s", filteredTerm));
784                 }
785             } catch (Exception e) {
786                 logger.warn(String.format("Error filtering anchor and wildcard characters from string: %s", e.getMessage()));
787                 return term;
788             }
789         }
790         // Wrap the term in beginning and ending regex wildcards, unless a
791         // starting or ending anchor character was present.
792         return (anchorAtStart ? "" : ZERO_OR_MORE_ANY_CHAR_REGEX)
793                 + filteredTerm
794                 + (anchorAtEnd ? "" : ZERO_OR_MORE_ANY_CHAR_REGEX);
795     }
796     
797     @SuppressWarnings("unchecked")
798         private List<String> getPartialTermDisplayNameMatches(DocumentModel docModel, // REM - CSPACE-5133
799                         String schema, ListResultField field, String partialTerm) {
800         List<String> result = null;
801           
802         String xpath = field.getXpath(); // results in something like "persons_common:personTermGroupList/[0]/termDisplayName"
803         int endOfTermGroup = xpath.lastIndexOf("/[0]/");
804         String propertyName = endOfTermGroup != -1 ? xpath.substring(0, endOfTermGroup) : xpath; // it may not be multivalued so the xpath passed in would be the property name
805         Object value = null;
806         
807                 try {
808                         value = docModel.getProperty(schema, propertyName);
809                 } catch (Exception e) {
810                         logger.error("Could not extract term display name with property = "
811                                         + propertyName, e);
812                 }
813                 
814                 if (value != null && value instanceof ArrayList) {
815                         ArrayList<HashMap<String, Object>> termGroupList = (ArrayList<HashMap<String, Object>>)value;
816                         int arrayListSize = termGroupList.size();
817                         if (arrayListSize > 1) { // if there's only 1 element in the list then we've already matched the primary term's display name
818                                 List<String> displayNameList = new ArrayList<String>();
819                                 for (int i = 1; i < arrayListSize; i++) { // start at 1, skip the primary term's displayName since we will always return it
820                                         HashMap<String, Object> map = (HashMap<String, Object>)termGroupList.get(i);
821                                         String termDisplayName = (String) map.get(AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
822                                         displayNameList.add(i - 1, termDisplayName);
823                                 }
824                                 
825                                 result = getPartialTermDisplayNameMatches(displayNameList, partialTerm);
826                         }
827                 }
828
829         return result;
830     }
831
832     @Override
833         protected Object getListResultValue(DocumentModel docModel, // REM - CSPACE-5133
834                         String schema, ListResultField field) throws DocumentException {
835                 Object result = null;           
836
837                 result = NuxeoUtils.getXPathValue(docModel, schema, field.getXpath());
838                 
839                 //
840                 // Special handling of list item values for authority items (only)
841                 // takes place here:
842                 //
843                 // If the list result field is the termDisplayName element,
844                 // check whether a partial term matching query was made.
845                 // If it was, emit values for both the preferred (aka primary)
846                 // term and for all non-preferred terms, if any.
847                 //
848                 String elName = field.getElement();
849                 if (isTermDisplayName(elName) == true) {
850                         MultivaluedMap<String, String> queryParams = this.getServiceContext().getQueryParams();
851                 String partialTerm = queryParams != null ? queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM) : null;
852                 if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
853                                 String primaryTermDisplayName = (String)result;
854                         List<String> matches = getPartialTermDisplayNameMatches(docModel, schema, field, partialTerm);
855                         if (matches != null && matches.isEmpty() == false) {
856                                 matches.add(0, primaryTermDisplayName); // insert the primary term's display name at the beginning of the list
857                                 result = matches; // set the result to a list of matching term display names with the primary term's display name at the beginning
858                         }
859                 }
860                 }
861                 
862                 return result;
863         }
864     
865     @Override
866     public void extractAllParts(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
867         MultipartServiceContext ctx = (MultipartServiceContext) getServiceContext();
868         super.extractAllParts(wrapDoc);
869     }
870
871     protected List<RelationsCommonList.RelationListItem> cloneList(List<RelationsCommonList.RelationListItem> inboundList) {
872         List<RelationsCommonList.RelationListItem> result = newRelationsCommonList();
873         for (RelationsCommonList.RelationListItem item : inboundList) {
874             result.add(item);
875         }
876         return result;
877     }
878
879
880     /* don't even THINK of re-using this method.
881      * String example_uri = "/locationauthorities/7ec60f01-84ab-4908-9a6a/items/a5466530-713f-43b4-bc05";
882      */
883     @Deprecated
884     private String extractInAuthorityCSID(String uri) {
885         String IN_AUTHORITY_REGEX = "/(.*?)/(.*?)/(.*)";
886         Pattern p = Pattern.compile(IN_AUTHORITY_REGEX);
887         Matcher m = p.matcher(uri);
888         if (m.find()) {
889             if (m.groupCount() < 3) {
890                 logger.warn("REGEX-WRONG-GROUPCOUNT looking in " + uri);
891                 return "";
892             } else {
893                 //String service = m.group(1);
894                 String inauth = m.group(2);
895                 //String theRest = m.group(3);
896                 return inauth;
897                 //print("service:"+service+", inauth:"+inauth+", rest:"+rest);
898             }
899         } else {
900             logger.warn("REGEX-NOT-MATCHED looking in " + uri);
901             return "";
902         }
903     }
904
905     //ensures CSPACE-4042
906     protected void uriPointsToSameAuthority(String thisURI, String inboundItemURI) throws Exception {
907         String authorityCSID = extractInAuthorityCSID(thisURI);
908         String authorityCSIDForInbound = extractInAuthorityCSID(inboundItemURI);
909         if (Tools.isBlank(authorityCSID)
910                 || Tools.isBlank(authorityCSIDForInbound)
911                 || (!authorityCSID.equalsIgnoreCase(authorityCSIDForInbound))) {
912             throw new Exception("Item URI " + thisURI + " must point to same authority as related item: " + inboundItemURI);
913         }
914     }
915
916     public String getItemTermInfoGroupXPathBase() {
917         return authorityItemTermGroupXPathBase;
918     }
919         
920     public void setItemTermInfoGroupXPathBase(String itemTermInfoGroupXPathBase) {
921         authorityItemTermGroupXPathBase = itemTermInfoGroupXPathBase;
922     }
923     
924     protected String getAuthorityItemCommonSchemaName() {
925         return authorityItemCommonSchemaName;
926     }
927     
928     // @Override
929     public boolean isJDBCQuery() {
930         boolean result = false;
931         
932         MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams();
933         //
934         // Look the query params to see if we need to make a SQL query.
935         //
936         String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
937         if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
938                 result = true;
939         }
940         
941         return result;
942     }
943     
944     // By convention, the name of the database table that contains
945     // repeatable term information group records is derivable from
946     // an existing XPath base value, by removing a suffix and converting
947     // to lowercase
948     protected String getTermGroupTableName() {
949         String termInfoGroupListName = getItemTermInfoGroupXPathBase();
950         return termInfoGroupListName.substring(0, termInfoGroupListName.lastIndexOf(LIST_SUFFIX)).toLowerCase();
951     }
952     
953     protected String getInAuthorityValue() {
954         String inAuthorityValue = getInAuthority();
955         if (Tools.notBlank(inAuthorityValue)) {
956             return inAuthorityValue;
957         } else {
958             return AuthorityResource.PARENT_WILDCARD;
959         }
960     }
961     
962     @Override
963     public Map<String,String> getJDBCQueryParams() {
964         // FIXME: Get all of the following values from appropriate external constants.
965         // At present, these are duplicated in both RepositoryClientImpl
966         // and in AuthorityItemDocumentModelHandler.
967         final String TERM_GROUP_LIST_NAME = "TERM_GROUP_LIST_NAME";
968         final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
969         final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
970         
971         Map<String,String> params = super.getJDBCQueryParams();
972         params.put(TERM_GROUP_LIST_NAME, getItemTermInfoGroupXPathBase());
973         params.put(TERM_GROUP_TABLE_NAME_PARAM, getTermGroupTableName());
974         params.put(IN_AUTHORITY_PARAM, getInAuthorityValue());
975         return params;
976     }
977     
978 }