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.UriTemplateRegistry;
31 import org.collectionspace.services.common.api.RefName;
32 import org.collectionspace.services.common.api.Tools;
33 import org.collectionspace.services.common.authorityref.AuthorityRefDocList;
34 import org.collectionspace.services.common.context.MultipartServiceContext;
35 import org.collectionspace.services.common.context.ServiceContext;
36 import org.collectionspace.services.common.document.DocumentException;
37 import org.collectionspace.services.common.document.DocumentFilter;
38 import org.collectionspace.services.common.document.DocumentWrapper;
39 import org.collectionspace.services.common.repository.RepositoryClient;
40 import org.collectionspace.services.common.vocabulary.AuthorityJAXBSchema;
41 import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema;
42 import org.collectionspace.services.common.vocabulary.AuthorityResource;
43 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils;
44 import org.collectionspace.services.config.service.ListResultField;
45 import org.collectionspace.services.config.service.ObjectPartType;
46 import org.collectionspace.services.nuxeo.client.java.NuxeoDocumentModelHandler;
47 import org.collectionspace.services.nuxeo.client.java.CoreSessionInterface;
48 import org.collectionspace.services.nuxeo.client.java.RepositoryJavaClientImpl;
49 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
50 import org.collectionspace.services.relation.RelationsCommonList;
51 import org.collectionspace.services.vocabulary.VocabularyItemJAXBSchema;
52 import org.nuxeo.ecm.core.api.ClientException;
53 import org.nuxeo.ecm.core.api.DocumentModel;
54 import org.nuxeo.ecm.core.api.model.PropertyException;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
58 import javax.ws.rs.core.MultivaluedMap;
60 import java.util.ArrayList;
61 import java.util.Collections;
62 import java.util.HashMap;
63 import java.util.List;
65 import java.util.regex.Matcher;
66 import java.util.regex.Pattern;
67 import java.util.regex.PatternSyntaxException;
69 //import org.collectionspace.services.common.authority.AuthorityItemRelations;
71 * AuthorityItemDocumentModelHandler
73 * $LastChangedRevision: $
76 public abstract class AuthorityItemDocumentModelHandler<AICommon>
77 extends NuxeoDocumentModelHandler<AICommon> {
79 private final Logger logger = LoggerFactory.getLogger(AuthorityItemDocumentModelHandler.class);
80 private String authorityItemCommonSchemaName;
81 private String authorityItemTermGroupXPathBase;
83 * inVocabulary is the parent Authority for this context
85 protected String inAuthority = null;
86 protected boolean wildcardedAuthorityRequest = false;
87 protected String authorityRefNameBase = null;
88 // Used to determine when the displayName changes as part of the update.
89 protected String oldDisplayNameOnUpdate = null;
90 private final static String LIST_SUFFIX = "List";
91 private final static String ZERO_OR_MORE_ANY_CHAR_REGEX = ".*";
93 public AuthorityItemDocumentModelHandler(String authorityItemCommonSchemaName) {
94 this.authorityItemCommonSchemaName = authorityItemCommonSchemaName;
98 protected String getRefnameDisplayName(DocumentWrapper<DocumentModel> docWrapper) {
101 DocumentModel docModel = docWrapper.getWrappedObject();
102 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = this.getServiceContext();
103 RefName.AuthorityItem refname = (RefName.AuthorityItem)getRefName(ctx, docModel);
104 result = refname.getDisplayName();
110 * After calling this method successfully, the document model will contain an updated refname and short ID
112 * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#getRefName(org.collectionspace.services.common.context.ServiceContext, org.nuxeo.ecm.core.api.DocumentModel)
115 public RefName.RefNameInterface getRefName(ServiceContext ctx,
116 DocumentModel docModel) {
117 RefName.RefNameInterface refname = null;
120 String displayName = getPrimaryDisplayName(docModel, authorityItemCommonSchemaName,
121 getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
122 if (Tools.isEmpty(displayName)) {
123 throw new Exception("The displayName for this authority term was empty or not set.");
126 String shortIdentifier = (String) docModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
127 if (Tools.isEmpty(shortIdentifier)) {
128 // We didn't find a short ID in the payload request, so we need to synthesize one.
129 shortIdentifier = handleDisplayNameAsShortIdentifier(docModel); // updates the document model with the new short ID as a side-effect
132 String authorityRefBaseName = getAuthorityRefNameBase();
133 if (Tools.isEmpty(authorityRefBaseName)) {
134 throw new Exception("Could not create the refName for this authority term, because the refName for its authority parent was empty.");
137 // Create the items refname using the parent's as a base
138 RefName.Authority parentsRefName = RefName.Authority.parse(authorityRefBaseName);
139 refname = RefName.buildAuthorityItem(parentsRefName, shortIdentifier, displayName);
140 // Now update the document model with the refname value
141 String refNameStr = refname.toString();
142 docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REF_NAME, refNameStr); // REM - This field is deprecated now that the refName is part of the collection_space core schema
144 } catch (Exception e) {
145 logger.error(e.getMessage(), e);
151 public void setInAuthority(String inAuthority) {
152 this.inAuthority = inAuthority;
155 public String getInAuthority() {
156 return this.inAuthority;
159 /** Subclasses may override this to customize the URI segment. */
160 public String getAuthorityServicePath() {
161 return getServiceContext().getServiceName().toLowerCase(); // Laramie20110510 CSPACE-3932
165 public String getUri(DocumentModel docModel) {
166 // Laramie20110510 CSPACE-3932
167 String authorityServicePath = getAuthorityServicePath();
168 if(inAuthority==null) { // Only true with the first document model received, on queries to wildcarded authorities
169 wildcardedAuthorityRequest = true;
171 // If this search crosses multiple authorities, get the inAuthority value
172 // from each record, rather than using the cached value from the first record
173 if(wildcardedAuthorityRequest) {
175 inAuthority = (String) docModel.getProperty(authorityItemCommonSchemaName,
176 AuthorityItemJAXBSchema.IN_AUTHORITY);
177 } catch (ClientException pe) {
178 throw new RuntimeException("Could not get parent specifier for item!");
181 return "/" + authorityServicePath + '/' + inAuthority + '/' + AuthorityClient.ITEMS + '/' + getCsid(docModel);
184 protected String getAuthorityRefNameBase() {
185 return this.authorityRefNameBase;
188 public void setAuthorityRefNameBase(String value) {
189 this.authorityRefNameBase = value;
193 * Note: the Vocabulary service's VocabularyItemDocumentModelHandler class overrides this method.
195 protected ListResultField getListResultsDisplayNameField() {
196 ListResultField result = new ListResultField();
197 // Per CSPACE-5132, the name of this element remains 'displayName'
198 // for backwards compatibility, although its value is obtained
199 // from the termDisplayName field.
201 // Update: this name is now being changed to 'termDisplayName', both
202 // because this is the actual field name and because the app layer
203 // work to convert over to this field is underway. Per Patrick, the
204 // app layer treats lists, in at least some context(s), as sparse record
205 // payloads, and thus fields in list results must all be present in
206 // (i.e. represent a strict subset of the fields in) record schemas.
210 // In CSPACE-5134, these list results will change substantially
211 // to return display names for both the preferred term and for
212 // each non-preferred term (if any).
213 result.setElement(AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
214 result.setXpath(NuxeoUtils.getPrimaryXPathPropertyName(
215 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_DISPLAY_NAME));
221 * Note: the Vocabulary service's VocabularyItemDocumentModelHandler class overrides this method.
223 protected ListResultField getListResultsTermStatusField() {
224 ListResultField result = new ListResultField();
226 result.setElement(AuthorityItemJAXBSchema.TERM_STATUS);
227 result.setXpath(NuxeoUtils.getPrimaryXPathPropertyName(
228 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_STATUS));
233 private boolean isTermDisplayName(String elName) {
234 return AuthorityItemJAXBSchema.TERM_DISPLAY_NAME.equals(elName) || VocabularyItemJAXBSchema.DISPLAY_NAME.equals(elName);
239 * @see org.collectionspace.services.nuxeo.client.java.DocHandlerBase#getListItemsArray()
241 * Note: We're updating the "global" service and tenant bindings instance here -the list instance here is
242 * a reference to the tenant bindings instance in the singleton ServiceMain.
245 public List<ListResultField> getListItemsArray() throws DocumentException {
246 List<ListResultField> list = super.getListItemsArray();
248 // One-time initialization for each authority item service.
249 if (isListItemArrayExtended() == false) {
250 synchronized(AuthorityItemDocumentModelHandler.class) {
251 if (isListItemArrayExtended() == false) {
252 int nFields = list.size();
253 // Ensure that each item in a list of Authority items includes
254 // a set of common fields, so we do not depend upon configuration
255 // for general logic.
256 List<Integer> termDisplayNamePositionsInList = new ArrayList<>();
257 boolean hasShortId = false;
258 boolean hasTermStatus = false;
259 for (int i = 0; i < nFields; i++) {
260 ListResultField field = list.get(i);
261 String elName = field.getElement();
262 if (isTermDisplayName(elName) == true) {
263 termDisplayNamePositionsInList.add(i);
264 } else if (AuthorityItemJAXBSchema.SHORT_IDENTIFIER.equals(elName)) {
266 } else if (AuthorityItemJAXBSchema.TERM_STATUS.equals(elName)) {
267 hasTermStatus = true;
271 ListResultField field;
273 // Certain fields in authority item list results
274 // are handled specially here
278 // Ignore (throw out) any configuration entries that
279 // specify how the termDisplayName field should be
280 // emitted in authority item lists. This field will
281 // be handled in a standardized manner (see block below).
282 if (termDisplayNamePositionsInList.isEmpty() == false) {
283 // Remove matching items starting at the end of the list
284 // and moving towards the start, so that reshuffling of
285 // list order doesn't alter the positions of earlier items
286 Collections.sort(termDisplayNamePositionsInList, Collections.reverseOrder());
287 for (int i : termDisplayNamePositionsInList) {
291 // termDisplayName values in authority item lists
292 // will be handled via code that emits display names
293 // for both the preferred term and all non-preferred
294 // terms (if any). The following is a placeholder
295 // entry that will trigger this code. See the
296 // getListResultValue() method in this class.
297 field = getListResultsDisplayNameField();
302 field = new ListResultField();
303 field.setElement(AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
304 field.setXpath(AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
309 if (!hasTermStatus) {
310 field = getListResultsTermStatusField();
316 setListItemArrayExtended(true);
317 } // end of synchronized block
324 * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#handleCreate(org.collectionspace.services.common.document.DocumentWrapper)
327 public void handleCreate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
328 // first fill all the parts of the document, refname and short ID get set as well
329 super.handleCreate(wrapDoc);
330 // Ensure we have required fields set properly
331 handleInAuthority(wrapDoc.getWrappedObject());
335 * This method gets called after the primary update to an authority item has happened. If the authority item's refName
336 * has changed, then we need to updated all the records that use that refname with the new/updated version
339 * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#completeUpdate(org.collectionspace.services.common.document.DocumentWrapper)
341 public void completeUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
342 // Must call our super class' version first
343 super.completeUpdate(wrapDoc);
346 // Look for and update authority references with the updated refName
348 if (hasRefNameUpdate() == true) {
349 // We have work to do.
350 if (logger.isDebugEnabled()) {
351 final String EOL = System.getProperty("line.separator");
352 logger.debug("Need to find and update references to authority item." + EOL
353 + " Old refName" + oldRefNameOnUpdate + EOL
354 + " New refName" + newRefNameOnUpdate);
356 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
357 RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient = getRepositoryClient(ctx);
358 CoreSessionInterface repoSession = this.getRepositorySession();
360 // Update all the existing records that have a field with the old refName in it
361 int nUpdated = RefNameServiceUtils.updateAuthorityRefDocs(ctx, repoClient, repoSession,
362 oldRefNameOnUpdate, newRefNameOnUpdate, getRefPropName());
364 // Finished so log a message.
365 if (logger.isDebugEnabled()) {
366 logger.debug("Updated " + nUpdated + " instances of oldRefName to newRefName");
372 * Note that the Vocabulary service's document-model for items overrides this method.
374 protected String getPrimaryDisplayName(DocumentModel docModel, String schema,
375 String complexPropertyName, String fieldName) {
376 String result = null;
378 result = getStringValueInPrimaryRepeatingComplexProperty(docModel, schema, complexPropertyName, fieldName);
384 * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#handleUpdate(org.collectionspace.services.common.document.DocumentWrapper)
387 // 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.
389 public void handleUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
390 // Must call our super's version first, this updates the core schema and the relationship records to deal with possible refName changes/update
391 super.handleUpdate(wrapDoc);
392 if (this.hasRefNameUpdate() == true) {
393 DocumentModel docModel = wrapDoc.getWrappedObject();
394 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
399 * If no short identifier was provided in the input payload, generate a
400 * short identifier from the preferred term display name or term name.
402 private String handleDisplayNameAsShortIdentifier(DocumentModel docModel) throws Exception {
403 String result = (String) docModel.getProperty(authorityItemCommonSchemaName,
404 AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
406 if (Tools.isEmpty(result)) {
407 String termDisplayName = getPrimaryDisplayName(
408 docModel, authorityItemCommonSchemaName,
409 getItemTermInfoGroupXPathBase(),
410 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
412 String termName = getPrimaryDisplayName(
413 docModel, authorityItemCommonSchemaName,
414 getItemTermInfoGroupXPathBase(),
415 AuthorityItemJAXBSchema.TERM_NAME);
417 String generatedShortIdentifier = AuthorityIdentifierUtils.generateShortIdentifierFromDisplayName(termDisplayName,
419 docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER,
420 generatedShortIdentifier);
421 result = generatedShortIdentifier;
428 * Generate a refName for the authority item from the short identifier
431 * All refNames for authority items are generated. If a client supplies
432 * a refName, it will be overwritten during create (per this method)
433 * or discarded during update (per filterReadOnlyPropertiesForPart).
435 * @see #filterReadOnlyPropertiesForPart(Map<String, Object>, org.collectionspace.services.common.service.ObjectPartType)
438 protected String updateRefnameForAuthorityItem(DocumentModel docModel,
439 String schemaName) throws Exception {
440 String result = null;
442 RefName.RefNameInterface refname = getRefName(getServiceContext(), docModel);
443 String refNameStr = refname.toString();
444 docModel.setProperty(schemaName, AuthorityItemJAXBSchema.REF_NAME, refNameStr);
451 * Check the logic around the parent pointer. Note that we only need do this on
452 * create, since we have logic to make this read-only on update.
456 * @throws Exception the exception
458 private void handleInAuthority(DocumentModel docModel) throws Exception {
459 if(inAuthority==null) { // Only happens on queries to wildcarded authorities
460 throw new IllegalStateException("Trying to Create an object with no inAuthority value!");
462 docModel.setProperty(authorityItemCommonSchemaName,
463 AuthorityItemJAXBSchema.IN_AUTHORITY, inAuthority);
466 public AuthorityRefDocList getReferencingObjects(
467 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
468 UriTemplateRegistry uriTemplateRegistry,
469 List<String> serviceTypes,
471 String itemcsid) throws Exception {
472 AuthorityRefDocList authRefDocList = null;
473 CoreSessionInterface repoSession = null;
474 boolean releaseRepoSession = false;
477 RepositoryJavaClientImpl repoClient = (RepositoryJavaClientImpl)this.getRepositoryClient(ctx);
478 repoSession = this.getRepositorySession();
479 if (repoSession == null) {
480 repoSession = repoClient.getRepositorySession(ctx);
481 releaseRepoSession = true;
483 DocumentFilter myFilter = getDocumentFilter();
486 DocumentWrapper<DocumentModel> wrapper = repoClient.getDoc(repoSession, ctx, itemcsid);
487 DocumentModel docModel = wrapper.getWrappedObject();
488 String refName = (String) NuxeoUtils.getProperyValue(docModel, AuthorityItemJAXBSchema.REF_NAME); //docModel.getPropertyValue(AuthorityItemJAXBSchema.REF_NAME);
489 authRefDocList = RefNameServiceUtils.getAuthorityRefDocs(
490 repoSession, ctx, uriTemplateRegistry, repoClient,
494 myFilter, true /*computeTotal*/);
495 } catch (PropertyException pe) {
497 } catch (DocumentException de) {
499 } catch (Exception e) {
500 if (logger.isDebugEnabled()) {
501 logger.debug("Caught exception ", e);
503 throw new DocumentException(e);
505 // If we got/aquired a new seesion then we're responsible for releasing it.
506 if (releaseRepoSession && repoSession != null) {
507 repoClient.releaseRepositorySession(ctx, repoSession);
510 } catch (Exception e) {
511 if (logger.isDebugEnabled()) {
512 logger.debug("Caught exception ", e);
514 throw new DocumentException(e);
517 return authRefDocList;
521 * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#extractPart(org.nuxeo.ecm.core.api.DocumentModel, java.lang.String, org.collectionspace.services.common.service.ObjectPartType)
524 protected Map<String, Object> extractPart(DocumentModel docModel, String schema, ObjectPartType partMeta)
526 Map<String, Object> unQObjectProperties = super.extractPart(docModel, schema, partMeta);
528 // Add the CSID to the common part, since they may have fetched via the shortId.
529 if (partMeta.getLabel().equalsIgnoreCase(authorityItemCommonSchemaName)) {
530 String csid = getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
531 unQObjectProperties.put("csid", csid);
534 return unQObjectProperties;
538 * Filters out selected values supplied in an update request.
540 * For example, filters out AuthorityItemJAXBSchema.IN_AUTHORITY, to ensure
541 * that the link to the item's parent remains untouched.
543 * @param objectProps the properties filtered out from the update payload
544 * @param partMeta metadata for the object to fill
547 public void filterReadOnlyPropertiesForPart(
548 Map<String, Object> objectProps, ObjectPartType partMeta) {
549 super.filterReadOnlyPropertiesForPart(objectProps, partMeta);
550 String commonPartLabel = getServiceContext().getCommonPartLabel();
551 if (partMeta.getLabel().equalsIgnoreCase(commonPartLabel)) {
552 objectProps.remove(AuthorityItemJAXBSchema.IN_AUTHORITY);
553 objectProps.remove(AuthorityItemJAXBSchema.CSID);
554 objectProps.remove(AuthorityJAXBSchema.SHORT_IDENTIFIER);
555 objectProps.remove(AuthorityItemJAXBSchema.REF_NAME);
560 * Returns the items in a list of term display names whose names contain
561 * a partial term (as might be submitted in a search query, for instance).
562 * @param termDisplayNameList a list of term display names.
563 * @param partialTerm a partial term display name; that is, a portion
564 * of a display name that might be expected to match 0-n terms in the list.
565 * @return a list of term display names that matches the partial term.
566 * Matches are case-insensitive. As well, before matching is performed, any
567 * special-purpose characters that may appear in the partial term (such as
568 * wildcards and anchor characters) are filtered out from both compared terms.
570 protected List<String> getPartialTermDisplayNameMatches(List<String> termDisplayNameList, String partialTerm) {
571 List<String> result = new ArrayList<>();
572 String partialTermMatchExpression = filterAnchorAndWildcardChars(partialTerm).toLowerCase();
574 for (String termDisplayName : termDisplayNameList) {
575 if (termDisplayName.toLowerCase()
576 .matches(partialTermMatchExpression) == true) {
577 result.add(termDisplayName);
580 } catch (PatternSyntaxException pse) {
581 logger.warn("Error in regex match pattern '%s' for term display names: %s",
582 partialTermMatchExpression, pse.getMessage());
588 * Filters user-supplied anchor and wildcard characters in a string,
589 * replacing them with equivalent regular expressions.
590 * @param term a term in which to filter anchor and wildcard characters.
591 * @return the term with those characters filtered.
593 protected String filterAnchorAndWildcardChars(String term) {
594 if (Tools.isBlank(term)) {
597 if (term.length() < 3) {
600 if (logger.isTraceEnabled()) {
601 logger.trace(String.format("Term = %s", term));
603 Boolean anchorAtStart = false;
604 Boolean anchorAtEnd = false;
606 StringBuilder filteredTermBuilder = new StringBuilder(term);
607 // Term contains no anchor or wildcard characters.
608 if ( (! term.contains(RepositoryJavaClientImpl.USER_SUPPLIED_ANCHOR_CHAR))
609 && (! term.contains(RepositoryJavaClientImpl.USER_SUPPLIED_WILDCARD)) ) {
612 // Term contains at least one such character.
614 // Filter the starting anchor or wildcard character, if any.
615 String firstChar = filteredTermBuilder.substring(0,1);
617 case RepositoryJavaClientImpl.USER_SUPPLIED_ANCHOR_CHAR:
618 anchorAtStart = true;
620 case RepositoryJavaClientImpl.USER_SUPPLIED_WILDCARD:
621 filteredTermBuilder.deleteCharAt(0);
624 if (logger.isTraceEnabled()) {
625 logger.trace(String.format("After first char filtering = %s", filteredTermBuilder.toString()));
627 // Filter the ending anchor or wildcard character, if any.
628 int lastPos = filteredTermBuilder.length() - 1;
629 String lastChar = filteredTermBuilder.substring(lastPos);
631 case RepositoryJavaClientImpl.USER_SUPPLIED_ANCHOR_CHAR:
632 filteredTermBuilder.deleteCharAt(lastPos);
633 filteredTermBuilder.insert(filteredTermBuilder.length(), RepositoryJavaClientImpl.ENDING_ANCHOR_CHAR);
636 case RepositoryJavaClientImpl.USER_SUPPLIED_WILDCARD:
637 filteredTermBuilder.deleteCharAt(lastPos);
640 if (logger.isTraceEnabled()) {
641 logger.trace(String.format("After last char filtering = %s", filteredTermBuilder.toString()));
643 filteredTerm = filteredTermBuilder.toString();
644 // Filter all other wildcards, if any.
645 filteredTerm = filteredTerm.replaceAll(RepositoryJavaClientImpl.USER_SUPPLIED_WILDCARD_REGEX, ZERO_OR_MORE_ANY_CHAR_REGEX);
646 if (logger.isTraceEnabled()) {
647 logger.trace(String.format("After replacing user wildcards = %s", filteredTerm));
649 } catch (Exception e) {
650 logger.warn(String.format("Error filtering anchor and wildcard characters from string: %s", e.getMessage()));
654 // Wrap the term in beginning and ending regex wildcards, unless a
655 // starting or ending anchor character was present.
656 return (anchorAtStart ? "" : ZERO_OR_MORE_ANY_CHAR_REGEX)
658 + (anchorAtEnd ? "" : ZERO_OR_MORE_ANY_CHAR_REGEX);
661 @SuppressWarnings("unchecked")
662 private List<String> getPartialTermDisplayNameMatches(DocumentModel docModel, // REM - CSPACE-5133
663 String schema, ListResultField field, String partialTerm) {
664 List<String> result = null;
666 String xpath = field.getXpath(); // results in something like "persons_common:personTermGroupList/[0]/termDisplayName"
667 int endOfTermGroup = xpath.lastIndexOf("/[0]/");
668 String propertyName = endOfTermGroup != -1 ? xpath.substring(0, endOfTermGroup) : xpath; // it may not be multivalued so the xpath passed in would be the property name
672 value = docModel.getProperty(schema, propertyName);
673 } catch (Exception e) {
674 logger.error("Could not extract term display name with property = "
678 if (value != null && value instanceof ArrayList) {
679 ArrayList<HashMap<String, Object>> termGroupList = (ArrayList<HashMap<String, Object>>)value;
680 int arrayListSize = termGroupList.size();
681 if (arrayListSize > 1) { // if there's only 1 element in the list then we've already matched the primary term's display name
682 List<String> displayNameList = new ArrayList<String>();
683 for (int i = 1; i < arrayListSize; i++) { // start at 1, skip the primary term's displayName since we will always return it
684 HashMap<String, Object> map = (HashMap<String, Object>)termGroupList.get(i);
685 String termDisplayName = (String) map.get(AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
686 displayNameList.add(i - 1, termDisplayName);
689 result = getPartialTermDisplayNameMatches(displayNameList, partialTerm);
697 protected Object getListResultValue(DocumentModel docModel, // REM - CSPACE-5133
698 String schema, ListResultField field) throws DocumentException {
699 Object result = null;
701 result = NuxeoUtils.getXPathValue(docModel, schema, field.getXpath());
704 // Special handling of list item values for authority items (only)
707 // If the list result field is the termDisplayName element,
708 // check whether a partial term matching query was made.
709 // If it was, emit values for both the preferred (aka primary)
710 // term and for all non-preferred terms, if any.
712 String elName = field.getElement();
713 if (isTermDisplayName(elName) == true) {
714 MultivaluedMap<String, String> queryParams = this.getServiceContext().getQueryParams();
715 String partialTerm = queryParams != null ? queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM) : null;
716 if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
717 String primaryTermDisplayName = (String)result;
718 List<String> matches = getPartialTermDisplayNameMatches(docModel, schema, field, partialTerm);
719 if (matches != null && matches.isEmpty() == false) {
720 matches.add(0, primaryTermDisplayName); // insert the primary term's display name at the beginning of the list
721 result = matches; // set the result to a list of matching term display names with the primary term's display name at the beginning
730 public void extractAllParts(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
731 MultipartServiceContext ctx = (MultipartServiceContext) getServiceContext();
732 super.extractAllParts(wrapDoc);
736 public void fillAllParts(DocumentWrapper<DocumentModel> wrapDoc, Action action) throws Exception {
738 // We currently don't override this method with any AuthorityItemDocumentModelHandler specific functionality, so
739 // we could remove this method.
741 super.fillAllParts(wrapDoc, action);
744 protected List<RelationsCommonList.RelationListItem> cloneList(List<RelationsCommonList.RelationListItem> inboundList) {
745 List<RelationsCommonList.RelationListItem> result = newRelationsCommonList();
746 for (RelationsCommonList.RelationListItem item : inboundList) {
753 /* don't even THINK of re-using this method.
754 * String example_uri = "/locationauthorities/7ec60f01-84ab-4908-9a6a/items/a5466530-713f-43b4-bc05";
757 private String extractInAuthorityCSID(String uri) {
758 String IN_AUTHORITY_REGEX = "/(.*?)/(.*?)/(.*)";
759 Pattern p = Pattern.compile(IN_AUTHORITY_REGEX);
760 Matcher m = p.matcher(uri);
762 if (m.groupCount() < 3) {
763 logger.warn("REGEX-WRONG-GROUPCOUNT looking in " + uri);
766 //String service = m.group(1);
767 String inauth = m.group(2);
768 //String theRest = m.group(3);
770 //print("service:"+service+", inauth:"+inauth+", rest:"+rest);
773 logger.warn("REGEX-NOT-MATCHED looking in " + uri);
778 //ensures CSPACE-4042
779 protected void uriPointsToSameAuthority(String thisURI, String inboundItemURI) throws Exception {
780 String authorityCSID = extractInAuthorityCSID(thisURI);
781 String authorityCSIDForInbound = extractInAuthorityCSID(inboundItemURI);
782 if (Tools.isBlank(authorityCSID)
783 || Tools.isBlank(authorityCSIDForInbound)
784 || (!authorityCSID.equalsIgnoreCase(authorityCSIDForInbound))) {
785 throw new Exception("Item URI " + thisURI + " must point to same authority as related item: " + inboundItemURI);
789 public String getItemTermInfoGroupXPathBase() {
790 return authorityItemTermGroupXPathBase;
793 public void setItemTermInfoGroupXPathBase(String itemTermInfoGroupXPathBase) {
794 authorityItemTermGroupXPathBase = itemTermInfoGroupXPathBase;
797 protected String getAuthorityItemCommonSchemaName() {
798 return authorityItemCommonSchemaName;
802 public boolean isJDBCQuery() {
803 boolean result = false;
805 MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams();
807 // Look the query params to see if we need to make a SQL query.
809 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
810 if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
817 // By convention, the name of the database table that contains
818 // repeatable term information group records is derivable from
819 // an existing XPath base value, by removing a suffix and converting
821 protected String getTermGroupTableName() {
822 String termInfoGroupListName = getItemTermInfoGroupXPathBase();
823 return termInfoGroupListName.substring(0, termInfoGroupListName.lastIndexOf(LIST_SUFFIX)).toLowerCase();
826 protected String getInAuthorityValue() {
827 String inAuthorityValue = getInAuthority();
828 if (Tools.notBlank(inAuthorityValue)) {
829 return inAuthorityValue;
831 return AuthorityResource.PARENT_WILDCARD;
836 public Map<String,String> getJDBCQueryParams() {
837 // FIXME: Get all of the following values from appropriate external constants.
838 // At present, these are duplicated in both RepositoryJavaClientImpl
839 // and in AuthorityItemDocumentModelHandler.
840 final String TERM_GROUP_LIST_NAME = "TERM_GROUP_LIST_NAME";
841 final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
842 final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
844 Map<String,String> params = super.getJDBCQueryParams();
845 params.put(TERM_GROUP_LIST_NAME, getItemTermInfoGroupXPathBase());
846 params.put(TERM_GROUP_TABLE_NAME_PARAM, getTermGroupTableName());
847 params.put(IN_AUTHORITY_PARAM, getInAuthorityValue());