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