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.CollectionSpaceClient;
28 import org.collectionspace.services.client.IQueryManager;
29 import org.collectionspace.services.client.PoxPayloadIn;
30 import org.collectionspace.services.client.PoxPayloadOut;
31 import org.collectionspace.services.client.workflow.WorkflowClient;
32 import org.collectionspace.services.common.ResourceMap;
33 import org.collectionspace.services.common.ServiceMain;
34 import org.collectionspace.services.common.UriTemplateRegistry;
35 import org.collectionspace.services.common.api.RefName;
36 import org.collectionspace.services.common.api.RefNameUtils;
37 import org.collectionspace.services.common.api.Tools;
38 import org.collectionspace.services.common.api.RefNameUtils.AuthorityInfo;
39 import org.collectionspace.services.common.authorityref.AuthorityRefDocList;
40 import org.collectionspace.services.common.context.MultipartServiceContext;
41 import org.collectionspace.services.common.context.ServiceContext;
42 import org.collectionspace.services.common.document.DocumentException;
43 import org.collectionspace.services.common.document.DocumentFilter;
44 import org.collectionspace.services.common.document.DocumentNotFoundException;
45 import org.collectionspace.services.common.document.DocumentReferenceException;
46 import org.collectionspace.services.common.document.DocumentWrapper;
47 import org.collectionspace.services.common.repository.RepositoryClient;
48 import org.collectionspace.services.common.vocabulary.AuthorityJAXBSchema;
49 import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema;
50 import org.collectionspace.services.common.vocabulary.AuthorityResource;
51 import org.collectionspace.services.common.vocabulary.AuthorityServiceUtils;
52 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils;
53 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.AuthorityItemSpecifier;
54 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.Specifier;
55 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.SpecifierForm;
56 import org.collectionspace.services.config.service.ListResultField;
57 import org.collectionspace.services.config.service.ObjectPartType;
58 import org.collectionspace.services.lifecycle.TransitionDef;
59 import org.collectionspace.services.nuxeo.client.java.NuxeoDocumentModelHandler;
60 import org.collectionspace.services.nuxeo.client.java.CoreSessionInterface;
61 import org.collectionspace.services.nuxeo.client.java.RepositoryClientImpl;
62 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
63 import org.collectionspace.services.relation.RelationsCommonList;
64 import org.collectionspace.services.vocabulary.VocabularyItemJAXBSchema;
65 import org.nuxeo.ecm.core.api.ClientException;
66 import org.nuxeo.ecm.core.api.DocumentModel;
67 import org.nuxeo.ecm.core.api.model.PropertyException;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
71 import javax.ws.rs.core.MultivaluedMap;
72 import javax.ws.rs.core.UriInfo;
74 import java.util.ArrayList;
75 import java.util.Collection;
76 import java.util.Collections;
77 import java.util.HashMap;
78 import java.util.List;
80 import java.util.regex.Matcher;
81 import java.util.regex.Pattern;
82 import java.util.regex.PatternSyntaxException;
84 //import org.collectionspace.services.common.authority.AuthorityItemRelations;
86 * AuthorityItemDocumentModelHandler
88 * $LastChangedRevision: $
91 public abstract class AuthorityItemDocumentModelHandler<AICommon>
92 extends NuxeoDocumentModelHandler<AICommon> {
94 private final Logger logger = LoggerFactory.getLogger(AuthorityItemDocumentModelHandler.class);
96 protected String authorityCommonSchemaName;
97 protected String authorityItemCommonSchemaName;
98 private String authorityItemTermGroupXPathBase;
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
104 * inVocabulary is the parent Authority for this context
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 = ".*";
114 public AuthorityItemDocumentModelHandler(String authorityCommonSchemaName, String authorityItemCommonSchemaName) {
115 this.authorityItemCommonSchemaName = authorityItemCommonSchemaName;
118 abstract public String getParentCommonSchemaName();
121 // Getter and Setter for 'proposed'
123 public boolean getIsProposed() {
124 return this.isProposed;
127 public void setIsProposed(boolean flag) {
128 this.isProposed = flag;
132 // Getter and Setter for 'isSAS'
134 public boolean getIsSASItem() {
138 public void setIsSASItem(boolean flag) {
143 // Getter and Setter for 'shouldUpdateRevNumber'
145 public boolean getShouldUpdateRevNumber() {
146 return this.shouldUpdateRevNumber;
149 public void setShouldUpdateRevNumber(boolean flag) {
150 this.shouldUpdateRevNumber = flag;
154 public void prepareSync() throws Exception {
155 this.setShouldUpdateRevNumber(AuthorityServiceUtils.DONT_UPDATE_REV); // Never update rev nums on sync operations
159 protected String getRefnameDisplayName(DocumentWrapper<DocumentModel> docWrapper) {
160 String result = null;
162 DocumentModel docModel = docWrapper.getWrappedObject();
163 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = this.getServiceContext();
164 RefName.AuthorityItem refname = (RefName.AuthorityItem)getRefName(ctx, docModel);
165 result = refname.getDisplayName();
171 * After calling this method successfully, the document model will contain an updated refname and short ID
173 * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#getRefName(org.collectionspace.services.common.context.ServiceContext, org.nuxeo.ecm.core.api.DocumentModel)
176 public RefName.RefNameInterface getRefName(ServiceContext ctx,
177 DocumentModel docModel) {
178 RefName.RefNameInterface refname = null;
181 String displayName = getPrimaryDisplayName(docModel, authorityItemCommonSchemaName,
182 getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
183 if (Tools.isEmpty(displayName)) {
184 throw new Exception("The displayName for this authority term was empty or not set.");
187 String shortIdentifier = (String) docModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
188 if (Tools.isEmpty(shortIdentifier)) {
189 // We didn't find a short ID in the payload request, so we need to synthesize one.
190 shortIdentifier = handleDisplayNameAsShortIdentifier(docModel); // updates the document model with the new short ID as a side-effect
193 String authorityRefBaseName = getAuthorityRefNameBase();
194 if (Tools.isEmpty(authorityRefBaseName)) {
195 throw new Exception("Could not create the refName for this authority term, because the refName for its authority parent was empty.");
198 // Create the items refname using the parent's as a base
199 RefName.Authority parentsRefName = RefName.Authority.parse(authorityRefBaseName);
200 refname = RefName.buildAuthorityItem(parentsRefName, shortIdentifier, displayName);
201 // Now update the document model with the refname value
202 String refNameStr = refname.toString();
203 docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REF_NAME, refNameStr); // REM - This field is deprecated now that the refName is part of the collection_space core schema
205 } catch (Exception e) {
206 logger.error(e.getMessage(), e);
212 public void setInAuthority(String inAuthority) {
213 this.inAuthority = inAuthority;
216 public String getInAuthorityCsid() {
217 return this.inAuthority;
220 /** Subclasses may override this to customize the URI segment. */
221 public String getAuthorityServicePath() {
222 return getServiceContext().getServiceName().toLowerCase(); // Laramie20110510 CSPACE-3932
226 public String getUri(DocumentModel docModel) {
227 // Laramie20110510 CSPACE-3932
228 String authorityServicePath = getAuthorityServicePath();
229 if(inAuthority==null) { // Only true with the first document model received, on queries to wildcarded authorities
230 wildcardedAuthorityRequest = true;
232 // If this search crosses multiple authorities, get the inAuthority value
233 // from each record, rather than using the cached value from the first record
234 if(wildcardedAuthorityRequest) {
236 inAuthority = (String) docModel.getProperty(authorityItemCommonSchemaName,
237 AuthorityItemJAXBSchema.IN_AUTHORITY);
238 } catch (ClientException pe) {
239 throw new RuntimeException("Could not get parent specifier for item!");
242 return "/" + authorityServicePath + '/' + inAuthority + '/' + AuthorityClient.ITEMS + '/' + getCsid(docModel);
245 protected String getAuthorityRefNameBase() {
246 return this.authorityRefNameBase;
249 public void setAuthorityRefNameBase(String value) {
250 this.authorityRefNameBase = value;
254 * Note: the Vocabulary service's VocabularyItemDocumentModelHandler class overrides this method.
256 protected ListResultField getListResultsDisplayNameField() {
257 ListResultField result = new ListResultField();
258 // Per CSPACE-5132, the name of this element remains 'displayName'
259 // for backwards compatibility, although its value is obtained
260 // from the termDisplayName field.
262 // Update: this name is now being changed to 'termDisplayName', both
263 // because this is the actual field name and because the app layer
264 // work to convert over to this field is underway. Per Patrick, the
265 // app layer treats lists, in at least some context(s), as sparse record
266 // payloads, and thus fields in list results must all be present in
267 // (i.e. represent a strict subset of the fields in) record schemas.
271 // In CSPACE-5134, these list results will change substantially
272 // to return display names for both the preferred term and for
273 // each non-preferred term (if any).
274 result.setElement(AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
275 result.setXpath(NuxeoUtils.getPrimaryXPathPropertyName(
276 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_DISPLAY_NAME));
282 * Note: the Vocabulary service's VocabularyItemDocumentModelHandler class overrides this method.
284 protected ListResultField getListResultsTermStatusField() {
285 ListResultField result = new ListResultField();
287 result.setElement(AuthorityItemJAXBSchema.TERM_STATUS);
288 result.setXpath(NuxeoUtils.getPrimaryXPathPropertyName(
289 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_STATUS));
294 private boolean isTermDisplayName(String elName) {
295 return AuthorityItemJAXBSchema.TERM_DISPLAY_NAME.equals(elName) || VocabularyItemJAXBSchema.DISPLAY_NAME.equals(elName);
300 * @see org.collectionspace.services.nuxeo.client.java.DocHandlerBase#getListItemsArray()
302 * Note: We're updating the "global" service and tenant bindings instance here -the list instance here is
303 * a reference to the tenant bindings instance in the singleton ServiceMain.
306 public List<ListResultField> getListItemsArray() throws DocumentException {
307 List<ListResultField> list = super.getListItemsArray();
309 // One-time initialization for each authority item service.
310 if (isListItemArrayExtended() == false) {
311 synchronized(AuthorityItemDocumentModelHandler.class) {
312 if (isListItemArrayExtended() == false) {
313 int nFields = list.size();
314 // Ensure that each item in a list of Authority items includes
315 // a set of common fields, so we do not depend upon configuration
316 // for general logic.
317 List<Integer> termDisplayNamePositionsInList = new ArrayList<>();
318 boolean hasShortId = false;
319 boolean hasTermStatus = false;
320 for (int i = 0; i < nFields; i++) {
321 ListResultField field = list.get(i);
322 String elName = field.getElement();
323 if (isTermDisplayName(elName) == true) {
324 termDisplayNamePositionsInList.add(i);
325 } else if (AuthorityItemJAXBSchema.SHORT_IDENTIFIER.equals(elName)) {
327 } else if (AuthorityItemJAXBSchema.TERM_STATUS.equals(elName)) {
328 hasTermStatus = true;
332 ListResultField field;
334 // Certain fields in authority item list results
335 // are handled specially here
339 // Ignore (throw out) any configuration entries that
340 // specify how the termDisplayName field should be
341 // emitted in authority item lists. This field will
342 // be handled in a standardized manner (see block below).
343 if (termDisplayNamePositionsInList.isEmpty() == false) {
344 // Remove matching items starting at the end of the list
345 // and moving towards the start, so that reshuffling of
346 // list order doesn't alter the positions of earlier items
347 Collections.sort(termDisplayNamePositionsInList, Collections.reverseOrder());
348 for (int i : termDisplayNamePositionsInList) {
352 // termDisplayName values in authority item lists
353 // will be handled via code that emits display names
354 // for both the preferred term and all non-preferred
355 // terms (if any). The following is a placeholder
356 // entry that will trigger this code. See the
357 // getListResultValue() method in this class.
358 field = getListResultsDisplayNameField();
363 field = new ListResultField();
364 field.setElement(AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
365 field.setXpath(AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
370 if (!hasTermStatus) {
371 field = getListResultsTermStatusField();
377 setListItemArrayExtended(true);
378 } // end of synchronized block
385 * We consider workflow state changes as a change that should bump the revision number.
386 * Warning: This method might change the transitionDef's transtionName value
389 public void handleWorkflowTransition(ServiceContext ctx, DocumentWrapper<DocumentModel> wrapDoc, TransitionDef transitionDef) throws Exception {
390 // Decide whether or not to update the revision number
391 if (this.getShouldUpdateRevNumber() == true) { // We don't update the rev number of synchronization requests
392 updateRevNumbers(wrapDoc);
395 // We can't delete an authority item that has referencing records.
397 DocumentModel docModel = wrapDoc.getWrappedObject();
398 if (transitionDef.getName().equalsIgnoreCase(WorkflowClient.WORKFLOWTRANSITION_DELETE)) {
399 long refsToAllObjects = hasReferencingObjects(ctx, docModel, false);
400 long refsToSoftDeletedObjects = hasReferencingObjects(ctx, docModel, true);
401 if (refsToAllObjects > 0) {
402 if (refsToAllObjects > refsToSoftDeletedObjects) {
404 // If the number of refs to active objects is greater than the number of refs to
405 // soft deleted objects then we can't delete the item.
407 throw new DocumentReferenceException(String.format("Cannot delete authority item '%s' because it still has records in the system that are referencing it. See the service layer log file for details.",
408 docModel.getName()));
415 * This method synchronizes/updates a single authority item resource.
416 * for the handleSync method, the wrapDoc argument contains a authority item specifier.
419 public boolean handleSync(DocumentWrapper<Object> wrapDoc) throws Exception {
420 boolean result = false;
421 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
424 // Get information about the local authority item so we can compare with corresponding item on the shared authority server
426 AuthorityItemSpecifier authorityItemSpecifier = (AuthorityItemSpecifier) wrapDoc.getWrappedObject();
427 DocumentModel itemDocModel = NuxeoUtils.getDocFromSpecifier(ctx, getRepositorySession(), getAuthorityItemCommonSchemaName(),
428 authorityItemSpecifier);
429 if (itemDocModel == null) {
430 throw new DocumentNotFoundException(String.format("Could not find authority item resource with CSID='%s'",
431 authorityItemSpecifier.getItemSpecifier().value));
433 Long localItemRev = (Long) NuxeoUtils.getProperyValue(itemDocModel, AuthorityItemJAXBSchema.REV);
434 Boolean localIsProposed = (Boolean) NuxeoUtils.getProperyValue(itemDocModel, AuthorityItemJAXBSchema.PROPOSED);
435 String localItemCsid = itemDocModel.getName();
436 String localItemWorkflowState = itemDocModel.getCurrentLifeCycleState();
437 String itemShortId = (String) NuxeoUtils.getProperyValue(itemDocModel, AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
440 // Now get the item's Authority (the parent) information
442 DocumentModel authorityDocModel = NuxeoUtils.getDocFromSpecifier(ctx, getRepositorySession(), authorityCommonSchemaName,
443 authorityItemSpecifier.getParentSpecifier());
444 String authorityShortId = (String) NuxeoUtils.getProperyValue(authorityDocModel, AuthorityJAXBSchema.SHORT_IDENTIFIER);
445 String localParentCsid = authorityDocModel.getName();
447 // Using the short IDs of the local authority and item, create URN specifiers to retrieve the SAS authority item
449 AuthorityItemSpecifier sasAuthorityItemSpecifier = new AuthorityItemSpecifier(SpecifierForm.URN_NAME, authorityShortId, itemShortId);
450 // Get the shared authority server's copy
451 PoxPayloadIn sasPayloadIn = AuthorityServiceUtils.requestPayloadIn(sasAuthorityItemSpecifier,
452 getAuthorityServicePath(), getEntityResponseType());
453 Long sasRev = getRevision(sasPayloadIn);
454 String sasWorkflowState = getWorkflowState(sasPayloadIn);
456 // If the shared authority item is newer, update our local copy
458 if (sasRev > localItemRev || localIsProposed) {
459 sasPayloadIn = AuthorityServiceUtils.filterRefnameDomains(ctx, sasPayloadIn); // We need to filter the domain name part of any and all refnames in the payload
460 AuthorityResource authorityResource = (AuthorityResource) ctx.getResource(getAuthorityServicePath());
461 PoxPayloadOut payloadOut = authorityResource.updateAuthorityItem(ctx,
462 ctx.getResourceMap(),
464 localParentCsid, // parent's CSID
465 localItemCsid, // item's CSID
466 sasPayloadIn, // the payload from the remote SAS
467 AuthorityServiceUtils.DONT_UPDATE_REV, // don't update the parent's revision number
468 AuthorityServiceUtils.NOT_PROPOSED, // The items is not proposed, make it a real SAS item now
469 AuthorityServiceUtils.SAS_ITEM); // Since we're sync'ing, this must be a SAS item
470 if (payloadOut != null) {
471 ctx.setOutput(payloadOut);
476 // Check to see if we need to update the local items's workflow state to reflect that of the remote's
478 List<String> transitionList = getTransitionList(sasWorkflowState, localItemWorkflowState);
479 if (transitionList.isEmpty() == false) {
480 AuthorityResource authorityResource = (AuthorityResource) ctx.getResource(getAuthorityServicePath()); // Get the authority (parent) client not the item client
482 // We need to move the local item to the SAS workflow state. This might involve multiple transitions.
484 for (String transition:transitionList) {
486 authorityResource.updateItemWorkflowWithTransition(ctx, localParentCsid, localItemCsid, transition, AuthorityServiceUtils.DONT_UPDATE_REV);
487 } catch (DocumentReferenceException de) {
489 // This exception means we tried unsuccessfully to soft-delete (workflow transition 'delete') an item that still has references to it from other records.
491 AuthorityServiceUtils.setAuthorityItemDeprecated(ctx, itemDocModel, authorityItemCommonSchemaName, AuthorityServiceUtils.DEPRECATED); // Since we can't sof-delete it, we need to mark it as deprecated since it is soft-deleted on the SAS
492 logger.warn(String.format("Could not transition item CSID='%s' from workflow state '%s' to '%s'. Check the services log file for details.",
493 localItemCsid, localItemWorkflowState, sasWorkflowState));
499 // We need to synchronize the hierarchy relationships here.
506 * We need to move the local item to the SAS workflow state. This might involve multiple transitions.
509 * See table at https://wiki.collectionspace.org/pages/viewpage.action?pageId=162496564
512 private List<String> getTransitionList(String sasWorkflowState, String localItemWorkflowState) throws DocumentException {
513 List<String> result = new ArrayList<String>();
515 // The first set of conditions maps a SAS "project" state to a local state of "locked"
517 if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT)) {
518 result.add(WorkflowClient.WORKFLOWTRANSITION_LOCK);
519 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED)) {
520 result.add(WorkflowClient.WORKFLOWTRANSITION_UNDELETE);
521 result.add(WorkflowClient.WORKFLOWTRANSITION_LOCK);
522 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_LOCKED)) {
523 // Do nothing. We're good with this state
524 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_LOCKED_DELETED)) {
525 result.add(WorkflowClient.WORKFLOWTRANSITION_UNDELETE);
527 // The second set of conditions maps a SAS "deleted" state to a local state of "deleted"
529 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT)) {
530 result.add(WorkflowClient.WORKFLOWTRANSITION_LOCK);
531 result.add(WorkflowClient.WORKFLOWTRANSITION_DELETE);
532 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED)) {
533 result.add(WorkflowClient.WORKFLOWTRANSITION_LOCK);
534 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_LOCKED)) {
535 result.add(WorkflowClient.WORKFLOWTRANSITION_DELETE);
536 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_LOCKED_DELETED)) {
537 // Do nothing. We're good with this state
539 // The third set of conditions maps a SAS "locked" state to a local state of "locked"
541 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_LOCKED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT)) {
542 result.add(WorkflowClient.WORKFLOWTRANSITION_LOCK);
543 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_LOCKED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED)) {
544 result.add(WorkflowClient.WORKFLOWTRANSITION_UNDELETE);
545 result.add(WorkflowClient.WORKFLOWTRANSITION_LOCK);
546 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_LOCKED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_LOCKED)) {
547 // Do nothing. We're good with this state
548 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_LOCKED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_LOCKED_DELETED)) {
549 result.add(WorkflowClient.WORKFLOWTRANSITION_UNDELETE);
551 // The last set of conditions maps a SAS "locked_deleted" state to a local state of "deleted"
553 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_LOCKED_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT)) {
554 result.add(WorkflowClient.WORKFLOWTRANSITION_LOCK);
555 result.add(WorkflowClient.WORKFLOWTRANSITION_DELETE);
556 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_LOCKED_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED)) {
557 result.add(WorkflowClient.WORKFLOWTRANSITION_LOCK);
558 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_LOCKED_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_LOCKED)) {
559 result.add(WorkflowClient.WORKFLOWTRANSITION_DELETE);
560 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_LOCKED_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_LOCKED_DELETED)) {
561 // Do nothing. We're good with this state
564 // If we get here, we've encountered a SAS workflow state that we don't recognize.
566 throw new DocumentException(String.format("Encountered an invalid workflow state of '%s' on a SAS authority item.", sasWorkflowState));
573 * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#handleCreate(org.collectionspace.services.common.document.DocumentWrapper)
576 public void handleCreate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
577 // first fill all the parts of the document, refname and short ID get set as well
578 super.handleCreate(wrapDoc);
579 // Ensure we have required fields set properly
580 handleInAuthority(wrapDoc.getWrappedObject());
584 * This method gets called after the primary update to an authority item has happened. If the authority item's refName
585 * has changed, then we need to updated all the records that use that refname with the new/updated version
590 public boolean handleDelete(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
591 boolean result = true;
593 ServiceContext ctx = getServiceContext();
594 DocumentModel docModel = wrapDoc.getWrappedObject();
596 long refsToAllObjects = hasReferencingObjects(ctx, docModel, false);
597 long refsToSoftDeletedObjects = hasReferencingObjects(ctx, docModel, true);
598 if (refsToAllObjects > 0) {
599 if (refsToAllObjects > refsToSoftDeletedObjects) {
601 // If the number of refs to active objects is greater than the number of refs to
602 // soft deleted objects then we can't delete the item.
604 throw new DocumentReferenceException(String.format("Cannot delete authority item '%s' because it still has records in the system that are referencing it. See the service layer log file for details.",
605 docModel.getName()));
608 // If all the refs are to soft-deleted objects, we should soft-delete this authority item instead of hard-deleting it and instead of failing.
610 Boolean shouldUpdateRev = (Boolean) ctx.getProperty(AuthorityServiceUtils.SHOULD_UPDATE_REV_PROPERTY);
611 String parentCsid = (String) NuxeoUtils.getProperyValue(docModel, AuthorityItemJAXBSchema.IN_AUTHORITY);
612 String itemCsid = docModel.getName();
613 AuthorityResource authorityResource = (AuthorityResource) ctx.getResource(getAuthorityServicePath());
614 authorityResource.updateItemWorkflowWithTransition(ctx, parentCsid, itemCsid, WorkflowClient.WORKFLOWTRANSITION_DELETE,
615 shouldUpdateRev != null ? shouldUpdateRev : true);
616 result = false; // Don't delete since we just soft-deleted it.
624 * Checks to see if an authority item has referencing objects.
631 private long hasReferencingObjects(ServiceContext ctx, DocumentModel docModel, boolean onlyRefsToDeletedObjects) throws Exception {
634 String inAuthorityCsid = (String) docModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.IN_AUTHORITY);
635 AuthorityResource authorityResource = (AuthorityResource)ctx.getResource(getAuthorityServicePath());
636 String itemCsid = docModel.getName();
637 UriTemplateRegistry uriTemplateRegistry = ServiceMain.getInstance().getUriTemplateRegistry();
638 if (ctx.getUriInfo() == null) {
640 // We need a UriInfo object so we can pass "query" params to the AuthorityResource's getReferencingObjects() method
642 ctx.setUriInfo(this.getServiceContext().getUriInfo()); // try to get a UriInfo instance from the handler's context
644 ctx.getUriInfo().getQueryParameters().addFirst(WorkflowClient.WORKFLOW_QUERY_ONLY_DELETED, Boolean.toString(onlyRefsToDeletedObjects)); // Add the wf_only_deleted query param to the resource call
645 AuthorityRefDocList refObjs = authorityResource.getReferencingObjects(ctx, inAuthorityCsid, itemCsid,
646 uriTemplateRegistry, ctx.getUriInfo());
647 ctx.getUriInfo().getQueryParameters().remove(WorkflowClient.WORKFLOW_QUERY_ONLY_DELETED); // Need to clear wf_only_deleted values to prevent unexpected side effects
649 result = refObjs.getTotalItems();
651 logger.error(String.format("Cannot delete authority item '%s' because it still has %d records in the system that are referencing it.",
652 itemCsid, refObjs.getTotalItems()));
653 if (logger.isWarnEnabled() == true) {
654 logReferencingObjects(docModel, refObjs);
661 private void logReferencingObjects(DocumentModel docModel, AuthorityRefDocList refObjs) {
662 List<AuthorityRefDocList.AuthorityRefDocItem> items = refObjs.getAuthorityRefDocItem();
664 logger.warn(String.format("The authority item '%s' has the following references:", docModel.getName()));
665 for (AuthorityRefDocList.AuthorityRefDocItem item : items) {
666 logger.warn(docModel.getName() + " referenced by : list-item[" + i + "] "
667 + item.getDocType() + "("
668 + item.getDocId() + ") Name:["
669 + item.getDocName() + "] Number:["
670 + item.getDocNumber() + "] in field:["
671 + item.getSourceField() + "]");
676 * This method gets called after the primary update to an authority item has happened. If the authority item's refName
677 * has changed, then we need to updated all the records that use that refname with the new/updated version
680 * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#completeUpdate(org.collectionspace.services.common.document.DocumentWrapper)
682 public void completeUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
683 // Must call our super class' version first
684 super.completeUpdate(wrapDoc);
687 // Look for and update authority references with the updated refName
689 if (hasRefNameUpdate() == true) {
690 // We have work to do.
691 if (logger.isDebugEnabled()) {
692 final String EOL = System.getProperty("line.separator");
693 logger.debug("Need to find and update references to authority item." + EOL
694 + " Old refName" + oldRefNameOnUpdate + EOL
695 + " New refName" + newRefNameOnUpdate);
697 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
698 RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient = getRepositoryClient(ctx);
699 CoreSessionInterface repoSession = this.getRepositorySession();
701 // Update all the existing records that have a field with the old refName in it
702 int nUpdated = RefNameServiceUtils.updateAuthorityRefDocs(ctx, repoClient, repoSession,
703 oldRefNameOnUpdate, newRefNameOnUpdate, getRefPropName());
705 // Finished so log a message.
706 if (logger.isDebugEnabled()) {
707 logger.debug("Updated " + nUpdated + " instances of oldRefName to newRefName");
713 * Note that the Vocabulary service's document-model for items overrides this method.
715 protected String getPrimaryDisplayName(DocumentModel docModel, String schema,
716 String complexPropertyName, String fieldName) {
717 String result = null;
719 result = getStringValueInPrimaryRepeatingComplexProperty(docModel, schema, complexPropertyName, fieldName);
725 * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#handleUpdate(org.collectionspace.services.common.document.DocumentWrapper)
728 // FIXME: Once we remove the refName field from the authority item schemas, we can remove this override method since our super does everthing for us now.
730 public void handleUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
731 // Must call our super's version first, this updates the core schema and the relationship records to deal with possible refName changes/update
732 super.handleUpdate(wrapDoc);
733 if (this.hasRefNameUpdate() == true) {
734 DocumentModel docModel = wrapDoc.getWrappedObject();
735 docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REF_NAME, this.newRefNameOnUpdate); // This field is deprecated since it is now a duplicate of what is in the collectionspace_core:refName field
740 // Handles both update calls (PUTS) AND create calls (POSTS)
742 public void fillAllParts(DocumentWrapper<DocumentModel> wrapDoc, Action action) throws Exception {
743 super.fillAllParts(wrapDoc, action);
744 DocumentModel documentModel = wrapDoc.getWrappedObject();
747 // Update the record's revision number on both CREATE and UPDATE actions (as long as it is NOT a SAS authority item)
749 Boolean propertyValue = (Boolean) documentModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SAS);
750 boolean isMarkedAsSASItem = propertyValue != null ? propertyValue : false;
751 if (this.getShouldUpdateRevNumber() == true && !isMarkedAsSASItem) { // We won't update rev numbers on synchronization with SAS items and on local changes to SAS items
752 updateRevNumbers(wrapDoc);
755 // If this is a proposed item (not part of the SAS), mark it as such
757 documentModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.PROPOSED,
758 new Boolean(this.getIsProposed()));
760 // If it is a SAS authority item, mark it as such
762 documentModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SAS,
763 new Boolean(this.getIsSASItem()));
767 * Update the revision number of both the item and the item's parent.
771 protected void updateRevNumbers(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
772 DocumentModel documentModel = wrapDoc.getWrappedObject();
773 Long rev = (Long)documentModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REV);
779 documentModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REV, rev);
781 // Next, update the inAuthority (the parent's) rev number
783 String inAuthorityCsid = this.getInAuthorityCsid();
784 if (inAuthorityCsid == null) {
785 // When inAuthorityCsid is null, it usually means we're performing and update or synch with the SAS
786 inAuthorityCsid = (String)documentModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.IN_AUTHORITY);
788 DocumentModel inAuthorityDocModel = NuxeoUtils.getDocFromCsid(getServiceContext(), getRepositorySession(), inAuthorityCsid);
789 Long parentRev = (Long)inAuthorityDocModel.getProperty(getParentCommonSchemaName(), AuthorityJAXBSchema.REV);
790 if (parentRev == null) {
791 parentRev = new Long(0);
794 inAuthorityDocModel.setProperty(getParentCommonSchemaName(), AuthorityJAXBSchema.REV, parentRev);
795 getRepositorySession().saveDocument(inAuthorityDocModel);
799 * If no short identifier was provided in the input payload, generate a
800 * short identifier from the preferred term display name or term name.
802 private String handleDisplayNameAsShortIdentifier(DocumentModel docModel) throws Exception {
803 String result = (String) docModel.getProperty(authorityItemCommonSchemaName,
804 AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
806 if (Tools.isEmpty(result)) {
807 String termDisplayName = getPrimaryDisplayName(
808 docModel, authorityItemCommonSchemaName,
809 getItemTermInfoGroupXPathBase(),
810 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
812 String termName = getPrimaryDisplayName(
813 docModel, authorityItemCommonSchemaName,
814 getItemTermInfoGroupXPathBase(),
815 AuthorityItemJAXBSchema.TERM_NAME);
817 String generatedShortIdentifier = AuthorityIdentifierUtils.generateShortIdentifierFromDisplayName(termDisplayName,
819 docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER,
820 generatedShortIdentifier);
821 result = generatedShortIdentifier;
828 * Generate a refName for the authority item from the short identifier
831 * All refNames for authority items are generated. If a client supplies
832 * a refName, it will be overwritten during create (per this method)
833 * or discarded during update (per filterReadOnlyPropertiesForPart).
835 * @see #filterReadOnlyPropertiesForPart(Map<String, Object>, org.collectionspace.services.common.service.ObjectPartType)
838 protected String updateRefnameForAuthorityItem(DocumentModel docModel,
839 String schemaName) throws Exception {
840 String result = null;
842 RefName.RefNameInterface refname = getRefName(getServiceContext(), docModel);
843 String refNameStr = refname.toString();
844 docModel.setProperty(schemaName, AuthorityItemJAXBSchema.REF_NAME, refNameStr);
851 * Check the logic around the parent pointer. Note that we only need do this on
852 * create, since we have logic to make this read-only on update.
856 * @throws Exception the exception
858 private void handleInAuthority(DocumentModel docModel) throws Exception {
859 if(inAuthority==null) { // Only happens on queries to wildcarded authorities
860 throw new IllegalStateException("Trying to Create an object with no inAuthority value!");
862 docModel.setProperty(authorityItemCommonSchemaName,
863 AuthorityItemJAXBSchema.IN_AUTHORITY, inAuthority);
867 * Returns a list of records that reference this authority item
870 * @param uriTemplateRegistry
871 * @param serviceTypes
872 * @param propertyName
877 public AuthorityRefDocList getReferencingObjects(
878 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
879 UriTemplateRegistry uriTemplateRegistry,
880 List<String> serviceTypes,
882 String itemcsid) throws Exception {
883 AuthorityRefDocList authRefDocList = null;
884 CoreSessionInterface repoSession = (CoreSessionInterface) ctx.getCurrentRepositorySession();
885 boolean releaseRepoSession = false;
888 RepositoryClientImpl repoClient = (RepositoryClientImpl)this.getRepositoryClient(ctx);
889 repoSession = this.getRepositorySession();
890 if (repoSession == null) {
891 repoSession = repoClient.getRepositorySession(ctx);
892 releaseRepoSession = true;
894 DocumentFilter myFilter = getDocumentFilter();
897 DocumentWrapper<DocumentModel> wrapper = repoClient.getDoc(repoSession, ctx, itemcsid);
898 DocumentModel docModel = wrapper.getWrappedObject();
899 String refName = (String) NuxeoUtils.getProperyValue(docModel, AuthorityItemJAXBSchema.REF_NAME); //docModel.getPropertyValue(AuthorityItemJAXBSchema.REF_NAME);
900 authRefDocList = RefNameServiceUtils.getAuthorityRefDocs(
901 repoSession, ctx, uriTemplateRegistry, repoClient,
905 myFilter, true /*computeTotal*/);
906 } catch (PropertyException pe) {
908 } catch (DocumentException de) {
910 } catch (Exception e) {
911 if (logger.isDebugEnabled()) {
912 logger.debug("Caught exception ", e);
914 throw new DocumentException(e);
916 // If we got/aquired a new seesion then we're responsible for releasing it.
917 if (releaseRepoSession && repoSession != null) {
918 repoClient.releaseRepositorySession(ctx, repoSession);
921 } catch (Exception e) {
922 if (logger.isDebugEnabled()) {
923 logger.debug("Caught exception ", e);
925 throw new DocumentException(e);
928 return authRefDocList;
932 * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#extractPart(org.nuxeo.ecm.core.api.DocumentModel, java.lang.String, org.collectionspace.services.common.service.ObjectPartType)
935 protected Map<String, Object> extractPart(DocumentModel docModel, String schema, ObjectPartType partMeta)
937 Map<String, Object> unQObjectProperties = super.extractPart(docModel, schema, partMeta);
939 // Add the CSID to the common part, since they may have fetched via the shortId.
940 if (partMeta.getLabel().equalsIgnoreCase(authorityItemCommonSchemaName)) {
941 String csid = getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
942 unQObjectProperties.put("csid", csid);
945 return unQObjectProperties;
949 * Filters out selected values supplied in an update request.
951 * For example, filters out AuthorityItemJAXBSchema.IN_AUTHORITY, to ensure
952 * that the link to the item's parent remains untouched.
954 * @param objectProps the properties filtered out from the update payload
955 * @param partMeta metadata for the object to fill
958 public void filterReadOnlyPropertiesForPart(
959 Map<String, Object> objectProps, ObjectPartType partMeta) {
960 super.filterReadOnlyPropertiesForPart(objectProps, partMeta);
961 String commonPartLabel = getServiceContext().getCommonPartLabel();
962 if (partMeta.getLabel().equalsIgnoreCase(commonPartLabel)) {
963 objectProps.remove(AuthorityItemJAXBSchema.IN_AUTHORITY);
964 objectProps.remove(AuthorityItemJAXBSchema.CSID);
965 objectProps.remove(AuthorityJAXBSchema.SHORT_IDENTIFIER);
966 objectProps.remove(AuthorityItemJAXBSchema.REF_NAME);
971 * Returns the items in a list of term display names whose names contain
972 * a partial term (as might be submitted in a search query, for instance).
973 * @param termDisplayNameList a list of term display names.
974 * @param partialTerm a partial term display name; that is, a portion
975 * of a display name that might be expected to match 0-n terms in the list.
976 * @return a list of term display names that matches the partial term.
977 * Matches are case-insensitive. As well, before matching is performed, any
978 * special-purpose characters that may appear in the partial term (such as
979 * wildcards and anchor characters) are filtered out from both compared terms.
981 protected List<String> getPartialTermDisplayNameMatches(List<String> termDisplayNameList, String partialTerm) {
982 List<String> result = new ArrayList<>();
983 String partialTermMatchExpression = filterAnchorAndWildcardChars(partialTerm).toLowerCase();
985 for (String termDisplayName : termDisplayNameList) {
986 if (termDisplayName.toLowerCase()
987 .matches(partialTermMatchExpression) == true) {
988 result.add(termDisplayName);
991 } catch (PatternSyntaxException pse) {
992 logger.warn("Error in regex match pattern '%s' for term display names: %s",
993 partialTermMatchExpression, pse.getMessage());
999 * Filters user-supplied anchor and wildcard characters in a string,
1000 * replacing them with equivalent regular expressions.
1001 * @param term a term in which to filter anchor and wildcard characters.
1002 * @return the term with those characters filtered.
1004 protected String filterAnchorAndWildcardChars(String term) {
1005 if (Tools.isBlank(term)) {
1008 if (term.length() < 3) {
1011 if (logger.isTraceEnabled()) {
1012 logger.trace(String.format("Term = %s", term));
1014 Boolean anchorAtStart = false;
1015 Boolean anchorAtEnd = false;
1016 String filteredTerm;
1017 StringBuilder filteredTermBuilder = new StringBuilder(term);
1018 // Term contains no anchor or wildcard characters.
1019 if ( (! term.contains(RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR))
1020 && (! term.contains(RepositoryClientImpl.USER_SUPPLIED_WILDCARD)) ) {
1021 filteredTerm = term;
1023 // Term contains at least one such character.
1025 // Filter the starting anchor or wildcard character, if any.
1026 String firstChar = filteredTermBuilder.substring(0,1);
1027 switch (firstChar) {
1028 case RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR:
1029 anchorAtStart = true;
1031 case RepositoryClientImpl.USER_SUPPLIED_WILDCARD:
1032 filteredTermBuilder.deleteCharAt(0);
1035 if (logger.isTraceEnabled()) {
1036 logger.trace(String.format("After first char filtering = %s", filteredTermBuilder.toString()));
1038 // Filter the ending anchor or wildcard character, if any.
1039 int lastPos = filteredTermBuilder.length() - 1;
1040 String lastChar = filteredTermBuilder.substring(lastPos);
1042 case RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR:
1043 filteredTermBuilder.deleteCharAt(lastPos);
1044 filteredTermBuilder.insert(filteredTermBuilder.length(), RepositoryClientImpl.ENDING_ANCHOR_CHAR);
1047 case RepositoryClientImpl.USER_SUPPLIED_WILDCARD:
1048 filteredTermBuilder.deleteCharAt(lastPos);
1051 if (logger.isTraceEnabled()) {
1052 logger.trace(String.format("After last char filtering = %s", filteredTermBuilder.toString()));
1054 filteredTerm = filteredTermBuilder.toString();
1055 // Filter all other wildcards, if any.
1056 filteredTerm = filteredTerm.replaceAll(RepositoryClientImpl.USER_SUPPLIED_WILDCARD_REGEX, ZERO_OR_MORE_ANY_CHAR_REGEX);
1057 if (logger.isTraceEnabled()) {
1058 logger.trace(String.format("After replacing user wildcards = %s", filteredTerm));
1060 } catch (Exception e) {
1061 logger.warn(String.format("Error filtering anchor and wildcard characters from string: %s", e.getMessage()));
1065 // Wrap the term in beginning and ending regex wildcards, unless a
1066 // starting or ending anchor character was present.
1067 return (anchorAtStart ? "" : ZERO_OR_MORE_ANY_CHAR_REGEX)
1069 + (anchorAtEnd ? "" : ZERO_OR_MORE_ANY_CHAR_REGEX);
1072 @SuppressWarnings("unchecked")
1073 private List<String> getPartialTermDisplayNameMatches(DocumentModel docModel, // REM - CSPACE-5133
1074 String schema, ListResultField field, String partialTerm) {
1075 List<String> result = null;
1077 String xpath = field.getXpath(); // results in something like "persons_common:personTermGroupList/[0]/termDisplayName"
1078 int endOfTermGroup = xpath.lastIndexOf("/[0]/");
1079 String propertyName = endOfTermGroup != -1 ? xpath.substring(0, endOfTermGroup) : xpath; // it may not be multivalued so the xpath passed in would be the property name
1080 Object value = null;
1083 value = docModel.getProperty(schema, propertyName);
1084 } catch (Exception e) {
1085 logger.error("Could not extract term display name with property = "
1089 if (value != null && value instanceof ArrayList) {
1090 ArrayList<HashMap<String, Object>> termGroupList = (ArrayList<HashMap<String, Object>>)value;
1091 int arrayListSize = termGroupList.size();
1092 if (arrayListSize > 1) { // if there's only 1 element in the list then we've already matched the primary term's display name
1093 List<String> displayNameList = new ArrayList<String>();
1094 for (int i = 1; i < arrayListSize; i++) { // start at 1, skip the primary term's displayName since we will always return it
1095 HashMap<String, Object> map = (HashMap<String, Object>)termGroupList.get(i);
1096 String termDisplayName = (String) map.get(AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
1097 displayNameList.add(i - 1, termDisplayName);
1100 result = getPartialTermDisplayNameMatches(displayNameList, partialTerm);
1108 protected Object getListResultValue(DocumentModel docModel, // REM - CSPACE-5133
1109 String schema, ListResultField field) throws DocumentException {
1110 Object result = null;
1112 result = NuxeoUtils.getXPathValue(docModel, schema, field.getXpath());
1115 // Special handling of list item values for authority items (only)
1116 // takes place here:
1118 // If the list result field is the termDisplayName element,
1119 // check whether a partial term matching query was made.
1120 // If it was, emit values for both the preferred (aka primary)
1121 // term and for all non-preferred terms, if any.
1123 String elName = field.getElement();
1124 if (isTermDisplayName(elName) == true) {
1125 MultivaluedMap<String, String> queryParams = this.getServiceContext().getQueryParams();
1126 String partialTerm = queryParams != null ? queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM) : null;
1127 if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
1128 String primaryTermDisplayName = (String)result;
1129 List<String> matches = getPartialTermDisplayNameMatches(docModel, schema, field, partialTerm);
1130 if (matches != null && matches.isEmpty() == false) {
1131 matches.add(0, primaryTermDisplayName); // insert the primary term's display name at the beginning of the list
1132 result = matches; // set the result to a list of matching term display names with the primary term's display name at the beginning
1141 public void extractAllParts(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
1142 MultipartServiceContext ctx = (MultipartServiceContext) getServiceContext();
1143 super.extractAllParts(wrapDoc);
1146 protected List<RelationsCommonList.RelationListItem> cloneList(List<RelationsCommonList.RelationListItem> inboundList) {
1147 List<RelationsCommonList.RelationListItem> result = newRelationsCommonList();
1148 for (RelationsCommonList.RelationListItem item : inboundList) {
1155 /* don't even THINK of re-using this method.
1156 * String example_uri = "/locationauthorities/7ec60f01-84ab-4908-9a6a/items/a5466530-713f-43b4-bc05";
1159 private String extractInAuthorityCSID(String uri) {
1160 String IN_AUTHORITY_REGEX = "/(.*?)/(.*?)/(.*)";
1161 Pattern p = Pattern.compile(IN_AUTHORITY_REGEX);
1162 Matcher m = p.matcher(uri);
1164 if (m.groupCount() < 3) {
1165 logger.warn("REGEX-WRONG-GROUPCOUNT looking in " + uri);
1168 //String service = m.group(1);
1169 String inauth = m.group(2);
1170 //String theRest = m.group(3);
1172 //print("service:"+service+", inauth:"+inauth+", rest:"+rest);
1175 logger.warn("REGEX-NOT-MATCHED looking in " + uri);
1180 //ensures CSPACE-4042
1181 protected void uriPointsToSameAuthority(String thisURI, String inboundItemURI) throws Exception {
1182 String authorityCSID = extractInAuthorityCSID(thisURI);
1183 String authorityCSIDForInbound = extractInAuthorityCSID(inboundItemURI);
1184 if (Tools.isBlank(authorityCSID)
1185 || Tools.isBlank(authorityCSIDForInbound)
1186 || (!authorityCSID.equalsIgnoreCase(authorityCSIDForInbound))) {
1187 throw new Exception("Item URI " + thisURI + " must point to same authority as related item: " + inboundItemURI);
1191 public String getItemTermInfoGroupXPathBase() {
1192 return authorityItemTermGroupXPathBase;
1195 public void setItemTermInfoGroupXPathBase(String itemTermInfoGroupXPathBase) {
1196 authorityItemTermGroupXPathBase = itemTermInfoGroupXPathBase;
1199 protected String getAuthorityItemCommonSchemaName() {
1200 return authorityItemCommonSchemaName;
1204 public boolean isJDBCQuery() {
1205 boolean result = false;
1207 MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams();
1209 // Look the query params to see if we need to make a SQL query.
1211 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
1212 if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
1219 // By convention, the name of the database table that contains
1220 // repeatable term information group records is derivable from
1221 // an existing XPath base value, by removing a suffix and converting
1223 protected String getTermGroupTableName() {
1224 String termInfoGroupListName = getItemTermInfoGroupXPathBase();
1225 return termInfoGroupListName.substring(0, termInfoGroupListName.lastIndexOf(LIST_SUFFIX)).toLowerCase();
1228 protected String getInAuthorityValue() {
1229 String inAuthorityValue = getInAuthorityCsid();
1230 if (Tools.notBlank(inAuthorityValue)) {
1231 return inAuthorityValue;
1233 return AuthorityResource.PARENT_WILDCARD;
1238 public Map<String,String> getJDBCQueryParams() {
1239 // FIXME: Get all of the following values from appropriate external constants.
1240 // At present, these are duplicated in both RepositoryClientImpl
1241 // and in AuthorityItemDocumentModelHandler.
1242 final String TERM_GROUP_LIST_NAME = "TERM_GROUP_LIST_NAME";
1243 final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
1244 final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
1246 Map<String,String> params = super.getJDBCQueryParams();
1247 params.put(TERM_GROUP_LIST_NAME, getItemTermInfoGroupXPathBase());
1248 params.put(TERM_GROUP_TABLE_NAME_PARAM, getTermGroupTableName());
1249 params.put(IN_AUTHORITY_PARAM, getInAuthorityValue());