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 isProposed = false; // used by local authority to propose a new shared item. Allows local deployments to use new terms until they become official
94 private boolean isSAS = false; // used to indicate if the authority item originated as a SAS item
95 private boolean shouldUpdateRevNumber = true; // by default we should update the revision number -not true on synchronization with SAS
97 * inVocabulary is the parent Authority for this context
99 protected String inAuthority = null;
100 protected boolean wildcardedAuthorityRequest = false;
101 protected String authorityRefNameBase = null;
102 // Used to determine when the displayName changes as part of the update.
103 protected String oldDisplayNameOnUpdate = null;
104 private final static String LIST_SUFFIX = "List";
105 private final static String ZERO_OR_MORE_ANY_CHAR_REGEX = ".*";
107 public AuthorityItemDocumentModelHandler(String authorityCommonSchemaName, String authorityItemCommonSchemaName) {
108 this.authorityItemCommonSchemaName = authorityItemCommonSchemaName;
111 abstract public String getParentCommonSchemaName();
114 // Getter and Setter for 'proposed'
116 public boolean getIsProposed() {
117 return this.isProposed;
120 public void setIsProposed(boolean flag) {
121 this.isProposed = flag;
125 // Getter and Setter for 'isSAS'
127 public boolean getIsSASItem() {
131 public void setIsSASItem(boolean flag) {
136 // Getter and Setter for 'shouldUpdateRevNumber'
138 public boolean getShouldUpdateRevNumber() {
139 return this.shouldUpdateRevNumber;
142 public void setShouldUpdateRevNumber(boolean flag) {
143 this.shouldUpdateRevNumber = flag;
147 public void prepareSync() throws Exception {
148 this.setShouldUpdateRevNumber(AuthorityServiceUtils.DONT_UPDATE_REV); // Never update rev nums on sync operations
152 protected String getRefnameDisplayName(DocumentWrapper<DocumentModel> docWrapper) {
153 String result = null;
155 DocumentModel docModel = docWrapper.getWrappedObject();
156 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = this.getServiceContext();
157 RefName.AuthorityItem refname = (RefName.AuthorityItem)getRefName(ctx, docModel);
158 result = refname.getDisplayName();
164 * After calling this method successfully, the document model will contain an updated refname and short ID
166 * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#getRefName(org.collectionspace.services.common.context.ServiceContext, org.nuxeo.ecm.core.api.DocumentModel)
169 public RefName.RefNameInterface getRefName(ServiceContext ctx,
170 DocumentModel docModel) {
171 RefName.RefNameInterface refname = null;
174 String displayName = getPrimaryDisplayName(docModel, authorityItemCommonSchemaName,
175 getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
176 if (Tools.isEmpty(displayName)) {
177 throw new Exception("The displayName for this authority term was empty or not set.");
180 String shortIdentifier = (String) docModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
181 if (Tools.isEmpty(shortIdentifier)) {
182 // We didn't find a short ID in the payload request, so we need to synthesize one.
183 shortIdentifier = handleDisplayNameAsShortIdentifier(docModel); // updates the document model with the new short ID as a side-effect
186 String authorityRefBaseName = getAuthorityRefNameBase();
187 if (Tools.isEmpty(authorityRefBaseName)) {
188 throw new Exception("Could not create the refName for this authority term, because the refName for its authority parent was empty.");
191 // Create the items refname using the parent's as a base
192 RefName.Authority parentsRefName = RefName.Authority.parse(authorityRefBaseName);
193 refname = RefName.buildAuthorityItem(parentsRefName, shortIdentifier, displayName);
194 // Now update the document model with the refname value
195 String refNameStr = refname.toString();
196 docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REF_NAME, refNameStr); // REM - This field is deprecated now that the refName is part of the collection_space core schema
198 } catch (Exception e) {
199 logger.error(e.getMessage(), e);
205 public void setInAuthority(String inAuthority) {
206 this.inAuthority = inAuthority;
209 public String getInAuthorityCsid() {
210 return this.inAuthority;
213 /** Subclasses may override this to customize the URI segment. */
214 public String getAuthorityServicePath() {
215 return getServiceContext().getServiceName().toLowerCase(); // Laramie20110510 CSPACE-3932
219 public String getUri(DocumentModel docModel) {
220 // Laramie20110510 CSPACE-3932
221 String authorityServicePath = getAuthorityServicePath();
222 if(inAuthority==null) { // Only true with the first document model received, on queries to wildcarded authorities
223 wildcardedAuthorityRequest = true;
225 // If this search crosses multiple authorities, get the inAuthority value
226 // from each record, rather than using the cached value from the first record
227 if(wildcardedAuthorityRequest) {
229 inAuthority = (String) docModel.getProperty(authorityItemCommonSchemaName,
230 AuthorityItemJAXBSchema.IN_AUTHORITY);
231 } catch (ClientException pe) {
232 throw new RuntimeException("Could not get parent specifier for item!");
235 return "/" + authorityServicePath + '/' + inAuthority + '/' + AuthorityClient.ITEMS + '/' + getCsid(docModel);
238 protected String getAuthorityRefNameBase() {
239 return this.authorityRefNameBase;
242 public void setAuthorityRefNameBase(String value) {
243 this.authorityRefNameBase = value;
247 * Note: the Vocabulary service's VocabularyItemDocumentModelHandler class overrides this method.
249 protected ListResultField getListResultsDisplayNameField() {
250 ListResultField result = new ListResultField();
251 // Per CSPACE-5132, the name of this element remains 'displayName'
252 // for backwards compatibility, although its value is obtained
253 // from the termDisplayName field.
255 // Update: this name is now being changed to 'termDisplayName', both
256 // because this is the actual field name and because the app layer
257 // work to convert over to this field is underway. Per Patrick, the
258 // app layer treats lists, in at least some context(s), as sparse record
259 // payloads, and thus fields in list results must all be present in
260 // (i.e. represent a strict subset of the fields in) record schemas.
264 // In CSPACE-5134, these list results will change substantially
265 // to return display names for both the preferred term and for
266 // each non-preferred term (if any).
267 result.setElement(AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
268 result.setXpath(NuxeoUtils.getPrimaryXPathPropertyName(
269 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_DISPLAY_NAME));
275 * Note: the Vocabulary service's VocabularyItemDocumentModelHandler class overrides this method.
277 protected ListResultField getListResultsTermStatusField() {
278 ListResultField result = new ListResultField();
280 result.setElement(AuthorityItemJAXBSchema.TERM_STATUS);
281 result.setXpath(NuxeoUtils.getPrimaryXPathPropertyName(
282 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_STATUS));
287 private boolean isTermDisplayName(String elName) {
288 return AuthorityItemJAXBSchema.TERM_DISPLAY_NAME.equals(elName) || VocabularyItemJAXBSchema.DISPLAY_NAME.equals(elName);
293 * @see org.collectionspace.services.nuxeo.client.java.DocHandlerBase#getListItemsArray()
295 * Note: We're updating the "global" service and tenant bindings instance here -the list instance here is
296 * a reference to the tenant bindings instance in the singleton ServiceMain.
299 public List<ListResultField> getListItemsArray() throws DocumentException {
300 List<ListResultField> list = super.getListItemsArray();
302 // One-time initialization for each authority item service.
303 if (isListItemArrayExtended() == false) {
304 synchronized(AuthorityItemDocumentModelHandler.class) {
305 if (isListItemArrayExtended() == false) {
306 int nFields = list.size();
307 // Ensure that each item in a list of Authority items includes
308 // a set of common fields, so we do not depend upon configuration
309 // for general logic.
310 List<Integer> termDisplayNamePositionsInList = new ArrayList<>();
311 boolean hasShortId = false;
312 boolean hasTermStatus = false;
313 for (int i = 0; i < nFields; i++) {
314 ListResultField field = list.get(i);
315 String elName = field.getElement();
316 if (isTermDisplayName(elName) == true) {
317 termDisplayNamePositionsInList.add(i);
318 } else if (AuthorityItemJAXBSchema.SHORT_IDENTIFIER.equals(elName)) {
320 } else if (AuthorityItemJAXBSchema.TERM_STATUS.equals(elName)) {
321 hasTermStatus = true;
325 ListResultField field;
327 // Certain fields in authority item list results
328 // are handled specially here
332 // Ignore (throw out) any configuration entries that
333 // specify how the termDisplayName field should be
334 // emitted in authority item lists. This field will
335 // be handled in a standardized manner (see block below).
336 if (termDisplayNamePositionsInList.isEmpty() == false) {
337 // Remove matching items starting at the end of the list
338 // and moving towards the start, so that reshuffling of
339 // list order doesn't alter the positions of earlier items
340 Collections.sort(termDisplayNamePositionsInList, Collections.reverseOrder());
341 for (int i : termDisplayNamePositionsInList) {
345 // termDisplayName values in authority item lists
346 // will be handled via code that emits display names
347 // for both the preferred term and all non-preferred
348 // terms (if any). The following is a placeholder
349 // entry that will trigger this code. See the
350 // getListResultValue() method in this class.
351 field = getListResultsDisplayNameField();
356 field = new ListResultField();
357 field.setElement(AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
358 field.setXpath(AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
363 if (!hasTermStatus) {
364 field = getListResultsTermStatusField();
370 setListItemArrayExtended(true);
371 } // end of synchronized block
378 * We consider workflow state changes as a change that should bump the revision number.
379 * Warning: This method might change the transitionDef's transtionName value
382 public void handleWorkflowTransition(ServiceContext ctx, DocumentWrapper<DocumentModel> wrapDoc, TransitionDef transitionDef) throws Exception {
383 // Decide whether or not to update the revision number
384 if (this.getShouldUpdateRevNumber() == true) { // We don't update the rev number of synchronization requests
385 updateRevNumbers(wrapDoc);
388 // We can't delete an authority item that has referencing records.
390 DocumentModel docModel = wrapDoc.getWrappedObject();
391 if (transitionDef.getName().equalsIgnoreCase(WorkflowClient.WORKFLOWTRANSITION_DELETE)) {
392 long refsToAllObjects = hasReferencingObjects(ctx, docModel, false);
393 long refsToSoftDeletedObjects = hasReferencingObjects(ctx, docModel, true);
394 if (refsToAllObjects > 0) {
395 if (refsToAllObjects > refsToSoftDeletedObjects) {
397 // If the number of refs to active objects is greater than the number of refs to
398 // soft deleted objects then we can't delete the item.
400 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.",
401 docModel.getName()));
408 * This method synchronizes/updates a single authority item resource.
409 * for the handleSync method, the wrapDoc argument contains a authority item specifier.
412 public boolean handleSync(DocumentWrapper<Object> wrapDoc) throws Exception {
413 boolean result = false;
414 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
417 // Get information about the local authority item so we can compare with corresponding item on the shared authority server
419 AuthorityItemSpecifier authorityItemSpecifier = (AuthorityItemSpecifier) wrapDoc.getWrappedObject();
420 DocumentModel itemDocModel = NuxeoUtils.getDocFromSpecifier(ctx, getRepositorySession(), getAuthorityItemCommonSchemaName(),
421 authorityItemSpecifier);
422 if (itemDocModel == null) {
423 throw new DocumentNotFoundException(String.format("Could not find authority item resource with CSID='%s'",
424 authorityItemSpecifier.getItemSpecifier().value));
426 Long localItemRev = (Long) NuxeoUtils.getProperyValue(itemDocModel, AuthorityItemJAXBSchema.REV);
427 Boolean localIsProposed = (Boolean) NuxeoUtils.getProperyValue(itemDocModel, AuthorityItemJAXBSchema.PROPOSED);
428 String localItemCsid = itemDocModel.getName();
429 String localItemWorkflowState = itemDocModel.getCurrentLifeCycleState();
430 String itemShortId = (String) NuxeoUtils.getProperyValue(itemDocModel, AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
433 // Now get the item's Authority (the parent) information
435 DocumentModel authorityDocModel = NuxeoUtils.getDocFromSpecifier(ctx, getRepositorySession(), authorityCommonSchemaName,
436 authorityItemSpecifier.getParentSpecifier());
437 String authorityShortId = (String) NuxeoUtils.getProperyValue(authorityDocModel, AuthorityJAXBSchema.SHORT_IDENTIFIER);
438 String localParentCsid = authorityDocModel.getName();
440 // Using the short IDs of the local authority and item, create URN specifiers to retrieve the SAS authority item
442 AuthorityItemSpecifier sasAuthorityItemSpecifier = new AuthorityItemSpecifier(SpecifierForm.URN_NAME, authorityShortId, itemShortId);
443 // Get the shared authority server's copy
444 PoxPayloadIn sasPayloadIn = AuthorityServiceUtils.requestPayloadIn(sasAuthorityItemSpecifier,
445 getAuthorityServicePath(), getEntityResponseType());
446 Long sasRev = getRevision(sasPayloadIn);
447 String sasWorkflowState = getWorkflowState(sasPayloadIn);
449 // If the shared authority item is newer, update our local copy
451 if (sasRev > localItemRev || localIsProposed) {
452 sasPayloadIn = AuthorityServiceUtils.filterRefnameDomains(ctx, sasPayloadIn); // We need to filter the domain name part of any and all refnames in the payload
453 AuthorityResource authorityResource = (AuthorityResource) ctx.getResource(getAuthorityServicePath());
454 PoxPayloadOut payloadOut = authorityResource.updateAuthorityItem(ctx,
455 ctx.getResourceMap(),
457 localParentCsid, // parent's CSID
458 localItemCsid, // item's CSID
459 sasPayloadIn, // the payload from the remote SAS
460 AuthorityServiceUtils.DONT_UPDATE_REV, // don't update the parent's revision number
461 AuthorityServiceUtils.NOT_PROPOSED, // The items is not proposed, make it a real SAS item now
462 AuthorityServiceUtils.SAS_ITEM); // Since we're sync'ing, this must be a SAS item
463 if (payloadOut != null) {
464 ctx.setOutput(payloadOut);
469 // Check to see if we need to update the local items's workflow state to reflect that of the remote's
471 List<String> transitionList = getTransitionList(sasWorkflowState, localItemWorkflowState);
472 if (transitionList.isEmpty() == false) {
473 AuthorityResource authorityResource = (AuthorityResource) ctx.getResource(getAuthorityServicePath()); // Get the authority (parent) client not the item client
475 // We need to move the local item to the SAS workflow state. This might involve multiple transitions.
477 for (String transition:transitionList) {
479 authorityResource.updateItemWorkflowWithTransition(ctx, localParentCsid, localItemCsid, transition, AuthorityServiceUtils.DONT_UPDATE_REV);
480 } catch (DocumentReferenceException de) {
482 // This exception means we tried unsuccessfully to soft-delete (workflow transition 'delete') an item that still has references to it from other records.
484 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
485 logger.warn(String.format("Could not transition item CSID='%s' from workflow state '%s' to '%s'. Check the services log file for details.",
486 localItemCsid, localItemWorkflowState, sasWorkflowState));
492 // We need to synchronize the hierarchy relationships here.
499 * We need to change the local item's state to one that maps to the replication server's workflow
500 * state. This might involve making multiple transitions.
503 * See table at https://wiki.collectionspace.org/pages/viewpage.action?pageId=162496564
506 private List<String> getTransitionList(String sasWorkflowState, String localItemWorkflowState) throws DocumentException {
507 List<String> result = new ArrayList<String>();
509 // The first set of conditions maps a replication-server "project" state to a local client state of "replicated"
511 if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT)) {
512 result.add(WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
513 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED)) {
514 result.add(WorkflowClient.WORKFLOWTRANSITION_UNDELETE);
515 result.add(WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
516 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED)) {
517 // Do nothing. We're good with this state
518 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED)) {
519 result.add(WorkflowClient.WORKFLOWTRANSITION_UNDELETE);
521 // The second set of conditions maps a replication-server "deleted" state to a local client state of "deleted"
523 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT)) {
524 result.add(WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
525 result.add(WorkflowClient.WORKFLOWTRANSITION_DELETE);
526 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED)) {
527 result.add(WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
528 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED)) {
529 result.add(WorkflowClient.WORKFLOWTRANSITION_DELETE);
530 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED)) {
531 // Do nothing. We're good with this state
533 // The third set of conditions maps a replication-server "replicated" state to a local state of "replicated"
535 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT)) {
536 result.add(WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
537 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED)) {
538 result.add(WorkflowClient.WORKFLOWTRANSITION_UNDELETE);
539 result.add(WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
540 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED)) {
541 // Do nothing. We're good with this state
542 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED)) {
543 result.add(WorkflowClient.WORKFLOWTRANSITION_UNDELETE);
545 // The last set of conditions maps a replication-server "replicated_deleted" state to a local client state of "deleted"
547 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_PROJECT)) {
548 result.add(WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
549 result.add(WorkflowClient.WORKFLOWTRANSITION_DELETE);
550 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_DELETED)) {
551 result.add(WorkflowClient.WORKFLOWTRANSITION_REPLICATE);
552 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED)) {
553 result.add(WorkflowClient.WORKFLOWTRANSITION_DELETE);
554 } else if (sasWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED) && localItemWorkflowState.equals(WorkflowClient.WORKFLOWSTATE_REPLICATED_DELETED)) {
555 // Do nothing. We're good with this state
558 // If we get here, we've encountered a SAS workflow state that we don't recognize.
560 throw new DocumentException(String.format("Encountered an invalid workflow state of '%s' on a SAS authority item.", sasWorkflowState));
567 * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#handleCreate(org.collectionspace.services.common.document.DocumentWrapper)
570 public void handleCreate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
571 // first fill all the parts of the document, refname and short ID get set as well
572 super.handleCreate(wrapDoc);
573 // Ensure we have required fields set properly
574 handleInAuthority(wrapDoc.getWrappedObject());
578 * This method gets called after the primary update to an authority item has happened. If the authority item's refName
579 * has changed, then we need to updated all the records that use that refname with the new/updated version
584 public boolean handleDelete(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
585 boolean result = true;
587 ServiceContext ctx = getServiceContext();
588 DocumentModel docModel = wrapDoc.getWrappedObject();
590 long refsToAllObjects = hasReferencingObjects(ctx, docModel, false);
591 long refsToSoftDeletedObjects = hasReferencingObjects(ctx, docModel, true);
592 if (refsToAllObjects > 0) {
593 if (refsToAllObjects > refsToSoftDeletedObjects) {
595 // If the number of refs to active objects is greater than the number of refs to
596 // soft deleted objects then we can't delete the item.
598 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.",
599 docModel.getName()));
602 // 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.
604 Boolean shouldUpdateRev = (Boolean) ctx.getProperty(AuthorityServiceUtils.SHOULD_UPDATE_REV_PROPERTY);
605 String parentCsid = (String) NuxeoUtils.getProperyValue(docModel, AuthorityItemJAXBSchema.IN_AUTHORITY);
606 String itemCsid = docModel.getName();
607 AuthorityResource authorityResource = (AuthorityResource) ctx.getResource(getAuthorityServicePath());
608 authorityResource.updateItemWorkflowWithTransition(ctx, parentCsid, itemCsid, WorkflowClient.WORKFLOWTRANSITION_DELETE,
609 shouldUpdateRev != null ? shouldUpdateRev : true);
610 result = false; // Don't delete since we just soft-deleted it.
618 * Checks to see if an authority item has referencing objects.
625 private long hasReferencingObjects(ServiceContext ctx, DocumentModel docModel, boolean onlyRefsToDeletedObjects) throws Exception {
628 String inAuthorityCsid = (String) docModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.IN_AUTHORITY);
629 AuthorityResource authorityResource = (AuthorityResource)ctx.getResource(getAuthorityServicePath());
630 String itemCsid = docModel.getName();
631 UriTemplateRegistry uriTemplateRegistry = ServiceMain.getInstance().getUriTemplateRegistry();
632 if (ctx.getUriInfo() == null) {
634 // We need a UriInfo object so we can pass "query" params to the AuthorityResource's getReferencingObjects() method
636 ctx.setUriInfo(this.getServiceContext().getUriInfo()); // try to get a UriInfo instance from the handler's context
638 ctx.getUriInfo().getQueryParameters().addFirst(WorkflowClient.WORKFLOW_QUERY_ONLY_DELETED, Boolean.toString(onlyRefsToDeletedObjects)); // Add the wf_only_deleted query param to the resource call
639 AuthorityRefDocList refObjs = authorityResource.getReferencingObjects(ctx, inAuthorityCsid, itemCsid,
640 uriTemplateRegistry, ctx.getUriInfo());
641 ctx.getUriInfo().getQueryParameters().remove(WorkflowClient.WORKFLOW_QUERY_ONLY_DELETED); // Need to clear wf_only_deleted values to prevent unexpected side effects
643 result = refObjs.getTotalItems();
645 logger.error(String.format("Cannot delete authority item '%s' because it still has %d records in the system that are referencing it.",
646 itemCsid, refObjs.getTotalItems()));
647 if (logger.isWarnEnabled() == true) {
648 logReferencingObjects(docModel, refObjs);
655 private void logReferencingObjects(DocumentModel docModel, AuthorityRefDocList refObjs) {
656 List<AuthorityRefDocList.AuthorityRefDocItem> items = refObjs.getAuthorityRefDocItem();
658 logger.warn(String.format("The authority item '%s' has the following references:", docModel.getName()));
659 for (AuthorityRefDocList.AuthorityRefDocItem item : items) {
660 logger.warn(docModel.getName() + " referenced by : list-item[" + i + "] "
661 + item.getDocType() + "("
662 + item.getDocId() + ") Name:["
663 + item.getDocName() + "] Number:["
664 + item.getDocNumber() + "] in field:["
665 + item.getSourceField() + "]");
670 * This method gets called after the primary update to an authority item has happened. If the authority item's refName
671 * has changed, then we need to updated all the records that use that refname with the new/updated version
674 * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#completeUpdate(org.collectionspace.services.common.document.DocumentWrapper)
676 public void completeUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
677 // Must call our super class' version first
678 super.completeUpdate(wrapDoc);
681 // Look for and update authority references with the updated refName
683 if (hasRefNameUpdate() == true) {
684 // We have work to do.
685 if (logger.isDebugEnabled()) {
686 final String EOL = System.getProperty("line.separator");
687 logger.debug("Need to find and update references to authority item." + EOL
688 + " Old refName" + oldRefNameOnUpdate + EOL
689 + " New refName" + newRefNameOnUpdate);
691 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
692 RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient = getRepositoryClient(ctx);
693 CoreSessionInterface repoSession = this.getRepositorySession();
695 // Update all the existing records that have a field with the old refName in it
696 int nUpdated = RefNameServiceUtils.updateAuthorityRefDocs(ctx, repoClient, repoSession,
697 oldRefNameOnUpdate, newRefNameOnUpdate, getRefPropName());
699 // Finished so log a message.
700 if (logger.isDebugEnabled()) {
701 logger.debug("Updated " + nUpdated + " instances of oldRefName to newRefName");
707 * Note that the Vocabulary service's document-model for items overrides this method.
709 protected String getPrimaryDisplayName(DocumentModel docModel, String schema,
710 String complexPropertyName, String fieldName) {
711 String result = null;
713 result = getStringValueInPrimaryRepeatingComplexProperty(docModel, schema, complexPropertyName, fieldName);
719 * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#handleUpdate(org.collectionspace.services.common.document.DocumentWrapper)
722 // 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.
724 public void handleUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
725 // Must call our super's version first, this updates the core schema and the relationship records to deal with possible refName changes/update
726 super.handleUpdate(wrapDoc);
727 if (this.hasRefNameUpdate() == true) {
728 DocumentModel docModel = wrapDoc.getWrappedObject();
729 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
734 // Handles both update calls (PUTS) AND create calls (POSTS)
736 public void fillAllParts(DocumentWrapper<DocumentModel> wrapDoc, Action action) throws Exception {
737 super.fillAllParts(wrapDoc, action);
738 DocumentModel documentModel = wrapDoc.getWrappedObject();
741 // Update the record's revision number on both CREATE and UPDATE actions (as long as it is NOT a SAS authority item)
743 Boolean propertyValue = (Boolean) documentModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SAS);
744 boolean isMarkedAsSASItem = propertyValue != null ? propertyValue : false;
745 if (this.getShouldUpdateRevNumber() == true && !isMarkedAsSASItem) { // We won't update rev numbers on synchronization with SAS items and on local changes to SAS items
746 updateRevNumbers(wrapDoc);
749 // If this is a proposed item (not part of the SAS), mark it as such
751 documentModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.PROPOSED,
752 new Boolean(this.getIsProposed()));
754 // If it is a SAS authority item, mark it as such
756 documentModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SAS,
757 new Boolean(this.getIsSASItem()));
761 * Update the revision number of both the item and the item's parent.
765 protected void updateRevNumbers(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
766 DocumentModel documentModel = wrapDoc.getWrappedObject();
767 Long rev = (Long)documentModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REV);
773 documentModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REV, rev);
775 // Next, update the inAuthority (the parent's) rev number
777 String inAuthorityCsid = this.getInAuthorityCsid();
778 if (inAuthorityCsid == null) {
779 // When inAuthorityCsid is null, it usually means we're performing and update or synch with the SAS
780 inAuthorityCsid = (String)documentModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.IN_AUTHORITY);
782 DocumentModel inAuthorityDocModel = NuxeoUtils.getDocFromCsid(getServiceContext(), getRepositorySession(), inAuthorityCsid);
783 Long parentRev = (Long)inAuthorityDocModel.getProperty(getParentCommonSchemaName(), AuthorityJAXBSchema.REV);
784 if (parentRev == null) {
785 parentRev = new Long(0);
788 inAuthorityDocModel.setProperty(getParentCommonSchemaName(), AuthorityJAXBSchema.REV, parentRev);
789 getRepositorySession().saveDocument(inAuthorityDocModel);
793 * If no short identifier was provided in the input payload, generate a
794 * short identifier from the preferred term display name or term name.
796 private String handleDisplayNameAsShortIdentifier(DocumentModel docModel) throws Exception {
797 String result = (String) docModel.getProperty(authorityItemCommonSchemaName,
798 AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
800 if (Tools.isEmpty(result)) {
801 String termDisplayName = getPrimaryDisplayName(
802 docModel, authorityItemCommonSchemaName,
803 getItemTermInfoGroupXPathBase(),
804 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
806 String termName = getPrimaryDisplayName(
807 docModel, authorityItemCommonSchemaName,
808 getItemTermInfoGroupXPathBase(),
809 AuthorityItemJAXBSchema.TERM_NAME);
811 String generatedShortIdentifier = AuthorityIdentifierUtils.generateShortIdentifierFromDisplayName(termDisplayName,
813 docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER,
814 generatedShortIdentifier);
815 result = generatedShortIdentifier;
822 * Generate a refName for the authority item from the short identifier
825 * All refNames for authority items are generated. If a client supplies
826 * a refName, it will be overwritten during create (per this method)
827 * or discarded during update (per filterReadOnlyPropertiesForPart).
829 * @see #filterReadOnlyPropertiesForPart(Map<String, Object>, org.collectionspace.services.common.service.ObjectPartType)
832 protected String updateRefnameForAuthorityItem(DocumentModel docModel,
833 String schemaName) throws Exception {
834 String result = null;
836 RefName.RefNameInterface refname = getRefName(getServiceContext(), docModel);
837 String refNameStr = refname.toString();
838 docModel.setProperty(schemaName, AuthorityItemJAXBSchema.REF_NAME, refNameStr);
845 * Check the logic around the parent pointer. Note that we only need do this on
846 * create, since we have logic to make this read-only on update.
850 * @throws Exception the exception
852 private void handleInAuthority(DocumentModel docModel) throws Exception {
853 if(inAuthority==null) { // Only happens on queries to wildcarded authorities
854 throw new IllegalStateException("Trying to Create an object with no inAuthority value!");
856 docModel.setProperty(authorityItemCommonSchemaName,
857 AuthorityItemJAXBSchema.IN_AUTHORITY, inAuthority);
861 * Returns a list of records that reference this authority item
864 * @param uriTemplateRegistry
865 * @param serviceTypes
866 * @param propertyName
871 public AuthorityRefDocList getReferencingObjects(
872 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
873 UriTemplateRegistry uriTemplateRegistry,
874 List<String> serviceTypes,
876 String itemcsid) throws Exception {
877 AuthorityRefDocList authRefDocList = null;
878 CoreSessionInterface repoSession = (CoreSessionInterface) ctx.getCurrentRepositorySession();
879 boolean releaseRepoSession = false;
882 RepositoryClientImpl repoClient = (RepositoryClientImpl)this.getRepositoryClient(ctx);
883 repoSession = this.getRepositorySession();
884 if (repoSession == null) {
885 repoSession = repoClient.getRepositorySession(ctx);
886 releaseRepoSession = true;
888 DocumentFilter myFilter = getDocumentFilter();
891 DocumentWrapper<DocumentModel> wrapper = repoClient.getDoc(repoSession, ctx, itemcsid);
892 DocumentModel docModel = wrapper.getWrappedObject();
893 String refName = (String) NuxeoUtils.getProperyValue(docModel, AuthorityItemJAXBSchema.REF_NAME); //docModel.getPropertyValue(AuthorityItemJAXBSchema.REF_NAME);
894 authRefDocList = RefNameServiceUtils.getAuthorityRefDocs(
895 repoSession, ctx, uriTemplateRegistry, repoClient,
899 myFilter, true /*computeTotal*/);
900 } catch (PropertyException pe) {
902 } catch (DocumentException de) {
904 } catch (Exception e) {
905 if (logger.isDebugEnabled()) {
906 logger.debug("Caught exception ", e);
908 throw new DocumentException(e);
910 // If we got/aquired a new seesion then we're responsible for releasing it.
911 if (releaseRepoSession && repoSession != null) {
912 repoClient.releaseRepositorySession(ctx, repoSession);
915 } catch (Exception e) {
916 if (logger.isDebugEnabled()) {
917 logger.debug("Caught exception ", e);
919 throw new DocumentException(e);
922 return authRefDocList;
926 * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#extractPart(org.nuxeo.ecm.core.api.DocumentModel, java.lang.String, org.collectionspace.services.common.service.ObjectPartType)
929 protected Map<String, Object> extractPart(DocumentModel docModel, String schema, ObjectPartType partMeta)
931 Map<String, Object> unQObjectProperties = super.extractPart(docModel, schema, partMeta);
933 // Add the CSID to the common part, since they may have fetched via the shortId.
934 if (partMeta.getLabel().equalsIgnoreCase(authorityItemCommonSchemaName)) {
935 String csid = getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
936 unQObjectProperties.put("csid", csid);
939 return unQObjectProperties;
943 * Filters out selected values supplied in an update request.
945 * For example, filters out AuthorityItemJAXBSchema.IN_AUTHORITY, to ensure
946 * that the link to the item's parent remains untouched.
948 * @param objectProps the properties filtered out from the update payload
949 * @param partMeta metadata for the object to fill
952 public void filterReadOnlyPropertiesForPart(
953 Map<String, Object> objectProps, ObjectPartType partMeta) {
954 super.filterReadOnlyPropertiesForPart(objectProps, partMeta);
955 String commonPartLabel = getServiceContext().getCommonPartLabel();
956 if (partMeta.getLabel().equalsIgnoreCase(commonPartLabel)) {
957 objectProps.remove(AuthorityItemJAXBSchema.IN_AUTHORITY);
958 objectProps.remove(AuthorityItemJAXBSchema.CSID);
959 objectProps.remove(AuthorityJAXBSchema.SHORT_IDENTIFIER);
960 objectProps.remove(AuthorityItemJAXBSchema.REF_NAME);
965 * Returns the items in a list of term display names whose names contain
966 * a partial term (as might be submitted in a search query, for instance).
967 * @param termDisplayNameList a list of term display names.
968 * @param partialTerm a partial term display name; that is, a portion
969 * of a display name that might be expected to match 0-n terms in the list.
970 * @return a list of term display names that matches the partial term.
971 * Matches are case-insensitive. As well, before matching is performed, any
972 * special-purpose characters that may appear in the partial term (such as
973 * wildcards and anchor characters) are filtered out from both compared terms.
975 protected List<String> getPartialTermDisplayNameMatches(List<String> termDisplayNameList, String partialTerm) {
976 List<String> result = new ArrayList<>();
977 String partialTermMatchExpression = filterAnchorAndWildcardChars(partialTerm).toLowerCase();
979 for (String termDisplayName : termDisplayNameList) {
980 if (termDisplayName.toLowerCase()
981 .matches(partialTermMatchExpression) == true) {
982 result.add(termDisplayName);
985 } catch (PatternSyntaxException pse) {
986 logger.warn("Error in regex match pattern '%s' for term display names: %s",
987 partialTermMatchExpression, pse.getMessage());
993 * Filters user-supplied anchor and wildcard characters in a string,
994 * replacing them with equivalent regular expressions.
995 * @param term a term in which to filter anchor and wildcard characters.
996 * @return the term with those characters filtered.
998 protected String filterAnchorAndWildcardChars(String term) {
999 if (Tools.isBlank(term)) {
1002 if (term.length() < 3) {
1005 if (logger.isTraceEnabled()) {
1006 logger.trace(String.format("Term = %s", term));
1008 Boolean anchorAtStart = false;
1009 Boolean anchorAtEnd = false;
1010 String filteredTerm;
1011 StringBuilder filteredTermBuilder = new StringBuilder(term);
1012 // Term contains no anchor or wildcard characters.
1013 if ( (! term.contains(RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR))
1014 && (! term.contains(RepositoryClientImpl.USER_SUPPLIED_WILDCARD)) ) {
1015 filteredTerm = term;
1017 // Term contains at least one such character.
1019 // Filter the starting anchor or wildcard character, if any.
1020 String firstChar = filteredTermBuilder.substring(0,1);
1021 switch (firstChar) {
1022 case RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR:
1023 anchorAtStart = true;
1025 case RepositoryClientImpl.USER_SUPPLIED_WILDCARD:
1026 filteredTermBuilder.deleteCharAt(0);
1029 if (logger.isTraceEnabled()) {
1030 logger.trace(String.format("After first char filtering = %s", filteredTermBuilder.toString()));
1032 // Filter the ending anchor or wildcard character, if any.
1033 int lastPos = filteredTermBuilder.length() - 1;
1034 String lastChar = filteredTermBuilder.substring(lastPos);
1036 case RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR:
1037 filteredTermBuilder.deleteCharAt(lastPos);
1038 filteredTermBuilder.insert(filteredTermBuilder.length(), RepositoryClientImpl.ENDING_ANCHOR_CHAR);
1041 case RepositoryClientImpl.USER_SUPPLIED_WILDCARD:
1042 filteredTermBuilder.deleteCharAt(lastPos);
1045 if (logger.isTraceEnabled()) {
1046 logger.trace(String.format("After last char filtering = %s", filteredTermBuilder.toString()));
1048 filteredTerm = filteredTermBuilder.toString();
1049 // Filter all other wildcards, if any.
1050 filteredTerm = filteredTerm.replaceAll(RepositoryClientImpl.USER_SUPPLIED_WILDCARD_REGEX, ZERO_OR_MORE_ANY_CHAR_REGEX);
1051 if (logger.isTraceEnabled()) {
1052 logger.trace(String.format("After replacing user wildcards = %s", filteredTerm));
1054 } catch (Exception e) {
1055 logger.warn(String.format("Error filtering anchor and wildcard characters from string: %s", e.getMessage()));
1059 // Wrap the term in beginning and ending regex wildcards, unless a
1060 // starting or ending anchor character was present.
1061 return (anchorAtStart ? "" : ZERO_OR_MORE_ANY_CHAR_REGEX)
1063 + (anchorAtEnd ? "" : ZERO_OR_MORE_ANY_CHAR_REGEX);
1066 @SuppressWarnings("unchecked")
1067 private List<String> getPartialTermDisplayNameMatches(DocumentModel docModel, // REM - CSPACE-5133
1068 String schema, ListResultField field, String partialTerm) {
1069 List<String> result = null;
1071 String xpath = field.getXpath(); // results in something like "persons_common:personTermGroupList/[0]/termDisplayName"
1072 int endOfTermGroup = xpath.lastIndexOf("/[0]/");
1073 String propertyName = endOfTermGroup != -1 ? xpath.substring(0, endOfTermGroup) : xpath; // it may not be multivalued so the xpath passed in would be the property name
1074 Object value = null;
1077 value = docModel.getProperty(schema, propertyName);
1078 } catch (Exception e) {
1079 logger.error("Could not extract term display name with property = "
1083 if (value != null && value instanceof ArrayList) {
1084 ArrayList<HashMap<String, Object>> termGroupList = (ArrayList<HashMap<String, Object>>)value;
1085 int arrayListSize = termGroupList.size();
1086 if (arrayListSize > 1) { // if there's only 1 element in the list then we've already matched the primary term's display name
1087 List<String> displayNameList = new ArrayList<String>();
1088 for (int i = 1; i < arrayListSize; i++) { // start at 1, skip the primary term's displayName since we will always return it
1089 HashMap<String, Object> map = (HashMap<String, Object>)termGroupList.get(i);
1090 String termDisplayName = (String) map.get(AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
1091 displayNameList.add(i - 1, termDisplayName);
1094 result = getPartialTermDisplayNameMatches(displayNameList, partialTerm);
1102 protected Object getListResultValue(DocumentModel docModel, // REM - CSPACE-5133
1103 String schema, ListResultField field) throws DocumentException {
1104 Object result = null;
1106 result = NuxeoUtils.getXPathValue(docModel, schema, field.getXpath());
1109 // Special handling of list item values for authority items (only)
1110 // takes place here:
1112 // If the list result field is the termDisplayName element,
1113 // check whether a partial term matching query was made.
1114 // If it was, emit values for both the preferred (aka primary)
1115 // term and for all non-preferred terms, if any.
1117 String elName = field.getElement();
1118 if (isTermDisplayName(elName) == true) {
1119 MultivaluedMap<String, String> queryParams = this.getServiceContext().getQueryParams();
1120 String partialTerm = queryParams != null ? queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM) : null;
1121 if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
1122 String primaryTermDisplayName = (String)result;
1123 List<String> matches = getPartialTermDisplayNameMatches(docModel, schema, field, partialTerm);
1124 if (matches != null && matches.isEmpty() == false) {
1125 matches.add(0, primaryTermDisplayName); // insert the primary term's display name at the beginning of the list
1126 result = matches; // set the result to a list of matching term display names with the primary term's display name at the beginning
1135 public void extractAllParts(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
1136 MultipartServiceContext ctx = (MultipartServiceContext) getServiceContext();
1137 super.extractAllParts(wrapDoc);
1140 protected List<RelationsCommonList.RelationListItem> cloneList(List<RelationsCommonList.RelationListItem> inboundList) {
1141 List<RelationsCommonList.RelationListItem> result = newRelationsCommonList();
1142 for (RelationsCommonList.RelationListItem item : inboundList) {
1149 /* don't even THINK of re-using this method.
1150 * String example_uri = "/locationauthorities/7ec60f01-84ab-4908-9a6a/items/a5466530-713f-43b4-bc05";
1153 private String extractInAuthorityCSID(String uri) {
1154 String IN_AUTHORITY_REGEX = "/(.*?)/(.*?)/(.*)";
1155 Pattern p = Pattern.compile(IN_AUTHORITY_REGEX);
1156 Matcher m = p.matcher(uri);
1158 if (m.groupCount() < 3) {
1159 logger.warn("REGEX-WRONG-GROUPCOUNT looking in " + uri);
1162 //String service = m.group(1);
1163 String inauth = m.group(2);
1164 //String theRest = m.group(3);
1166 //print("service:"+service+", inauth:"+inauth+", rest:"+rest);
1169 logger.warn("REGEX-NOT-MATCHED looking in " + uri);
1174 //ensures CSPACE-4042
1175 protected void uriPointsToSameAuthority(String thisURI, String inboundItemURI) throws Exception {
1176 String authorityCSID = extractInAuthorityCSID(thisURI);
1177 String authorityCSIDForInbound = extractInAuthorityCSID(inboundItemURI);
1178 if (Tools.isBlank(authorityCSID)
1179 || Tools.isBlank(authorityCSIDForInbound)
1180 || (!authorityCSID.equalsIgnoreCase(authorityCSIDForInbound))) {
1181 throw new Exception("Item URI " + thisURI + " must point to same authority as related item: " + inboundItemURI);
1185 public String getItemTermInfoGroupXPathBase() {
1186 return authorityItemTermGroupXPathBase;
1189 public void setItemTermInfoGroupXPathBase(String itemTermInfoGroupXPathBase) {
1190 authorityItemTermGroupXPathBase = itemTermInfoGroupXPathBase;
1193 protected String getAuthorityItemCommonSchemaName() {
1194 return authorityItemCommonSchemaName;
1198 public boolean isJDBCQuery() {
1199 boolean result = false;
1201 MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams();
1203 // Look the query params to see if we need to make a SQL query.
1205 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
1206 if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
1213 // By convention, the name of the database table that contains
1214 // repeatable term information group records is derivable from
1215 // an existing XPath base value, by removing a suffix and converting
1217 protected String getTermGroupTableName() {
1218 String termInfoGroupListName = getItemTermInfoGroupXPathBase();
1219 return termInfoGroupListName.substring(0, termInfoGroupListName.lastIndexOf(LIST_SUFFIX)).toLowerCase();
1222 protected String getInAuthorityValue() {
1223 String inAuthorityValue = getInAuthorityCsid();
1224 if (Tools.notBlank(inAuthorityValue)) {
1225 return inAuthorityValue;
1227 return AuthorityResource.PARENT_WILDCARD;
1232 public Map<String,String> getJDBCQueryParams() {
1233 // FIXME: Get all of the following values from appropriate external constants.
1234 // At present, these are duplicated in both RepositoryClientImpl
1235 // and in AuthorityItemDocumentModelHandler.
1236 final String TERM_GROUP_LIST_NAME = "TERM_GROUP_LIST_NAME";
1237 final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
1238 final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
1240 Map<String,String> params = super.getJDBCQueryParams();
1241 params.put(TERM_GROUP_LIST_NAME, getItemTermInfoGroupXPathBase());
1242 params.put(TERM_GROUP_TABLE_NAME_PARAM, getTermGroupTableName());
1243 params.put(IN_AUTHORITY_PARAM, getInAuthorityValue());