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