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