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.common.ResourceMap;
31 import org.collectionspace.services.common.UriTemplateRegistry;
32 import org.collectionspace.services.common.api.RefName;
33 import org.collectionspace.services.common.api.RefNameUtils;
34 import org.collectionspace.services.common.api.RefNameUtils.AuthorityTermInfo;
35 import org.collectionspace.services.common.api.Tools;
36 import org.collectionspace.services.common.api.RefNameUtils.AuthorityInfo;
37 import org.collectionspace.services.common.authorityref.AuthorityRefDocList;
38 import org.collectionspace.services.common.context.MultipartServiceContext;
39 import org.collectionspace.services.common.context.MultipartServiceContextImpl;
40 import org.collectionspace.services.common.context.ServiceContext;
41 import org.collectionspace.services.common.document.DocumentException;
42 import org.collectionspace.services.common.document.DocumentFilter;
43 import org.collectionspace.services.common.document.DocumentNotFoundException;
44 import org.collectionspace.services.common.document.DocumentWrapper;
45 import org.collectionspace.services.common.document.DocumentHandler.Action;
46 import org.collectionspace.services.common.repository.RepositoryClient;
47 import org.collectionspace.services.common.vocabulary.AuthorityJAXBSchema;
48 import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema;
49 import org.collectionspace.services.common.vocabulary.AuthorityResource;
50 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils;
51 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.AuthorityItemSpecifier;
52 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.Specifier;
53 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.SpecifierForm;
54 import org.collectionspace.services.config.service.ListResultField;
55 import org.collectionspace.services.config.service.ObjectPartType;
56 import org.collectionspace.services.nuxeo.client.java.NuxeoDocumentModelHandler;
57 import org.collectionspace.services.nuxeo.client.java.CoreSessionInterface;
58 import org.collectionspace.services.nuxeo.client.java.RepositoryClientImpl;
59 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
60 import org.collectionspace.services.relation.RelationsCommonList;
61 import org.collectionspace.services.vocabulary.VocabularyItemJAXBSchema;
62 import org.nuxeo.ecm.core.api.ClientException;
63 import org.nuxeo.ecm.core.api.DocumentModel;
64 import org.nuxeo.ecm.core.api.model.PropertyException;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
68 import javax.ws.rs.core.MultivaluedMap;
69 import javax.ws.rs.core.Response;
71 import java.util.ArrayList;
72 import java.util.Collections;
73 import java.util.HashMap;
74 import java.util.List;
76 import java.util.regex.Matcher;
77 import java.util.regex.Pattern;
78 import java.util.regex.PatternSyntaxException;
80 //import org.collectionspace.services.common.authority.AuthorityItemRelations;
82 * AuthorityItemDocumentModelHandler
84 * $LastChangedRevision: $
87 public abstract class AuthorityItemDocumentModelHandler<AICommon>
88 extends NuxeoDocumentModelHandler<AICommon> {
90 private final Logger logger = LoggerFactory.getLogger(AuthorityItemDocumentModelHandler.class);
92 protected String authorityCommonSchemaName;
93 protected String authorityItemCommonSchemaName;
94 private String authorityItemTermGroupXPathBase;
95 private boolean shouldUpdateRevNumber = true;
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();
113 public boolean getShouldUpdateRevNumber() {
114 return this.shouldUpdateRevNumber;
117 public void setShouldUpdateRevNumber(boolean flag) {
118 this.shouldUpdateRevNumber = flag;
122 protected String getRefnameDisplayName(DocumentWrapper<DocumentModel> docWrapper) {
123 String result = null;
125 DocumentModel docModel = docWrapper.getWrappedObject();
126 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = this.getServiceContext();
127 RefName.AuthorityItem refname = (RefName.AuthorityItem)getRefName(ctx, docModel);
128 result = refname.getDisplayName();
134 * After calling this method successfully, the document model will contain an updated refname and short ID
136 * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#getRefName(org.collectionspace.services.common.context.ServiceContext, org.nuxeo.ecm.core.api.DocumentModel)
139 public RefName.RefNameInterface getRefName(ServiceContext ctx,
140 DocumentModel docModel) {
141 RefName.RefNameInterface refname = null;
144 String displayName = getPrimaryDisplayName(docModel, authorityItemCommonSchemaName,
145 getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
146 if (Tools.isEmpty(displayName)) {
147 throw new Exception("The displayName for this authority term was empty or not set.");
150 String shortIdentifier = (String) docModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
151 if (Tools.isEmpty(shortIdentifier)) {
152 // We didn't find a short ID in the payload request, so we need to synthesize one.
153 shortIdentifier = handleDisplayNameAsShortIdentifier(docModel); // updates the document model with the new short ID as a side-effect
156 String authorityRefBaseName = getAuthorityRefNameBase();
157 if (Tools.isEmpty(authorityRefBaseName)) {
158 throw new Exception("Could not create the refName for this authority term, because the refName for its authority parent was empty.");
161 // Create the items refname using the parent's as a base
162 RefName.Authority parentsRefName = RefName.Authority.parse(authorityRefBaseName);
163 refname = RefName.buildAuthorityItem(parentsRefName, shortIdentifier, displayName);
164 // Now update the document model with the refname value
165 String refNameStr = refname.toString();
166 docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REF_NAME, refNameStr); // REM - This field is deprecated now that the refName is part of the collection_space core schema
168 } catch (Exception e) {
169 logger.error(e.getMessage(), e);
175 public void setInAuthority(String inAuthority) {
176 this.inAuthority = inAuthority;
179 public String getInAuthority() {
180 return this.inAuthority;
183 /** Subclasses may override this to customize the URI segment. */
184 public String getAuthorityServicePath() {
185 return getServiceContext().getServiceName().toLowerCase(); // Laramie20110510 CSPACE-3932
189 public String getUri(DocumentModel docModel) {
190 // Laramie20110510 CSPACE-3932
191 String authorityServicePath = getAuthorityServicePath();
192 if(inAuthority==null) { // Only true with the first document model received, on queries to wildcarded authorities
193 wildcardedAuthorityRequest = true;
195 // If this search crosses multiple authorities, get the inAuthority value
196 // from each record, rather than using the cached value from the first record
197 if(wildcardedAuthorityRequest) {
199 inAuthority = (String) docModel.getProperty(authorityItemCommonSchemaName,
200 AuthorityItemJAXBSchema.IN_AUTHORITY);
201 } catch (ClientException pe) {
202 throw new RuntimeException("Could not get parent specifier for item!");
205 return "/" + authorityServicePath + '/' + inAuthority + '/' + AuthorityClient.ITEMS + '/' + getCsid(docModel);
208 protected String getAuthorityRefNameBase() {
209 return this.authorityRefNameBase;
212 public void setAuthorityRefNameBase(String value) {
213 this.authorityRefNameBase = value;
217 * Note: the Vocabulary service's VocabularyItemDocumentModelHandler class overrides this method.
219 protected ListResultField getListResultsDisplayNameField() {
220 ListResultField result = new ListResultField();
221 // Per CSPACE-5132, the name of this element remains 'displayName'
222 // for backwards compatibility, although its value is obtained
223 // from the termDisplayName field.
225 // Update: this name is now being changed to 'termDisplayName', both
226 // because this is the actual field name and because the app layer
227 // work to convert over to this field is underway. Per Patrick, the
228 // app layer treats lists, in at least some context(s), as sparse record
229 // payloads, and thus fields in list results must all be present in
230 // (i.e. represent a strict subset of the fields in) record schemas.
234 // In CSPACE-5134, these list results will change substantially
235 // to return display names for both the preferred term and for
236 // each non-preferred term (if any).
237 result.setElement(AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
238 result.setXpath(NuxeoUtils.getPrimaryXPathPropertyName(
239 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_DISPLAY_NAME));
245 * Note: the Vocabulary service's VocabularyItemDocumentModelHandler class overrides this method.
247 protected ListResultField getListResultsTermStatusField() {
248 ListResultField result = new ListResultField();
250 result.setElement(AuthorityItemJAXBSchema.TERM_STATUS);
251 result.setXpath(NuxeoUtils.getPrimaryXPathPropertyName(
252 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_STATUS));
257 private boolean isTermDisplayName(String elName) {
258 return AuthorityItemJAXBSchema.TERM_DISPLAY_NAME.equals(elName) || VocabularyItemJAXBSchema.DISPLAY_NAME.equals(elName);
263 * @see org.collectionspace.services.nuxeo.client.java.DocHandlerBase#getListItemsArray()
265 * Note: We're updating the "global" service and tenant bindings instance here -the list instance here is
266 * a reference to the tenant bindings instance in the singleton ServiceMain.
269 public List<ListResultField> getListItemsArray() throws DocumentException {
270 List<ListResultField> list = super.getListItemsArray();
272 // One-time initialization for each authority item service.
273 if (isListItemArrayExtended() == false) {
274 synchronized(AuthorityItemDocumentModelHandler.class) {
275 if (isListItemArrayExtended() == false) {
276 int nFields = list.size();
277 // Ensure that each item in a list of Authority items includes
278 // a set of common fields, so we do not depend upon configuration
279 // for general logic.
280 List<Integer> termDisplayNamePositionsInList = new ArrayList<>();
281 boolean hasShortId = false;
282 boolean hasTermStatus = false;
283 for (int i = 0; i < nFields; i++) {
284 ListResultField field = list.get(i);
285 String elName = field.getElement();
286 if (isTermDisplayName(elName) == true) {
287 termDisplayNamePositionsInList.add(i);
288 } else if (AuthorityItemJAXBSchema.SHORT_IDENTIFIER.equals(elName)) {
290 } else if (AuthorityItemJAXBSchema.TERM_STATUS.equals(elName)) {
291 hasTermStatus = true;
295 ListResultField field;
297 // Certain fields in authority item list results
298 // are handled specially here
302 // Ignore (throw out) any configuration entries that
303 // specify how the termDisplayName field should be
304 // emitted in authority item lists. This field will
305 // be handled in a standardized manner (see block below).
306 if (termDisplayNamePositionsInList.isEmpty() == false) {
307 // Remove matching items starting at the end of the list
308 // and moving towards the start, so that reshuffling of
309 // list order doesn't alter the positions of earlier items
310 Collections.sort(termDisplayNamePositionsInList, Collections.reverseOrder());
311 for (int i : termDisplayNamePositionsInList) {
315 // termDisplayName values in authority item lists
316 // will be handled via code that emits display names
317 // for both the preferred term and all non-preferred
318 // terms (if any). The following is a placeholder
319 // entry that will trigger this code. See the
320 // getListResultValue() method in this class.
321 field = getListResultsDisplayNameField();
326 field = new ListResultField();
327 field.setElement(AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
328 field.setXpath(AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
333 if (!hasTermStatus) {
334 field = getListResultsTermStatusField();
340 setListItemArrayExtended(true);
341 } // end of synchronized block
347 // private PoxPayloadIn getPayloadIn(AuthorityItemSpecifier specifier) throws Exception {
348 // PoxPayloadIn result = null;
350 // ServiceContext parentCtx = new MultipartServiceContextImpl(this.getAuthorityServicePath());
351 // AuthorityClient client = (AuthorityClient) parentCtx.getClient();
352 // Response res = client.readItem(specifier.getParentSpecifier().value, specifier.getItemSpecifier().value);
354 // int statusCode = res.getStatus();
356 // // Check the status code of the response: does it match
357 // // the expected response(s)?
358 // if (logger.isDebugEnabled()) {
359 // logger.debug(client.getClass().getCanonicalName() + ": status = " + statusCode);
362 // result = new PoxPayloadIn((String)res.readEntity(getEntityResponseType())); // Get the entire response!
371 public boolean handleSync(DocumentWrapper<Object> wrapDoc) throws Exception {
372 boolean result = false;
373 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
374 AuthorityItemSpecifier authorityItemSpecifier = (AuthorityItemSpecifier) wrapDoc.getWrappedObject();
376 // Get the rev number of the authority item so we can compare with rev number of shared authority
378 DocumentModel itemDocModel = NuxeoUtils.getDocFromSpecifier(ctx, getRepositorySession(), getAuthorityItemCommonSchemaName(),
379 authorityItemSpecifier);
380 if (itemDocModel == null) {
381 throw new DocumentNotFoundException(String.format("Could not find authority item resource with CSID='%s'",
382 authorityItemSpecifier.getItemSpecifier().value));
384 Long itemRev = (Long) NuxeoUtils.getProperyValue(itemDocModel, AuthorityItemJAXBSchema.REV);
385 String itemShortId = (String) NuxeoUtils.getProperyValue(itemDocModel, AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
386 String itemRefName = (String) NuxeoUtils.getProperyValue(itemDocModel, AuthorityItemJAXBSchema.REF_NAME);
388 // Now get the Authority (the parent) information
390 DocumentModel authorityDocModel = NuxeoUtils.getDocFromSpecifier(ctx, getRepositorySession(), authorityCommonSchemaName,
391 authorityItemSpecifier.getParentSpecifier());
392 Long authorityRev = (Long) NuxeoUtils.getProperyValue(authorityDocModel, AuthorityJAXBSchema.REV);
393 String authorityShortId = (String) NuxeoUtils.getProperyValue(authorityDocModel, AuthorityJAXBSchema.SHORT_IDENTIFIER);
394 String authorityRefName = (String) NuxeoUtils.getProperyValue(authorityDocModel, AuthorityJAXBSchema.REF_NAME);
395 AuthorityInfo authorityInfo = RefNameUtils.parseAuthorityInfo(authorityRefName);
397 // Using the short IDs of the local authority and item, create URN specifiers to retrieve the SAS authority item
399 Specifier sasAuthoritySpecifier = new Specifier(SpecifierForm.URN_NAME, RefNameUtils.createShortIdRefName(authorityShortId));
400 Specifier sasItemSpecifier = new Specifier(SpecifierForm.URN_NAME, RefNameUtils.createShortIdRefName(itemShortId));
401 AuthorityItemSpecifier sasAuthorityItemSpecifier = new AuthorityItemSpecifier(sasAuthoritySpecifier, sasItemSpecifier);
402 // Get the shared authority server's copy
403 PoxPayloadIn sasPayloadIn = AuthorityServiceUtils.getPayloadIn(sasAuthorityItemSpecifier,
404 getAuthorityServicePath(), getEntityResponseType());
406 Long sasRev = getRevision(sasPayloadIn);
407 if (sasRev > itemRev) {
408 ResourceMap resourceMap = ctx.getResourceMap();
409 String resourceName = this.getAuthorityServicePath();
410 AuthorityResource authorityResource = (AuthorityResource) resourceMap.get(resourceName);
411 PoxPayloadOut payloadOut = authorityResource.updateAuthorityItem(ctx,
414 authorityDocModel.getName(), // parent's CSID
415 itemDocModel.getName(), // item's CSID
416 sasPayloadIn, // the payload from the SAS
417 false); // don't update the parent's revision number
418 if (payloadOut != null) {
419 ctx.setOutput(payloadOut);
428 * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#handleCreate(org.collectionspace.services.common.document.DocumentWrapper)
431 public void handleCreate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
432 // first fill all the parts of the document, refname and short ID get set as well
433 super.handleCreate(wrapDoc);
434 // Ensure we have required fields set properly
435 handleInAuthority(wrapDoc.getWrappedObject());
439 * This method gets called after the primary update to an authority item has happened. If the authority item's refName
440 * has changed, then we need to updated all the records that use that refname with the new/updated version
443 * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#completeUpdate(org.collectionspace.services.common.document.DocumentWrapper)
445 public void completeUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
446 // Must call our super class' version first
447 super.completeUpdate(wrapDoc);
450 // Look for and update authority references with the updated refName
452 if (hasRefNameUpdate() == true) {
453 // We have work to do.
454 if (logger.isDebugEnabled()) {
455 final String EOL = System.getProperty("line.separator");
456 logger.debug("Need to find and update references to authority item." + EOL
457 + " Old refName" + oldRefNameOnUpdate + EOL
458 + " New refName" + newRefNameOnUpdate);
460 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
461 RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient = getRepositoryClient(ctx);
462 CoreSessionInterface repoSession = this.getRepositorySession();
464 // Update all the existing records that have a field with the old refName in it
465 int nUpdated = RefNameServiceUtils.updateAuthorityRefDocs(ctx, repoClient, repoSession,
466 oldRefNameOnUpdate, newRefNameOnUpdate, getRefPropName());
468 // Finished so log a message.
469 if (logger.isDebugEnabled()) {
470 logger.debug("Updated " + nUpdated + " instances of oldRefName to newRefName");
476 * Note that the Vocabulary service's document-model for items overrides this method.
478 protected String getPrimaryDisplayName(DocumentModel docModel, String schema,
479 String complexPropertyName, String fieldName) {
480 String result = null;
482 result = getStringValueInPrimaryRepeatingComplexProperty(docModel, schema, complexPropertyName, fieldName);
488 * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#handleUpdate(org.collectionspace.services.common.document.DocumentWrapper)
491 // 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.
493 public void handleUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
494 // Must call our super's version first, this updates the core schema and the relationship records to deal with possible refName changes/update
495 super.handleUpdate(wrapDoc);
496 if (this.hasRefNameUpdate() == true) {
497 DocumentModel docModel = wrapDoc.getWrappedObject();
498 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
502 public void fillAllParts(DocumentWrapper<DocumentModel> wrapDoc, Action action) throws Exception {
503 super.fillAllParts(wrapDoc, action);
505 // Update the record's revision number on both CREATE and UPDATE actions
507 if (this.getShouldUpdateRevNumber() == true) { // We won't update rev numbers on synchronization with SAS
508 updateRevNumbers(wrapDoc);
513 * Update the revision number of both the item and the item's parent.
517 protected void updateRevNumbers(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
518 DocumentModel documentModel = wrapDoc.getWrappedObject();
519 Long rev = (Long)documentModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REV);
525 documentModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REV, rev);
527 // Next, update the inAuthority (the parent's) rev number
529 DocumentModel inAuthorityDocModel = NuxeoUtils.getDocFromCsid(getServiceContext(), getRepositorySession(), getInAuthority());
530 Long parentRev = (Long)inAuthorityDocModel.getProperty(getParentCommonSchemaName(), AuthorityJAXBSchema.REV);
531 if (parentRev == null) {
532 parentRev = new Long(0);
535 inAuthorityDocModel.setProperty(getParentCommonSchemaName(), AuthorityJAXBSchema.REV, parentRev);
536 getRepositorySession().saveDocument(inAuthorityDocModel);
540 * If no short identifier was provided in the input payload, generate a
541 * short identifier from the preferred term display name or term name.
543 private String handleDisplayNameAsShortIdentifier(DocumentModel docModel) throws Exception {
544 String result = (String) docModel.getProperty(authorityItemCommonSchemaName,
545 AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
547 if (Tools.isEmpty(result)) {
548 String termDisplayName = getPrimaryDisplayName(
549 docModel, authorityItemCommonSchemaName,
550 getItemTermInfoGroupXPathBase(),
551 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
553 String termName = getPrimaryDisplayName(
554 docModel, authorityItemCommonSchemaName,
555 getItemTermInfoGroupXPathBase(),
556 AuthorityItemJAXBSchema.TERM_NAME);
558 String generatedShortIdentifier = AuthorityIdentifierUtils.generateShortIdentifierFromDisplayName(termDisplayName,
560 docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER,
561 generatedShortIdentifier);
562 result = generatedShortIdentifier;
569 * Generate a refName for the authority item from the short identifier
572 * All refNames for authority items are generated. If a client supplies
573 * a refName, it will be overwritten during create (per this method)
574 * or discarded during update (per filterReadOnlyPropertiesForPart).
576 * @see #filterReadOnlyPropertiesForPart(Map<String, Object>, org.collectionspace.services.common.service.ObjectPartType)
579 protected String updateRefnameForAuthorityItem(DocumentModel docModel,
580 String schemaName) throws Exception {
581 String result = null;
583 RefName.RefNameInterface refname = getRefName(getServiceContext(), docModel);
584 String refNameStr = refname.toString();
585 docModel.setProperty(schemaName, AuthorityItemJAXBSchema.REF_NAME, refNameStr);
592 * Check the logic around the parent pointer. Note that we only need do this on
593 * create, since we have logic to make this read-only on update.
597 * @throws Exception the exception
599 private void handleInAuthority(DocumentModel docModel) throws Exception {
600 if(inAuthority==null) { // Only happens on queries to wildcarded authorities
601 throw new IllegalStateException("Trying to Create an object with no inAuthority value!");
603 docModel.setProperty(authorityItemCommonSchemaName,
604 AuthorityItemJAXBSchema.IN_AUTHORITY, inAuthority);
607 public AuthorityRefDocList getReferencingObjects(
608 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
609 UriTemplateRegistry uriTemplateRegistry,
610 List<String> serviceTypes,
612 String itemcsid) throws Exception {
613 AuthorityRefDocList authRefDocList = null;
614 CoreSessionInterface repoSession = null;
615 boolean releaseRepoSession = false;
618 RepositoryClientImpl repoClient = (RepositoryClientImpl)this.getRepositoryClient(ctx);
619 repoSession = this.getRepositorySession();
620 if (repoSession == null) {
621 repoSession = repoClient.getRepositorySession(ctx);
622 releaseRepoSession = true;
624 DocumentFilter myFilter = getDocumentFilter();
627 DocumentWrapper<DocumentModel> wrapper = repoClient.getDoc(repoSession, ctx, itemcsid);
628 DocumentModel docModel = wrapper.getWrappedObject();
629 String refName = (String) NuxeoUtils.getProperyValue(docModel, AuthorityItemJAXBSchema.REF_NAME); //docModel.getPropertyValue(AuthorityItemJAXBSchema.REF_NAME);
630 authRefDocList = RefNameServiceUtils.getAuthorityRefDocs(
631 repoSession, ctx, uriTemplateRegistry, repoClient,
635 myFilter, true /*computeTotal*/);
636 } catch (PropertyException pe) {
638 } catch (DocumentException de) {
640 } catch (Exception e) {
641 if (logger.isDebugEnabled()) {
642 logger.debug("Caught exception ", e);
644 throw new DocumentException(e);
646 // If we got/aquired a new seesion then we're responsible for releasing it.
647 if (releaseRepoSession && repoSession != null) {
648 repoClient.releaseRepositorySession(ctx, repoSession);
651 } catch (Exception e) {
652 if (logger.isDebugEnabled()) {
653 logger.debug("Caught exception ", e);
655 throw new DocumentException(e);
658 return authRefDocList;
662 * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#extractPart(org.nuxeo.ecm.core.api.DocumentModel, java.lang.String, org.collectionspace.services.common.service.ObjectPartType)
665 protected Map<String, Object> extractPart(DocumentModel docModel, String schema, ObjectPartType partMeta)
667 Map<String, Object> unQObjectProperties = super.extractPart(docModel, schema, partMeta);
669 // Add the CSID to the common part, since they may have fetched via the shortId.
670 if (partMeta.getLabel().equalsIgnoreCase(authorityItemCommonSchemaName)) {
671 String csid = getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
672 unQObjectProperties.put("csid", csid);
675 return unQObjectProperties;
679 * Filters out selected values supplied in an update request.
681 * For example, filters out AuthorityItemJAXBSchema.IN_AUTHORITY, to ensure
682 * that the link to the item's parent remains untouched.
684 * @param objectProps the properties filtered out from the update payload
685 * @param partMeta metadata for the object to fill
688 public void filterReadOnlyPropertiesForPart(
689 Map<String, Object> objectProps, ObjectPartType partMeta) {
690 super.filterReadOnlyPropertiesForPart(objectProps, partMeta);
691 String commonPartLabel = getServiceContext().getCommonPartLabel();
692 if (partMeta.getLabel().equalsIgnoreCase(commonPartLabel)) {
693 objectProps.remove(AuthorityItemJAXBSchema.IN_AUTHORITY);
694 objectProps.remove(AuthorityItemJAXBSchema.CSID);
695 objectProps.remove(AuthorityJAXBSchema.SHORT_IDENTIFIER);
696 objectProps.remove(AuthorityItemJAXBSchema.REF_NAME);
701 * Returns the items in a list of term display names whose names contain
702 * a partial term (as might be submitted in a search query, for instance).
703 * @param termDisplayNameList a list of term display names.
704 * @param partialTerm a partial term display name; that is, a portion
705 * of a display name that might be expected to match 0-n terms in the list.
706 * @return a list of term display names that matches the partial term.
707 * Matches are case-insensitive. As well, before matching is performed, any
708 * special-purpose characters that may appear in the partial term (such as
709 * wildcards and anchor characters) are filtered out from both compared terms.
711 protected List<String> getPartialTermDisplayNameMatches(List<String> termDisplayNameList, String partialTerm) {
712 List<String> result = new ArrayList<>();
713 String partialTermMatchExpression = filterAnchorAndWildcardChars(partialTerm).toLowerCase();
715 for (String termDisplayName : termDisplayNameList) {
716 if (termDisplayName.toLowerCase()
717 .matches(partialTermMatchExpression) == true) {
718 result.add(termDisplayName);
721 } catch (PatternSyntaxException pse) {
722 logger.warn("Error in regex match pattern '%s' for term display names: %s",
723 partialTermMatchExpression, pse.getMessage());
729 * Filters user-supplied anchor and wildcard characters in a string,
730 * replacing them with equivalent regular expressions.
731 * @param term a term in which to filter anchor and wildcard characters.
732 * @return the term with those characters filtered.
734 protected String filterAnchorAndWildcardChars(String term) {
735 if (Tools.isBlank(term)) {
738 if (term.length() < 3) {
741 if (logger.isTraceEnabled()) {
742 logger.trace(String.format("Term = %s", term));
744 Boolean anchorAtStart = false;
745 Boolean anchorAtEnd = false;
747 StringBuilder filteredTermBuilder = new StringBuilder(term);
748 // Term contains no anchor or wildcard characters.
749 if ( (! term.contains(RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR))
750 && (! term.contains(RepositoryClientImpl.USER_SUPPLIED_WILDCARD)) ) {
753 // Term contains at least one such character.
755 // Filter the starting anchor or wildcard character, if any.
756 String firstChar = filteredTermBuilder.substring(0,1);
758 case RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR:
759 anchorAtStart = true;
761 case RepositoryClientImpl.USER_SUPPLIED_WILDCARD:
762 filteredTermBuilder.deleteCharAt(0);
765 if (logger.isTraceEnabled()) {
766 logger.trace(String.format("After first char filtering = %s", filteredTermBuilder.toString()));
768 // Filter the ending anchor or wildcard character, if any.
769 int lastPos = filteredTermBuilder.length() - 1;
770 String lastChar = filteredTermBuilder.substring(lastPos);
772 case RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR:
773 filteredTermBuilder.deleteCharAt(lastPos);
774 filteredTermBuilder.insert(filteredTermBuilder.length(), RepositoryClientImpl.ENDING_ANCHOR_CHAR);
777 case RepositoryClientImpl.USER_SUPPLIED_WILDCARD:
778 filteredTermBuilder.deleteCharAt(lastPos);
781 if (logger.isTraceEnabled()) {
782 logger.trace(String.format("After last char filtering = %s", filteredTermBuilder.toString()));
784 filteredTerm = filteredTermBuilder.toString();
785 // Filter all other wildcards, if any.
786 filteredTerm = filteredTerm.replaceAll(RepositoryClientImpl.USER_SUPPLIED_WILDCARD_REGEX, ZERO_OR_MORE_ANY_CHAR_REGEX);
787 if (logger.isTraceEnabled()) {
788 logger.trace(String.format("After replacing user wildcards = %s", filteredTerm));
790 } catch (Exception e) {
791 logger.warn(String.format("Error filtering anchor and wildcard characters from string: %s", e.getMessage()));
795 // Wrap the term in beginning and ending regex wildcards, unless a
796 // starting or ending anchor character was present.
797 return (anchorAtStart ? "" : ZERO_OR_MORE_ANY_CHAR_REGEX)
799 + (anchorAtEnd ? "" : ZERO_OR_MORE_ANY_CHAR_REGEX);
802 @SuppressWarnings("unchecked")
803 private List<String> getPartialTermDisplayNameMatches(DocumentModel docModel, // REM - CSPACE-5133
804 String schema, ListResultField field, String partialTerm) {
805 List<String> result = null;
807 String xpath = field.getXpath(); // results in something like "persons_common:personTermGroupList/[0]/termDisplayName"
808 int endOfTermGroup = xpath.lastIndexOf("/[0]/");
809 String propertyName = endOfTermGroup != -1 ? xpath.substring(0, endOfTermGroup) : xpath; // it may not be multivalued so the xpath passed in would be the property name
813 value = docModel.getProperty(schema, propertyName);
814 } catch (Exception e) {
815 logger.error("Could not extract term display name with property = "
819 if (value != null && value instanceof ArrayList) {
820 ArrayList<HashMap<String, Object>> termGroupList = (ArrayList<HashMap<String, Object>>)value;
821 int arrayListSize = termGroupList.size();
822 if (arrayListSize > 1) { // if there's only 1 element in the list then we've already matched the primary term's display name
823 List<String> displayNameList = new ArrayList<String>();
824 for (int i = 1; i < arrayListSize; i++) { // start at 1, skip the primary term's displayName since we will always return it
825 HashMap<String, Object> map = (HashMap<String, Object>)termGroupList.get(i);
826 String termDisplayName = (String) map.get(AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
827 displayNameList.add(i - 1, termDisplayName);
830 result = getPartialTermDisplayNameMatches(displayNameList, partialTerm);
838 protected Object getListResultValue(DocumentModel docModel, // REM - CSPACE-5133
839 String schema, ListResultField field) throws DocumentException {
840 Object result = null;
842 result = NuxeoUtils.getXPathValue(docModel, schema, field.getXpath());
845 // Special handling of list item values for authority items (only)
848 // If the list result field is the termDisplayName element,
849 // check whether a partial term matching query was made.
850 // If it was, emit values for both the preferred (aka primary)
851 // term and for all non-preferred terms, if any.
853 String elName = field.getElement();
854 if (isTermDisplayName(elName) == true) {
855 MultivaluedMap<String, String> queryParams = this.getServiceContext().getQueryParams();
856 String partialTerm = queryParams != null ? queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM) : null;
857 if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
858 String primaryTermDisplayName = (String)result;
859 List<String> matches = getPartialTermDisplayNameMatches(docModel, schema, field, partialTerm);
860 if (matches != null && matches.isEmpty() == false) {
861 matches.add(0, primaryTermDisplayName); // insert the primary term's display name at the beginning of the list
862 result = matches; // set the result to a list of matching term display names with the primary term's display name at the beginning
871 public void extractAllParts(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
872 MultipartServiceContext ctx = (MultipartServiceContext) getServiceContext();
873 super.extractAllParts(wrapDoc);
876 protected List<RelationsCommonList.RelationListItem> cloneList(List<RelationsCommonList.RelationListItem> inboundList) {
877 List<RelationsCommonList.RelationListItem> result = newRelationsCommonList();
878 for (RelationsCommonList.RelationListItem item : inboundList) {
885 /* don't even THINK of re-using this method.
886 * String example_uri = "/locationauthorities/7ec60f01-84ab-4908-9a6a/items/a5466530-713f-43b4-bc05";
889 private String extractInAuthorityCSID(String uri) {
890 String IN_AUTHORITY_REGEX = "/(.*?)/(.*?)/(.*)";
891 Pattern p = Pattern.compile(IN_AUTHORITY_REGEX);
892 Matcher m = p.matcher(uri);
894 if (m.groupCount() < 3) {
895 logger.warn("REGEX-WRONG-GROUPCOUNT looking in " + uri);
898 //String service = m.group(1);
899 String inauth = m.group(2);
900 //String theRest = m.group(3);
902 //print("service:"+service+", inauth:"+inauth+", rest:"+rest);
905 logger.warn("REGEX-NOT-MATCHED looking in " + uri);
910 //ensures CSPACE-4042
911 protected void uriPointsToSameAuthority(String thisURI, String inboundItemURI) throws Exception {
912 String authorityCSID = extractInAuthorityCSID(thisURI);
913 String authorityCSIDForInbound = extractInAuthorityCSID(inboundItemURI);
914 if (Tools.isBlank(authorityCSID)
915 || Tools.isBlank(authorityCSIDForInbound)
916 || (!authorityCSID.equalsIgnoreCase(authorityCSIDForInbound))) {
917 throw new Exception("Item URI " + thisURI + " must point to same authority as related item: " + inboundItemURI);
921 public String getItemTermInfoGroupXPathBase() {
922 return authorityItemTermGroupXPathBase;
925 public void setItemTermInfoGroupXPathBase(String itemTermInfoGroupXPathBase) {
926 authorityItemTermGroupXPathBase = itemTermInfoGroupXPathBase;
929 protected String getAuthorityItemCommonSchemaName() {
930 return authorityItemCommonSchemaName;
934 public boolean isJDBCQuery() {
935 boolean result = false;
937 MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams();
939 // Look the query params to see if we need to make a SQL query.
941 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
942 if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
949 // By convention, the name of the database table that contains
950 // repeatable term information group records is derivable from
951 // an existing XPath base value, by removing a suffix and converting
953 protected String getTermGroupTableName() {
954 String termInfoGroupListName = getItemTermInfoGroupXPathBase();
955 return termInfoGroupListName.substring(0, termInfoGroupListName.lastIndexOf(LIST_SUFFIX)).toLowerCase();
958 protected String getInAuthorityValue() {
959 String inAuthorityValue = getInAuthority();
960 if (Tools.notBlank(inAuthorityValue)) {
961 return inAuthorityValue;
963 return AuthorityResource.PARENT_WILDCARD;
968 public Map<String,String> getJDBCQueryParams() {
969 // FIXME: Get all of the following values from appropriate external constants.
970 // At present, these are duplicated in both RepositoryClientImpl
971 // and in AuthorityItemDocumentModelHandler.
972 final String TERM_GROUP_LIST_NAME = "TERM_GROUP_LIST_NAME";
973 final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
974 final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
976 Map<String,String> params = super.getJDBCQueryParams();
977 params.put(TERM_GROUP_LIST_NAME, getItemTermInfoGroupXPathBase());
978 params.put(TERM_GROUP_TABLE_NAME_PARAM, getTermGroupTableName());
979 params.put(IN_AUTHORITY_PARAM, getInAuthorityValue());