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;
73 import java.util.ArrayList;
74 import java.util.Collection;
75 import java.util.Collections;
76 import java.util.HashMap;
77 import java.util.List;
79 import java.util.regex.Matcher;
80 import java.util.regex.Pattern;
81 import java.util.regex.PatternSyntaxException;
83 //import org.collectionspace.services.common.authority.AuthorityItemRelations;
85 * AuthorityItemDocumentModelHandler
87 * $LastChangedRevision: $
90 public abstract class AuthorityItemDocumentModelHandler<AICommon>
91 extends NuxeoDocumentModelHandler<AICommon> {
93 private final Logger logger = LoggerFactory.getLogger(AuthorityItemDocumentModelHandler.class);
95 protected String authorityCommonSchemaName;
96 protected String authorityItemCommonSchemaName;
97 private String authorityItemTermGroupXPathBase;
99 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
100 private boolean shouldUpdateRevNumber = true; // by default we should update the revision number -not true on synchronization with SAS
102 * inVocabulary is the parent Authority for this context
104 protected String inAuthority = null;
105 protected boolean wildcardedAuthorityRequest = false;
106 protected String authorityRefNameBase = null;
107 // Used to determine when the displayName changes as part of the update.
108 protected String oldDisplayNameOnUpdate = null;
109 private final static String LIST_SUFFIX = "List";
110 private final static String ZERO_OR_MORE_ANY_CHAR_REGEX = ".*";
112 public AuthorityItemDocumentModelHandler(String authorityCommonSchemaName, String authorityItemCommonSchemaName) {
113 this.authorityItemCommonSchemaName = authorityItemCommonSchemaName;
116 abstract public String getParentCommonSchemaName();
119 // Getter and Setter for 'proposed'
121 public boolean getIsProposed() {
122 return this.isProposed;
125 public void setIsProposed(boolean flag) {
126 this.isProposed = flag;
130 // Getter and Setter for 'shouldUpdateRevNumber'
132 public boolean getShouldUpdateRevNumber() {
133 return this.shouldUpdateRevNumber;
136 public void setShouldUpdateRevNumber(boolean flag) {
137 this.shouldUpdateRevNumber = flag;
141 public void prepareSync() throws Exception {
142 this.setShouldUpdateRevNumber(AuthorityServiceUtils.DONT_UPDATE_REV); // Never update rev nums on sync operations
146 protected String getRefnameDisplayName(DocumentWrapper<DocumentModel> docWrapper) {
147 String result = null;
149 DocumentModel docModel = docWrapper.getWrappedObject();
150 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = this.getServiceContext();
151 RefName.AuthorityItem refname = (RefName.AuthorityItem)getRefName(ctx, docModel);
152 result = refname.getDisplayName();
158 * After calling this method successfully, the document model will contain an updated refname and short ID
160 * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#getRefName(org.collectionspace.services.common.context.ServiceContext, org.nuxeo.ecm.core.api.DocumentModel)
163 public RefName.RefNameInterface getRefName(ServiceContext ctx,
164 DocumentModel docModel) {
165 RefName.RefNameInterface refname = null;
168 String displayName = getPrimaryDisplayName(docModel, authorityItemCommonSchemaName,
169 getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
170 if (Tools.isEmpty(displayName)) {
171 throw new Exception("The displayName for this authority term was empty or not set.");
174 String shortIdentifier = (String) docModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
175 if (Tools.isEmpty(shortIdentifier)) {
176 // We didn't find a short ID in the payload request, so we need to synthesize one.
177 shortIdentifier = handleDisplayNameAsShortIdentifier(docModel); // updates the document model with the new short ID as a side-effect
180 String authorityRefBaseName = getAuthorityRefNameBase();
181 if (Tools.isEmpty(authorityRefBaseName)) {
182 throw new Exception("Could not create the refName for this authority term, because the refName for its authority parent was empty.");
185 // Create the items refname using the parent's as a base
186 RefName.Authority parentsRefName = RefName.Authority.parse(authorityRefBaseName);
187 refname = RefName.buildAuthorityItem(parentsRefName, shortIdentifier, displayName);
188 // Now update the document model with the refname value
189 String refNameStr = refname.toString();
190 docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REF_NAME, refNameStr); // REM - This field is deprecated now that the refName is part of the collection_space core schema
192 } catch (Exception e) {
193 logger.error(e.getMessage(), e);
199 public void setInAuthority(String inAuthority) {
200 this.inAuthority = inAuthority;
203 public String getInAuthorityCsid() {
204 return this.inAuthority;
207 /** Subclasses may override this to customize the URI segment. */
208 public String getAuthorityServicePath() {
209 return getServiceContext().getServiceName().toLowerCase(); // Laramie20110510 CSPACE-3932
213 public String getUri(DocumentModel docModel) {
214 // Laramie20110510 CSPACE-3932
215 String authorityServicePath = getAuthorityServicePath();
216 if(inAuthority==null) { // Only true with the first document model received, on queries to wildcarded authorities
217 wildcardedAuthorityRequest = true;
219 // If this search crosses multiple authorities, get the inAuthority value
220 // from each record, rather than using the cached value from the first record
221 if(wildcardedAuthorityRequest) {
223 inAuthority = (String) docModel.getProperty(authorityItemCommonSchemaName,
224 AuthorityItemJAXBSchema.IN_AUTHORITY);
225 } catch (ClientException pe) {
226 throw new RuntimeException("Could not get parent specifier for item!");
229 return "/" + authorityServicePath + '/' + inAuthority + '/' + AuthorityClient.ITEMS + '/' + getCsid(docModel);
232 protected String getAuthorityRefNameBase() {
233 return this.authorityRefNameBase;
236 public void setAuthorityRefNameBase(String value) {
237 this.authorityRefNameBase = value;
241 * Note: the Vocabulary service's VocabularyItemDocumentModelHandler class overrides this method.
243 protected ListResultField getListResultsDisplayNameField() {
244 ListResultField result = new ListResultField();
245 // Per CSPACE-5132, the name of this element remains 'displayName'
246 // for backwards compatibility, although its value is obtained
247 // from the termDisplayName field.
249 // Update: this name is now being changed to 'termDisplayName', both
250 // because this is the actual field name and because the app layer
251 // work to convert over to this field is underway. Per Patrick, the
252 // app layer treats lists, in at least some context(s), as sparse record
253 // payloads, and thus fields in list results must all be present in
254 // (i.e. represent a strict subset of the fields in) record schemas.
258 // In CSPACE-5134, these list results will change substantially
259 // to return display names for both the preferred term and for
260 // each non-preferred term (if any).
261 result.setElement(AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
262 result.setXpath(NuxeoUtils.getPrimaryXPathPropertyName(
263 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_DISPLAY_NAME));
269 * Note: the Vocabulary service's VocabularyItemDocumentModelHandler class overrides this method.
271 protected ListResultField getListResultsTermStatusField() {
272 ListResultField result = new ListResultField();
274 result.setElement(AuthorityItemJAXBSchema.TERM_STATUS);
275 result.setXpath(NuxeoUtils.getPrimaryXPathPropertyName(
276 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_STATUS));
281 private boolean isTermDisplayName(String elName) {
282 return AuthorityItemJAXBSchema.TERM_DISPLAY_NAME.equals(elName) || VocabularyItemJAXBSchema.DISPLAY_NAME.equals(elName);
287 * @see org.collectionspace.services.nuxeo.client.java.DocHandlerBase#getListItemsArray()
289 * Note: We're updating the "global" service and tenant bindings instance here -the list instance here is
290 * a reference to the tenant bindings instance in the singleton ServiceMain.
293 public List<ListResultField> getListItemsArray() throws DocumentException {
294 List<ListResultField> list = super.getListItemsArray();
296 // One-time initialization for each authority item service.
297 if (isListItemArrayExtended() == false) {
298 synchronized(AuthorityItemDocumentModelHandler.class) {
299 if (isListItemArrayExtended() == false) {
300 int nFields = list.size();
301 // Ensure that each item in a list of Authority items includes
302 // a set of common fields, so we do not depend upon configuration
303 // for general logic.
304 List<Integer> termDisplayNamePositionsInList = new ArrayList<>();
305 boolean hasShortId = false;
306 boolean hasTermStatus = false;
307 for (int i = 0; i < nFields; i++) {
308 ListResultField field = list.get(i);
309 String elName = field.getElement();
310 if (isTermDisplayName(elName) == true) {
311 termDisplayNamePositionsInList.add(i);
312 } else if (AuthorityItemJAXBSchema.SHORT_IDENTIFIER.equals(elName)) {
314 } else if (AuthorityItemJAXBSchema.TERM_STATUS.equals(elName)) {
315 hasTermStatus = true;
319 ListResultField field;
321 // Certain fields in authority item list results
322 // are handled specially here
326 // Ignore (throw out) any configuration entries that
327 // specify how the termDisplayName field should be
328 // emitted in authority item lists. This field will
329 // be handled in a standardized manner (see block below).
330 if (termDisplayNamePositionsInList.isEmpty() == false) {
331 // Remove matching items starting at the end of the list
332 // and moving towards the start, so that reshuffling of
333 // list order doesn't alter the positions of earlier items
334 Collections.sort(termDisplayNamePositionsInList, Collections.reverseOrder());
335 for (int i : termDisplayNamePositionsInList) {
339 // termDisplayName values in authority item lists
340 // will be handled via code that emits display names
341 // for both the preferred term and all non-preferred
342 // terms (if any). The following is a placeholder
343 // entry that will trigger this code. See the
344 // getListResultValue() method in this class.
345 field = getListResultsDisplayNameField();
350 field = new ListResultField();
351 field.setElement(AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
352 field.setXpath(AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
357 if (!hasTermStatus) {
358 field = getListResultsTermStatusField();
364 setListItemArrayExtended(true);
365 } // end of synchronized block
372 * We consider workflow state changes as a change that should bump the revision number.
373 * Warning: This method might change the transitionDef's transtionName value
376 public void handleWorkflowTransition(DocumentWrapper<DocumentModel> wrapDoc, TransitionDef transitionDef) throws Exception {
377 // Decide whether or not to update the revision number
378 if (this.getShouldUpdateRevNumber() == true) { // We don't update the rev number of synchronization requests
379 updateRevNumbers(wrapDoc);
382 DocumentModel docModel = wrapDoc.getWrappedObject();
383 if (this.hasReferencingObjects(this.getServiceContext(), docModel) == true) {
389 * This method synchronizes/updates a single authority item resource.
390 * for the handleSync method, the wrapDoc argument contains a authority item specifier.
393 public boolean handleSync(DocumentWrapper<Object> wrapDoc) throws Exception {
394 boolean result = false;
395 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
398 // Get information about the local authority item so we can compare with corresponding item on the shared authority server
400 AuthorityItemSpecifier authorityItemSpecifier = (AuthorityItemSpecifier) wrapDoc.getWrappedObject();
401 DocumentModel itemDocModel = NuxeoUtils.getDocFromSpecifier(ctx, getRepositorySession(), getAuthorityItemCommonSchemaName(),
402 authorityItemSpecifier);
403 if (itemDocModel == null) {
404 throw new DocumentNotFoundException(String.format("Could not find authority item resource with CSID='%s'",
405 authorityItemSpecifier.getItemSpecifier().value));
407 Long localItemRev = (Long) NuxeoUtils.getProperyValue(itemDocModel, AuthorityItemJAXBSchema.REV);
408 Boolean localIsProposed = (Boolean) NuxeoUtils.getProperyValue(itemDocModel, AuthorityItemJAXBSchema.PROPOSED);
409 String localItemCsid = itemDocModel.getName();
410 String localItemWorkflowState = itemDocModel.getCurrentLifeCycleState();
411 String itemShortId = (String) NuxeoUtils.getProperyValue(itemDocModel, AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
414 // Now get the item's Authority (the parent) information
416 DocumentModel authorityDocModel = NuxeoUtils.getDocFromSpecifier(ctx, getRepositorySession(), authorityCommonSchemaName,
417 authorityItemSpecifier.getParentSpecifier());
418 String authorityShortId = (String) NuxeoUtils.getProperyValue(authorityDocModel, AuthorityJAXBSchema.SHORT_IDENTIFIER);
419 String localParentCsid = authorityDocModel.getName();
421 // Using the short IDs of the local authority and item, create URN specifiers to retrieve the SAS authority item
423 AuthorityItemSpecifier sasAuthorityItemSpecifier = new AuthorityItemSpecifier(SpecifierForm.URN_NAME, authorityShortId, itemShortId);
424 // Get the shared authority server's copy
425 PoxPayloadIn sasPayloadIn = AuthorityServiceUtils.requestPayloadIn(sasAuthorityItemSpecifier,
426 getAuthorityServicePath(), getEntityResponseType());
427 Long sasRev = getRevision(sasPayloadIn);
428 String sasWorkflowState = getWorkflowState(sasPayloadIn);
430 // If the shared authority item is newer, update our local copy
432 if (sasRev > localItemRev || localIsProposed) {
433 AuthorityResource authorityResource = (AuthorityResource) ctx.getResource(getAuthorityServicePath());
434 PoxPayloadOut payloadOut = authorityResource.updateAuthorityItem(ctx,
435 ctx.getResourceMap(),
437 localParentCsid, // parent's CSID
438 localItemCsid, // item's CSID
439 sasPayloadIn, // the payload from the remote SAS
440 AuthorityServiceUtils.DONT_UPDATE_REV, // don't update the parent's revision number
441 AuthorityServiceUtils.NOT_PROPOSED); // The items is not proposed, make it a real SAS item now
442 if (payloadOut != null) {
443 ctx.setOutput(payloadOut);
448 // If the workflow states are different, we need to update the local's to reflects the remote's
450 if (localItemWorkflowState.equalsIgnoreCase(sasWorkflowState) == false) {
451 AuthorityResource authorityResource = (AuthorityResource) ctx.getResource(getAuthorityServicePath()); // Get the authority (parent) client not the item client
453 // We need to move the local item to the SAS workflow state. This might involve multiple transitions.
455 List<String> transitionList = getTransitionList(sasWorkflowState, localItemWorkflowState);
456 for (String transition:transitionList) {
457 if (transition.equalsIgnoreCase(WorkflowClient.WORKFLOWTRANSITION_DELETE) == true) {
458 if (hasReferencingObjects(ctx, itemDocModel)) {
459 throw new DocumentReferenceException(String.format("Cannot soft-delete authority item '%s' because it still has records in the system that are referencing it. See the service layer log file for details.",
460 itemDocModel.getName()));
463 authorityResource.updateItemWorkflowWithTransition(ctx, localParentCsid, localItemCsid, transition, AuthorityServiceUtils.DONT_UPDATE_REV);
472 * We need to move the local item to the SAS workflow state. This might involve multiple transitions.
474 private List<String> getTransitionList(String sasWorkflowState, String localItemWorkflowState) {
475 List<String> result = new ArrayList<String>();
478 // If the SAS authority items is soft-deleted, we need to mark the local item as soft-deleted
480 if (sasWorkflowState.contains(WorkflowClient.WORKFLOWSTATE_DELETED)) {
481 result.add(WorkflowClient.WORKFLOWTRANSITION_DELETE);
482 } else if (sasWorkflowState.equalsIgnoreCase(WorkflowClient.WORKFLOWSTATE_PROJECT)) {
483 result.add(WorkflowClient.WORKFLOWTRANSITION_UNDELETE);
487 // Ensure the local item is always in a "locked" state. Items sync'd with a SAS should always be locked
489 if (localItemWorkflowState.contains(WorkflowClient.WORKFLOWSTATE_LOCKED) != true) { // REM - This may be a bad assumption to make.
490 result.add(WorkflowClient.WORKFLOWTRANSITION_LOCK);
497 * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#handleCreate(org.collectionspace.services.common.document.DocumentWrapper)
500 public void handleCreate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
501 // first fill all the parts of the document, refname and short ID get set as well
502 super.handleCreate(wrapDoc);
503 // Ensure we have required fields set properly
504 handleInAuthority(wrapDoc.getWrappedObject());
508 * This method gets called after the primary update to an authority item has happened. If the authority item's refName
509 * has changed, then we need to updated all the records that use that refname with the new/updated version
514 public void handleDelete(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
515 ServiceContext ctx = getServiceContext();
516 DocumentModel docModel = wrapDoc.getWrappedObject();
518 if (hasReferencingObjects(ctx, docModel) == true) {
519 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.",
520 docModel.getName()));
525 * Checks to see if an authority item has referencing objects.
532 private boolean hasReferencingObjects(ServiceContext ctx, DocumentModel docModel) throws Exception {
533 boolean result = false;
535 String inAuthorityCsid = (String) docModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.IN_AUTHORITY);
536 AuthorityResource authorityResource = (AuthorityResource)ctx.getResource(getAuthorityServicePath());
537 String itemCsid = docModel.getName();
538 UriTemplateRegistry uriTemplateRegistry = ServiceMain.getInstance().getUriTemplateRegistry();
539 AuthorityRefDocList refObjs = authorityResource.getReferencingObjects(ctx, inAuthorityCsid, itemCsid,
540 uriTemplateRegistry, ctx.getUriInfo());
542 if (refObjs.getTotalItems() > 0) {
544 logger.error(String.format("Cannot delete authority item '%s' because it still has %d records in the system that are referencing it.",
545 itemCsid, refObjs.getTotalItems()));
546 logReferencingObjects(docModel, refObjs);
552 private void logReferencingObjects(DocumentModel docModel, AuthorityRefDocList refObjs) {
553 List<AuthorityRefDocList.AuthorityRefDocItem> items = refObjs.getAuthorityRefDocItem();
555 for (AuthorityRefDocList.AuthorityRefDocItem item : items) {
556 logger.debug(docModel.getName() + ": list-item[" + i + "] "
557 + item.getDocType() + "("
558 + item.getDocId() + ") Name:["
559 + item.getDocName() + "] Number:["
560 + item.getDocNumber() + "] in field:["
561 + item.getSourceField() + "]");
566 * This method gets called after the primary update to an authority item has happened. If the authority item's refName
567 * has changed, then we need to updated all the records that use that refname with the new/updated version
570 * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#completeUpdate(org.collectionspace.services.common.document.DocumentWrapper)
572 public void completeUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
573 // Must call our super class' version first
574 super.completeUpdate(wrapDoc);
577 // Look for and update authority references with the updated refName
579 if (hasRefNameUpdate() == true) {
580 // We have work to do.
581 if (logger.isDebugEnabled()) {
582 final String EOL = System.getProperty("line.separator");
583 logger.debug("Need to find and update references to authority item." + EOL
584 + " Old refName" + oldRefNameOnUpdate + EOL
585 + " New refName" + newRefNameOnUpdate);
587 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
588 RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient = getRepositoryClient(ctx);
589 CoreSessionInterface repoSession = this.getRepositorySession();
591 // Update all the existing records that have a field with the old refName in it
592 int nUpdated = RefNameServiceUtils.updateAuthorityRefDocs(ctx, repoClient, repoSession,
593 oldRefNameOnUpdate, newRefNameOnUpdate, getRefPropName());
595 // Finished so log a message.
596 if (logger.isDebugEnabled()) {
597 logger.debug("Updated " + nUpdated + " instances of oldRefName to newRefName");
603 * Note that the Vocabulary service's document-model for items overrides this method.
605 protected String getPrimaryDisplayName(DocumentModel docModel, String schema,
606 String complexPropertyName, String fieldName) {
607 String result = null;
609 result = getStringValueInPrimaryRepeatingComplexProperty(docModel, schema, complexPropertyName, fieldName);
615 * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#handleUpdate(org.collectionspace.services.common.document.DocumentWrapper)
618 // 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.
620 public void handleUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
621 // Must call our super's version first, this updates the core schema and the relationship records to deal with possible refName changes/update
622 super.handleUpdate(wrapDoc);
623 if (this.hasRefNameUpdate() == true) {
624 DocumentModel docModel = wrapDoc.getWrappedObject();
625 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
630 // Handles both update calls (PUTS) AND create calls (POSTS)
632 public void fillAllParts(DocumentWrapper<DocumentModel> wrapDoc, Action action) throws Exception {
633 super.fillAllParts(wrapDoc, action);
635 // Update the record's revision number on both CREATE and UPDATE actions
637 if (this.getShouldUpdateRevNumber() == true) { // We won't update rev numbers on synchronization with SAS
638 updateRevNumbers(wrapDoc);
641 // If this is a proposed item (not part of the SAS), mark it as such
643 DocumentModel documentModel = wrapDoc.getWrappedObject();
644 documentModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.PROPOSED,
645 new Boolean(this.getIsProposed()));
649 * Update the revision number of both the item and the item's parent.
653 protected void updateRevNumbers(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
654 DocumentModel documentModel = wrapDoc.getWrappedObject();
655 Long rev = (Long)documentModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REV);
661 documentModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REV, rev);
663 // Next, update the inAuthority (the parent's) rev number
665 String inAuthorityCsid = this.getInAuthorityCsid();
666 if (inAuthorityCsid == null) {
667 // When inAuthorityCsid is null, it usually means we're performing and update or synch with the SAS
668 inAuthorityCsid = (String)documentModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.IN_AUTHORITY);
670 DocumentModel inAuthorityDocModel = NuxeoUtils.getDocFromCsid(getServiceContext(), getRepositorySession(), inAuthorityCsid);
671 Long parentRev = (Long)inAuthorityDocModel.getProperty(getParentCommonSchemaName(), AuthorityJAXBSchema.REV);
672 if (parentRev == null) {
673 parentRev = new Long(0);
676 inAuthorityDocModel.setProperty(getParentCommonSchemaName(), AuthorityJAXBSchema.REV, parentRev);
677 getRepositorySession().saveDocument(inAuthorityDocModel);
681 * If no short identifier was provided in the input payload, generate a
682 * short identifier from the preferred term display name or term name.
684 private String handleDisplayNameAsShortIdentifier(DocumentModel docModel) throws Exception {
685 String result = (String) docModel.getProperty(authorityItemCommonSchemaName,
686 AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
688 if (Tools.isEmpty(result)) {
689 String termDisplayName = getPrimaryDisplayName(
690 docModel, authorityItemCommonSchemaName,
691 getItemTermInfoGroupXPathBase(),
692 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
694 String termName = getPrimaryDisplayName(
695 docModel, authorityItemCommonSchemaName,
696 getItemTermInfoGroupXPathBase(),
697 AuthorityItemJAXBSchema.TERM_NAME);
699 String generatedShortIdentifier = AuthorityIdentifierUtils.generateShortIdentifierFromDisplayName(termDisplayName,
701 docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER,
702 generatedShortIdentifier);
703 result = generatedShortIdentifier;
710 * Generate a refName for the authority item from the short identifier
713 * All refNames for authority items are generated. If a client supplies
714 * a refName, it will be overwritten during create (per this method)
715 * or discarded during update (per filterReadOnlyPropertiesForPart).
717 * @see #filterReadOnlyPropertiesForPart(Map<String, Object>, org.collectionspace.services.common.service.ObjectPartType)
720 protected String updateRefnameForAuthorityItem(DocumentModel docModel,
721 String schemaName) throws Exception {
722 String result = null;
724 RefName.RefNameInterface refname = getRefName(getServiceContext(), docModel);
725 String refNameStr = refname.toString();
726 docModel.setProperty(schemaName, AuthorityItemJAXBSchema.REF_NAME, refNameStr);
733 * Check the logic around the parent pointer. Note that we only need do this on
734 * create, since we have logic to make this read-only on update.
738 * @throws Exception the exception
740 private void handleInAuthority(DocumentModel docModel) throws Exception {
741 if(inAuthority==null) { // Only happens on queries to wildcarded authorities
742 throw new IllegalStateException("Trying to Create an object with no inAuthority value!");
744 docModel.setProperty(authorityItemCommonSchemaName,
745 AuthorityItemJAXBSchema.IN_AUTHORITY, inAuthority);
749 * Returns a list of records that reference this authority item
752 * @param uriTemplateRegistry
753 * @param serviceTypes
754 * @param propertyName
759 public AuthorityRefDocList getReferencingObjects(
760 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
761 UriTemplateRegistry uriTemplateRegistry,
762 List<String> serviceTypes,
764 String itemcsid) throws Exception {
765 AuthorityRefDocList authRefDocList = null;
766 CoreSessionInterface repoSession = null;
767 boolean releaseRepoSession = false;
770 RepositoryClientImpl repoClient = (RepositoryClientImpl)this.getRepositoryClient(ctx);
771 repoSession = this.getRepositorySession();
772 if (repoSession == null) {
773 repoSession = repoClient.getRepositorySession(ctx);
774 releaseRepoSession = true;
776 DocumentFilter myFilter = getDocumentFilter();
779 DocumentWrapper<DocumentModel> wrapper = repoClient.getDoc(repoSession, ctx, itemcsid);
780 DocumentModel docModel = wrapper.getWrappedObject();
781 String refName = (String) NuxeoUtils.getProperyValue(docModel, AuthorityItemJAXBSchema.REF_NAME); //docModel.getPropertyValue(AuthorityItemJAXBSchema.REF_NAME);
782 authRefDocList = RefNameServiceUtils.getAuthorityRefDocs(
783 repoSession, ctx, uriTemplateRegistry, repoClient,
787 myFilter, true /*computeTotal*/);
788 } catch (PropertyException pe) {
790 } catch (DocumentException de) {
792 } catch (Exception e) {
793 if (logger.isDebugEnabled()) {
794 logger.debug("Caught exception ", e);
796 throw new DocumentException(e);
798 // If we got/aquired a new seesion then we're responsible for releasing it.
799 if (releaseRepoSession && repoSession != null) {
800 repoClient.releaseRepositorySession(ctx, repoSession);
803 } catch (Exception e) {
804 if (logger.isDebugEnabled()) {
805 logger.debug("Caught exception ", e);
807 throw new DocumentException(e);
810 return authRefDocList;
814 * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#extractPart(org.nuxeo.ecm.core.api.DocumentModel, java.lang.String, org.collectionspace.services.common.service.ObjectPartType)
817 protected Map<String, Object> extractPart(DocumentModel docModel, String schema, ObjectPartType partMeta)
819 Map<String, Object> unQObjectProperties = super.extractPart(docModel, schema, partMeta);
821 // Add the CSID to the common part, since they may have fetched via the shortId.
822 if (partMeta.getLabel().equalsIgnoreCase(authorityItemCommonSchemaName)) {
823 String csid = getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
824 unQObjectProperties.put("csid", csid);
827 return unQObjectProperties;
831 * Filters out selected values supplied in an update request.
833 * For example, filters out AuthorityItemJAXBSchema.IN_AUTHORITY, to ensure
834 * that the link to the item's parent remains untouched.
836 * @param objectProps the properties filtered out from the update payload
837 * @param partMeta metadata for the object to fill
840 public void filterReadOnlyPropertiesForPart(
841 Map<String, Object> objectProps, ObjectPartType partMeta) {
842 super.filterReadOnlyPropertiesForPart(objectProps, partMeta);
843 String commonPartLabel = getServiceContext().getCommonPartLabel();
844 if (partMeta.getLabel().equalsIgnoreCase(commonPartLabel)) {
845 objectProps.remove(AuthorityItemJAXBSchema.IN_AUTHORITY);
846 objectProps.remove(AuthorityItemJAXBSchema.CSID);
847 objectProps.remove(AuthorityJAXBSchema.SHORT_IDENTIFIER);
848 objectProps.remove(AuthorityItemJAXBSchema.REF_NAME);
853 * Returns the items in a list of term display names whose names contain
854 * a partial term (as might be submitted in a search query, for instance).
855 * @param termDisplayNameList a list of term display names.
856 * @param partialTerm a partial term display name; that is, a portion
857 * of a display name that might be expected to match 0-n terms in the list.
858 * @return a list of term display names that matches the partial term.
859 * Matches are case-insensitive. As well, before matching is performed, any
860 * special-purpose characters that may appear in the partial term (such as
861 * wildcards and anchor characters) are filtered out from both compared terms.
863 protected List<String> getPartialTermDisplayNameMatches(List<String> termDisplayNameList, String partialTerm) {
864 List<String> result = new ArrayList<>();
865 String partialTermMatchExpression = filterAnchorAndWildcardChars(partialTerm).toLowerCase();
867 for (String termDisplayName : termDisplayNameList) {
868 if (termDisplayName.toLowerCase()
869 .matches(partialTermMatchExpression) == true) {
870 result.add(termDisplayName);
873 } catch (PatternSyntaxException pse) {
874 logger.warn("Error in regex match pattern '%s' for term display names: %s",
875 partialTermMatchExpression, pse.getMessage());
881 * Filters user-supplied anchor and wildcard characters in a string,
882 * replacing them with equivalent regular expressions.
883 * @param term a term in which to filter anchor and wildcard characters.
884 * @return the term with those characters filtered.
886 protected String filterAnchorAndWildcardChars(String term) {
887 if (Tools.isBlank(term)) {
890 if (term.length() < 3) {
893 if (logger.isTraceEnabled()) {
894 logger.trace(String.format("Term = %s", term));
896 Boolean anchorAtStart = false;
897 Boolean anchorAtEnd = false;
899 StringBuilder filteredTermBuilder = new StringBuilder(term);
900 // Term contains no anchor or wildcard characters.
901 if ( (! term.contains(RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR))
902 && (! term.contains(RepositoryClientImpl.USER_SUPPLIED_WILDCARD)) ) {
905 // Term contains at least one such character.
907 // Filter the starting anchor or wildcard character, if any.
908 String firstChar = filteredTermBuilder.substring(0,1);
910 case RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR:
911 anchorAtStart = true;
913 case RepositoryClientImpl.USER_SUPPLIED_WILDCARD:
914 filteredTermBuilder.deleteCharAt(0);
917 if (logger.isTraceEnabled()) {
918 logger.trace(String.format("After first char filtering = %s", filteredTermBuilder.toString()));
920 // Filter the ending anchor or wildcard character, if any.
921 int lastPos = filteredTermBuilder.length() - 1;
922 String lastChar = filteredTermBuilder.substring(lastPos);
924 case RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR:
925 filteredTermBuilder.deleteCharAt(lastPos);
926 filteredTermBuilder.insert(filteredTermBuilder.length(), RepositoryClientImpl.ENDING_ANCHOR_CHAR);
929 case RepositoryClientImpl.USER_SUPPLIED_WILDCARD:
930 filteredTermBuilder.deleteCharAt(lastPos);
933 if (logger.isTraceEnabled()) {
934 logger.trace(String.format("After last char filtering = %s", filteredTermBuilder.toString()));
936 filteredTerm = filteredTermBuilder.toString();
937 // Filter all other wildcards, if any.
938 filteredTerm = filteredTerm.replaceAll(RepositoryClientImpl.USER_SUPPLIED_WILDCARD_REGEX, ZERO_OR_MORE_ANY_CHAR_REGEX);
939 if (logger.isTraceEnabled()) {
940 logger.trace(String.format("After replacing user wildcards = %s", filteredTerm));
942 } catch (Exception e) {
943 logger.warn(String.format("Error filtering anchor and wildcard characters from string: %s", e.getMessage()));
947 // Wrap the term in beginning and ending regex wildcards, unless a
948 // starting or ending anchor character was present.
949 return (anchorAtStart ? "" : ZERO_OR_MORE_ANY_CHAR_REGEX)
951 + (anchorAtEnd ? "" : ZERO_OR_MORE_ANY_CHAR_REGEX);
954 @SuppressWarnings("unchecked")
955 private List<String> getPartialTermDisplayNameMatches(DocumentModel docModel, // REM - CSPACE-5133
956 String schema, ListResultField field, String partialTerm) {
957 List<String> result = null;
959 String xpath = field.getXpath(); // results in something like "persons_common:personTermGroupList/[0]/termDisplayName"
960 int endOfTermGroup = xpath.lastIndexOf("/[0]/");
961 String propertyName = endOfTermGroup != -1 ? xpath.substring(0, endOfTermGroup) : xpath; // it may not be multivalued so the xpath passed in would be the property name
965 value = docModel.getProperty(schema, propertyName);
966 } catch (Exception e) {
967 logger.error("Could not extract term display name with property = "
971 if (value != null && value instanceof ArrayList) {
972 ArrayList<HashMap<String, Object>> termGroupList = (ArrayList<HashMap<String, Object>>)value;
973 int arrayListSize = termGroupList.size();
974 if (arrayListSize > 1) { // if there's only 1 element in the list then we've already matched the primary term's display name
975 List<String> displayNameList = new ArrayList<String>();
976 for (int i = 1; i < arrayListSize; i++) { // start at 1, skip the primary term's displayName since we will always return it
977 HashMap<String, Object> map = (HashMap<String, Object>)termGroupList.get(i);
978 String termDisplayName = (String) map.get(AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
979 displayNameList.add(i - 1, termDisplayName);
982 result = getPartialTermDisplayNameMatches(displayNameList, partialTerm);
990 protected Object getListResultValue(DocumentModel docModel, // REM - CSPACE-5133
991 String schema, ListResultField field) throws DocumentException {
992 Object result = null;
994 result = NuxeoUtils.getXPathValue(docModel, schema, field.getXpath());
997 // Special handling of list item values for authority items (only)
1000 // If the list result field is the termDisplayName element,
1001 // check whether a partial term matching query was made.
1002 // If it was, emit values for both the preferred (aka primary)
1003 // term and for all non-preferred terms, if any.
1005 String elName = field.getElement();
1006 if (isTermDisplayName(elName) == true) {
1007 MultivaluedMap<String, String> queryParams = this.getServiceContext().getQueryParams();
1008 String partialTerm = queryParams != null ? queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM) : null;
1009 if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
1010 String primaryTermDisplayName = (String)result;
1011 List<String> matches = getPartialTermDisplayNameMatches(docModel, schema, field, partialTerm);
1012 if (matches != null && matches.isEmpty() == false) {
1013 matches.add(0, primaryTermDisplayName); // insert the primary term's display name at the beginning of the list
1014 result = matches; // set the result to a list of matching term display names with the primary term's display name at the beginning
1023 public void extractAllParts(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
1024 MultipartServiceContext ctx = (MultipartServiceContext) getServiceContext();
1025 super.extractAllParts(wrapDoc);
1028 protected List<RelationsCommonList.RelationListItem> cloneList(List<RelationsCommonList.RelationListItem> inboundList) {
1029 List<RelationsCommonList.RelationListItem> result = newRelationsCommonList();
1030 for (RelationsCommonList.RelationListItem item : inboundList) {
1037 /* don't even THINK of re-using this method.
1038 * String example_uri = "/locationauthorities/7ec60f01-84ab-4908-9a6a/items/a5466530-713f-43b4-bc05";
1041 private String extractInAuthorityCSID(String uri) {
1042 String IN_AUTHORITY_REGEX = "/(.*?)/(.*?)/(.*)";
1043 Pattern p = Pattern.compile(IN_AUTHORITY_REGEX);
1044 Matcher m = p.matcher(uri);
1046 if (m.groupCount() < 3) {
1047 logger.warn("REGEX-WRONG-GROUPCOUNT looking in " + uri);
1050 //String service = m.group(1);
1051 String inauth = m.group(2);
1052 //String theRest = m.group(3);
1054 //print("service:"+service+", inauth:"+inauth+", rest:"+rest);
1057 logger.warn("REGEX-NOT-MATCHED looking in " + uri);
1062 //ensures CSPACE-4042
1063 protected void uriPointsToSameAuthority(String thisURI, String inboundItemURI) throws Exception {
1064 String authorityCSID = extractInAuthorityCSID(thisURI);
1065 String authorityCSIDForInbound = extractInAuthorityCSID(inboundItemURI);
1066 if (Tools.isBlank(authorityCSID)
1067 || Tools.isBlank(authorityCSIDForInbound)
1068 || (!authorityCSID.equalsIgnoreCase(authorityCSIDForInbound))) {
1069 throw new Exception("Item URI " + thisURI + " must point to same authority as related item: " + inboundItemURI);
1073 public String getItemTermInfoGroupXPathBase() {
1074 return authorityItemTermGroupXPathBase;
1077 public void setItemTermInfoGroupXPathBase(String itemTermInfoGroupXPathBase) {
1078 authorityItemTermGroupXPathBase = itemTermInfoGroupXPathBase;
1081 protected String getAuthorityItemCommonSchemaName() {
1082 return authorityItemCommonSchemaName;
1086 public boolean isJDBCQuery() {
1087 boolean result = false;
1089 MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams();
1091 // Look the query params to see if we need to make a SQL query.
1093 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
1094 if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
1101 // By convention, the name of the database table that contains
1102 // repeatable term information group records is derivable from
1103 // an existing XPath base value, by removing a suffix and converting
1105 protected String getTermGroupTableName() {
1106 String termInfoGroupListName = getItemTermInfoGroupXPathBase();
1107 return termInfoGroupListName.substring(0, termInfoGroupListName.lastIndexOf(LIST_SUFFIX)).toLowerCase();
1110 protected String getInAuthorityValue() {
1111 String inAuthorityValue = getInAuthorityCsid();
1112 if (Tools.notBlank(inAuthorityValue)) {
1113 return inAuthorityValue;
1115 return AuthorityResource.PARENT_WILDCARD;
1120 public Map<String,String> getJDBCQueryParams() {
1121 // FIXME: Get all of the following values from appropriate external constants.
1122 // At present, these are duplicated in both RepositoryClientImpl
1123 // and in AuthorityItemDocumentModelHandler.
1124 final String TERM_GROUP_LIST_NAME = "TERM_GROUP_LIST_NAME";
1125 final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
1126 final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
1128 Map<String,String> params = super.getJDBCQueryParams();
1129 params.put(TERM_GROUP_LIST_NAME, getItemTermInfoGroupXPathBase());
1130 params.put(TERM_GROUP_TABLE_NAME_PARAM, getTermGroupTableName());
1131 params.put(IN_AUTHORITY_PARAM, getInAuthorityValue());