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.DocHandlerBase;
47 import org.collectionspace.services.nuxeo.client.java.NuxeoDocumentException;
48 import org.collectionspace.services.nuxeo.client.java.RepositoryInstanceInterface;
49 import org.collectionspace.services.nuxeo.client.java.RepositoryJavaClientImpl;
50 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
51 import org.collectionspace.services.relation.RelationsCommonList;
52 import org.collectionspace.services.relation.RelationsDocListItem;
53 import org.collectionspace.services.vocabulary.VocabularyItemJAXBSchema;
54 import org.nuxeo.ecm.core.api.ClientException;
55 import org.nuxeo.ecm.core.api.DocumentModel;
56 import org.nuxeo.ecm.core.api.model.PropertyException;
57 import org.nuxeo.ecm.core.api.repository.RepositoryInstance;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
61 import javax.ws.rs.core.MultivaluedMap;
63 import java.util.ArrayList;
64 import java.util.Collections;
65 import java.util.HashMap;
66 import java.util.List;
68 import java.util.regex.Matcher;
69 import java.util.regex.Pattern;
70 import java.util.regex.PatternSyntaxException;
72 //import org.collectionspace.services.common.authority.AuthorityItemRelations;
74 * AuthorityItemDocumentModelHandler
76 * $LastChangedRevision: $
79 public abstract class AuthorityItemDocumentModelHandler<AICommon>
80 extends DocHandlerBase<AICommon> {
82 private final Logger logger = LoggerFactory.getLogger(AuthorityItemDocumentModelHandler.class);
83 private String authorityItemCommonSchemaName;
84 private String authorityItemTermGroupXPathBase;
86 * inVocabulary is the parent Authority for this context
88 protected String inAuthority = null;
89 protected boolean wildcardedAuthorityRequest = false;
90 protected String authorityRefNameBase = null;
91 // Used to determine when the displayName changes as part of the update.
92 protected String oldDisplayNameOnUpdate = null;
93 private final static String LIST_SUFFIX = "List";
94 private final static String ZERO_OR_MORE_ANY_CHAR_REGEX = ".*";
96 public AuthorityItemDocumentModelHandler(String authorityItemCommonSchemaName) {
97 this.authorityItemCommonSchemaName = authorityItemCommonSchemaName;
101 protected String getRefnameDisplayName(DocumentWrapper<DocumentModel> docWrapper) {
102 String result = null;
104 DocumentModel docModel = docWrapper.getWrappedObject();
105 ServiceContext ctx = this.getServiceContext();
106 RefName.AuthorityItem refname = (RefName.AuthorityItem)getRefName(ctx, docModel);
107 result = refname.getDisplayName();
113 * After calling this method successfully, the document model will contain an updated refname and short ID
115 * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#getRefName(org.collectionspace.services.common.context.ServiceContext, org.nuxeo.ecm.core.api.DocumentModel)
118 public RefName.RefNameInterface getRefName(ServiceContext ctx,
119 DocumentModel docModel) {
120 RefName.RefNameInterface refname = null;
123 String displayName = getPrimaryDisplayName(docModel, authorityItemCommonSchemaName,
124 getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
125 if (Tools.isEmpty(displayName)) {
126 throw new Exception("The displayName for this authority term was empty or not set.");
129 String shortIdentifier = (String) docModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
130 if (Tools.isEmpty(shortIdentifier)) {
131 // We didn't find a short ID in the payload request, so we need to synthesize one.
132 shortIdentifier = handleDisplayNameAsShortIdentifier(docModel); // updates the document model with the new short ID as a side-effect
135 String authorityRefBaseName = getAuthorityRefNameBase();
136 if (Tools.isEmpty(authorityRefBaseName)) {
137 throw new Exception("Could not create the refName for this authority term, because the refName for its authority parent was empty.");
140 // Create the items refname using the parent's as a base
141 RefName.Authority parentsRefName = RefName.Authority.parse(authorityRefBaseName);
142 refname = RefName.buildAuthorityItem(parentsRefName, shortIdentifier, displayName);
143 // Now update the document model with the refname value
144 String refNameStr = refname.toString();
145 docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REF_NAME, refNameStr); // REM - This field is deprecated now that the refName is part of the collection_space core schema
147 } catch (Exception e) {
148 logger.error(e.getMessage(), e);
154 public void setInAuthority(String inAuthority) {
155 this.inAuthority = inAuthority;
158 public String getInAuthority() {
159 return this.inAuthority;
162 /** Subclasses may override this to customize the URI segment. */
163 public String getAuthorityServicePath() {
164 return getServiceContext().getServiceName().toLowerCase(); // Laramie20110510 CSPACE-3932
168 public String getUri(DocumentModel docModel) {
169 // Laramie20110510 CSPACE-3932
170 String authorityServicePath = getAuthorityServicePath();
171 if(inAuthority==null) { // Only true with the first document model received, on queries to wildcarded authorities
172 wildcardedAuthorityRequest = true;
174 // If this search crosses multiple authorities, get the inAuthority value
175 // from each record, rather than using the cached value from the first record
176 if(wildcardedAuthorityRequest) {
178 inAuthority = (String) docModel.getProperty(authorityItemCommonSchemaName,
179 AuthorityItemJAXBSchema.IN_AUTHORITY);
180 } catch (ClientException pe) {
181 throw new RuntimeException("Could not get parent specifier for item!");
184 return "/" + authorityServicePath + '/' + inAuthority + '/' + AuthorityClient.ITEMS + '/' + getCsid(docModel);
187 protected String getAuthorityRefNameBase() {
188 return this.authorityRefNameBase;
191 public void setAuthorityRefNameBase(String value) {
192 this.authorityRefNameBase = value;
196 * Note: the Vocabulary service's VocabularyItemDocumentModelHandler class overrides this method.
198 protected ListResultField getListResultsDisplayNameField() {
199 ListResultField result = new ListResultField();
200 // Per CSPACE-5132, the name of this element remains 'displayName'
201 // for backwards compatibility, although its value is obtained
202 // from the termDisplayName field.
204 // Update: this name is now being changed to 'termDisplayName', both
205 // because this is the actual field name and because the app layer
206 // work to convert over to this field is underway. Per Patrick, the
207 // app layer treats lists, in at least some context(s), as sparse record
208 // payloads, and thus fields in list results must all be present in
209 // (i.e. represent a strict subset of the fields in) record schemas.
213 // In CSPACE-5134, these list results will change substantially
214 // to return display names for both the preferred term and for
215 // each non-preferred term (if any).
216 result.setElement(AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
217 result.setXpath(NuxeoUtils.getPrimaryXPathPropertyName(
218 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_DISPLAY_NAME));
224 * Note: the Vocabulary service's VocabularyItemDocumentModelHandler class overrides this method.
226 protected ListResultField getListResultsTermStatusField() {
227 ListResultField result = new ListResultField();
229 result.setElement(AuthorityItemJAXBSchema.TERM_STATUS);
230 result.setXpath(NuxeoUtils.getPrimaryXPathPropertyName(
231 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_STATUS));
236 private boolean isTermDisplayName(String elName) {
237 return AuthorityItemJAXBSchema.TERM_DISPLAY_NAME.equals(elName) || VocabularyItemJAXBSchema.DISPLAY_NAME.equals(elName);
242 * @see org.collectionspace.services.nuxeo.client.java.DocHandlerBase#getListItemsArray()
244 * Note: We're updating the "global" service and tenant bindings instance here -the list instance here is
245 * a reference to the tenant bindings instance in the singleton ServiceMain.
248 public List<ListResultField> getListItemsArray() throws DocumentException {
249 List<ListResultField> list = super.getListItemsArray();
251 // One-time initialization for each authority item service.
252 if (isListItemArrayExtended() == false) {
253 synchronized(AuthorityItemDocumentModelHandler.class) {
254 if (isListItemArrayExtended() == false) {
255 int nFields = list.size();
256 // Ensure that each item in a list of Authority items includes
257 // a set of common fields, so we do not depend upon configuration
258 // for general logic.
259 List<Integer> termDisplayNamePositionsInList = new ArrayList<>();
260 boolean hasShortId = false;
261 boolean hasTermStatus = false;
262 for (int i = 0; i < nFields; i++) {
263 ListResultField field = list.get(i);
264 String elName = field.getElement();
265 if (isTermDisplayName(elName) == true) {
266 termDisplayNamePositionsInList.add(i);
267 } else if (AuthorityItemJAXBSchema.SHORT_IDENTIFIER.equals(elName)) {
269 } else if (AuthorityItemJAXBSchema.TERM_STATUS.equals(elName)) {
270 hasTermStatus = true;
274 ListResultField field;
276 // Certain fields in authority item list results
277 // are handled specially here
281 // Ignore (throw out) any configuration entries that
282 // specify how the termDisplayName field should be
283 // emitted in authority item lists. This field will
284 // be handled in a standardized manner (see block below).
285 if (termDisplayNamePositionsInList.isEmpty() == false) {
286 // Remove matching items starting at the end of the list
287 // and moving towards the start, so that reshuffling of
288 // list order doesn't alter the positions of earlier items
289 Collections.sort(termDisplayNamePositionsInList, Collections.reverseOrder());
290 for (int i : termDisplayNamePositionsInList) {
294 // termDisplayName values in authority item lists
295 // will be handled via code that emits display names
296 // for both the preferred term and all non-preferred
297 // terms (if any). The following is a placeholder
298 // entry that will trigger this code. See the
299 // getListResultValue() method in this class.
300 field = getListResultsDisplayNameField();
305 field = new ListResultField();
306 field.setElement(AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
307 field.setXpath(AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
312 if (!hasTermStatus) {
313 field = getListResultsTermStatusField();
319 setListItemArrayExtended(true);
320 } // end of synchronized block
327 * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#handleCreate(org.collectionspace.services.common.document.DocumentWrapper)
330 public void handleCreate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
331 // first fill all the parts of the document, refname and short ID get set as well
332 super.handleCreate(wrapDoc);
333 // Ensure we have required fields set properly
334 handleInAuthority(wrapDoc.getWrappedObject());
338 * This method gets called after the primary update to an authority item has happened. If the authority item's refName
339 * has changed, then we need to updated all the records that use that refname with the new/updated version
342 * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#completeUpdate(org.collectionspace.services.common.document.DocumentWrapper)
344 public void completeUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
345 // Must call our super class' version first
346 super.completeUpdate(wrapDoc);
349 // Look for and update authority references with the updated refName
351 if (hasRefNameUpdate() == true) {
352 // We have work to do.
353 if (logger.isDebugEnabled()) {
354 final String EOL = System.getProperty("line.separator");
355 logger.debug("Need to find and update references to authority item." + EOL
356 + " Old refName" + oldRefNameOnUpdate + EOL
357 + " New refName" + newRefNameOnUpdate);
359 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
360 RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient = getRepositoryClient(ctx);
361 RepositoryInstanceInterface repoSession = this.getRepositorySession();
363 // Update all the existing records that have a field with the old refName in it
364 int nUpdated = RefNameServiceUtils.updateAuthorityRefDocs(ctx, repoClient, repoSession,
365 oldRefNameOnUpdate, newRefNameOnUpdate, getRefPropName());
367 // Finished so log a message.
368 if (logger.isDebugEnabled()) {
369 logger.debug("Updated " + nUpdated + " instances of oldRefName to newRefName");
375 * Note that the Vocabulary service's document-model for items overrides this method.
377 protected String getPrimaryDisplayName(DocumentModel docModel, String schema,
378 String complexPropertyName, String fieldName) {
379 String result = null;
381 result = getStringValueInPrimaryRepeatingComplexProperty(docModel, schema, complexPropertyName, fieldName);
387 * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#handleUpdate(org.collectionspace.services.common.document.DocumentWrapper)
390 // 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.
392 public void handleUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
393 // Must call our super's version first, this updates the core schema and the relationship records to deal with possible refName changes/update
394 super.handleUpdate(wrapDoc);
395 if (this.hasRefNameUpdate() == true) {
396 DocumentModel docModel = wrapDoc.getWrappedObject();
397 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
402 * If no short identifier was provided in the input payload, generate a
403 * short identifier from the preferred term display name or term name.
405 private String handleDisplayNameAsShortIdentifier(DocumentModel docModel) throws Exception {
406 String result = (String) docModel.getProperty(authorityItemCommonSchemaName,
407 AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
409 if (Tools.isEmpty(result)) {
410 String termDisplayName = getPrimaryDisplayName(
411 docModel, authorityItemCommonSchemaName,
412 getItemTermInfoGroupXPathBase(),
413 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
415 String termName = getPrimaryDisplayName(
416 docModel, authorityItemCommonSchemaName,
417 getItemTermInfoGroupXPathBase(),
418 AuthorityItemJAXBSchema.TERM_NAME);
420 String generatedShortIdentifier = AuthorityIdentifierUtils.generateShortIdentifierFromDisplayName(termDisplayName,
422 docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER,
423 generatedShortIdentifier);
424 result = generatedShortIdentifier;
431 * Generate a refName for the authority item from the short identifier
434 * All refNames for authority items are generated. If a client supplies
435 * a refName, it will be overwritten during create (per this method)
436 * or discarded during update (per filterReadOnlyPropertiesForPart).
438 * @see #filterReadOnlyPropertiesForPart(Map<String, Object>, org.collectionspace.services.common.service.ObjectPartType)
441 protected String updateRefnameForAuthorityItem(DocumentModel docModel,
442 String schemaName) throws Exception {
443 String result = null;
445 RefName.RefNameInterface refname = getRefName(getServiceContext(), docModel);
446 String refNameStr = refname.toString();
447 docModel.setProperty(schemaName, AuthorityItemJAXBSchema.REF_NAME, refNameStr);
454 * Check the logic around the parent pointer. Note that we only need do this on
455 * create, since we have logic to make this read-only on update.
459 * @throws Exception the exception
461 private void handleInAuthority(DocumentModel docModel) throws Exception {
462 if(inAuthority==null) { // Only happens on queries to wildcarded authorities
463 throw new IllegalStateException("Trying to Create an object with no inAuthority value!");
465 docModel.setProperty(authorityItemCommonSchemaName,
466 AuthorityItemJAXBSchema.IN_AUTHORITY, inAuthority);
469 public AuthorityRefDocList getReferencingObjects(
470 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
471 UriTemplateRegistry uriTemplateRegistry,
472 List<String> serviceTypes,
474 String itemcsid) throws Exception {
475 AuthorityRefDocList authRefDocList = null;
476 RepositoryInstanceInterface repoSession = null;
477 boolean releaseRepoSession = false;
480 RepositoryJavaClientImpl repoClient = (RepositoryJavaClientImpl)this.getRepositoryClient(ctx);
481 repoSession = this.getRepositorySession();
482 if (repoSession == null) {
483 repoSession = repoClient.getRepositorySession(ctx);
484 releaseRepoSession = true;
486 DocumentFilter myFilter = getDocumentFilter();
489 DocumentWrapper<DocumentModel> wrapper = repoClient.getDoc(repoSession, ctx, itemcsid);
490 DocumentModel docModel = wrapper.getWrappedObject();
491 String refName = (String) docModel.getPropertyValue(AuthorityItemJAXBSchema.REF_NAME);
492 authRefDocList = RefNameServiceUtils.getAuthorityRefDocs(
493 repoSession, ctx, uriTemplateRegistry, repoClient,
497 myFilter, true /*computeTotal*/);
498 } catch (PropertyException pe) {
500 } catch (DocumentException de) {
502 } catch (Exception e) {
503 if (logger.isDebugEnabled()) {
504 logger.debug("Caught exception ", e);
506 throw new DocumentException(e);
508 // If we got/aquired a new seesion then we're responsible for releasing it.
509 if (releaseRepoSession && repoSession != null) {
510 repoClient.releaseRepositorySession(ctx, repoSession);
513 } catch (Exception e) {
514 if (logger.isDebugEnabled()) {
515 logger.debug("Caught exception ", e);
517 throw new DocumentException(e);
520 return authRefDocList;
524 * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#extractPart(org.nuxeo.ecm.core.api.DocumentModel, java.lang.String, org.collectionspace.services.common.service.ObjectPartType)
527 protected Map<String, Object> extractPart(DocumentModel docModel, String schema, ObjectPartType partMeta)
529 Map<String, Object> unQObjectProperties = super.extractPart(docModel, schema, partMeta);
531 // Add the CSID to the common part, since they may have fetched via the shortId.
532 if (partMeta.getLabel().equalsIgnoreCase(authorityItemCommonSchemaName)) {
533 String csid = getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
534 unQObjectProperties.put("csid", csid);
537 return unQObjectProperties;
541 * Filters out selected values supplied in an update request.
543 * For example, filters out AuthorityItemJAXBSchema.IN_AUTHORITY, to ensure
544 * that the link to the item's parent remains untouched.
546 * @param objectProps the properties filtered out from the update payload
547 * @param partMeta metadata for the object to fill
550 public void filterReadOnlyPropertiesForPart(
551 Map<String, Object> objectProps, ObjectPartType partMeta) {
552 super.filterReadOnlyPropertiesForPart(objectProps, partMeta);
553 String commonPartLabel = getServiceContext().getCommonPartLabel();
554 if (partMeta.getLabel().equalsIgnoreCase(commonPartLabel)) {
555 objectProps.remove(AuthorityItemJAXBSchema.IN_AUTHORITY);
556 objectProps.remove(AuthorityItemJAXBSchema.CSID);
557 objectProps.remove(AuthorityJAXBSchema.SHORT_IDENTIFIER);
558 objectProps.remove(AuthorityItemJAXBSchema.REF_NAME);
563 * Returns the items in a list of term display names whose names contain
564 * a partial term (as might be submitted in a search query, for instance).
565 * @param termDisplayNameList a list of term display names.
566 * @param partialTerm a partial term display name; that is, a portion
567 * of a display name that might be expected to match 0-n terms in the list.
568 * @return a list of term display names that matches the partial term.
569 * Matches are case-insensitive. As well, before matching is performed, any
570 * special-purpose characters that may appear in the partial term (such as
571 * wildcards and anchor characters) are filtered out from both compared terms.
573 protected List<String> getPartialTermDisplayNameMatches(List<String> termDisplayNameList, String partialTerm) {
574 List<String> result = new ArrayList<>();
575 String partialTermMatchExpression = filterAnchorAndWildcardChars(partialTerm).toLowerCase();
577 for (String termDisplayName : termDisplayNameList) {
578 if (termDisplayName.toLowerCase()
579 .matches(partialTermMatchExpression) == true) {
580 result.add(termDisplayName);
583 } catch (PatternSyntaxException pse) {
584 logger.warn("Error in regex match pattern '%s' for term display names: %s",
585 partialTermMatchExpression, pse.getMessage());
591 * Filters user-supplied anchor and wildcard characters in a string,
592 * replacing them with equivalent regular expressions.
593 * @param term a term in which to filter anchor and wildcard characters.
594 * @return the term with those characters filtered.
596 protected String filterAnchorAndWildcardChars(String term) {
597 if (Tools.isBlank(term)) {
600 if (term.length() < 3) {
603 if (logger.isTraceEnabled()) {
604 logger.trace(String.format("Term = %s", term));
606 Boolean anchorAtStart = false;
607 Boolean anchorAtEnd = false;
609 StringBuilder filteredTermBuilder = new StringBuilder(term);
610 // Term contains no anchor or wildcard characters.
611 if ( (! term.contains(RepositoryJavaClientImpl.USER_SUPPLIED_ANCHOR_CHAR))
612 && (! term.contains(RepositoryJavaClientImpl.USER_SUPPLIED_WILDCARD)) ) {
615 // Term contains at least one such character.
617 // Filter the starting anchor or wildcard character, if any.
618 String firstChar = filteredTermBuilder.substring(0,1);
620 case RepositoryJavaClientImpl.USER_SUPPLIED_ANCHOR_CHAR:
621 anchorAtStart = true;
623 case RepositoryJavaClientImpl.USER_SUPPLIED_WILDCARD:
624 filteredTermBuilder.deleteCharAt(0);
627 if (logger.isTraceEnabled()) {
628 logger.trace(String.format("After first char filtering = %s", filteredTermBuilder.toString()));
630 // Filter the ending anchor or wildcard character, if any.
631 int lastPos = filteredTermBuilder.length() - 1;
632 String lastChar = filteredTermBuilder.substring(lastPos);
634 case RepositoryJavaClientImpl.USER_SUPPLIED_ANCHOR_CHAR:
635 filteredTermBuilder.deleteCharAt(lastPos);
636 filteredTermBuilder.insert(filteredTermBuilder.length(), RepositoryJavaClientImpl.ENDING_ANCHOR_CHAR);
639 case RepositoryJavaClientImpl.USER_SUPPLIED_WILDCARD:
640 filteredTermBuilder.deleteCharAt(lastPos);
643 if (logger.isTraceEnabled()) {
644 logger.trace(String.format("After last char filtering = %s", filteredTermBuilder.toString()));
646 filteredTerm = filteredTermBuilder.toString();
647 // Filter all other wildcards, if any.
648 filteredTerm = filteredTerm.replaceAll(RepositoryJavaClientImpl.USER_SUPPLIED_WILDCARD_REGEX, ZERO_OR_MORE_ANY_CHAR_REGEX);
649 if (logger.isTraceEnabled()) {
650 logger.trace(String.format("After replacing user wildcards = %s", filteredTerm));
652 } catch (Exception e) {
653 logger.warn(String.format("Error filtering anchor and wildcard characters from string: %s", e.getMessage()));
657 // Wrap the term in beginning and ending regex wildcards, unless a
658 // starting or ending anchor character was present.
659 return (anchorAtStart ? "" : ZERO_OR_MORE_ANY_CHAR_REGEX)
661 + (anchorAtEnd ? "" : ZERO_OR_MORE_ANY_CHAR_REGEX);
664 @SuppressWarnings("unchecked")
665 private List<String> getPartialTermDisplayNameMatches(DocumentModel docModel, // REM - CSPACE-5133
666 String schema, ListResultField field, String partialTerm) {
667 List<String> result = null;
669 String xpath = field.getXpath(); // results in something like "persons_common:personTermGroupList/[0]/termDisplayName"
670 int endOfTermGroup = xpath.lastIndexOf("/[0]/");
671 String propertyName = endOfTermGroup != -1 ? xpath.substring(0, endOfTermGroup) : xpath; // it may not be multivalued so the xpath passed in would be the property name
675 value = docModel.getProperty(schema, propertyName);
676 } catch (Exception e) {
677 logger.error("Could not extract term display name with property = "
681 if (value != null && value instanceof ArrayList) {
682 ArrayList<HashMap<String, Object>> termGroupList = (ArrayList<HashMap<String, Object>>)value;
683 int arrayListSize = termGroupList.size();
684 if (arrayListSize > 1) { // if there's only 1 element in the list then we've already matched the primary term's display name
685 List<String> displayNameList = new ArrayList<String>();
686 for (int i = 1; i < arrayListSize; i++) { // start at 1, skip the primary term's displayName since we will always return it
687 HashMap<String, Object> map = (HashMap<String, Object>)termGroupList.get(i);
688 String termDisplayName = (String) map.get(AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
689 displayNameList.add(i - 1, termDisplayName);
692 result = getPartialTermDisplayNameMatches(displayNameList, partialTerm);
700 protected Object getListResultValue(DocumentModel docModel, // REM - CSPACE-5133
701 String schema, ListResultField field) throws DocumentException {
702 Object result = null;
704 result = NuxeoUtils.getXPathValue(docModel, schema, field.getXpath());
707 // Special handling of list item values for authority items (only)
710 // If the list result field is the termDisplayName element,
711 // check whether a partial term matching query was made.
712 // If it was, emit values for both the preferred (aka primary)
713 // term and for all non-preferred terms, if any.
715 String elName = field.getElement();
716 if (isTermDisplayName(elName) == true) {
717 MultivaluedMap<String, String> queryParams = this.getServiceContext().getQueryParams();
718 String partialTerm = queryParams != null ? queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM) : null;
719 if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
720 String primaryTermDisplayName = (String)result;
721 List<String> matches = getPartialTermDisplayNameMatches(docModel, schema, field, partialTerm);
722 if (matches != null && matches.isEmpty() == false) {
723 matches.add(0, primaryTermDisplayName); // insert the primary term's display name at the beginning of the list
724 result = matches; // set the result to a list of matching term display names with the primary term's display name at the beginning
733 public void extractAllParts(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
734 MultipartServiceContext ctx = (MultipartServiceContext) getServiceContext();
735 super.extractAllParts(wrapDoc);
739 public void fillAllParts(DocumentWrapper<DocumentModel> wrapDoc, Action action) throws Exception {
741 // We currently don't override this method with any AuthorityItemDocumentModelHandler specific functionality, so
742 // we could remove this method.
744 super.fillAllParts(wrapDoc, action);
747 protected List<RelationsCommonList.RelationListItem> cloneList(List<RelationsCommonList.RelationListItem> inboundList) {
748 List<RelationsCommonList.RelationListItem> result = newRelationsCommonList();
749 for (RelationsCommonList.RelationListItem item : inboundList) {
756 /* don't even THINK of re-using this method.
757 * String example_uri = "/locationauthorities/7ec60f01-84ab-4908-9a6a/items/a5466530-713f-43b4-bc05";
760 private String extractInAuthorityCSID(String uri) {
761 String IN_AUTHORITY_REGEX = "/(.*?)/(.*?)/(.*)";
762 Pattern p = Pattern.compile(IN_AUTHORITY_REGEX);
763 Matcher m = p.matcher(uri);
765 if (m.groupCount() < 3) {
766 logger.warn("REGEX-WRONG-GROUPCOUNT looking in " + uri);
769 //String service = m.group(1);
770 String inauth = m.group(2);
771 //String theRest = m.group(3);
773 //print("service:"+service+", inauth:"+inauth+", rest:"+rest);
776 logger.warn("REGEX-NOT-MATCHED looking in " + uri);
781 //ensures CSPACE-4042
782 protected void uriPointsToSameAuthority(String thisURI, String inboundItemURI) throws Exception {
783 String authorityCSID = extractInAuthorityCSID(thisURI);
784 String authorityCSIDForInbound = extractInAuthorityCSID(inboundItemURI);
785 if (Tools.isBlank(authorityCSID)
786 || Tools.isBlank(authorityCSIDForInbound)
787 || (!authorityCSID.equalsIgnoreCase(authorityCSIDForInbound))) {
788 throw new Exception("Item URI " + thisURI + " must point to same authority as related item: " + inboundItemURI);
792 public String getItemTermInfoGroupXPathBase() {
793 return authorityItemTermGroupXPathBase;
796 public void setItemTermInfoGroupXPathBase(String itemTermInfoGroupXPathBase) {
797 authorityItemTermGroupXPathBase = itemTermInfoGroupXPathBase;
800 protected String getAuthorityItemCommonSchemaName() {
801 return authorityItemCommonSchemaName;
805 public boolean isJDBCQuery() {
806 boolean result = false;
808 MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams();
810 // Look the query params to see if we need to make a SQL query.
812 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
813 if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
820 // By convention, the name of the database table that contains
821 // repeatable term information group records is derivable from
822 // an existing XPath base value, by removing a suffix and converting
824 protected String getTermGroupTableName() {
825 String termInfoGroupListName = getItemTermInfoGroupXPathBase();
826 return termInfoGroupListName.substring(0, termInfoGroupListName.lastIndexOf(LIST_SUFFIX)).toLowerCase();
829 protected String getInAuthorityValue() {
830 String inAuthorityValue = getInAuthority();
831 if (Tools.notBlank(inAuthorityValue)) {
832 return inAuthorityValue;
834 return AuthorityResource.PARENT_WILDCARD;
839 public Map<String,String> getJDBCQueryParams() {
840 // FIXME: Get all of the following values from appropriate external constants.
841 // At present, these are duplicated in both RepositoryJavaClientImpl
842 // and in AuthorityItemDocumentModelHandler.
843 final String TERM_GROUP_LIST_NAME = "TERM_GROUP_LIST_NAME";
844 final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
845 final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
847 Map<String,String> params = super.getJDBCQueryParams();
848 params.put(TERM_GROUP_LIST_NAME, getItemTermInfoGroupXPathBase());
849 params.put(TERM_GROUP_TABLE_NAME_PARAM, getTermGroupTableName());
850 params.put(IN_AUTHORITY_PARAM, getInAuthorityValue());