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.document.DocumentHandler.Action;
40 import org.collectionspace.services.common.repository.RepositoryClient;
41 import org.collectionspace.services.common.vocabulary.AuthorityJAXBSchema;
42 import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema;
43 import org.collectionspace.services.common.vocabulary.AuthorityResource;
44 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils;
45 import org.collectionspace.services.config.service.ListResultField;
46 import org.collectionspace.services.config.service.ObjectPartType;
47 import org.collectionspace.services.nuxeo.client.java.NuxeoDocumentModelHandler;
48 import org.collectionspace.services.nuxeo.client.java.CoreSessionInterface;
49 import org.collectionspace.services.nuxeo.client.java.RepositoryClientImpl;
50 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
51 import org.collectionspace.services.relation.RelationsCommonList;
52 import org.collectionspace.services.vocabulary.VocabularyItemJAXBSchema;
53 import org.nuxeo.ecm.core.api.ClientException;
54 import org.nuxeo.ecm.core.api.DocumentModel;
55 import org.nuxeo.ecm.core.api.model.PropertyException;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
59 import javax.ws.rs.core.MultivaluedMap;
61 import java.util.ArrayList;
62 import java.util.Collections;
63 import java.util.HashMap;
64 import java.util.List;
66 import java.util.regex.Matcher;
67 import java.util.regex.Pattern;
68 import java.util.regex.PatternSyntaxException;
70 //import org.collectionspace.services.common.authority.AuthorityItemRelations;
72 * AuthorityItemDocumentModelHandler
74 * $LastChangedRevision: $
77 public abstract class AuthorityItemDocumentModelHandler<AICommon>
78 extends NuxeoDocumentModelHandler<AICommon> {
80 private final Logger logger = LoggerFactory.getLogger(AuthorityItemDocumentModelHandler.class);
81 private String authorityItemCommonSchemaName;
82 private String authorityItemTermGroupXPathBase;
84 * inVocabulary is the parent Authority for this context
86 protected String inAuthority = null;
87 protected boolean wildcardedAuthorityRequest = false;
88 protected String authorityRefNameBase = null;
89 // Used to determine when the displayName changes as part of the update.
90 protected String oldDisplayNameOnUpdate = null;
91 private final static String LIST_SUFFIX = "List";
92 private final static String ZERO_OR_MORE_ANY_CHAR_REGEX = ".*";
94 public AuthorityItemDocumentModelHandler(String authorityItemCommonSchemaName) {
95 this.authorityItemCommonSchemaName = authorityItemCommonSchemaName;
98 abstract public String getParentCommonSchemaName();
101 protected String getRefnameDisplayName(DocumentWrapper<DocumentModel> docWrapper) {
102 String result = null;
104 DocumentModel docModel = docWrapper.getWrappedObject();
105 ServiceContext<PoxPayloadIn, PoxPayloadOut> 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 CoreSessionInterface 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
401 public void fillAllParts(DocumentWrapper<DocumentModel> wrapDoc, Action action) throws Exception {
402 super.fillAllParts(wrapDoc, action);
404 // Update the record's revision number on both CREATE and UPDATE actions
406 updateRevNumbers(wrapDoc);
409 protected void updateRevNumbers(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
410 DocumentModel documentModel = wrapDoc.getWrappedObject();
411 Long rev = (Long)documentModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REV);
417 documentModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REV, rev);
419 // Next, update the inAuthority (the parent's) rev number
421 DocumentModel inAuthorityDocModel = NuxeoUtils.getDocFromCsid(getServiceContext(), getRepositorySession(), getInAuthority());
422 Long parentRev = (Long)inAuthorityDocModel.getProperty(getParentCommonSchemaName(), AuthorityJAXBSchema.REV);
424 inAuthorityDocModel.setProperty(getParentCommonSchemaName(), AuthorityJAXBSchema.REV, parentRev);
425 getRepositorySession().saveDocument(inAuthorityDocModel);
429 * If no short identifier was provided in the input payload, generate a
430 * short identifier from the preferred term display name or term name.
432 private String handleDisplayNameAsShortIdentifier(DocumentModel docModel) throws Exception {
433 String result = (String) docModel.getProperty(authorityItemCommonSchemaName,
434 AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
436 if (Tools.isEmpty(result)) {
437 String termDisplayName = getPrimaryDisplayName(
438 docModel, authorityItemCommonSchemaName,
439 getItemTermInfoGroupXPathBase(),
440 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
442 String termName = getPrimaryDisplayName(
443 docModel, authorityItemCommonSchemaName,
444 getItemTermInfoGroupXPathBase(),
445 AuthorityItemJAXBSchema.TERM_NAME);
447 String generatedShortIdentifier = AuthorityIdentifierUtils.generateShortIdentifierFromDisplayName(termDisplayName,
449 docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER,
450 generatedShortIdentifier);
451 result = generatedShortIdentifier;
458 * Generate a refName for the authority item from the short identifier
461 * All refNames for authority items are generated. If a client supplies
462 * a refName, it will be overwritten during create (per this method)
463 * or discarded during update (per filterReadOnlyPropertiesForPart).
465 * @see #filterReadOnlyPropertiesForPart(Map<String, Object>, org.collectionspace.services.common.service.ObjectPartType)
468 protected String updateRefnameForAuthorityItem(DocumentModel docModel,
469 String schemaName) throws Exception {
470 String result = null;
472 RefName.RefNameInterface refname = getRefName(getServiceContext(), docModel);
473 String refNameStr = refname.toString();
474 docModel.setProperty(schemaName, AuthorityItemJAXBSchema.REF_NAME, refNameStr);
481 * Check the logic around the parent pointer. Note that we only need do this on
482 * create, since we have logic to make this read-only on update.
486 * @throws Exception the exception
488 private void handleInAuthority(DocumentModel docModel) throws Exception {
489 if(inAuthority==null) { // Only happens on queries to wildcarded authorities
490 throw new IllegalStateException("Trying to Create an object with no inAuthority value!");
492 docModel.setProperty(authorityItemCommonSchemaName,
493 AuthorityItemJAXBSchema.IN_AUTHORITY, inAuthority);
496 public AuthorityRefDocList getReferencingObjects(
497 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
498 UriTemplateRegistry uriTemplateRegistry,
499 List<String> serviceTypes,
501 String itemcsid) throws Exception {
502 AuthorityRefDocList authRefDocList = null;
503 CoreSessionInterface repoSession = null;
504 boolean releaseRepoSession = false;
507 RepositoryClientImpl repoClient = (RepositoryClientImpl)this.getRepositoryClient(ctx);
508 repoSession = this.getRepositorySession();
509 if (repoSession == null) {
510 repoSession = repoClient.getRepositorySession(ctx);
511 releaseRepoSession = true;
513 DocumentFilter myFilter = getDocumentFilter();
516 DocumentWrapper<DocumentModel> wrapper = repoClient.getDoc(repoSession, ctx, itemcsid);
517 DocumentModel docModel = wrapper.getWrappedObject();
518 String refName = (String) NuxeoUtils.getProperyValue(docModel, AuthorityItemJAXBSchema.REF_NAME); //docModel.getPropertyValue(AuthorityItemJAXBSchema.REF_NAME);
519 authRefDocList = RefNameServiceUtils.getAuthorityRefDocs(
520 repoSession, ctx, uriTemplateRegistry, repoClient,
524 myFilter, true /*computeTotal*/);
525 } catch (PropertyException pe) {
527 } catch (DocumentException de) {
529 } catch (Exception e) {
530 if (logger.isDebugEnabled()) {
531 logger.debug("Caught exception ", e);
533 throw new DocumentException(e);
535 // If we got/aquired a new seesion then we're responsible for releasing it.
536 if (releaseRepoSession && repoSession != null) {
537 repoClient.releaseRepositorySession(ctx, repoSession);
540 } catch (Exception e) {
541 if (logger.isDebugEnabled()) {
542 logger.debug("Caught exception ", e);
544 throw new DocumentException(e);
547 return authRefDocList;
551 * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#extractPart(org.nuxeo.ecm.core.api.DocumentModel, java.lang.String, org.collectionspace.services.common.service.ObjectPartType)
554 protected Map<String, Object> extractPart(DocumentModel docModel, String schema, ObjectPartType partMeta)
556 Map<String, Object> unQObjectProperties = super.extractPart(docModel, schema, partMeta);
558 // Add the CSID to the common part, since they may have fetched via the shortId.
559 if (partMeta.getLabel().equalsIgnoreCase(authorityItemCommonSchemaName)) {
560 String csid = getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
561 unQObjectProperties.put("csid", csid);
564 return unQObjectProperties;
568 * Filters out selected values supplied in an update request.
570 * For example, filters out AuthorityItemJAXBSchema.IN_AUTHORITY, to ensure
571 * that the link to the item's parent remains untouched.
573 * @param objectProps the properties filtered out from the update payload
574 * @param partMeta metadata for the object to fill
577 public void filterReadOnlyPropertiesForPart(
578 Map<String, Object> objectProps, ObjectPartType partMeta) {
579 super.filterReadOnlyPropertiesForPart(objectProps, partMeta);
580 String commonPartLabel = getServiceContext().getCommonPartLabel();
581 if (partMeta.getLabel().equalsIgnoreCase(commonPartLabel)) {
582 objectProps.remove(AuthorityItemJAXBSchema.IN_AUTHORITY);
583 objectProps.remove(AuthorityItemJAXBSchema.CSID);
584 objectProps.remove(AuthorityJAXBSchema.SHORT_IDENTIFIER);
585 objectProps.remove(AuthorityItemJAXBSchema.REF_NAME);
590 * Returns the items in a list of term display names whose names contain
591 * a partial term (as might be submitted in a search query, for instance).
592 * @param termDisplayNameList a list of term display names.
593 * @param partialTerm a partial term display name; that is, a portion
594 * of a display name that might be expected to match 0-n terms in the list.
595 * @return a list of term display names that matches the partial term.
596 * Matches are case-insensitive. As well, before matching is performed, any
597 * special-purpose characters that may appear in the partial term (such as
598 * wildcards and anchor characters) are filtered out from both compared terms.
600 protected List<String> getPartialTermDisplayNameMatches(List<String> termDisplayNameList, String partialTerm) {
601 List<String> result = new ArrayList<>();
602 String partialTermMatchExpression = filterAnchorAndWildcardChars(partialTerm).toLowerCase();
604 for (String termDisplayName : termDisplayNameList) {
605 if (termDisplayName.toLowerCase()
606 .matches(partialTermMatchExpression) == true) {
607 result.add(termDisplayName);
610 } catch (PatternSyntaxException pse) {
611 logger.warn("Error in regex match pattern '%s' for term display names: %s",
612 partialTermMatchExpression, pse.getMessage());
618 * Filters user-supplied anchor and wildcard characters in a string,
619 * replacing them with equivalent regular expressions.
620 * @param term a term in which to filter anchor and wildcard characters.
621 * @return the term with those characters filtered.
623 protected String filterAnchorAndWildcardChars(String term) {
624 if (Tools.isBlank(term)) {
627 if (term.length() < 3) {
630 if (logger.isTraceEnabled()) {
631 logger.trace(String.format("Term = %s", term));
633 Boolean anchorAtStart = false;
634 Boolean anchorAtEnd = false;
636 StringBuilder filteredTermBuilder = new StringBuilder(term);
637 // Term contains no anchor or wildcard characters.
638 if ( (! term.contains(RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR))
639 && (! term.contains(RepositoryClientImpl.USER_SUPPLIED_WILDCARD)) ) {
642 // Term contains at least one such character.
644 // Filter the starting anchor or wildcard character, if any.
645 String firstChar = filteredTermBuilder.substring(0,1);
647 case RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR:
648 anchorAtStart = true;
650 case RepositoryClientImpl.USER_SUPPLIED_WILDCARD:
651 filteredTermBuilder.deleteCharAt(0);
654 if (logger.isTraceEnabled()) {
655 logger.trace(String.format("After first char filtering = %s", filteredTermBuilder.toString()));
657 // Filter the ending anchor or wildcard character, if any.
658 int lastPos = filteredTermBuilder.length() - 1;
659 String lastChar = filteredTermBuilder.substring(lastPos);
661 case RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR:
662 filteredTermBuilder.deleteCharAt(lastPos);
663 filteredTermBuilder.insert(filteredTermBuilder.length(), RepositoryClientImpl.ENDING_ANCHOR_CHAR);
666 case RepositoryClientImpl.USER_SUPPLIED_WILDCARD:
667 filteredTermBuilder.deleteCharAt(lastPos);
670 if (logger.isTraceEnabled()) {
671 logger.trace(String.format("After last char filtering = %s", filteredTermBuilder.toString()));
673 filteredTerm = filteredTermBuilder.toString();
674 // Filter all other wildcards, if any.
675 filteredTerm = filteredTerm.replaceAll(RepositoryClientImpl.USER_SUPPLIED_WILDCARD_REGEX, ZERO_OR_MORE_ANY_CHAR_REGEX);
676 if (logger.isTraceEnabled()) {
677 logger.trace(String.format("After replacing user wildcards = %s", filteredTerm));
679 } catch (Exception e) {
680 logger.warn(String.format("Error filtering anchor and wildcard characters from string: %s", e.getMessage()));
684 // Wrap the term in beginning and ending regex wildcards, unless a
685 // starting or ending anchor character was present.
686 return (anchorAtStart ? "" : ZERO_OR_MORE_ANY_CHAR_REGEX)
688 + (anchorAtEnd ? "" : ZERO_OR_MORE_ANY_CHAR_REGEX);
691 @SuppressWarnings("unchecked")
692 private List<String> getPartialTermDisplayNameMatches(DocumentModel docModel, // REM - CSPACE-5133
693 String schema, ListResultField field, String partialTerm) {
694 List<String> result = null;
696 String xpath = field.getXpath(); // results in something like "persons_common:personTermGroupList/[0]/termDisplayName"
697 int endOfTermGroup = xpath.lastIndexOf("/[0]/");
698 String propertyName = endOfTermGroup != -1 ? xpath.substring(0, endOfTermGroup) : xpath; // it may not be multivalued so the xpath passed in would be the property name
702 value = docModel.getProperty(schema, propertyName);
703 } catch (Exception e) {
704 logger.error("Could not extract term display name with property = "
708 if (value != null && value instanceof ArrayList) {
709 ArrayList<HashMap<String, Object>> termGroupList = (ArrayList<HashMap<String, Object>>)value;
710 int arrayListSize = termGroupList.size();
711 if (arrayListSize > 1) { // if there's only 1 element in the list then we've already matched the primary term's display name
712 List<String> displayNameList = new ArrayList<String>();
713 for (int i = 1; i < arrayListSize; i++) { // start at 1, skip the primary term's displayName since we will always return it
714 HashMap<String, Object> map = (HashMap<String, Object>)termGroupList.get(i);
715 String termDisplayName = (String) map.get(AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
716 displayNameList.add(i - 1, termDisplayName);
719 result = getPartialTermDisplayNameMatches(displayNameList, partialTerm);
727 protected Object getListResultValue(DocumentModel docModel, // REM - CSPACE-5133
728 String schema, ListResultField field) throws DocumentException {
729 Object result = null;
731 result = NuxeoUtils.getXPathValue(docModel, schema, field.getXpath());
734 // Special handling of list item values for authority items (only)
737 // If the list result field is the termDisplayName element,
738 // check whether a partial term matching query was made.
739 // If it was, emit values for both the preferred (aka primary)
740 // term and for all non-preferred terms, if any.
742 String elName = field.getElement();
743 if (isTermDisplayName(elName) == true) {
744 MultivaluedMap<String, String> queryParams = this.getServiceContext().getQueryParams();
745 String partialTerm = queryParams != null ? queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM) : null;
746 if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
747 String primaryTermDisplayName = (String)result;
748 List<String> matches = getPartialTermDisplayNameMatches(docModel, schema, field, partialTerm);
749 if (matches != null && matches.isEmpty() == false) {
750 matches.add(0, primaryTermDisplayName); // insert the primary term's display name at the beginning of the list
751 result = matches; // set the result to a list of matching term display names with the primary term's display name at the beginning
760 public void extractAllParts(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
761 MultipartServiceContext ctx = (MultipartServiceContext) getServiceContext();
762 super.extractAllParts(wrapDoc);
765 protected List<RelationsCommonList.RelationListItem> cloneList(List<RelationsCommonList.RelationListItem> inboundList) {
766 List<RelationsCommonList.RelationListItem> result = newRelationsCommonList();
767 for (RelationsCommonList.RelationListItem item : inboundList) {
774 /* don't even THINK of re-using this method.
775 * String example_uri = "/locationauthorities/7ec60f01-84ab-4908-9a6a/items/a5466530-713f-43b4-bc05";
778 private String extractInAuthorityCSID(String uri) {
779 String IN_AUTHORITY_REGEX = "/(.*?)/(.*?)/(.*)";
780 Pattern p = Pattern.compile(IN_AUTHORITY_REGEX);
781 Matcher m = p.matcher(uri);
783 if (m.groupCount() < 3) {
784 logger.warn("REGEX-WRONG-GROUPCOUNT looking in " + uri);
787 //String service = m.group(1);
788 String inauth = m.group(2);
789 //String theRest = m.group(3);
791 //print("service:"+service+", inauth:"+inauth+", rest:"+rest);
794 logger.warn("REGEX-NOT-MATCHED looking in " + uri);
799 //ensures CSPACE-4042
800 protected void uriPointsToSameAuthority(String thisURI, String inboundItemURI) throws Exception {
801 String authorityCSID = extractInAuthorityCSID(thisURI);
802 String authorityCSIDForInbound = extractInAuthorityCSID(inboundItemURI);
803 if (Tools.isBlank(authorityCSID)
804 || Tools.isBlank(authorityCSIDForInbound)
805 || (!authorityCSID.equalsIgnoreCase(authorityCSIDForInbound))) {
806 throw new Exception("Item URI " + thisURI + " must point to same authority as related item: " + inboundItemURI);
810 public String getItemTermInfoGroupXPathBase() {
811 return authorityItemTermGroupXPathBase;
814 public void setItemTermInfoGroupXPathBase(String itemTermInfoGroupXPathBase) {
815 authorityItemTermGroupXPathBase = itemTermInfoGroupXPathBase;
818 protected String getAuthorityItemCommonSchemaName() {
819 return authorityItemCommonSchemaName;
823 public boolean isJDBCQuery() {
824 boolean result = false;
826 MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams();
828 // Look the query params to see if we need to make a SQL query.
830 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
831 if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
838 // By convention, the name of the database table that contains
839 // repeatable term information group records is derivable from
840 // an existing XPath base value, by removing a suffix and converting
842 protected String getTermGroupTableName() {
843 String termInfoGroupListName = getItemTermInfoGroupXPathBase();
844 return termInfoGroupListName.substring(0, termInfoGroupListName.lastIndexOf(LIST_SUFFIX)).toLowerCase();
847 protected String getInAuthorityValue() {
848 String inAuthorityValue = getInAuthority();
849 if (Tools.notBlank(inAuthorityValue)) {
850 return inAuthorityValue;
852 return AuthorityResource.PARENT_WILDCARD;
857 public Map<String,String> getJDBCQueryParams() {
858 // FIXME: Get all of the following values from appropriate external constants.
859 // At present, these are duplicated in both RepositoryClientImpl
860 // and in AuthorityItemDocumentModelHandler.
861 final String TERM_GROUP_LIST_NAME = "TERM_GROUP_LIST_NAME";
862 final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
863 final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
865 Map<String,String> params = super.getJDBCQueryParams();
866 params.put(TERM_GROUP_LIST_NAME, getItemTermInfoGroupXPathBase());
867 params.put(TERM_GROUP_TABLE_NAME_PARAM, getTermGroupTableName());
868 params.put(IN_AUTHORITY_PARAM, getInAuthorityValue());