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