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