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