]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
fdcf0c5d529ff77082cbe950e0f0c54945fb7be8
[tmp/jakarta-migration.git] /
1 /**
2  *  This document is a part of the source code and related artifacts
3  *  for CollectionSpace, an open source collections management system
4  *  for museums and related institutions:
5
6  *  http://www.collectionspace.org
7  *  http://wiki.collectionspace.org
8
9  *  Copyright 2009 University of California at Berkeley
10
11  *  Licensed under the Educational Community License (ECL), Version 2.0.
12  *  You may not use this file except in compliance with this License.
13
14  *  You may obtain a copy of the ECL 2.0 License at
15
16  *  https://source.collectionspace.org/collection-space/LICENSE.txt
17
18  *  Unless required by applicable law or agreed to in writing, software
19  *  distributed under the License is distributed on an "AS IS" BASIS,
20  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21  *  See the License for the specific language governing permissions and
22  *  limitations under the License.
23  */
24 package org.collectionspace.services.common.vocabulary.nuxeo;
25
26 import org.collectionspace.services.client.AuthorityClient;
27 import org.collectionspace.services.client.IQueryManager;
28 import org.collectionspace.services.client.PoxPayloadIn;
29 import org.collectionspace.services.client.PoxPayloadOut;
30 import org.collectionspace.services.client.workflow.WorkflowClient;
31 import org.collectionspace.services.common.ServiceMain;
32 import org.collectionspace.services.common.UriTemplateRegistry;
33 import org.collectionspace.services.common.api.RefName;
34 import org.collectionspace.services.common.api.Tools;
35 import org.collectionspace.services.common.authorityref.AuthorityRefDocList;
36 import org.collectionspace.services.common.context.MultipartServiceContext;
37 import org.collectionspace.services.common.context.ServiceContext;
38 import org.collectionspace.services.common.document.DocumentException;
39 import org.collectionspace.services.common.document.DocumentFilter;
40 import org.collectionspace.services.common.document.DocumentNotFoundException;
41 import org.collectionspace.services.common.document.DocumentReferenceException;
42 import org.collectionspace.services.common.document.DocumentWrapper;
43 import org.collectionspace.services.common.repository.RepositoryClient;
44 import org.collectionspace.services.common.vocabulary.AuthorityJAXBSchema;
45 import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema;
46 import org.collectionspace.services.common.vocabulary.AuthorityResource;
47 import org.collectionspace.services.common.vocabulary.AuthorityServiceUtils;
48 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils;
49 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.AuthorityItemSpecifier;
50 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.SpecifierForm;
51 import org.collectionspace.services.config.service.ListResultField;
52 import org.collectionspace.services.config.service.ObjectPartType;
53 import org.collectionspace.services.lifecycle.TransitionDef;
54 import org.collectionspace.services.nuxeo.client.java.NuxeoDocumentModelHandler;
55 import org.collectionspace.services.nuxeo.client.java.CoreSessionInterface;
56 import org.collectionspace.services.nuxeo.client.java.RepositoryClientImpl;
57 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
58 import org.collectionspace.services.relation.RelationsCommonList;
59 import org.collectionspace.services.vocabulary.VocabularyItemJAXBSchema;
60
61 import org.nuxeo.ecm.core.api.ClientException;
62 import org.nuxeo.ecm.core.api.DocumentModel;
63 import org.nuxeo.ecm.core.api.model.PropertyException;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
66
67 import javax.ws.rs.core.MultivaluedMap;
68 import java.util.ArrayList;
69 import java.util.Collections;
70 import java.util.HashMap;
71 import java.util.List;
72 import java.util.Map;
73 import java.util.regex.Matcher;
74 import java.util.regex.Pattern;
75 import java.util.regex.PatternSyntaxException;
76
77 //import org.collectionspace.services.common.authority.AuthorityItemRelations;
78 /**
79  * AuthorityItemDocumentModelHandler
80  *
81  * $LastChangedRevision: $
82  * $LastChangedDate: $
83  */
84 public abstract class AuthorityItemDocumentModelHandler<AICommon>
85         extends NuxeoDocumentModelHandler<AICommon> {
86
87     private final Logger logger = LoggerFactory.getLogger(AuthorityItemDocumentModelHandler.class);
88     
89     protected String authorityCommonSchemaName;
90     protected String authorityItemCommonSchemaName;
91     private String authorityItemTermGroupXPathBase;
92     
93     private boolean isProposed = false; // used by local authority to propose a new shared item. Allows local deployments to use new terms until they become official
94     private boolean isSAS = false; // used to indicate if the authority item originated as a SAS item
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     //
114     // Getter and Setter for 'proposed'
115     //
116     public boolean getIsProposed() {
117         return this.isProposed;
118     }
119     
120     public void setIsProposed(boolean flag) {
121         this.isProposed = flag;
122     }
123     
124     //
125     // Getter and Setter for 'isSAS'
126     //
127     public boolean getIsSASItem() {
128         return this.isSAS;
129     }
130
131     public void setIsSASItem(boolean flag) {
132         this.isSAS = flag;
133     }
134     
135     //
136     // Getter and Setter for 'shouldUpdateRevNumber'
137     //
138     public boolean getShouldUpdateRevNumber() {
139         return this.shouldUpdateRevNumber;
140     }
141     
142     public void setShouldUpdateRevNumber(boolean flag) {
143         this.shouldUpdateRevNumber = flag;
144     }
145
146     @Override
147     public void prepareSync() throws Exception {
148         this.setShouldUpdateRevNumber(AuthorityServiceUtils.DONT_UPDATE_REV);  // Never update rev nums on sync operations
149     }
150
151     @Override
152     protected String getRefnameDisplayName(DocumentWrapper<DocumentModel> docWrapper) {
153         String result = null;
154         
155         DocumentModel docModel = docWrapper.getWrappedObject();
156         ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = this.getServiceContext();
157         RefName.AuthorityItem refname = (RefName.AuthorityItem)getRefName(ctx, docModel);
158         result = refname.getDisplayName();
159         
160         return result;
161     }
162     
163     /*
164      * After calling this method successfully, the document model will contain an updated refname and short ID
165      * (non-Javadoc)
166      * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#getRefName(org.collectionspace.services.common.context.ServiceContext, org.nuxeo.ecm.core.api.DocumentModel)
167      */
168     @Override
169     public RefName.RefNameInterface getRefName(ServiceContext ctx,
170                 DocumentModel docModel) {
171         RefName.RefNameInterface refname = null;
172         
173         try {
174                 String displayName = getPrimaryDisplayName(docModel, authorityItemCommonSchemaName,
175                     getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
176                 if (Tools.isEmpty(displayName)) {
177                     throw new Exception("The displayName for this authority term was empty or not set.");
178                 }
179         
180                 String shortIdentifier = (String) docModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
181                 if (Tools.isEmpty(shortIdentifier)) {
182                         // We didn't find a short ID in the payload request, so we need to synthesize one.
183                         shortIdentifier = handleDisplayNameAsShortIdentifier(docModel); // updates the document model with the new short ID as a side-effect
184                 }
185                 
186                 String authorityRefBaseName = getAuthorityRefNameBase();
187                 if (Tools.isEmpty(authorityRefBaseName)) {
188                     throw new Exception("Could not create the refName for this authority term, because the refName for its authority parent was empty.");
189                 }
190                 
191                 // Create the items refname using the parent's as a base
192                 RefName.Authority parentsRefName = RefName.Authority.parse(authorityRefBaseName);
193                 refname = RefName.buildAuthorityItem(parentsRefName, shortIdentifier, displayName);
194                 // Now update the document model with the refname value
195                 String refNameStr = refname.toString();
196                 docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REF_NAME, refNameStr); // REM - This field is deprecated now that the refName is part of the collection_space core schema
197
198         } catch (Exception e) {
199                 logger.error(e.getMessage(), e);
200         }
201
202         return refname;
203     }
204     
205     public void setInAuthority(String inAuthority) {
206         this.inAuthority = inAuthority;
207     }
208     
209    public String getInAuthorityCsid() {
210         return this.inAuthority;
211     }
212
213     /** Subclasses may override this to customize the URI segment. */
214     public String getAuthorityServicePath() {
215         return getServiceContext().getServiceName().toLowerCase();    // Laramie20110510 CSPACE-3932
216     }
217
218     @Override
219     public String getUri(DocumentModel docModel) {
220         // Laramie20110510 CSPACE-3932
221         String authorityServicePath = getAuthorityServicePath();
222         if(inAuthority==null) { // Only true with the first document model received, on queries to wildcarded authorities
223             wildcardedAuthorityRequest = true;
224         }
225         // If this search crosses multiple authorities, get the inAuthority value
226         // from each record, rather than using the cached value from the first record
227         if(wildcardedAuthorityRequest) {
228                 try {
229                         inAuthority = (String) docModel.getProperty(authorityItemCommonSchemaName,
230                         AuthorityItemJAXBSchema.IN_AUTHORITY);
231                 } catch (ClientException pe) {
232                         throw new RuntimeException("Could not get parent specifier for item!");
233                 }
234         }
235         return "/" + authorityServicePath + '/' + inAuthority + '/' + AuthorityClient.ITEMS + '/' + getCsid(docModel);
236     }
237
238     protected String getAuthorityRefNameBase() {
239         return this.authorityRefNameBase;
240     }
241
242     public void setAuthorityRefNameBase(String value) {
243         this.authorityRefNameBase = value;
244     }
245
246     /*
247      * Note: the Vocabulary service's VocabularyItemDocumentModelHandler class overrides this method.
248      */
249     protected ListResultField getListResultsDisplayNameField() {
250         ListResultField result = new ListResultField();
251         // Per CSPACE-5132, the name of this element remains 'displayName'
252         // for backwards compatibility, although its value is obtained
253         // from the termDisplayName field.
254         //
255         // Update: this name is now being changed to 'termDisplayName', both
256         // because this is the actual field name and because the app layer
257         // work to convert over to this field is underway. Per Patrick, the
258         // app layer treats lists, in at least some context(s), as sparse record
259         // payloads, and thus fields in list results must all be present in
260         // (i.e. represent a strict subset of the fields in) record schemas.
261         // - ADR 2012-05-11
262         // 
263         //
264         // In CSPACE-5134, these list results will change substantially
265         // to return display names for both the preferred term and for
266         // each non-preferred term (if any).
267         result.setElement(AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
268         result.setXpath(NuxeoUtils.getPrimaryXPathPropertyName(
269                 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_DISPLAY_NAME));
270         
271         return result;
272     }
273     
274     /*
275      * Note: the Vocabulary service's VocabularyItemDocumentModelHandler class overrides this method.
276      */    
277     protected ListResultField getListResultsTermStatusField() {
278         ListResultField result = new ListResultField();
279         
280         result.setElement(AuthorityItemJAXBSchema.TERM_STATUS);
281         result.setXpath(NuxeoUtils.getPrimaryXPathPropertyName(
282                 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_STATUS));
283
284         return result;
285     }    
286     
287     private boolean isTermDisplayName(String elName) {
288         return AuthorityItemJAXBSchema.TERM_DISPLAY_NAME.equals(elName) || VocabularyItemJAXBSchema.DISPLAY_NAME.equals(elName);
289     }
290     
291     /*
292      * (non-Javadoc)
293      * @see org.collectionspace.services.nuxeo.client.java.DocHandlerBase#getListItemsArray()
294      * 
295      * Note: We're updating the "global" service and tenant bindings instance here -the list instance here is
296      * a reference to the tenant bindings instance in the singleton ServiceMain.
297      */
298     @Override
299     public List<ListResultField> getListItemsArray() throws DocumentException {
300         List<ListResultField> list = super.getListItemsArray();
301         
302         // One-time initialization for each authority item service.
303         if (isListItemArrayExtended() == false) {
304                 synchronized(AuthorityItemDocumentModelHandler.class) {
305                         if (isListItemArrayExtended() == false) {                               
306                         int nFields = list.size();
307                         // Ensure that each item in a list of Authority items includes
308                         // a set of common fields, so we do not depend upon configuration
309                         // for general logic.
310                         List<Integer> termDisplayNamePositionsInList = new ArrayList<>();
311                         boolean hasShortId = false;
312                         boolean hasTermStatus = false;
313                         for (int i = 0; i < nFields; i++) {
314                             ListResultField field = list.get(i);
315                             String elName = field.getElement();
316                             if (isTermDisplayName(elName) == true) {
317                                 termDisplayNamePositionsInList.add(i);
318                             } else if (AuthorityItemJAXBSchema.SHORT_IDENTIFIER.equals(elName)) {
319                                 hasShortId = true;
320                             } else if (AuthorityItemJAXBSchema.TERM_STATUS.equals(elName)) {
321                                 hasTermStatus = true;
322                             }
323                         }
324                                 
325                         ListResultField field;
326                         
327                         // Certain fields in authority item list results
328                         // are handled specially here
329                         
330                         // Term display name
331                         //
332                         // Ignore (throw out) any configuration entries that
333                         // specify how the termDisplayName field should be
334                         // emitted in authority item lists. This field will
335                         // be handled in a standardized manner (see block below).
336                         if (termDisplayNamePositionsInList.isEmpty() == false) {
337                             // Remove matching items starting at the end of the list
338                             // and moving towards the start, so that reshuffling of
339                             // list order doesn't alter the positions of earlier items
340                             Collections.sort(termDisplayNamePositionsInList, Collections.reverseOrder());
341                             for (int i : termDisplayNamePositionsInList) {
342                                 list.remove(i);
343                             }
344                         }
345                         // termDisplayName values in authority item lists
346                         // will be handled via code that emits display names
347                         // for both the preferred term and all non-preferred
348                         // terms (if any). The following is a placeholder
349                         // entry that will trigger this code. See the
350                         // getListResultValue() method in this class.
351                         field = getListResultsDisplayNameField();
352                         list.add(field);
353                         
354                         // Short identifier
355                         if (!hasShortId) {
356                             field = new ListResultField();
357                             field.setElement(AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
358                             field.setXpath(AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
359                             list.add(field);
360                         }
361                         
362                         // Term status
363                         if (!hasTermStatus) {
364                             field = getListResultsTermStatusField();
365                             list.add(field);
366                         }
367                         
368                         }
369      
370                         setListItemArrayExtended(true);
371                 } // end of synchronized block
372         }
373
374         return list;
375     }
376     
377     /**
378      * We consider workflow state changes as a change that should bump the revision number.
379      * Warning: This method might change the transitionDef's transtionName value
380      */
381     @Override
382     public void handleWorkflowTransition(ServiceContext ctx, DocumentWrapper<DocumentModel> wrapDoc, TransitionDef transitionDef) throws Exception {
383         // Decide whether or not to update the revision number
384         if (this.getShouldUpdateRevNumber() == true) { // We don't update the rev number of synchronization requests
385                 updateRevNumbers(wrapDoc);
386         }
387         //
388         // We can't delete an authority item that has referencing records.
389         //
390         DocumentModel docModel = wrapDoc.getWrappedObject();
391         if (transitionDef.getName().equalsIgnoreCase(WorkflowClient.WORKFLOWTRANSITION_DELETE)) {
392                 long refsToAllObjects = hasReferencingObjects(ctx, docModel, false);
393                 long refsToSoftDeletedObjects = hasReferencingObjects(ctx, docModel, true);
394                 if (refsToAllObjects > 0) {
395                 if (refsToAllObjects > refsToSoftDeletedObjects) {
396                         //
397                         // If the number of refs to active objects is greater than the number of refs to
398                         // soft deleted objects then we can't delete the item.
399                         //
400                         throw new DocumentReferenceException(String.format("Cannot delete authority item '%s' because it still has records in the system that are referencing it.  See the service layer log file for details.",
401                                         docModel.getName()));
402                 }
403                 }
404         }
405     }
406         
407     /**
408      * This method synchronizes/updates a single authority item resource.
409      * for the handleSync method, the wrapDoc argument contains a authority item specifier.
410      */
411     @Override
412     public boolean handleSync(DocumentWrapper<Object> wrapDoc) throws Exception {
413         boolean result = false;
414         ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
415         
416         //
417         // Get information about the local authority item so we can compare with corresponding item on the shared authority server
418         //
419         AuthorityItemSpecifier authorityItemSpecifier = (AuthorityItemSpecifier) wrapDoc.getWrappedObject();
420         DocumentModel itemDocModel = NuxeoUtils.getDocFromSpecifier(ctx, getRepositorySession(), getAuthorityItemCommonSchemaName(), 
421                         authorityItemSpecifier);
422         if (itemDocModel == null) {
423                 throw new DocumentNotFoundException(String.format("Could not find authority item resource with CSID='%s'",
424                                 authorityItemSpecifier.getItemSpecifier().value));
425         }
426         Long localItemRev = (Long) NuxeoUtils.getProperyValue(itemDocModel, AuthorityItemJAXBSchema.REV);
427         Boolean localIsProposed = (Boolean) NuxeoUtils.getProperyValue(itemDocModel, AuthorityItemJAXBSchema.PROPOSED);
428         String localItemCsid = itemDocModel.getName();
429         String localItemWorkflowState = itemDocModel.getCurrentLifeCycleState();
430         String itemShortId = (String) NuxeoUtils.getProperyValue(itemDocModel, AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
431         
432         //
433         // Now get the item's Authority (the parent) information
434         //
435         DocumentModel authorityDocModel = NuxeoUtils.getDocFromSpecifier(ctx, getRepositorySession(), authorityCommonSchemaName,
436                         authorityItemSpecifier.getParentSpecifier());
437         String authorityShortId = (String) NuxeoUtils.getProperyValue(authorityDocModel, AuthorityJAXBSchema.SHORT_IDENTIFIER);
438         String localParentCsid = authorityDocModel.getName();
439         //
440         // Using the short IDs of the local authority and item, create URN specifiers to retrieve the SAS authority item
441         //
442         AuthorityItemSpecifier sasAuthorityItemSpecifier = new AuthorityItemSpecifier(SpecifierForm.URN_NAME, authorityShortId, itemShortId);
443         // Get the shared authority server's copy
444         PoxPayloadIn sasPayloadIn = AuthorityServiceUtils.requestPayloadIn(sasAuthorityItemSpecifier, 
445                         getAuthorityServicePath(), getEntityResponseType());
446         Long sasRev = getRevision(sasPayloadIn);
447         String sasWorkflowState = getWorkflowState(sasPayloadIn);
448         //
449         // If the shared authority item is newer, update our local copy
450         //
451         if (sasRev > localItemRev || localIsProposed) {
452                 sasPayloadIn = AuthorityServiceUtils.filterRefnameDomains(ctx, sasPayloadIn); // We need to filter the domain name part of any and all refnames in the payload
453                 AuthorityResource authorityResource = (AuthorityResource) ctx.getResource(getAuthorityServicePath());
454                 PoxPayloadOut payloadOut = authorityResource.updateAuthorityItem(ctx, 
455                                 ctx.getResourceMap(),                                   
456                                 ctx.getUriInfo(),
457                                 localParentCsid,                                                // parent's CSID
458                                 localItemCsid,                                                  // item's CSID
459                                 sasPayloadIn,                                                   // the payload from the remote SAS
460                                 AuthorityServiceUtils.DONT_UPDATE_REV,  // don't update the parent's revision number
461                                 AuthorityServiceUtils.NOT_PROPOSED,             // The items is not proposed, make it a real SAS item now
462                                 AuthorityServiceUtils.SAS_ITEM);                // Since we're sync'ing, this must be a SAS item
463                 if (payloadOut != null) {       
464                         ctx.setOutput(payloadOut);
465                         result = true;
466                 }
467         }
468         //
469         // Check to see if we need to update the local items's workflow state to reflect that of the remote's
470         //
471         List<String> transitionList = getTransitionList(sasWorkflowState, localItemWorkflowState);
472         if (transitionList.isEmpty() == false) {
473                 AuthorityResource authorityResource = (AuthorityResource) ctx.getResource(getAuthorityServicePath()); // Get the authority (parent) client not the item client
474                 //
475                 // We need to move the local item to the SAS workflow state.  This might involve multiple transitions.
476                 //
477                 for (String transition:transitionList) {
478                         try {
479                                 authorityResource.updateItemWorkflowWithTransition(ctx, localParentCsid, localItemCsid, transition, AuthorityServiceUtils.DONT_UPDATE_REV);
480                         } catch (DocumentReferenceException de) {
481                                 //
482                                 // This exception means we tried unsuccessfully to soft-delete (workflow transition 'delete') an item that still has references to it from other records.
483                                 //
484                                 AuthorityServiceUtils.setAuthorityItemDeprecated(ctx, itemDocModel, authorityItemCommonSchemaName, AuthorityServiceUtils.DEPRECATED);  // Since we can't sof-delete it, we need to mark it as deprecated since it is soft-deleted on the SAS
485                                 logger.warn(String.format("Could not transition item CSID='%s' from workflow state '%s' to '%s'.  Check the services log file for details.",
486                                                 localItemCsid, localItemWorkflowState, sasWorkflowState));
487                         }
488                 }
489                 result = true;
490         }
491         //
492         // We need to synchronize the hierarchy relationships here.
493         //
494         
495         return result;
496     }
497     
498     /**
499      * We need to change the local item's state to one that maps to the replication server's workflow
500      * state.  This might involve making multiple transitions.
501      * 
502      * WIKI:
503      *  See table at https://wiki.collectionspace.org/pages/viewpage.action?pageId=162496564
504      * 
505      */
506     private List<String> getTransitionList(String sasWorkflowState, String localItemWorkflowState) throws DocumentException {
507         List<String> result = new ArrayList<String>();          
508         //
509         // The first set of conditions maps a replication-server "project" state to a local client state of "replicated"
510         //
511         if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT)) {
512                 result.add(WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
513         } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED)) {
514                 result.add(WorkflowClient.WORKFLOWTRANSITION_UNDELETE);
515                 result.add(WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
516         } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED)) {
517                 // Do nothing.  We're good with this state
518         } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED)) {
519                 result.add(WorkflowClient.WORKFLOWTRANSITION_UNDELETE);
520         //
521         // The second set of conditions maps a replication-server "deleted" state to a local client state of "deleted"
522         //
523         } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT)) {
524                 result.add(WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
525                 result.add(WorkflowClient.WORKFLOWTRANSITION_DELETE);
526         } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED)) {
527                 result.add(WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
528         } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED)) {
529                 result.add(WorkflowClient.WORKFLOWTRANSITION_DELETE);
530         } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED)) {
531                 // Do nothing.  We're good with this state
532         //
533         // The third set of conditions maps a replication-server "replicated" state to a local state of "replicated"
534         //
535         } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT)) {
536                 result.add(WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
537         } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED)) {
538                 result.add(WorkflowClient.WORKFLOWTRANSITION_UNDELETE);
539                 result.add(WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
540         } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED)) {
541                 // Do nothing.  We're good with this state
542         } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED)) {
543                 result.add(WorkflowClient.WORKFLOWTRANSITION_UNDELETE);
544                 //
545         // The last set of conditions maps a replication-server "replicated_deleted" state to a local client state of "deleted"
546         //
547         } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT)) {
548                 result.add(WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
549                 result.add(WorkflowClient.WORKFLOWTRANSITION_DELETE);
550         } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED)) {
551                 result.add(WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
552         } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED)) {
553                 result.add(WorkflowClient.WORKFLOWTRANSITION_DELETE);
554         } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED)) {
555                 // Do nothing.  We're good with this state              
556         } else {
557                 //
558                 // If we get here, we've encountered a SAS workflow state that we don't recognize.
559                 //
560                 throw new DocumentException(String.format("Encountered an invalid workflow state of '%s' on a SAS authority item.", sasWorkflowState));
561         }
562         
563         return result;
564     }
565     
566     /* (non-Javadoc)
567      * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#handleCreate(org.collectionspace.services.common.document.DocumentWrapper)
568      */
569     @Override
570     public void handleCreate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
571         // first fill all the parts of the document, refname and short ID get set as well
572         super.handleCreate(wrapDoc);
573         // Ensure we have required fields set properly
574         handleInAuthority(wrapDoc.getWrappedObject());        
575     }
576
577     /*
578      * This method gets called after the primary update to an authority item has happened.  If the authority item's refName
579      * has changed, then we need to updated all the records that use that refname with the new/updated version
580      * 
581      * (non-Javadoc)
582      */
583     @Override
584     public boolean handleDelete(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
585         boolean result = true;
586         
587         ServiceContext ctx = getServiceContext();
588         DocumentModel docModel = wrapDoc.getWrappedObject();
589         
590         long refsToAllObjects = hasReferencingObjects(ctx, docModel, false);
591         long refsToSoftDeletedObjects = hasReferencingObjects(ctx, docModel, true);
592         if (refsToAllObjects > 0) {
593                 if (refsToAllObjects > refsToSoftDeletedObjects) {
594                         //
595                         // If the number of refs to active objects is greater than the number of refs to
596                         // soft deleted objects then we can't delete the item.
597                         //
598                         throw new DocumentReferenceException(String.format("Cannot delete authority item '%s' because it still has records in the system that are referencing it.  See the service layer log file for details.",
599                                         docModel.getName()));
600                 } else {
601                         //
602                         // If all the refs are to soft-deleted objects, we should soft-delete this authority item instead of hard-deleting it and instead of failing.
603                         //
604                         Boolean shouldUpdateRev = (Boolean) ctx.getProperty(AuthorityServiceUtils.SHOULD_UPDATE_REV_PROPERTY);
605                         String parentCsid = (String) NuxeoUtils.getProperyValue(docModel, AuthorityItemJAXBSchema.IN_AUTHORITY);
606                         String itemCsid = docModel.getName();
607                         AuthorityResource authorityResource = (AuthorityResource) ctx.getResource(getAuthorityServicePath());
608                         authorityResource.updateItemWorkflowWithTransition(ctx, parentCsid, itemCsid, WorkflowClient.WORKFLOWTRANSITION_DELETE, 
609                                         shouldUpdateRev != null ? shouldUpdateRev : true);
610                         result = false; // Don't delete since we just soft-deleted it.
611                 }
612         }
613         
614         return result;
615     }
616     
617     /**
618      * Checks to see if an authority item has referencing objects.
619      * 
620      * @param ctx
621      * @param docModel
622      * @return
623      * @throws Exception
624      */
625     private long hasReferencingObjects(ServiceContext ctx, DocumentModel docModel, boolean onlyRefsToDeletedObjects) throws Exception {
626         long result = 0;
627         
628         String inAuthorityCsid = (String) docModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.IN_AUTHORITY);
629         AuthorityResource authorityResource = (AuthorityResource)ctx.getResource(getAuthorityServicePath());
630         String itemCsid = docModel.getName();
631         UriTemplateRegistry uriTemplateRegistry = ServiceMain.getInstance().getUriTemplateRegistry();
632         if (ctx.getUriInfo() == null) {
633                 //
634                 // We need a UriInfo object so we can pass "query" params to the AuthorityResource's getReferencingObjects() method
635                 //
636                 ctx.setUriInfo(this.getServiceContext().getUriInfo()); // try to get a UriInfo instance from the handler's context
637         }
638         ctx.getUriInfo().getQueryParameters().addFirst(WorkflowClient.WORKFLOW_QUERY_ONLY_DELETED, Boolean.toString(onlyRefsToDeletedObjects));  // Add the wf_only_deleted query param to the resource call
639         AuthorityRefDocList refObjs = authorityResource.getReferencingObjects(ctx, inAuthorityCsid, itemCsid, 
640                         uriTemplateRegistry, ctx.getUriInfo());
641         ctx.getUriInfo().getQueryParameters().remove(WorkflowClient.WORKFLOW_QUERY_ONLY_DELETED);  // Need to clear wf_only_deleted values to prevent unexpected side effects
642         
643         result = refObjs.getTotalItems();
644         if (result > 0) {
645                 logger.error(String.format("Cannot delete authority item '%s' because it still has %d records in the system that are referencing it.",
646                                 itemCsid, refObjs.getTotalItems()));
647                 if (logger.isWarnEnabled() == true) {
648                         logReferencingObjects(docModel, refObjs);
649                 }
650         }
651         
652         return result;
653     }
654     
655     private void logReferencingObjects(DocumentModel docModel, AuthorityRefDocList refObjs) {
656         List<AuthorityRefDocList.AuthorityRefDocItem> items = refObjs.getAuthorityRefDocItem();
657         int i = 0;
658         logger.warn(String.format("The authority item '%s' has the following references:", docModel.getName()));
659         for (AuthorityRefDocList.AuthorityRefDocItem item : items) {
660             logger.warn(docModel.getName() + " referenced by : list-item[" + i + "] "
661                     + item.getDocType() + "("
662                     + item.getDocId() + ") Name:["
663                     + item.getDocName() + "] Number:["
664                     + item.getDocNumber() + "] in field:["
665                     + item.getSourceField() + "]");
666         }
667     }
668
669     /*
670      * This method gets called after the primary update to an authority item has happened.  If the authority item's refName
671      * has changed, then we need to updated all the records that use that refname with the new/updated version
672      * 
673      * (non-Javadoc)
674      * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#completeUpdate(org.collectionspace.services.common.document.DocumentWrapper)
675      */
676     public void completeUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
677         // Must call our super class' version first
678         super.completeUpdate(wrapDoc);
679         
680         //
681         // Look for and update authority references with the updated refName
682         //
683         if (hasRefNameUpdate() == true) {
684             // We have work to do.
685             if (logger.isDebugEnabled()) {
686                 final String EOL = System.getProperty("line.separator");
687                 logger.debug("Need to find and update references to authority item." + EOL
688                         + "   Old refName" + oldRefNameOnUpdate + EOL
689                         + "   New refName" + newRefNameOnUpdate);
690             }
691             ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
692             RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient = getRepositoryClient(ctx);
693             CoreSessionInterface repoSession = this.getRepositorySession();
694             
695             // Update all the existing records that have a field with the old refName in it
696             int nUpdated = RefNameServiceUtils.updateAuthorityRefDocs(ctx, repoClient, repoSession,
697                     oldRefNameOnUpdate, newRefNameOnUpdate, getRefPropName());
698             
699             // Finished so log a message.
700             if (logger.isDebugEnabled()) {
701                 logger.debug("Updated " + nUpdated + " instances of oldRefName to newRefName");
702             }
703         }
704     }
705     
706     /*
707      * Note that the Vocabulary service's document-model for items overrides this method.
708      */
709         protected String getPrimaryDisplayName(DocumentModel docModel, String schema,
710                         String complexPropertyName, String fieldName) {
711                 String result = null;
712
713                 result = getStringValueInPrimaryRepeatingComplexProperty(docModel, schema, complexPropertyName, fieldName);
714                 
715                 return result;
716         }
717     
718     /* (non-Javadoc)
719      * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#handleUpdate(org.collectionspace.services.common.document.DocumentWrapper)
720      */
721     @Override
722     // 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.
723     @Deprecated
724     public void handleUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
725         // Must call our super's version first, this updates the core schema and the relationship records to deal with possible refName changes/update
726         super.handleUpdate(wrapDoc);
727         if (this.hasRefNameUpdate() == true) {
728                 DocumentModel docModel = wrapDoc.getWrappedObject();
729             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                
730         }
731     }
732     
733     //
734     // Handles both update calls (PUTS) AND create calls (POSTS)
735     //
736     public void fillAllParts(DocumentWrapper<DocumentModel> wrapDoc, Action action) throws Exception {
737         super.fillAllParts(wrapDoc, action);
738         DocumentModel documentModel = wrapDoc.getWrappedObject();
739
740         //
741         // Update the record's revision number on both CREATE and UPDATE actions (as long as it is NOT a SAS authority item)
742         //
743         Boolean propertyValue = (Boolean) documentModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SAS);
744         boolean isMarkedAsSASItem = propertyValue != null ? propertyValue : false;
745         if (this.getShouldUpdateRevNumber() == true && !isMarkedAsSASItem) { // We won't update rev numbers on synchronization with SAS items and on local changes to SAS items
746                 updateRevNumbers(wrapDoc);
747         }
748         //
749         // If this is a proposed item (not part of the SAS), mark it as such
750         //
751         documentModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.PROPOSED,
752                         new Boolean(this.getIsProposed()));
753         //
754         // If it is a SAS authority item, mark it as such
755         //
756         documentModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SAS,
757                         new Boolean(this.getIsSASItem()));
758     }
759     
760     /**
761      * Update the revision number of both the item and the item's parent.
762      * @param wrapDoc
763      * @throws Exception
764      */
765     protected void updateRevNumbers(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
766         DocumentModel documentModel = wrapDoc.getWrappedObject();
767         Long rev = (Long)documentModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REV);
768         if (rev == null) {
769                 rev = (long)0;
770         } else {
771                 rev++;
772         }
773         documentModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REV, rev);
774         //
775         // Next, update the inAuthority (the parent's) rev number
776         //
777         String inAuthorityCsid = this.getInAuthorityCsid();
778         if (inAuthorityCsid == null) {
779                 // When inAuthorityCsid is null, it usually means we're performing and update or synch with the SAS
780                 inAuthorityCsid = (String)documentModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.IN_AUTHORITY);
781         }
782         DocumentModel inAuthorityDocModel = NuxeoUtils.getDocFromCsid(getServiceContext(), getRepositorySession(), inAuthorityCsid);
783         Long parentRev = (Long)inAuthorityDocModel.getProperty(getParentCommonSchemaName(), AuthorityJAXBSchema.REV);
784         if (parentRev == null) {
785                 parentRev = new Long(0);
786         }
787                 parentRev++;
788                 inAuthorityDocModel.setProperty(getParentCommonSchemaName(), AuthorityJAXBSchema.REV, parentRev);
789                 getRepositorySession().saveDocument(inAuthorityDocModel);
790     }    
791     
792     /**
793      * If no short identifier was provided in the input payload, generate a
794      * short identifier from the preferred term display name or term name.
795      */
796         private String handleDisplayNameAsShortIdentifier(DocumentModel docModel) throws Exception {
797                 String result = (String) docModel.getProperty(authorityItemCommonSchemaName,
798                                 AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
799
800                 if (Tools.isEmpty(result)) {
801                         String termDisplayName = getPrimaryDisplayName(
802                                         docModel, authorityItemCommonSchemaName,
803                                         getItemTermInfoGroupXPathBase(),
804                                         AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
805
806                         String termName = getPrimaryDisplayName(
807                                         docModel, authorityItemCommonSchemaName,
808                                         getItemTermInfoGroupXPathBase(),
809                                         AuthorityItemJAXBSchema.TERM_NAME);
810
811                         String generatedShortIdentifier = AuthorityIdentifierUtils.generateShortIdentifierFromDisplayName(termDisplayName,
812                                                         termName);
813                         docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER,
814                                         generatedShortIdentifier);
815                         result = generatedShortIdentifier;
816                 }
817                 
818                 return result;
819         }
820
821     /**
822      * Generate a refName for the authority item from the short identifier
823      * and display name.
824      * 
825      * All refNames for authority items are generated.  If a client supplies
826      * a refName, it will be overwritten during create (per this method) 
827      * or discarded during update (per filterReadOnlyPropertiesForPart).
828      * 
829      * @see #filterReadOnlyPropertiesForPart(Map<String, Object>, org.collectionspace.services.common.service.ObjectPartType)
830      * 
831      */
832     protected String updateRefnameForAuthorityItem(DocumentModel docModel,
833             String schemaName) throws Exception {
834         String result = null;
835         
836         RefName.RefNameInterface refname = getRefName(getServiceContext(), docModel);
837         String refNameStr = refname.toString();
838         docModel.setProperty(schemaName, AuthorityItemJAXBSchema.REF_NAME, refNameStr);
839         result = refNameStr;
840         
841         return result;
842     }
843
844     /**
845      * Check the logic around the parent pointer. Note that we only need do this on
846      * create, since we have logic to make this read-only on update. 
847      * 
848      * @param docModel
849      * 
850      * @throws Exception the exception
851      */
852     private void handleInAuthority(DocumentModel docModel) throws Exception {
853         if(inAuthority==null) { // Only happens on queries to wildcarded authorities
854                 throw new IllegalStateException("Trying to Create an object with no inAuthority value!");
855         }
856         docModel.setProperty(authorityItemCommonSchemaName,
857                 AuthorityItemJAXBSchema.IN_AUTHORITY, inAuthority);
858     }
859     
860     /**
861      * Returns a list of records that reference this authority item
862      * 
863      * @param ctx
864      * @param uriTemplateRegistry
865      * @param serviceTypes
866      * @param propertyName
867      * @param itemcsid
868      * @return
869      * @throws Exception
870      */
871     public AuthorityRefDocList getReferencingObjects(
872                 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
873                 UriTemplateRegistry uriTemplateRegistry, 
874                 List<String> serviceTypes,
875                 String propertyName,
876             String itemcsid) throws Exception {
877         AuthorityRefDocList authRefDocList = null;
878         CoreSessionInterface repoSession = (CoreSessionInterface) ctx.getCurrentRepositorySession();
879         boolean releaseRepoSession = false;
880         
881         try {
882                 RepositoryClientImpl repoClient = (RepositoryClientImpl)this.getRepositoryClient(ctx);
883                 repoSession = this.getRepositorySession();
884                 if (repoSession == null) {
885                         repoSession = repoClient.getRepositorySession(ctx);
886                         releaseRepoSession = true;
887                 }
888             DocumentFilter myFilter = getDocumentFilter();
889
890                 try {
891                         DocumentWrapper<DocumentModel> wrapper = repoClient.getDoc(repoSession, ctx, itemcsid);
892                         DocumentModel docModel = wrapper.getWrappedObject();
893                         String refName = (String) NuxeoUtils.getProperyValue(docModel, AuthorityItemJAXBSchema.REF_NAME); //docModel.getPropertyValue(AuthorityItemJAXBSchema.REF_NAME);
894                 authRefDocList = RefNameServiceUtils.getAuthorityRefDocs(
895                                 repoSession, ctx, uriTemplateRegistry, repoClient,
896                         serviceTypes,
897                         refName,
898                         propertyName,
899                         myFilter, true /*computeTotal*/);
900                 } catch (PropertyException pe) {
901                         throw pe;
902                 } catch (DocumentException de) {
903                         throw de;
904                 } catch (Exception e) {
905                         if (logger.isDebugEnabled()) {
906                                 logger.debug("Caught exception ", e);
907                         }
908                         throw new DocumentException(e);
909                 } finally {
910                         // If we got/aquired a new seesion then we're responsible for releasing it.
911                         if (releaseRepoSession && repoSession != null) {
912                                 repoClient.releaseRepositorySession(ctx, repoSession);
913                         }
914                 }
915         } catch (Exception e) {
916                 if (logger.isDebugEnabled()) {
917                         logger.debug("Caught exception ", e);
918                 }
919                 throw new DocumentException(e);
920         }
921         
922         return authRefDocList;
923     }
924
925     /* (non-Javadoc)
926      * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#extractPart(org.nuxeo.ecm.core.api.DocumentModel, java.lang.String, org.collectionspace.services.common.service.ObjectPartType)
927      */
928     @Override
929     protected Map<String, Object> extractPart(DocumentModel docModel, String schema, ObjectPartType partMeta)
930             throws Exception {
931         Map<String, Object> unQObjectProperties = super.extractPart(docModel, schema, partMeta);
932
933         // Add the CSID to the common part, since they may have fetched via the shortId.
934         if (partMeta.getLabel().equalsIgnoreCase(authorityItemCommonSchemaName)) {
935             String csid = getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
936             unQObjectProperties.put("csid", csid);
937         }
938
939         return unQObjectProperties;
940     }
941
942     /**
943      * Filters out selected values supplied in an update request.
944      * 
945      * For example, filters out AuthorityItemJAXBSchema.IN_AUTHORITY, to ensure
946      * that the link to the item's parent remains untouched.
947      * 
948      * @param objectProps the properties filtered out from the update payload
949      * @param partMeta metadata for the object to fill
950      */
951     @Override
952     public void filterReadOnlyPropertiesForPart(
953             Map<String, Object> objectProps, ObjectPartType partMeta) {
954         super.filterReadOnlyPropertiesForPart(objectProps, partMeta);
955         String commonPartLabel = getServiceContext().getCommonPartLabel();
956         if (partMeta.getLabel().equalsIgnoreCase(commonPartLabel)) {
957             objectProps.remove(AuthorityItemJAXBSchema.IN_AUTHORITY);
958             objectProps.remove(AuthorityItemJAXBSchema.CSID);
959             objectProps.remove(AuthorityJAXBSchema.SHORT_IDENTIFIER);
960             objectProps.remove(AuthorityItemJAXBSchema.REF_NAME);
961         }
962     }
963     
964     /**
965      * Returns the items in a list of term display names whose names contain
966      * a partial term (as might be submitted in a search query, for instance).
967      * @param termDisplayNameList a list of term display names.
968      * @param partialTerm a partial term display name; that is, a portion
969      * of a display name that might be expected to match 0-n terms in the list.
970      * @return a list of term display names that matches the partial term.
971      * Matches are case-insensitive. As well, before matching is performed, any
972      * special-purpose characters that may appear in the partial term (such as
973      * wildcards and anchor characters) are filtered out from both compared terms.
974      */
975     protected List<String> getPartialTermDisplayNameMatches(List<String> termDisplayNameList, String partialTerm) {
976         List<String> result = new ArrayList<>();
977         String partialTermMatchExpression = filterAnchorAndWildcardChars(partialTerm).toLowerCase();
978         try {
979             for (String termDisplayName : termDisplayNameList) {
980                 if (termDisplayName.toLowerCase()
981                         .matches(partialTermMatchExpression) == true) {
982                         result.add(termDisplayName);
983                 }
984             }
985         } catch (PatternSyntaxException pse) {
986             logger.warn("Error in regex match pattern '%s' for term display names: %s",
987                     partialTermMatchExpression, pse.getMessage());
988         }
989         return result;
990     }
991     
992     /**
993      * Filters user-supplied anchor and wildcard characters in a string,
994      * replacing them with equivalent regular expressions.
995      * @param term a term in which to filter anchor and wildcard characters.
996      * @return the term with those characters filtered.
997      */
998     protected String filterAnchorAndWildcardChars(String term) {
999         if (Tools.isBlank(term)) {
1000             return term;
1001         }
1002         if (term.length() < 3) {
1003             return term;
1004         }
1005         if (logger.isTraceEnabled()) {
1006             logger.trace(String.format("Term = %s", term));
1007         }
1008         Boolean anchorAtStart = false;
1009         Boolean anchorAtEnd = false;
1010         String filteredTerm;
1011         StringBuilder filteredTermBuilder = new StringBuilder(term);
1012         // Term contains no anchor or wildcard characters.
1013         if ( (! term.contains(RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR))
1014                 && (! term.contains(RepositoryClientImpl.USER_SUPPLIED_WILDCARD)) ) {
1015             filteredTerm = term;
1016         } else {
1017             // Term contains at least one such character.
1018             try {
1019                 // Filter the starting anchor or wildcard character, if any.
1020                 String firstChar = filteredTermBuilder.substring(0,1);
1021                 switch (firstChar) {
1022                     case RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR:
1023                         anchorAtStart = true;
1024                         break;
1025                     case RepositoryClientImpl.USER_SUPPLIED_WILDCARD:
1026                         filteredTermBuilder.deleteCharAt(0);
1027                         break;
1028                 }
1029                 if (logger.isTraceEnabled()) {
1030                     logger.trace(String.format("After first char filtering = %s", filteredTermBuilder.toString()));
1031                 }
1032                 // Filter the ending anchor or wildcard character, if any.
1033                 int lastPos = filteredTermBuilder.length() - 1;
1034                 String lastChar = filteredTermBuilder.substring(lastPos);
1035                 switch (lastChar) {
1036                     case RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR:
1037                         filteredTermBuilder.deleteCharAt(lastPos);
1038                         filteredTermBuilder.insert(filteredTermBuilder.length(), RepositoryClientImpl.ENDING_ANCHOR_CHAR);
1039                         anchorAtEnd = true;
1040                         break;
1041                     case RepositoryClientImpl.USER_SUPPLIED_WILDCARD:
1042                         filteredTermBuilder.deleteCharAt(lastPos);
1043                         break;
1044                 }
1045                 if (logger.isTraceEnabled()) {
1046                     logger.trace(String.format("After last char filtering = %s", filteredTermBuilder.toString()));
1047                 }
1048                 filteredTerm = filteredTermBuilder.toString();
1049                 // Filter all other wildcards, if any.
1050                 filteredTerm = filteredTerm.replaceAll(RepositoryClientImpl.USER_SUPPLIED_WILDCARD_REGEX, ZERO_OR_MORE_ANY_CHAR_REGEX);
1051                 if (logger.isTraceEnabled()) {
1052                     logger.trace(String.format("After replacing user wildcards = %s", filteredTerm));
1053                 }
1054             } catch (Exception e) {
1055                 logger.warn(String.format("Error filtering anchor and wildcard characters from string: %s", e.getMessage()));
1056                 return term;
1057             }
1058         }
1059         // Wrap the term in beginning and ending regex wildcards, unless a
1060         // starting or ending anchor character was present.
1061         return (anchorAtStart ? "" : ZERO_OR_MORE_ANY_CHAR_REGEX)
1062                 + filteredTerm
1063                 + (anchorAtEnd ? "" : ZERO_OR_MORE_ANY_CHAR_REGEX);
1064     }
1065     
1066     @SuppressWarnings("unchecked")
1067         private List<String> getPartialTermDisplayNameMatches(DocumentModel docModel, // REM - CSPACE-5133
1068                         String schema, ListResultField field, String partialTerm) {
1069         List<String> result = null;
1070           
1071         String xpath = field.getXpath(); // results in something like "persons_common:personTermGroupList/[0]/termDisplayName"
1072         int endOfTermGroup = xpath.lastIndexOf("/[0]/");
1073         String propertyName = endOfTermGroup != -1 ? xpath.substring(0, endOfTermGroup) : xpath; // it may not be multivalued so the xpath passed in would be the property name
1074         Object value = null;
1075         
1076                 try {
1077                         value = docModel.getProperty(schema, propertyName);
1078                 } catch (Exception e) {
1079                         logger.error("Could not extract term display name with property = "
1080                                         + propertyName, e);
1081                 }
1082                 
1083                 if (value != null && value instanceof ArrayList) {
1084                         ArrayList<HashMap<String, Object>> termGroupList = (ArrayList<HashMap<String, Object>>)value;
1085                         int arrayListSize = termGroupList.size();
1086                         if (arrayListSize > 1) { // if there's only 1 element in the list then we've already matched the primary term's display name
1087                                 List<String> displayNameList = new ArrayList<String>();
1088                                 for (int i = 1; i < arrayListSize; i++) { // start at 1, skip the primary term's displayName since we will always return it
1089                                         HashMap<String, Object> map = (HashMap<String, Object>)termGroupList.get(i);
1090                                         String termDisplayName = (String) map.get(AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
1091                                         displayNameList.add(i - 1, termDisplayName);
1092                                 }
1093                                 
1094                                 result = getPartialTermDisplayNameMatches(displayNameList, partialTerm);
1095                         }
1096                 }
1097
1098         return result;
1099     }
1100
1101     @Override
1102         protected Object getListResultValue(DocumentModel docModel, // REM - CSPACE-5133
1103                         String schema, ListResultField field) throws DocumentException {
1104                 Object result = null;           
1105
1106                 result = NuxeoUtils.getXPathValue(docModel, schema, field.getXpath());
1107                 
1108                 //
1109                 // Special handling of list item values for authority items (only)
1110                 // takes place here:
1111                 //
1112                 // If the list result field is the termDisplayName element,
1113                 // check whether a partial term matching query was made.
1114                 // If it was, emit values for both the preferred (aka primary)
1115                 // term and for all non-preferred terms, if any.
1116                 //
1117                 String elName = field.getElement();
1118                 if (isTermDisplayName(elName) == true) {
1119                         MultivaluedMap<String, String> queryParams = this.getServiceContext().getQueryParams();
1120                 String partialTerm = queryParams != null ? queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM) : null;
1121                 if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
1122                                 String primaryTermDisplayName = (String)result;
1123                         List<String> matches = getPartialTermDisplayNameMatches(docModel, schema, field, partialTerm);
1124                         if (matches != null && matches.isEmpty() == false) {
1125                                 matches.add(0, primaryTermDisplayName); // insert the primary term's display name at the beginning of the list
1126                                 result = matches; // set the result to a list of matching term display names with the primary term's display name at the beginning
1127                         }
1128                 }
1129                 }
1130                 
1131                 return result;
1132         }
1133     
1134     @Override
1135     public void extractAllParts(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
1136         MultipartServiceContext ctx = (MultipartServiceContext) getServiceContext();
1137         super.extractAllParts(wrapDoc);
1138     }
1139
1140     protected List<RelationsCommonList.RelationListItem> cloneList(List<RelationsCommonList.RelationListItem> inboundList) {
1141         List<RelationsCommonList.RelationListItem> result = newRelationsCommonList();
1142         for (RelationsCommonList.RelationListItem item : inboundList) {
1143             result.add(item);
1144         }
1145         return result;
1146     }
1147
1148
1149     /* don't even THINK of re-using this method.
1150      * String example_uri = "/locationauthorities/7ec60f01-84ab-4908-9a6a/items/a5466530-713f-43b4-bc05";
1151      */
1152     @Deprecated
1153     private String extractInAuthorityCSID(String uri) {
1154         String IN_AUTHORITY_REGEX = "/(.*?)/(.*?)/(.*)";
1155         Pattern p = Pattern.compile(IN_AUTHORITY_REGEX);
1156         Matcher m = p.matcher(uri);
1157         if (m.find()) {
1158             if (m.groupCount() < 3) {
1159                 logger.warn("REGEX-WRONG-GROUPCOUNT looking in " + uri);
1160                 return "";
1161             } else {
1162                 //String service = m.group(1);
1163                 String inauth = m.group(2);
1164                 //String theRest = m.group(3);
1165                 return inauth;
1166                 //print("service:"+service+", inauth:"+inauth+", rest:"+rest);
1167             }
1168         } else {
1169             logger.warn("REGEX-NOT-MATCHED looking in " + uri);
1170             return "";
1171         }
1172     }
1173
1174     //ensures CSPACE-4042
1175     protected void uriPointsToSameAuthority(String thisURI, String inboundItemURI) throws Exception {
1176         String authorityCSID = extractInAuthorityCSID(thisURI);
1177         String authorityCSIDForInbound = extractInAuthorityCSID(inboundItemURI);
1178         if (Tools.isBlank(authorityCSID)
1179                 || Tools.isBlank(authorityCSIDForInbound)
1180                 || (!authorityCSID.equalsIgnoreCase(authorityCSIDForInbound))) {
1181             throw new Exception("Item URI " + thisURI + " must point to same authority as related item: " + inboundItemURI);
1182         }
1183     }
1184
1185     public String getItemTermInfoGroupXPathBase() {
1186         return authorityItemTermGroupXPathBase;
1187     }
1188         
1189     public void setItemTermInfoGroupXPathBase(String itemTermInfoGroupXPathBase) {
1190         authorityItemTermGroupXPathBase = itemTermInfoGroupXPathBase;
1191     }
1192     
1193     protected String getAuthorityItemCommonSchemaName() {
1194         return authorityItemCommonSchemaName;
1195     }
1196     
1197     // @Override
1198     public boolean isJDBCQuery() {
1199         boolean result = false;
1200         
1201         MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams();
1202         //
1203         // Look the query params to see if we need to make a SQL query.
1204         //
1205         String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
1206         if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
1207                 result = true;
1208         }
1209         
1210         return result;
1211     }
1212     
1213     // By convention, the name of the database table that contains
1214     // repeatable term information group records is derivable from
1215     // an existing XPath base value, by removing a suffix and converting
1216     // to lowercase
1217     protected String getTermGroupTableName() {
1218         String termInfoGroupListName = getItemTermInfoGroupXPathBase();
1219         return termInfoGroupListName.substring(0, termInfoGroupListName.lastIndexOf(LIST_SUFFIX)).toLowerCase();
1220     }
1221     
1222     protected String getInAuthorityValue() {
1223         String inAuthorityValue = getInAuthorityCsid();
1224         if (Tools.notBlank(inAuthorityValue)) {
1225             return inAuthorityValue;
1226         } else {
1227             return AuthorityResource.PARENT_WILDCARD;
1228         }
1229     }
1230     
1231     @Override
1232     public Map<String,String> getJDBCQueryParams() {
1233         // FIXME: Get all of the following values from appropriate external constants.
1234         // At present, these are duplicated in both RepositoryClientImpl
1235         // and in AuthorityItemDocumentModelHandler.
1236         final String TERM_GROUP_LIST_NAME = "TERM_GROUP_LIST_NAME";
1237         final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
1238         final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
1239         
1240         Map<String,String> params = super.getJDBCQueryParams();
1241         params.put(TERM_GROUP_LIST_NAME, getItemTermInfoGroupXPathBase());
1242         params.put(TERM_GROUP_TABLE_NAME_PARAM, getTermGroupTableName());
1243         params.put(IN_AUTHORITY_PARAM, getInAuthorityValue());
1244         return params;
1245     }
1246     
1247 }