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