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