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