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:
6 * http://www.collectionspace.org
7 * http://wiki.collectionspace.org
9 * Copyright 2009 University of California at Berkeley
11 * Licensed under the Educational Community License (ECL), Version 2.0.
12 * You may not use this file except in compliance with this License.
14 * You may obtain a copy of the ECL 2.0 License at
16 * https://source.collectionspace.org/collection-space/LICENSE.txt
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.
24 package org.collectionspace.services.common.vocabulary.nuxeo;
26 import org.collectionspace.services.client.AuthorityClient;
27 import org.collectionspace.services.client.IQueryManager;
28 import org.collectionspace.services.client.PoxPayloadIn;
29 import org.collectionspace.services.client.PoxPayloadOut;
30 import org.collectionspace.services.client.workflow.WorkflowClient;
31 import org.collectionspace.services.common.ServiceMain;
32 import org.collectionspace.services.common.UriTemplateRegistry;
33 import org.collectionspace.services.common.api.RefName;
34 import org.collectionspace.services.common.api.Tools;
35 import org.collectionspace.services.common.authorityref.AuthorityRefDocList;
36 import org.collectionspace.services.common.context.MultipartServiceContext;
37 import org.collectionspace.services.common.context.ServiceContext;
38 import org.collectionspace.services.common.document.DocumentException;
39 import org.collectionspace.services.common.document.DocumentFilter;
40 import org.collectionspace.services.common.document.DocumentNotFoundException;
41 import org.collectionspace.services.common.document.DocumentReferenceException;
42 import org.collectionspace.services.common.document.DocumentWrapper;
43 import org.collectionspace.services.common.repository.RepositoryClient;
44 import org.collectionspace.services.common.vocabulary.AuthorityJAXBSchema;
45 import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema;
46 import org.collectionspace.services.common.vocabulary.AuthorityResource;
47 import org.collectionspace.services.common.vocabulary.AuthorityServiceUtils;
48 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils;
49 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.AuthorityItemSpecifier;
50 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.SpecifierForm;
51 import org.collectionspace.services.config.service.ListResultField;
52 import org.collectionspace.services.config.service.ObjectPartType;
53 import org.collectionspace.services.lifecycle.TransitionDef;
54 import org.collectionspace.services.nuxeo.client.java.NuxeoDocumentModelHandler;
55 import org.collectionspace.services.nuxeo.client.java.CoreSessionInterface;
56 import org.collectionspace.services.nuxeo.client.java.RepositoryClientImpl;
57 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
58 import org.collectionspace.services.relation.RelationsCommonList;
59 import org.collectionspace.services.vocabulary.VocabularyItemJAXBSchema;
61 import org.nuxeo.ecm.core.api.ClientException;
62 import org.nuxeo.ecm.core.api.DocumentModel;
63 import org.nuxeo.ecm.core.api.model.PropertyException;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
67 import javax.ws.rs.core.MultivaluedMap;
68 import java.util.ArrayList;
69 import java.util.Collections;
70 import java.util.HashMap;
71 import java.util.List;
73 import java.util.regex.Matcher;
74 import java.util.regex.Pattern;
75 import java.util.regex.PatternSyntaxException;
77 //import org.collectionspace.services.common.authority.AuthorityItemRelations;
79 * AuthorityItemDocumentModelHandler
81 * $LastChangedRevision: $
84 public abstract class AuthorityItemDocumentModelHandler<AICommon>
85 extends NuxeoDocumentModelHandler<AICommon> {
87 private final Logger logger = LoggerFactory.getLogger(AuthorityItemDocumentModelHandler.class);
89 protected String authorityCommonSchemaName;
90 protected String authorityItemCommonSchemaName;
91 private String authorityItemTermGroupXPathBase;
93 private boolean syncHierarchicalRelationships = false;
94 private boolean isProposed = false; // used by local authority to propose a new shared item. Allows local deployments to use new terms until they become official
95 private boolean isSAS = false; // used to indicate if the authority item originated as a SAS item
96 private boolean shouldUpdateRevNumber = true; // by default we should update the revision number -not true on synchronization with SAS
98 * inVocabulary is the parent Authority for this context
100 protected String inAuthority = null;
101 protected boolean wildcardedAuthorityRequest = false;
102 protected String authorityRefNameBase = null;
103 // Used to determine when the displayName changes as part of the update.
104 protected String oldDisplayNameOnUpdate = null;
105 private final static String LIST_SUFFIX = "List";
106 private final static String ZERO_OR_MORE_ANY_CHAR_REGEX = ".*";
108 public AuthorityItemDocumentModelHandler(String authorityCommonSchemaName, String authorityItemCommonSchemaName) {
109 this.authorityItemCommonSchemaName = authorityItemCommonSchemaName;
112 abstract public String getParentCommonSchemaName();
115 // Getter and Setter for 'proposed'
117 public boolean getIsProposed() {
118 return this.isProposed;
121 public void setIsProposed(boolean flag) {
122 this.isProposed = flag;
126 // Getter and Setter for 'isSAS'
128 public boolean getIsSASItem() {
132 public void setIsSASItem(boolean flag) {
137 // Getter and Setter for 'shouldUpdateRevNumber'
139 public boolean getShouldUpdateRevNumber() {
140 return this.shouldUpdateRevNumber;
143 public void setShouldUpdateRevNumber(boolean flag) {
144 this.shouldUpdateRevNumber = flag;
148 // Getter and Setter for deciding if we need to synch hierarchical relationships
150 public boolean getShouldSyncHierarchicalRelationships() {
151 return this.syncHierarchicalRelationships;
154 public void setShouldSyncHierarchicalRelationships(boolean flag) {
155 this.syncHierarchicalRelationships = flag;
159 public void prepareSync() throws Exception {
160 this.setShouldUpdateRevNumber(AuthorityServiceUtils.DONT_UPDATE_REV); // Never update rev nums on sync operations
164 protected String getRefnameDisplayName(DocumentWrapper<DocumentModel> docWrapper) {
165 String result = null;
167 DocumentModel docModel = docWrapper.getWrappedObject();
168 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = this.getServiceContext();
169 RefName.AuthorityItem refname = (RefName.AuthorityItem)getRefName(ctx, docModel);
170 result = refname.getDisplayName();
176 * After calling this method successfully, the document model will contain an updated refname and short ID
178 * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#getRefName(org.collectionspace.services.common.context.ServiceContext, org.nuxeo.ecm.core.api.DocumentModel)
181 public RefName.RefNameInterface getRefName(ServiceContext ctx,
182 DocumentModel docModel) {
183 RefName.RefNameInterface refname = null;
186 String displayName = getPrimaryDisplayName(docModel, authorityItemCommonSchemaName,
187 getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
188 if (Tools.isEmpty(displayName)) {
189 throw new Exception("The displayName for this authority term was empty or not set.");
192 String shortIdentifier = (String) docModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
193 if (Tools.isEmpty(shortIdentifier)) {
194 // We didn't find a short ID in the payload request, so we need to synthesize one.
195 shortIdentifier = handleDisplayNameAsShortIdentifier(docModel); // updates the document model with the new short ID as a side-effect
198 String authorityRefBaseName = getAuthorityRefNameBase();
199 if (Tools.isEmpty(authorityRefBaseName)) {
200 throw new Exception("Could not create the refName for this authority term, because the refName for its authority parent was empty.");
203 // Create the items refname using the parent's as a base
204 RefName.Authority parentsRefName = RefName.Authority.parse(authorityRefBaseName);
205 refname = RefName.buildAuthorityItem(parentsRefName, shortIdentifier, displayName);
206 // Now update the document model with the refname value
207 String refNameStr = refname.toString();
208 docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REF_NAME, refNameStr); // REM - This field is deprecated now that the refName is part of the collection_space core schema
210 } catch (Exception e) {
211 logger.error(e.getMessage(), e);
217 public void setInAuthority(String inAuthority) {
218 this.inAuthority = inAuthority;
221 public String getInAuthorityCsid() {
222 return this.inAuthority;
225 /** Subclasses may override this to customize the URI segment. */
226 public String getAuthorityServicePath() {
227 return getServiceContext().getServiceName().toLowerCase(); // Laramie20110510 CSPACE-3932
231 public String getUri(DocumentModel docModel) {
232 // Laramie20110510 CSPACE-3932
233 String authorityServicePath = getAuthorityServicePath();
234 if(inAuthority==null) { // Only true with the first document model received, on queries to wildcarded authorities
235 wildcardedAuthorityRequest = true;
237 // If this search crosses multiple authorities, get the inAuthority value
238 // from each record, rather than using the cached value from the first record
239 if(wildcardedAuthorityRequest) {
241 inAuthority = (String) docModel.getProperty(authorityItemCommonSchemaName,
242 AuthorityItemJAXBSchema.IN_AUTHORITY);
243 } catch (ClientException pe) {
244 throw new RuntimeException("Could not get parent specifier for item!");
247 return "/" + authorityServicePath + '/' + inAuthority + '/' + AuthorityClient.ITEMS + '/' + getCsid(docModel);
250 protected String getAuthorityRefNameBase() {
251 return this.authorityRefNameBase;
254 public void setAuthorityRefNameBase(String value) {
255 this.authorityRefNameBase = value;
259 * Note: the Vocabulary service's VocabularyItemDocumentModelHandler class overrides this method.
261 protected ListResultField getListResultsDisplayNameField() {
262 ListResultField result = new ListResultField();
263 // Per CSPACE-5132, the name of this element remains 'displayName'
264 // for backwards compatibility, although its value is obtained
265 // from the termDisplayName field.
267 // Update: this name is now being changed to 'termDisplayName', both
268 // because this is the actual field name and because the app layer
269 // work to convert over to this field is underway. Per Patrick, the
270 // app layer treats lists, in at least some context(s), as sparse record
271 // payloads, and thus fields in list results must all be present in
272 // (i.e. represent a strict subset of the fields in) record schemas.
276 // In CSPACE-5134, these list results will change substantially
277 // to return display names for both the preferred term and for
278 // each non-preferred term (if any).
279 result.setElement(AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
280 result.setXpath(NuxeoUtils.getPrimaryXPathPropertyName(
281 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_DISPLAY_NAME));
287 * Note: the Vocabulary service's VocabularyItemDocumentModelHandler class overrides this method.
289 protected ListResultField getListResultsTermStatusField() {
290 ListResultField result = new ListResultField();
292 result.setElement(AuthorityItemJAXBSchema.TERM_STATUS);
293 result.setXpath(NuxeoUtils.getPrimaryXPathPropertyName(
294 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_STATUS));
299 private boolean isTermDisplayName(String elName) {
300 return AuthorityItemJAXBSchema.TERM_DISPLAY_NAME.equals(elName) || VocabularyItemJAXBSchema.DISPLAY_NAME.equals(elName);
305 * @see org.collectionspace.services.nuxeo.client.java.DocHandlerBase#getListItemsArray()
307 * Note: We're updating the "global" service and tenant bindings instance here -the list instance here is
308 * a reference to the tenant bindings instance in the singleton ServiceMain.
311 public List<ListResultField> getListItemsArray() throws DocumentException {
312 List<ListResultField> list = super.getListItemsArray();
314 // One-time initialization for each authority item service.
315 if (isListItemArrayExtended() == false) {
316 synchronized(AuthorityItemDocumentModelHandler.class) {
317 if (isListItemArrayExtended() == false) {
318 int nFields = list.size();
319 // Ensure that each item in a list of Authority items includes
320 // a set of common fields, so we do not depend upon configuration
321 // for general logic.
322 List<Integer> termDisplayNamePositionsInList = new ArrayList<>();
323 boolean hasShortId = false;
324 boolean hasTermStatus = false;
325 for (int i = 0; i < nFields; i++) {
326 ListResultField field = list.get(i);
327 String elName = field.getElement();
328 if (isTermDisplayName(elName) == true) {
329 termDisplayNamePositionsInList.add(i);
330 } else if (AuthorityItemJAXBSchema.SHORT_IDENTIFIER.equals(elName)) {
332 } else if (AuthorityItemJAXBSchema.TERM_STATUS.equals(elName)) {
333 hasTermStatus = true;
337 ListResultField field;
339 // Certain fields in authority item list results
340 // are handled specially here
344 // Ignore (throw out) any configuration entries that
345 // specify how the termDisplayName field should be
346 // emitted in authority item lists. This field will
347 // be handled in a standardized manner (see block below).
348 if (termDisplayNamePositionsInList.isEmpty() == false) {
349 // Remove matching items starting at the end of the list
350 // and moving towards the start, so that reshuffling of
351 // list order doesn't alter the positions of earlier items
352 Collections.sort(termDisplayNamePositionsInList, Collections.reverseOrder());
353 for (int i : termDisplayNamePositionsInList) {
357 // termDisplayName values in authority item lists
358 // will be handled via code that emits display names
359 // for both the preferred term and all non-preferred
360 // terms (if any). The following is a placeholder
361 // entry that will trigger this code. See the
362 // getListResultValue() method in this class.
363 field = getListResultsDisplayNameField();
368 field = new ListResultField();
369 field.setElement(AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
370 field.setXpath(AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
375 if (!hasTermStatus) {
376 field = getListResultsTermStatusField();
382 setListItemArrayExtended(true);
383 } // end of synchronized block
390 * We consider workflow state changes as a change that should bump the revision number.
391 * Warning: This method might change the transitionDef's transtionName value
394 public void handleWorkflowTransition(ServiceContext ctx, DocumentWrapper<DocumentModel> wrapDoc, TransitionDef transitionDef) throws Exception {
395 // Decide whether or not to update the revision number
396 if (this.getShouldUpdateRevNumber() == true) { // We don't update the rev number of synchronization requests
397 updateRevNumbers(wrapDoc);
400 // We can't delete an authority item that has referencing records.
402 DocumentModel docModel = wrapDoc.getWrappedObject();
403 if (transitionDef.getName().equalsIgnoreCase(WorkflowClient.WORKFLOWTRANSITION_DELETE)) {
404 long refsToAllObjects = hasReferencingObjects(ctx, docModel, false);
405 long refsToSoftDeletedObjects = hasReferencingObjects(ctx, docModel, true);
406 if (refsToAllObjects > 0) {
407 if (refsToAllObjects > refsToSoftDeletedObjects) {
409 // If the number of refs to active objects is greater than the number of refs to
410 // soft deleted objects then we can't delete the item.
412 throw new DocumentReferenceException(String.format("Cannot delete authority item '%s' because it still has records in the system that are referencing it. See the service layer log file for details.",
413 docModel.getName()));
420 * This method synchronizes/updates a single authority item resource.
421 * for the handleSync method, the wrapDoc argument contains a authority item specifier.
424 public boolean handleSync(DocumentWrapper<Object> wrapDoc) throws Exception {
425 boolean result = false;
426 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
429 // Get information about the local authority item so we can compare with corresponding item on the shared authority server
431 AuthorityItemSpecifier authorityItemSpecifier = (AuthorityItemSpecifier) wrapDoc.getWrappedObject();
432 DocumentModel itemDocModel = NuxeoUtils.getDocFromSpecifier(ctx, getRepositorySession(), getAuthorityItemCommonSchemaName(),
433 authorityItemSpecifier);
434 if (itemDocModel == null) {
435 throw new DocumentNotFoundException(String.format("Could not find authority item resource with CSID='%s'",
436 authorityItemSpecifier.getItemSpecifier().value));
438 Long localItemRev = (Long) NuxeoUtils.getProperyValue(itemDocModel, AuthorityItemJAXBSchema.REV);
439 Boolean localIsProposed = (Boolean) NuxeoUtils.getProperyValue(itemDocModel, AuthorityItemJAXBSchema.PROPOSED);
440 String localItemCsid = itemDocModel.getName();
441 String localItemWorkflowState = itemDocModel.getCurrentLifeCycleState();
442 String itemShortId = (String) NuxeoUtils.getProperyValue(itemDocModel, AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
445 // Now get the item's Authority (the parent) information
447 DocumentModel authorityDocModel = NuxeoUtils.getDocFromSpecifier(ctx, getRepositorySession(), authorityCommonSchemaName,
448 authorityItemSpecifier.getParentSpecifier());
449 String authorityShortId = (String) NuxeoUtils.getProperyValue(authorityDocModel, AuthorityJAXBSchema.SHORT_IDENTIFIER);
450 String localParentCsid = authorityDocModel.getName();
452 // Using the short IDs of the local authority and item, create URN specifiers and retrieve the SAS authority item
454 AuthorityItemSpecifier sasAuthorityItemSpecifier = new AuthorityItemSpecifier(SpecifierForm.URN_NAME, authorityShortId, itemShortId);
455 // Get the shared authority server's copy
456 PoxPayloadIn sasPayloadIn = AuthorityServiceUtils.requestPayloadIn(sasAuthorityItemSpecifier,
457 getAuthorityServicePath(), getEntityResponseType());
458 Long sasRev = getRevision(sasPayloadIn);
459 String sasWorkflowState = getWorkflowState(sasPayloadIn);
461 // If the shared authority item is newer, update our local copy
463 if (sasRev > localItemRev || localIsProposed) {
464 sasPayloadIn = AuthorityServiceUtils.filterRefnameDomains(ctx, sasPayloadIn); // We need to filter the domain name part of any and all refnames in the payload
465 AuthorityResource authorityResource = (AuthorityResource) ctx.getResource(getAuthorityServicePath());
466 PoxPayloadOut payloadOut = authorityResource.updateAuthorityItem(ctx,
467 ctx.getResourceMap(),
469 localParentCsid, // parent's CSID
470 localItemCsid, // item's CSID
471 sasPayloadIn, // the payload from the remote SAS
472 AuthorityServiceUtils.DONT_UPDATE_REV, // don't update the parent's revision number
473 AuthorityServiceUtils.NOT_PROPOSED, // The items is not proposed, make it a real SAS item now
474 AuthorityServiceUtils.SAS_ITEM); // Since we're sync'ing, this must be a SAS item
475 if (payloadOut != null) {
476 ctx.setOutput(payloadOut);
481 // Check to see if we need to update the local items's workflow state to reflect that of the remote's
483 List<String> transitionList = getTransitionList(sasWorkflowState, localItemWorkflowState);
484 if (transitionList.isEmpty() == false) {
485 AuthorityResource authorityResource = (AuthorityResource) ctx.getResource(getAuthorityServicePath()); // Get the authority (parent) client not the item client
487 // We need to move the local item to the SAS workflow state. This might involve multiple transitions.
489 for (String transition:transitionList) {
491 authorityResource.updateItemWorkflowWithTransition(ctx, localParentCsid, localItemCsid, transition, AuthorityServiceUtils.DONT_UPDATE_REV);
492 } catch (DocumentReferenceException de) {
494 // This exception means we tried unsuccessfully to soft-delete (workflow transition 'delete') an item that still has references to it from other records.
496 AuthorityServiceUtils.setAuthorityItemDeprecated(ctx, itemDocModel, authorityItemCommonSchemaName, AuthorityServiceUtils.DEPRECATED); // Since we can't sof-delete it, we need to mark it as deprecated since it is soft-deleted on the SAS
497 logger.warn(String.format("Could not transition item CSID='%s' from workflow state '%s' to '%s'. Check the services log file for details.",
498 localItemCsid, localItemWorkflowState, sasWorkflowState));
504 // We need to synchronize the hierarchy relationships here.
511 * We need to change the local item's state to one that maps to the replication server's workflow
512 * state. This might involve making multiple transitions.
515 * See table at https://wiki.collectionspace.org/pages/viewpage.action?pageId=162496564
518 private List<String> getTransitionList(String sasWorkflowState, String localItemWorkflowState) throws DocumentException {
519 List<String> result = new ArrayList<String>();
521 // The first set of conditions maps a replication-server "project" state to a local client state of "replicated"
523 if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT)) {
524 result.add(WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
525 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED)) {
526 result.add(WorkflowClient.WORKFLOWTRANSITION_UNDELETE);
527 result.add(WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
528 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED)) {
529 // Do nothing. We're good with this state
530 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED)) {
531 result.add(WorkflowClient.WORKFLOWTRANSITION_UNDELETE);
533 // The second set of conditions maps a replication-server "deleted" state to a local client state of "deleted"
535 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT)) {
536 result.add(WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
537 result.add(WorkflowClient.WORKFLOWTRANSITION_DELETE);
538 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED)) {
539 result.add(WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
540 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED)) {
541 result.add(WorkflowClient.WORKFLOWTRANSITION_DELETE);
542 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED)) {
543 // Do nothing. We're good with this state
545 // The third set of conditions maps a replication-server "replicated" state to a local state of "replicated"
547 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT)) {
548 result.add(WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
549 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED)) {
550 result.add(WorkflowClient.WORKFLOWTRANSITION_UNDELETE);
551 result.add(WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
552 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED)) {
553 // Do nothing. We're good with this state
554 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED)) {
555 result.add(WorkflowClient.WORKFLOWTRANSITION_UNDELETE);
557 // The last set of conditions maps a replication-server "replicated_deleted" state to a local client state of "deleted"
559 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT)) {
560 result.add(WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
561 result.add(WorkflowClient.WORKFLOWTRANSITION_DELETE);
562 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED)) {
563 result.add(WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
564 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED)) {
565 result.add(WorkflowClient.WORKFLOWTRANSITION_DELETE);
566 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED)) {
567 // Do nothing. We're good with this state
570 // If we get here, we've encountered a SAS workflow state that we don't recognize.
572 throw new DocumentException(String.format("Encountered an invalid workflow state of '%s' on a SAS authority item.", sasWorkflowState));
579 * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#handleCreate(org.collectionspace.services.common.document.DocumentWrapper)
582 public void handleCreate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
583 // first fill all the parts of the document, refname and short ID get set as well
584 super.handleCreate(wrapDoc);
585 // Ensure we have required fields set properly
586 handleInAuthority(wrapDoc.getWrappedObject());
590 * This method gets called after the primary update to an authority item has happened. If the authority item's refName
591 * has changed, then we need to updated all the records that use that refname with the new/updated version
596 public boolean handleDelete(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
597 boolean result = true;
599 ServiceContext ctx = getServiceContext();
600 DocumentModel docModel = wrapDoc.getWrappedObject();
602 long refsToAllObjects = hasReferencingObjects(ctx, docModel, false);
603 long refsToSoftDeletedObjects = hasReferencingObjects(ctx, docModel, true);
604 if (refsToAllObjects > 0) {
605 if (refsToAllObjects > refsToSoftDeletedObjects) {
607 // If the number of refs to active objects is greater than the number of refs to
608 // soft deleted objects then we can't delete the item.
610 throw new DocumentReferenceException(String.format("Cannot delete authority item '%s' because it still has records in the system that are referencing it. See the service layer log file for details.",
611 docModel.getName()));
614 // If all the refs are to soft-deleted objects, we should soft-delete this authority item instead of hard-deleting it and instead of failing.
616 Boolean shouldUpdateRev = (Boolean) ctx.getProperty(AuthorityServiceUtils.SHOULD_UPDATE_REV_PROPERTY);
617 String parentCsid = (String) NuxeoUtils.getProperyValue(docModel, AuthorityItemJAXBSchema.IN_AUTHORITY);
618 String itemCsid = docModel.getName();
619 AuthorityResource authorityResource = (AuthorityResource) ctx.getResource(getAuthorityServicePath());
620 authorityResource.updateItemWorkflowWithTransition(ctx, parentCsid, itemCsid, WorkflowClient.WORKFLOWTRANSITION_DELETE,
621 shouldUpdateRev != null ? shouldUpdateRev : true);
622 result = false; // Don't delete since we just soft-deleted it.
630 * Checks to see if an authority item has referencing objects.
637 private long hasReferencingObjects(ServiceContext ctx, DocumentModel docModel, boolean onlyRefsToDeletedObjects) throws Exception {
640 String inAuthorityCsid = (String) docModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.IN_AUTHORITY);
641 AuthorityResource authorityResource = (AuthorityResource)ctx.getResource(getAuthorityServicePath());
642 String itemCsid = docModel.getName();
643 UriTemplateRegistry uriTemplateRegistry = ServiceMain.getInstance().getUriTemplateRegistry();
644 if (ctx.getUriInfo() == null) {
646 // We need a UriInfo object so we can pass "query" params to the AuthorityResource's getReferencingObjects() method
648 ctx.setUriInfo(this.getServiceContext().getUriInfo()); // try to get a UriInfo instance from the handler's context
650 ctx.getUriInfo().getQueryParameters().addFirst(WorkflowClient.WORKFLOW_QUERY_ONLY_DELETED, Boolean.toString(onlyRefsToDeletedObjects)); // Add the wf_only_deleted query param to the resource call
651 AuthorityRefDocList refObjs = authorityResource.getReferencingObjects(ctx, inAuthorityCsid, itemCsid,
652 uriTemplateRegistry, ctx.getUriInfo());
653 ctx.getUriInfo().getQueryParameters().remove(WorkflowClient.WORKFLOW_QUERY_ONLY_DELETED); // Need to clear wf_only_deleted values to prevent unexpected side effects
655 result = refObjs.getTotalItems();
657 logger.error(String.format("Cannot delete authority item '%s' because it still has %d records in the system that are referencing it.",
658 itemCsid, refObjs.getTotalItems()));
659 if (logger.isWarnEnabled() == true) {
660 logReferencingObjects(docModel, refObjs);
667 private void logReferencingObjects(DocumentModel docModel, AuthorityRefDocList refObjs) {
668 List<AuthorityRefDocList.AuthorityRefDocItem> items = refObjs.getAuthorityRefDocItem();
670 logger.warn(String.format("The authority item '%s' has the following references:", docModel.getName()));
671 for (AuthorityRefDocList.AuthorityRefDocItem item : items) {
672 logger.warn(docModel.getName() + " referenced by : list-item[" + i + "] "
673 + item.getDocType() + "("
674 + item.getDocId() + ") Name:["
675 + item.getDocName() + "] Number:["
676 + item.getDocNumber() + "] in field:["
677 + item.getSourceField() + "]");
682 * This method gets called after the primary update to an authority item has happened. If the authority item's refName
683 * has changed, then we need to updated all the records that use that refname with the new/updated version
686 * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#completeUpdate(org.collectionspace.services.common.document.DocumentWrapper)
688 public void completeUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
689 // Must call our super class' version first
690 super.completeUpdate(wrapDoc);
693 // Look for and update authority references with the updated refName
695 if (hasRefNameUpdate() == true) {
696 // We have work to do.
697 if (logger.isDebugEnabled()) {
698 final String EOL = System.getProperty("line.separator");
699 logger.debug("Need to find and update references to authority item." + EOL
700 + " Old refName" + oldRefNameOnUpdate + EOL
701 + " New refName" + newRefNameOnUpdate);
703 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
704 RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient = getRepositoryClient(ctx);
705 CoreSessionInterface repoSession = this.getRepositorySession();
707 // Update all the existing records that have a field with the old refName in it
708 int nUpdated = RefNameServiceUtils.updateAuthorityRefDocs(ctx, repoClient, repoSession,
709 oldRefNameOnUpdate, newRefNameOnUpdate, getRefPropName());
711 // Finished so log a message.
712 if (logger.isDebugEnabled()) {
713 logger.debug("Updated " + nUpdated + " instances of oldRefName to newRefName");
719 * Note that the Vocabulary service's document-model for items overrides this method.
721 protected String getPrimaryDisplayName(DocumentModel docModel, String schema,
722 String complexPropertyName, String fieldName) {
723 String result = null;
725 result = getStringValueInPrimaryRepeatingComplexProperty(docModel, schema, complexPropertyName, fieldName);
731 * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#handleUpdate(org.collectionspace.services.common.document.DocumentWrapper)
734 // FIXME: Once we remove the refName field from the authority item schemas, we can remove this override method since our super does everthing for us now.
736 public void handleUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
737 // Must call our super's version first, this updates the core schema and the relationship records to deal with possible refName changes/update
738 super.handleUpdate(wrapDoc);
739 if (this.hasRefNameUpdate() == true) {
740 DocumentModel docModel = wrapDoc.getWrappedObject();
741 docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REF_NAME, this.newRefNameOnUpdate); // This field is deprecated since it is now a duplicate of what is in the collectionspace_core:refName field
746 // Handles both update calls (PUTS) AND create calls (POSTS)
748 public void fillAllParts(DocumentWrapper<DocumentModel> wrapDoc, Action action) throws Exception {
749 super.fillAllParts(wrapDoc, action);
750 DocumentModel documentModel = wrapDoc.getWrappedObject();
753 // Update the record's revision number on both CREATE and UPDATE actions (as long as it is NOT a SAS authority item)
755 Boolean propertyValue = (Boolean) documentModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SAS);
756 boolean isMarkedAsSASItem = propertyValue != null ? propertyValue : false;
757 if (this.getShouldUpdateRevNumber() == true && !isMarkedAsSASItem) { // We won't update rev numbers on synchronization with SAS items and on local changes to SAS items
758 updateRevNumbers(wrapDoc);
761 // If this is a proposed item (not part of the SAS), mark it as such
763 documentModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.PROPOSED,
764 new Boolean(this.getIsProposed()));
766 // If it is a SAS authority item, mark it as such
768 documentModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SAS,
769 new Boolean(this.getIsSASItem()));
773 * Update the revision number of both the item and the item's parent.
777 protected void updateRevNumbers(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
778 DocumentModel documentModel = wrapDoc.getWrappedObject();
779 Long rev = (Long)documentModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REV);
785 documentModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REV, rev);
787 // Next, update the inAuthority (the parent's) rev number
789 String inAuthorityCsid = this.getInAuthorityCsid();
790 if (inAuthorityCsid == null) {
791 // When inAuthorityCsid is null, it usually means we're performing and update or synch with the SAS
792 inAuthorityCsid = (String)documentModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.IN_AUTHORITY);
794 DocumentModel inAuthorityDocModel = NuxeoUtils.getDocFromCsid(getServiceContext(), getRepositorySession(), inAuthorityCsid);
795 Long parentRev = (Long)inAuthorityDocModel.getProperty(getParentCommonSchemaName(), AuthorityJAXBSchema.REV);
796 if (parentRev == null) {
797 parentRev = new Long(0);
800 inAuthorityDocModel.setProperty(getParentCommonSchemaName(), AuthorityJAXBSchema.REV, parentRev);
801 getRepositorySession().saveDocument(inAuthorityDocModel);
805 * If no short identifier was provided in the input payload, generate a
806 * short identifier from the preferred term display name or term name.
808 private String handleDisplayNameAsShortIdentifier(DocumentModel docModel) throws Exception {
809 String result = (String) docModel.getProperty(authorityItemCommonSchemaName,
810 AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
812 if (Tools.isEmpty(result)) {
813 String termDisplayName = getPrimaryDisplayName(
814 docModel, authorityItemCommonSchemaName,
815 getItemTermInfoGroupXPathBase(),
816 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
818 String termName = getPrimaryDisplayName(
819 docModel, authorityItemCommonSchemaName,
820 getItemTermInfoGroupXPathBase(),
821 AuthorityItemJAXBSchema.TERM_NAME);
823 String generatedShortIdentifier = AuthorityIdentifierUtils.generateShortIdentifierFromDisplayName(termDisplayName,
825 docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER,
826 generatedShortIdentifier);
827 result = generatedShortIdentifier;
834 * Generate a refName for the authority item from the short identifier
837 * All refNames for authority items are generated. If a client supplies
838 * a refName, it will be overwritten during create (per this method)
839 * or discarded during update (per filterReadOnlyPropertiesForPart).
841 * @see #filterReadOnlyPropertiesForPart(Map<String, Object>, org.collectionspace.services.common.service.ObjectPartType)
844 protected String updateRefnameForAuthorityItem(DocumentModel docModel,
845 String schemaName) throws Exception {
846 String result = null;
848 RefName.RefNameInterface refname = getRefName(getServiceContext(), docModel);
849 String refNameStr = refname.toString();
850 docModel.setProperty(schemaName, AuthorityItemJAXBSchema.REF_NAME, refNameStr);
857 * Check the logic around the parent pointer. Note that we only need do this on
858 * create, since we have logic to make this read-only on update.
862 * @throws Exception the exception
864 private void handleInAuthority(DocumentModel docModel) throws Exception {
865 if(inAuthority==null) { // Only happens on queries to wildcarded authorities
866 throw new IllegalStateException("Trying to Create an object with no inAuthority value!");
868 docModel.setProperty(authorityItemCommonSchemaName,
869 AuthorityItemJAXBSchema.IN_AUTHORITY, inAuthority);
873 * Returns a list of records that reference this authority item
876 * @param uriTemplateRegistry
877 * @param serviceTypes
878 * @param propertyName
883 public AuthorityRefDocList getReferencingObjects(
884 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
885 UriTemplateRegistry uriTemplateRegistry,
886 List<String> serviceTypes,
888 String itemcsid) throws Exception {
889 AuthorityRefDocList authRefDocList = null;
890 CoreSessionInterface repoSession = (CoreSessionInterface) ctx.getCurrentRepositorySession();
891 boolean releaseRepoSession = false;
894 RepositoryClientImpl repoClient = (RepositoryClientImpl)this.getRepositoryClient(ctx);
895 repoSession = this.getRepositorySession();
896 if (repoSession == null) {
897 repoSession = repoClient.getRepositorySession(ctx);
898 releaseRepoSession = true;
900 DocumentFilter myFilter = getDocumentFilter();
903 DocumentWrapper<DocumentModel> wrapper = repoClient.getDoc(repoSession, ctx, itemcsid);
904 DocumentModel docModel = wrapper.getWrappedObject();
905 String refName = (String) NuxeoUtils.getProperyValue(docModel, AuthorityItemJAXBSchema.REF_NAME); //docModel.getPropertyValue(AuthorityItemJAXBSchema.REF_NAME);
906 authRefDocList = RefNameServiceUtils.getAuthorityRefDocs(
907 repoSession, ctx, uriTemplateRegistry, repoClient,
911 myFilter, true /*computeTotal*/);
912 } catch (PropertyException pe) {
914 } catch (DocumentException de) {
916 } catch (Exception e) {
917 if (logger.isDebugEnabled()) {
918 logger.debug("Caught exception ", e);
920 throw new DocumentException(e);
922 // If we got/aquired a new seesion then we're responsible for releasing it.
923 if (releaseRepoSession && repoSession != null) {
924 repoClient.releaseRepositorySession(ctx, repoSession);
927 } catch (Exception e) {
928 if (logger.isDebugEnabled()) {
929 logger.debug("Caught exception ", e);
931 throw new DocumentException(e);
934 return authRefDocList;
938 * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#extractPart(org.nuxeo.ecm.core.api.DocumentModel, java.lang.String, org.collectionspace.services.common.service.ObjectPartType)
941 protected Map<String, Object> extractPart(DocumentModel docModel, String schema, ObjectPartType partMeta)
943 Map<String, Object> unQObjectProperties = super.extractPart(docModel, schema, partMeta);
945 // Add the CSID to the common part, since they may have fetched via the shortId.
946 if (partMeta.getLabel().equalsIgnoreCase(authorityItemCommonSchemaName)) {
947 String csid = getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
948 unQObjectProperties.put("csid", csid);
951 return unQObjectProperties;
955 * Filters out selected values supplied in an update request.
957 * For example, filters out AuthorityItemJAXBSchema.IN_AUTHORITY, to ensure
958 * that the link to the item's parent remains untouched.
960 * @param objectProps the properties filtered out from the update payload
961 * @param partMeta metadata for the object to fill
964 public void filterReadOnlyPropertiesForPart(
965 Map<String, Object> objectProps, ObjectPartType partMeta) {
966 super.filterReadOnlyPropertiesForPart(objectProps, partMeta);
967 String commonPartLabel = getServiceContext().getCommonPartLabel();
968 if (partMeta.getLabel().equalsIgnoreCase(commonPartLabel)) {
969 objectProps.remove(AuthorityItemJAXBSchema.IN_AUTHORITY);
970 objectProps.remove(AuthorityItemJAXBSchema.CSID);
971 objectProps.remove(AuthorityJAXBSchema.SHORT_IDENTIFIER);
972 objectProps.remove(AuthorityItemJAXBSchema.REF_NAME);
977 * Returns the items in a list of term display names whose names contain
978 * a partial term (as might be submitted in a search query, for instance).
979 * @param termDisplayNameList a list of term display names.
980 * @param partialTerm a partial term display name; that is, a portion
981 * of a display name that might be expected to match 0-n terms in the list.
982 * @return a list of term display names that matches the partial term.
983 * Matches are case-insensitive. As well, before matching is performed, any
984 * special-purpose characters that may appear in the partial term (such as
985 * wildcards and anchor characters) are filtered out from both compared terms.
987 protected List<String> getPartialTermDisplayNameMatches(List<String> termDisplayNameList, String partialTerm) {
988 List<String> result = new ArrayList<>();
989 String partialTermMatchExpression = filterAnchorAndWildcardChars(partialTerm).toLowerCase();
991 for (String termDisplayName : termDisplayNameList) {
992 if (termDisplayName.toLowerCase()
993 .matches(partialTermMatchExpression) == true) {
994 result.add(termDisplayName);
997 } catch (PatternSyntaxException pse) {
998 logger.warn("Error in regex match pattern '%s' for term display names: %s",
999 partialTermMatchExpression, pse.getMessage());
1005 * Filters user-supplied anchor and wildcard characters in a string,
1006 * replacing them with equivalent regular expressions.
1007 * @param term a term in which to filter anchor and wildcard characters.
1008 * @return the term with those characters filtered.
1010 protected String filterAnchorAndWildcardChars(String term) {
1011 if (Tools.isBlank(term)) {
1014 if (term.length() < 3) {
1017 if (logger.isTraceEnabled()) {
1018 logger.trace(String.format("Term = %s", term));
1020 Boolean anchorAtStart = false;
1021 Boolean anchorAtEnd = false;
1022 String filteredTerm;
1023 StringBuilder filteredTermBuilder = new StringBuilder(term);
1024 // Term contains no anchor or wildcard characters.
1025 if ( (! term.contains(RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR))
1026 && (! term.contains(RepositoryClientImpl.USER_SUPPLIED_WILDCARD)) ) {
1027 filteredTerm = term;
1029 // Term contains at least one such character.
1031 // Filter the starting anchor or wildcard character, if any.
1032 String firstChar = filteredTermBuilder.substring(0,1);
1033 switch (firstChar) {
1034 case RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR:
1035 anchorAtStart = true;
1037 case RepositoryClientImpl.USER_SUPPLIED_WILDCARD:
1038 filteredTermBuilder.deleteCharAt(0);
1041 if (logger.isTraceEnabled()) {
1042 logger.trace(String.format("After first char filtering = %s", filteredTermBuilder.toString()));
1044 // Filter the ending anchor or wildcard character, if any.
1045 int lastPos = filteredTermBuilder.length() - 1;
1046 String lastChar = filteredTermBuilder.substring(lastPos);
1048 case RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR:
1049 filteredTermBuilder.deleteCharAt(lastPos);
1050 filteredTermBuilder.insert(filteredTermBuilder.length(), RepositoryClientImpl.ENDING_ANCHOR_CHAR);
1053 case RepositoryClientImpl.USER_SUPPLIED_WILDCARD:
1054 filteredTermBuilder.deleteCharAt(lastPos);
1057 if (logger.isTraceEnabled()) {
1058 logger.trace(String.format("After last char filtering = %s", filteredTermBuilder.toString()));
1060 filteredTerm = filteredTermBuilder.toString();
1061 // Filter all other wildcards, if any.
1062 filteredTerm = filteredTerm.replaceAll(RepositoryClientImpl.USER_SUPPLIED_WILDCARD_REGEX, ZERO_OR_MORE_ANY_CHAR_REGEX);
1063 if (logger.isTraceEnabled()) {
1064 logger.trace(String.format("After replacing user wildcards = %s", filteredTerm));
1066 } catch (Exception e) {
1067 logger.warn(String.format("Error filtering anchor and wildcard characters from string: %s", e.getMessage()));
1071 // Wrap the term in beginning and ending regex wildcards, unless a
1072 // starting or ending anchor character was present.
1073 return (anchorAtStart ? "" : ZERO_OR_MORE_ANY_CHAR_REGEX)
1075 + (anchorAtEnd ? "" : ZERO_OR_MORE_ANY_CHAR_REGEX);
1078 @SuppressWarnings("unchecked")
1079 private List<String> getPartialTermDisplayNameMatches(DocumentModel docModel, // REM - CSPACE-5133
1080 String schema, ListResultField field, String partialTerm) {
1081 List<String> result = null;
1083 String xpath = field.getXpath(); // results in something like "persons_common:personTermGroupList/[0]/termDisplayName"
1084 int endOfTermGroup = xpath.lastIndexOf("/[0]/");
1085 String propertyName = endOfTermGroup != -1 ? xpath.substring(0, endOfTermGroup) : xpath; // it may not be multivalued so the xpath passed in would be the property name
1086 Object value = null;
1089 value = docModel.getProperty(schema, propertyName);
1090 } catch (Exception e) {
1091 logger.error("Could not extract term display name with property = "
1095 if (value != null && value instanceof ArrayList) {
1096 ArrayList<HashMap<String, Object>> termGroupList = (ArrayList<HashMap<String, Object>>)value;
1097 int arrayListSize = termGroupList.size();
1098 if (arrayListSize > 1) { // if there's only 1 element in the list then we've already matched the primary term's display name
1099 List<String> displayNameList = new ArrayList<String>();
1100 for (int i = 1; i < arrayListSize; i++) { // start at 1, skip the primary term's displayName since we will always return it
1101 HashMap<String, Object> map = (HashMap<String, Object>)termGroupList.get(i);
1102 String termDisplayName = (String) map.get(AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
1103 displayNameList.add(i - 1, termDisplayName);
1106 result = getPartialTermDisplayNameMatches(displayNameList, partialTerm);
1114 protected Object getListResultValue(DocumentModel docModel, // REM - CSPACE-5133
1115 String schema, ListResultField field) throws DocumentException {
1116 Object result = null;
1118 result = NuxeoUtils.getXPathValue(docModel, schema, field.getXpath());
1121 // Special handling of list item values for authority items (only)
1122 // takes place here:
1124 // If the list result field is the termDisplayName element,
1125 // check whether a partial term matching query was made.
1126 // If it was, emit values for both the preferred (aka primary)
1127 // term and for all non-preferred terms, if any.
1129 String elName = field.getElement();
1130 if (isTermDisplayName(elName) == true) {
1131 MultivaluedMap<String, String> queryParams = this.getServiceContext().getQueryParams();
1132 String partialTerm = queryParams != null ? queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM) : null;
1133 if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
1134 String primaryTermDisplayName = (String)result;
1135 List<String> matches = getPartialTermDisplayNameMatches(docModel, schema, field, partialTerm);
1136 if (matches != null && matches.isEmpty() == false) {
1137 matches.add(0, primaryTermDisplayName); // insert the primary term's display name at the beginning of the list
1138 result = matches; // set the result to a list of matching term display names with the primary term's display name at the beginning
1147 public void extractAllParts(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
1148 MultipartServiceContext ctx = (MultipartServiceContext) getServiceContext();
1149 super.extractAllParts(wrapDoc);
1152 protected List<RelationsCommonList.RelationListItem> cloneList(List<RelationsCommonList.RelationListItem> inboundList) {
1153 List<RelationsCommonList.RelationListItem> result = newRelationsCommonList();
1154 for (RelationsCommonList.RelationListItem item : inboundList) {
1161 /* don't even THINK of re-using this method.
1162 * String example_uri = "/locationauthorities/7ec60f01-84ab-4908-9a6a/items/a5466530-713f-43b4-bc05";
1165 private String extractInAuthorityCSID(String uri) {
1166 String IN_AUTHORITY_REGEX = "/(.*?)/(.*?)/(.*)";
1167 Pattern p = Pattern.compile(IN_AUTHORITY_REGEX);
1168 Matcher m = p.matcher(uri);
1170 if (m.groupCount() < 3) {
1171 logger.warn("REGEX-WRONG-GROUPCOUNT looking in " + uri);
1174 //String service = m.group(1);
1175 String inauth = m.group(2);
1176 //String theRest = m.group(3);
1178 //print("service:"+service+", inauth:"+inauth+", rest:"+rest);
1181 logger.warn("REGEX-NOT-MATCHED looking in " + uri);
1186 //ensures CSPACE-4042
1187 protected void uriPointsToSameAuthority(String thisURI, String inboundItemURI) throws Exception {
1188 String authorityCSID = extractInAuthorityCSID(thisURI);
1189 String authorityCSIDForInbound = extractInAuthorityCSID(inboundItemURI);
1190 if (Tools.isBlank(authorityCSID)
1191 || Tools.isBlank(authorityCSIDForInbound)
1192 || (!authorityCSID.equalsIgnoreCase(authorityCSIDForInbound))) {
1193 throw new Exception("Item URI " + thisURI + " must point to same authority as related item: " + inboundItemURI);
1197 public String getItemTermInfoGroupXPathBase() {
1198 return authorityItemTermGroupXPathBase;
1201 public void setItemTermInfoGroupXPathBase(String itemTermInfoGroupXPathBase) {
1202 authorityItemTermGroupXPathBase = itemTermInfoGroupXPathBase;
1205 protected String getAuthorityItemCommonSchemaName() {
1206 return authorityItemCommonSchemaName;
1210 public boolean isJDBCQuery() {
1211 boolean result = false;
1213 MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams();
1215 // Look the query params to see if we need to make a SQL query.
1217 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
1218 if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
1225 // By convention, the name of the database table that contains
1226 // repeatable term information group records is derivable from
1227 // an existing XPath base value, by removing a suffix and converting
1229 protected String getTermGroupTableName() {
1230 String termInfoGroupListName = getItemTermInfoGroupXPathBase();
1231 return termInfoGroupListName.substring(0, termInfoGroupListName.lastIndexOf(LIST_SUFFIX)).toLowerCase();
1234 protected String getInAuthorityValue() {
1235 String inAuthorityValue = getInAuthorityCsid();
1236 if (Tools.notBlank(inAuthorityValue)) {
1237 return inAuthorityValue;
1239 return AuthorityResource.PARENT_WILDCARD;
1244 public Map<String,String> getJDBCQueryParams() {
1245 // FIXME: Get all of the following values from appropriate external constants.
1246 // At present, these are duplicated in both RepositoryClientImpl
1247 // and in AuthorityItemDocumentModelHandler.
1248 final String TERM_GROUP_LIST_NAME = "TERM_GROUP_LIST_NAME";
1249 final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
1250 final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
1252 Map<String,String> params = super.getJDBCQueryParams();
1253 params.put(TERM_GROUP_LIST_NAME, getItemTermInfoGroupXPathBase());
1254 params.put(TERM_GROUP_TABLE_NAME_PARAM, getTermGroupTableName());
1255 params.put(IN_AUTHORITY_PARAM, getInAuthorityValue());