2 * This document is a part of the source code and related artifacts
3 * for CollectionSpace, an open source collections management system
4 * for museums and related institutions:
6 * http://www.collectionspace.org
7 * http://wiki.collectionspace.org
9 * Copyright 2009 University of California at Berkeley
11 * Licensed under the Educational Community License (ECL), Version 2.0.
12 * You may not use this file except in compliance with this License.
14 * You may obtain a copy of the ECL 2.0 License at
16 * https://source.collectionspace.org/collection-space/LICENSE.txt
18 * Unless required by applicable law or agreed to in writing, software
19 * distributed under the License is distributed on an "AS IS" BASIS,
20 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21 * See the License for the specific language governing permissions and
22 * limitations under the License.
24 package org.collectionspace.services.common.vocabulary.nuxeo;
26 import org.collectionspace.services.client.AuthorityClient;
27 import org.collectionspace.services.client.IQueryManager;
28 import org.collectionspace.services.client.PoxPayloadIn;
29 import org.collectionspace.services.client.PoxPayloadOut;
30 import org.collectionspace.services.common.ResourceMap;
31 import org.collectionspace.services.common.UriTemplateRegistry;
32 import org.collectionspace.services.common.api.RefName;
33 import org.collectionspace.services.common.api.RefNameUtils;
34 import org.collectionspace.services.common.api.Tools;
35 import org.collectionspace.services.common.api.RefNameUtils.AuthorityInfo;
36 import org.collectionspace.services.common.authorityref.AuthorityRefDocList;
37 import org.collectionspace.services.common.context.MultipartServiceContext;
38 import org.collectionspace.services.common.context.ServiceContext;
39 import org.collectionspace.services.common.document.DocumentException;
40 import org.collectionspace.services.common.document.DocumentFilter;
41 import org.collectionspace.services.common.document.DocumentNotFoundException;
42 import org.collectionspace.services.common.document.DocumentWrapper;
43 import org.collectionspace.services.common.repository.RepositoryClient;
44 import org.collectionspace.services.common.vocabulary.AuthorityJAXBSchema;
45 import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema;
46 import org.collectionspace.services.common.vocabulary.AuthorityResource;
47 import org.collectionspace.services.common.vocabulary.AuthorityServiceUtils;
48 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils;
49 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.AuthorityItemSpecifier;
50 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.Specifier;
51 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.SpecifierForm;
52 import org.collectionspace.services.config.service.ListResultField;
53 import org.collectionspace.services.config.service.ObjectPartType;
54 import org.collectionspace.services.nuxeo.client.java.NuxeoDocumentModelHandler;
55 import org.collectionspace.services.nuxeo.client.java.CoreSessionInterface;
56 import org.collectionspace.services.nuxeo.client.java.RepositoryClientImpl;
57 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
58 import org.collectionspace.services.relation.RelationsCommonList;
59 import org.collectionspace.services.vocabulary.VocabularyItemJAXBSchema;
61 import org.nuxeo.ecm.core.api.ClientException;
62 import org.nuxeo.ecm.core.api.DocumentModel;
63 import org.nuxeo.ecm.core.api.model.PropertyException;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
67 import javax.ws.rs.core.MultivaluedMap;
69 import java.util.ArrayList;
70 import java.util.Collections;
71 import java.util.HashMap;
72 import java.util.List;
74 import java.util.regex.Matcher;
75 import java.util.regex.Pattern;
76 import java.util.regex.PatternSyntaxException;
78 //import org.collectionspace.services.common.authority.AuthorityItemRelations;
80 * AuthorityItemDocumentModelHandler
82 * $LastChangedRevision: $
85 public abstract class AuthorityItemDocumentModelHandler<AICommon>
86 extends NuxeoDocumentModelHandler<AICommon> {
88 private final Logger logger = LoggerFactory.getLogger(AuthorityItemDocumentModelHandler.class);
90 protected String authorityCommonSchemaName;
91 protected String authorityItemCommonSchemaName;
92 private String authorityItemTermGroupXPathBase;
93 private boolean shouldUpdateRevNumber = true; // by default we should update the revision number -not true on synchronization with SAS
95 * inVocabulary is the parent Authority for this context
97 protected String inAuthority = null;
98 protected boolean wildcardedAuthorityRequest = false;
99 protected String authorityRefNameBase = null;
100 // Used to determine when the displayName changes as part of the update.
101 protected String oldDisplayNameOnUpdate = null;
102 private final static String LIST_SUFFIX = "List";
103 private final static String ZERO_OR_MORE_ANY_CHAR_REGEX = ".*";
105 public AuthorityItemDocumentModelHandler(String authorityCommonSchemaName, String authorityItemCommonSchemaName) {
106 this.authorityItemCommonSchemaName = authorityItemCommonSchemaName;
109 abstract public String getParentCommonSchemaName();
111 public boolean getShouldUpdateRevNumber() {
112 return this.shouldUpdateRevNumber;
115 public void setShouldUpdateRevNumber(boolean flag) {
116 this.shouldUpdateRevNumber = flag;
120 public void prepareSync() throws Exception {
121 this.setShouldUpdateRevNumber(AuthorityServiceUtils.DONT_UPDATE_REV); // Never update rev nums on sync operations
125 protected String getRefnameDisplayName(DocumentWrapper<DocumentModel> docWrapper) {
126 String result = null;
128 DocumentModel docModel = docWrapper.getWrappedObject();
129 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = this.getServiceContext();
130 RefName.AuthorityItem refname = (RefName.AuthorityItem)getRefName(ctx, docModel);
131 result = refname.getDisplayName();
137 * After calling this method successfully, the document model will contain an updated refname and short ID
139 * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#getRefName(org.collectionspace.services.common.context.ServiceContext, org.nuxeo.ecm.core.api.DocumentModel)
142 public RefName.RefNameInterface getRefName(ServiceContext ctx,
143 DocumentModel docModel) {
144 RefName.RefNameInterface refname = null;
147 String displayName = getPrimaryDisplayName(docModel, authorityItemCommonSchemaName,
148 getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
149 if (Tools.isEmpty(displayName)) {
150 throw new Exception("The displayName for this authority term was empty or not set.");
153 String shortIdentifier = (String) docModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
154 if (Tools.isEmpty(shortIdentifier)) {
155 // We didn't find a short ID in the payload request, so we need to synthesize one.
156 shortIdentifier = handleDisplayNameAsShortIdentifier(docModel); // updates the document model with the new short ID as a side-effect
159 String authorityRefBaseName = getAuthorityRefNameBase();
160 if (Tools.isEmpty(authorityRefBaseName)) {
161 throw new Exception("Could not create the refName for this authority term, because the refName for its authority parent was empty.");
164 // Create the items refname using the parent's as a base
165 RefName.Authority parentsRefName = RefName.Authority.parse(authorityRefBaseName);
166 refname = RefName.buildAuthorityItem(parentsRefName, shortIdentifier, displayName);
167 // Now update the document model with the refname value
168 String refNameStr = refname.toString();
169 docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REF_NAME, refNameStr); // REM - This field is deprecated now that the refName is part of the collection_space core schema
171 } catch (Exception e) {
172 logger.error(e.getMessage(), e);
178 public void setInAuthority(String inAuthority) {
179 this.inAuthority = inAuthority;
182 public String getInAuthority() {
183 return this.inAuthority;
186 /** Subclasses may override this to customize the URI segment. */
187 public String getAuthorityServicePath() {
188 return getServiceContext().getServiceName().toLowerCase(); // Laramie20110510 CSPACE-3932
192 public String getUri(DocumentModel docModel) {
193 // Laramie20110510 CSPACE-3932
194 String authorityServicePath = getAuthorityServicePath();
195 if(inAuthority==null) { // Only true with the first document model received, on queries to wildcarded authorities
196 wildcardedAuthorityRequest = true;
198 // If this search crosses multiple authorities, get the inAuthority value
199 // from each record, rather than using the cached value from the first record
200 if(wildcardedAuthorityRequest) {
202 inAuthority = (String) docModel.getProperty(authorityItemCommonSchemaName,
203 AuthorityItemJAXBSchema.IN_AUTHORITY);
204 } catch (ClientException pe) {
205 throw new RuntimeException("Could not get parent specifier for item!");
208 return "/" + authorityServicePath + '/' + inAuthority + '/' + AuthorityClient.ITEMS + '/' + getCsid(docModel);
211 protected String getAuthorityRefNameBase() {
212 return this.authorityRefNameBase;
215 public void setAuthorityRefNameBase(String value) {
216 this.authorityRefNameBase = value;
220 * Note: the Vocabulary service's VocabularyItemDocumentModelHandler class overrides this method.
222 protected ListResultField getListResultsDisplayNameField() {
223 ListResultField result = new ListResultField();
224 // Per CSPACE-5132, the name of this element remains 'displayName'
225 // for backwards compatibility, although its value is obtained
226 // from the termDisplayName field.
228 // Update: this name is now being changed to 'termDisplayName', both
229 // because this is the actual field name and because the app layer
230 // work to convert over to this field is underway. Per Patrick, the
231 // app layer treats lists, in at least some context(s), as sparse record
232 // payloads, and thus fields in list results must all be present in
233 // (i.e. represent a strict subset of the fields in) record schemas.
237 // In CSPACE-5134, these list results will change substantially
238 // to return display names for both the preferred term and for
239 // each non-preferred term (if any).
240 result.setElement(AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
241 result.setXpath(NuxeoUtils.getPrimaryXPathPropertyName(
242 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_DISPLAY_NAME));
248 * Note: the Vocabulary service's VocabularyItemDocumentModelHandler class overrides this method.
250 protected ListResultField getListResultsTermStatusField() {
251 ListResultField result = new ListResultField();
253 result.setElement(AuthorityItemJAXBSchema.TERM_STATUS);
254 result.setXpath(NuxeoUtils.getPrimaryXPathPropertyName(
255 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_STATUS));
260 private boolean isTermDisplayName(String elName) {
261 return AuthorityItemJAXBSchema.TERM_DISPLAY_NAME.equals(elName) || VocabularyItemJAXBSchema.DISPLAY_NAME.equals(elName);
266 * @see org.collectionspace.services.nuxeo.client.java.DocHandlerBase#getListItemsArray()
268 * Note: We're updating the "global" service and tenant bindings instance here -the list instance here is
269 * a reference to the tenant bindings instance in the singleton ServiceMain.
272 public List<ListResultField> getListItemsArray() throws DocumentException {
273 List<ListResultField> list = super.getListItemsArray();
275 // One-time initialization for each authority item service.
276 if (isListItemArrayExtended() == false) {
277 synchronized(AuthorityItemDocumentModelHandler.class) {
278 if (isListItemArrayExtended() == false) {
279 int nFields = list.size();
280 // Ensure that each item in a list of Authority items includes
281 // a set of common fields, so we do not depend upon configuration
282 // for general logic.
283 List<Integer> termDisplayNamePositionsInList = new ArrayList<>();
284 boolean hasShortId = false;
285 boolean hasTermStatus = false;
286 for (int i = 0; i < nFields; i++) {
287 ListResultField field = list.get(i);
288 String elName = field.getElement();
289 if (isTermDisplayName(elName) == true) {
290 termDisplayNamePositionsInList.add(i);
291 } else if (AuthorityItemJAXBSchema.SHORT_IDENTIFIER.equals(elName)) {
293 } else if (AuthorityItemJAXBSchema.TERM_STATUS.equals(elName)) {
294 hasTermStatus = true;
298 ListResultField field;
300 // Certain fields in authority item list results
301 // are handled specially here
305 // Ignore (throw out) any configuration entries that
306 // specify how the termDisplayName field should be
307 // emitted in authority item lists. This field will
308 // be handled in a standardized manner (see block below).
309 if (termDisplayNamePositionsInList.isEmpty() == false) {
310 // Remove matching items starting at the end of the list
311 // and moving towards the start, so that reshuffling of
312 // list order doesn't alter the positions of earlier items
313 Collections.sort(termDisplayNamePositionsInList, Collections.reverseOrder());
314 for (int i : termDisplayNamePositionsInList) {
318 // termDisplayName values in authority item lists
319 // will be handled via code that emits display names
320 // for both the preferred term and all non-preferred
321 // terms (if any). The following is a placeholder
322 // entry that will trigger this code. See the
323 // getListResultValue() method in this class.
324 field = getListResultsDisplayNameField();
329 field = new ListResultField();
330 field.setElement(AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
331 field.setXpath(AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
336 if (!hasTermStatus) {
337 field = getListResultsTermStatusField();
343 setListItemArrayExtended(true);
344 } // end of synchronized block
351 * This method synchronizes/updates a single authority item resource.
354 public boolean handleSync(DocumentWrapper<Object> wrapDoc) throws Exception {
355 boolean result = false;
356 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
358 // Get the rev number of the local authority item so we can compare with rev number of shared authority
360 AuthorityItemSpecifier authorityItemSpecifier = (AuthorityItemSpecifier) wrapDoc.getWrappedObject();
361 DocumentModel itemDocModel = NuxeoUtils.getDocFromSpecifier(ctx, getRepositorySession(), getAuthorityItemCommonSchemaName(),
362 authorityItemSpecifier);
363 if (itemDocModel == null) {
364 throw new DocumentNotFoundException(String.format("Could not find authority item resource with CSID='%s'",
365 authorityItemSpecifier.getItemSpecifier().value));
367 Long localItemRev = (Long) NuxeoUtils.getProperyValue(itemDocModel, AuthorityItemJAXBSchema.REV);
368 String itemShortId = (String) NuxeoUtils.getProperyValue(itemDocModel, AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
370 // Now get the Authority (the parent) information
372 DocumentModel authorityDocModel = NuxeoUtils.getDocFromSpecifier(ctx, getRepositorySession(), authorityCommonSchemaName,
373 authorityItemSpecifier.getParentSpecifier());
374 String authorityShortId = (String) NuxeoUtils.getProperyValue(authorityDocModel, AuthorityJAXBSchema.SHORT_IDENTIFIER);
376 // Using the short IDs of the local authority and item, create URN specifiers to retrieve the SAS authority item
378 Specifier sasAuthoritySpecifier = new Specifier(SpecifierForm.URN_NAME, RefNameUtils.createShortIdRefName(authorityShortId));
379 Specifier sasItemSpecifier = new Specifier(SpecifierForm.URN_NAME, RefNameUtils.createShortIdRefName(itemShortId));
380 AuthorityItemSpecifier sasAuthorityItemSpecifier = new AuthorityItemSpecifier(sasAuthoritySpecifier, sasItemSpecifier);
381 // Get the shared authority server's copy
382 PoxPayloadIn sasPayloadIn = AuthorityServiceUtils.requestPayloadIn(sasAuthorityItemSpecifier,
383 getAuthorityServicePath(), getEntityResponseType());
384 Long sasRev = getRevision(sasPayloadIn);
386 // If the shared authority item is newer, update our local copy
388 if (sasRev > localItemRev) {
389 ResourceMap resourceMap = ctx.getResourceMap();
390 String resourceName = this.getAuthorityServicePath();
391 AuthorityResource authorityResource = (AuthorityResource) resourceMap.get(resourceName);
392 PoxPayloadOut payloadOut = authorityResource.updateAuthorityItem(ctx,
395 authorityDocModel.getName(), // parent's CSID
396 itemDocModel.getName(), // item's CSID
397 sasPayloadIn, // the payload from the SAS
398 AuthorityServiceUtils.DONT_UPDATE_REV); // don't update the parent's revision number
399 if (payloadOut != null) {
400 ctx.setOutput(payloadOut);
409 * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#handleCreate(org.collectionspace.services.common.document.DocumentWrapper)
412 public void handleCreate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
413 // first fill all the parts of the document, refname and short ID get set as well
414 super.handleCreate(wrapDoc);
415 // Ensure we have required fields set properly
416 handleInAuthority(wrapDoc.getWrappedObject());
420 * This method gets called after the primary update to an authority item has happened. If the authority item's refName
421 * has changed, then we need to updated all the records that use that refname with the new/updated version
424 * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#completeUpdate(org.collectionspace.services.common.document.DocumentWrapper)
426 public void completeUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
427 // Must call our super class' version first
428 super.completeUpdate(wrapDoc);
431 // Look for and update authority references with the updated refName
433 if (hasRefNameUpdate() == true) {
434 // We have work to do.
435 if (logger.isDebugEnabled()) {
436 final String EOL = System.getProperty("line.separator");
437 logger.debug("Need to find and update references to authority item." + EOL
438 + " Old refName" + oldRefNameOnUpdate + EOL
439 + " New refName" + newRefNameOnUpdate);
441 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
442 RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient = getRepositoryClient(ctx);
443 CoreSessionInterface repoSession = this.getRepositorySession();
445 // Update all the existing records that have a field with the old refName in it
446 int nUpdated = RefNameServiceUtils.updateAuthorityRefDocs(ctx, repoClient, repoSession,
447 oldRefNameOnUpdate, newRefNameOnUpdate, getRefPropName());
449 // Finished so log a message.
450 if (logger.isDebugEnabled()) {
451 logger.debug("Updated " + nUpdated + " instances of oldRefName to newRefName");
457 * Note that the Vocabulary service's document-model for items overrides this method.
459 protected String getPrimaryDisplayName(DocumentModel docModel, String schema,
460 String complexPropertyName, String fieldName) {
461 String result = null;
463 result = getStringValueInPrimaryRepeatingComplexProperty(docModel, schema, complexPropertyName, fieldName);
469 * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#handleUpdate(org.collectionspace.services.common.document.DocumentWrapper)
472 // 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.
474 public void handleUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
475 // Must call our super's version first, this updates the core schema and the relationship records to deal with possible refName changes/update
476 super.handleUpdate(wrapDoc);
477 if (this.hasRefNameUpdate() == true) {
478 DocumentModel docModel = wrapDoc.getWrappedObject();
479 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
483 public void fillAllParts(DocumentWrapper<DocumentModel> wrapDoc, Action action) throws Exception {
484 super.fillAllParts(wrapDoc, action);
486 // Update the record's revision number on both CREATE and UPDATE actions
488 if (this.getShouldUpdateRevNumber() == true) { // We won't update rev numbers on synchronization with SAS
489 updateRevNumbers(wrapDoc);
494 * Update the revision number of both the item and the item's parent.
498 protected void updateRevNumbers(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
499 DocumentModel documentModel = wrapDoc.getWrappedObject();
500 Long rev = (Long)documentModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REV);
506 documentModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REV, rev);
508 // Next, update the inAuthority (the parent's) rev number
510 DocumentModel inAuthorityDocModel = NuxeoUtils.getDocFromCsid(getServiceContext(), getRepositorySession(), getInAuthority());
511 Long parentRev = (Long)inAuthorityDocModel.getProperty(getParentCommonSchemaName(), AuthorityJAXBSchema.REV);
512 if (parentRev == null) {
513 parentRev = new Long(0);
516 inAuthorityDocModel.setProperty(getParentCommonSchemaName(), AuthorityJAXBSchema.REV, parentRev);
517 getRepositorySession().saveDocument(inAuthorityDocModel);
521 * If no short identifier was provided in the input payload, generate a
522 * short identifier from the preferred term display name or term name.
524 private String handleDisplayNameAsShortIdentifier(DocumentModel docModel) throws Exception {
525 String result = (String) docModel.getProperty(authorityItemCommonSchemaName,
526 AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
528 if (Tools.isEmpty(result)) {
529 String termDisplayName = getPrimaryDisplayName(
530 docModel, authorityItemCommonSchemaName,
531 getItemTermInfoGroupXPathBase(),
532 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
534 String termName = getPrimaryDisplayName(
535 docModel, authorityItemCommonSchemaName,
536 getItemTermInfoGroupXPathBase(),
537 AuthorityItemJAXBSchema.TERM_NAME);
539 String generatedShortIdentifier = AuthorityIdentifierUtils.generateShortIdentifierFromDisplayName(termDisplayName,
541 docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER,
542 generatedShortIdentifier);
543 result = generatedShortIdentifier;
550 * Generate a refName for the authority item from the short identifier
553 * All refNames for authority items are generated. If a client supplies
554 * a refName, it will be overwritten during create (per this method)
555 * or discarded during update (per filterReadOnlyPropertiesForPart).
557 * @see #filterReadOnlyPropertiesForPart(Map<String, Object>, org.collectionspace.services.common.service.ObjectPartType)
560 protected String updateRefnameForAuthorityItem(DocumentModel docModel,
561 String schemaName) throws Exception {
562 String result = null;
564 RefName.RefNameInterface refname = getRefName(getServiceContext(), docModel);
565 String refNameStr = refname.toString();
566 docModel.setProperty(schemaName, AuthorityItemJAXBSchema.REF_NAME, refNameStr);
573 * Check the logic around the parent pointer. Note that we only need do this on
574 * create, since we have logic to make this read-only on update.
578 * @throws Exception the exception
580 private void handleInAuthority(DocumentModel docModel) throws Exception {
581 if(inAuthority==null) { // Only happens on queries to wildcarded authorities
582 throw new IllegalStateException("Trying to Create an object with no inAuthority value!");
584 docModel.setProperty(authorityItemCommonSchemaName,
585 AuthorityItemJAXBSchema.IN_AUTHORITY, inAuthority);
588 public AuthorityRefDocList getReferencingObjects(
589 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
590 UriTemplateRegistry uriTemplateRegistry,
591 List<String> serviceTypes,
593 String itemcsid) throws Exception {
594 AuthorityRefDocList authRefDocList = null;
595 CoreSessionInterface repoSession = null;
596 boolean releaseRepoSession = false;
599 RepositoryClientImpl repoClient = (RepositoryClientImpl)this.getRepositoryClient(ctx);
600 repoSession = this.getRepositorySession();
601 if (repoSession == null) {
602 repoSession = repoClient.getRepositorySession(ctx);
603 releaseRepoSession = true;
605 DocumentFilter myFilter = getDocumentFilter();
608 DocumentWrapper<DocumentModel> wrapper = repoClient.getDoc(repoSession, ctx, itemcsid);
609 DocumentModel docModel = wrapper.getWrappedObject();
610 String refName = (String) NuxeoUtils.getProperyValue(docModel, AuthorityItemJAXBSchema.REF_NAME); //docModel.getPropertyValue(AuthorityItemJAXBSchema.REF_NAME);
611 authRefDocList = RefNameServiceUtils.getAuthorityRefDocs(
612 repoSession, ctx, uriTemplateRegistry, repoClient,
616 myFilter, true /*computeTotal*/);
617 } catch (PropertyException pe) {
619 } catch (DocumentException de) {
621 } catch (Exception e) {
622 if (logger.isDebugEnabled()) {
623 logger.debug("Caught exception ", e);
625 throw new DocumentException(e);
627 // If we got/aquired a new seesion then we're responsible for releasing it.
628 if (releaseRepoSession && repoSession != null) {
629 repoClient.releaseRepositorySession(ctx, repoSession);
632 } catch (Exception e) {
633 if (logger.isDebugEnabled()) {
634 logger.debug("Caught exception ", e);
636 throw new DocumentException(e);
639 return authRefDocList;
643 * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#extractPart(org.nuxeo.ecm.core.api.DocumentModel, java.lang.String, org.collectionspace.services.common.service.ObjectPartType)
646 protected Map<String, Object> extractPart(DocumentModel docModel, String schema, ObjectPartType partMeta)
648 Map<String, Object> unQObjectProperties = super.extractPart(docModel, schema, partMeta);
650 // Add the CSID to the common part, since they may have fetched via the shortId.
651 if (partMeta.getLabel().equalsIgnoreCase(authorityItemCommonSchemaName)) {
652 String csid = getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
653 unQObjectProperties.put("csid", csid);
656 return unQObjectProperties;
660 * Filters out selected values supplied in an update request.
662 * For example, filters out AuthorityItemJAXBSchema.IN_AUTHORITY, to ensure
663 * that the link to the item's parent remains untouched.
665 * @param objectProps the properties filtered out from the update payload
666 * @param partMeta metadata for the object to fill
669 public void filterReadOnlyPropertiesForPart(
670 Map<String, Object> objectProps, ObjectPartType partMeta) {
671 super.filterReadOnlyPropertiesForPart(objectProps, partMeta);
672 String commonPartLabel = getServiceContext().getCommonPartLabel();
673 if (partMeta.getLabel().equalsIgnoreCase(commonPartLabel)) {
674 objectProps.remove(AuthorityItemJAXBSchema.IN_AUTHORITY);
675 objectProps.remove(AuthorityItemJAXBSchema.CSID);
676 objectProps.remove(AuthorityJAXBSchema.SHORT_IDENTIFIER);
677 objectProps.remove(AuthorityItemJAXBSchema.REF_NAME);
682 * Returns the items in a list of term display names whose names contain
683 * a partial term (as might be submitted in a search query, for instance).
684 * @param termDisplayNameList a list of term display names.
685 * @param partialTerm a partial term display name; that is, a portion
686 * of a display name that might be expected to match 0-n terms in the list.
687 * @return a list of term display names that matches the partial term.
688 * Matches are case-insensitive. As well, before matching is performed, any
689 * special-purpose characters that may appear in the partial term (such as
690 * wildcards and anchor characters) are filtered out from both compared terms.
692 protected List<String> getPartialTermDisplayNameMatches(List<String> termDisplayNameList, String partialTerm) {
693 List<String> result = new ArrayList<>();
694 String partialTermMatchExpression = filterAnchorAndWildcardChars(partialTerm).toLowerCase();
696 for (String termDisplayName : termDisplayNameList) {
697 if (termDisplayName.toLowerCase()
698 .matches(partialTermMatchExpression) == true) {
699 result.add(termDisplayName);
702 } catch (PatternSyntaxException pse) {
703 logger.warn("Error in regex match pattern '%s' for term display names: %s",
704 partialTermMatchExpression, pse.getMessage());
710 * Filters user-supplied anchor and wildcard characters in a string,
711 * replacing them with equivalent regular expressions.
712 * @param term a term in which to filter anchor and wildcard characters.
713 * @return the term with those characters filtered.
715 protected String filterAnchorAndWildcardChars(String term) {
716 if (Tools.isBlank(term)) {
719 if (term.length() < 3) {
722 if (logger.isTraceEnabled()) {
723 logger.trace(String.format("Term = %s", term));
725 Boolean anchorAtStart = false;
726 Boolean anchorAtEnd = false;
728 StringBuilder filteredTermBuilder = new StringBuilder(term);
729 // Term contains no anchor or wildcard characters.
730 if ( (! term.contains(RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR))
731 && (! term.contains(RepositoryClientImpl.USER_SUPPLIED_WILDCARD)) ) {
734 // Term contains at least one such character.
736 // Filter the starting anchor or wildcard character, if any.
737 String firstChar = filteredTermBuilder.substring(0,1);
739 case RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR:
740 anchorAtStart = true;
742 case RepositoryClientImpl.USER_SUPPLIED_WILDCARD:
743 filteredTermBuilder.deleteCharAt(0);
746 if (logger.isTraceEnabled()) {
747 logger.trace(String.format("After first char filtering = %s", filteredTermBuilder.toString()));
749 // Filter the ending anchor or wildcard character, if any.
750 int lastPos = filteredTermBuilder.length() - 1;
751 String lastChar = filteredTermBuilder.substring(lastPos);
753 case RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR:
754 filteredTermBuilder.deleteCharAt(lastPos);
755 filteredTermBuilder.insert(filteredTermBuilder.length(), RepositoryClientImpl.ENDING_ANCHOR_CHAR);
758 case RepositoryClientImpl.USER_SUPPLIED_WILDCARD:
759 filteredTermBuilder.deleteCharAt(lastPos);
762 if (logger.isTraceEnabled()) {
763 logger.trace(String.format("After last char filtering = %s", filteredTermBuilder.toString()));
765 filteredTerm = filteredTermBuilder.toString();
766 // Filter all other wildcards, if any.
767 filteredTerm = filteredTerm.replaceAll(RepositoryClientImpl.USER_SUPPLIED_WILDCARD_REGEX, ZERO_OR_MORE_ANY_CHAR_REGEX);
768 if (logger.isTraceEnabled()) {
769 logger.trace(String.format("After replacing user wildcards = %s", filteredTerm));
771 } catch (Exception e) {
772 logger.warn(String.format("Error filtering anchor and wildcard characters from string: %s", e.getMessage()));
776 // Wrap the term in beginning and ending regex wildcards, unless a
777 // starting or ending anchor character was present.
778 return (anchorAtStart ? "" : ZERO_OR_MORE_ANY_CHAR_REGEX)
780 + (anchorAtEnd ? "" : ZERO_OR_MORE_ANY_CHAR_REGEX);
783 @SuppressWarnings("unchecked")
784 private List<String> getPartialTermDisplayNameMatches(DocumentModel docModel, // REM - CSPACE-5133
785 String schema, ListResultField field, String partialTerm) {
786 List<String> result = null;
788 String xpath = field.getXpath(); // results in something like "persons_common:personTermGroupList/[0]/termDisplayName"
789 int endOfTermGroup = xpath.lastIndexOf("/[0]/");
790 String propertyName = endOfTermGroup != -1 ? xpath.substring(0, endOfTermGroup) : xpath; // it may not be multivalued so the xpath passed in would be the property name
794 value = docModel.getProperty(schema, propertyName);
795 } catch (Exception e) {
796 logger.error("Could not extract term display name with property = "
800 if (value != null && value instanceof ArrayList) {
801 ArrayList<HashMap<String, Object>> termGroupList = (ArrayList<HashMap<String, Object>>)value;
802 int arrayListSize = termGroupList.size();
803 if (arrayListSize > 1) { // if there's only 1 element in the list then we've already matched the primary term's display name
804 List<String> displayNameList = new ArrayList<String>();
805 for (int i = 1; i < arrayListSize; i++) { // start at 1, skip the primary term's displayName since we will always return it
806 HashMap<String, Object> map = (HashMap<String, Object>)termGroupList.get(i);
807 String termDisplayName = (String) map.get(AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
808 displayNameList.add(i - 1, termDisplayName);
811 result = getPartialTermDisplayNameMatches(displayNameList, partialTerm);
819 protected Object getListResultValue(DocumentModel docModel, // REM - CSPACE-5133
820 String schema, ListResultField field) throws DocumentException {
821 Object result = null;
823 result = NuxeoUtils.getXPathValue(docModel, schema, field.getXpath());
826 // Special handling of list item values for authority items (only)
829 // If the list result field is the termDisplayName element,
830 // check whether a partial term matching query was made.
831 // If it was, emit values for both the preferred (aka primary)
832 // term and for all non-preferred terms, if any.
834 String elName = field.getElement();
835 if (isTermDisplayName(elName) == true) {
836 MultivaluedMap<String, String> queryParams = this.getServiceContext().getQueryParams();
837 String partialTerm = queryParams != null ? queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM) : null;
838 if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
839 String primaryTermDisplayName = (String)result;
840 List<String> matches = getPartialTermDisplayNameMatches(docModel, schema, field, partialTerm);
841 if (matches != null && matches.isEmpty() == false) {
842 matches.add(0, primaryTermDisplayName); // insert the primary term's display name at the beginning of the list
843 result = matches; // set the result to a list of matching term display names with the primary term's display name at the beginning
852 public void extractAllParts(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
853 MultipartServiceContext ctx = (MultipartServiceContext) getServiceContext();
854 super.extractAllParts(wrapDoc);
857 protected List<RelationsCommonList.RelationListItem> cloneList(List<RelationsCommonList.RelationListItem> inboundList) {
858 List<RelationsCommonList.RelationListItem> result = newRelationsCommonList();
859 for (RelationsCommonList.RelationListItem item : inboundList) {
866 /* don't even THINK of re-using this method.
867 * String example_uri = "/locationauthorities/7ec60f01-84ab-4908-9a6a/items/a5466530-713f-43b4-bc05";
870 private String extractInAuthorityCSID(String uri) {
871 String IN_AUTHORITY_REGEX = "/(.*?)/(.*?)/(.*)";
872 Pattern p = Pattern.compile(IN_AUTHORITY_REGEX);
873 Matcher m = p.matcher(uri);
875 if (m.groupCount() < 3) {
876 logger.warn("REGEX-WRONG-GROUPCOUNT looking in " + uri);
879 //String service = m.group(1);
880 String inauth = m.group(2);
881 //String theRest = m.group(3);
883 //print("service:"+service+", inauth:"+inauth+", rest:"+rest);
886 logger.warn("REGEX-NOT-MATCHED looking in " + uri);
891 //ensures CSPACE-4042
892 protected void uriPointsToSameAuthority(String thisURI, String inboundItemURI) throws Exception {
893 String authorityCSID = extractInAuthorityCSID(thisURI);
894 String authorityCSIDForInbound = extractInAuthorityCSID(inboundItemURI);
895 if (Tools.isBlank(authorityCSID)
896 || Tools.isBlank(authorityCSIDForInbound)
897 || (!authorityCSID.equalsIgnoreCase(authorityCSIDForInbound))) {
898 throw new Exception("Item URI " + thisURI + " must point to same authority as related item: " + inboundItemURI);
902 public String getItemTermInfoGroupXPathBase() {
903 return authorityItemTermGroupXPathBase;
906 public void setItemTermInfoGroupXPathBase(String itemTermInfoGroupXPathBase) {
907 authorityItemTermGroupXPathBase = itemTermInfoGroupXPathBase;
910 protected String getAuthorityItemCommonSchemaName() {
911 return authorityItemCommonSchemaName;
915 public boolean isJDBCQuery() {
916 boolean result = false;
918 MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams();
920 // Look the query params to see if we need to make a SQL query.
922 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
923 if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
930 // By convention, the name of the database table that contains
931 // repeatable term information group records is derivable from
932 // an existing XPath base value, by removing a suffix and converting
934 protected String getTermGroupTableName() {
935 String termInfoGroupListName = getItemTermInfoGroupXPathBase();
936 return termInfoGroupListName.substring(0, termInfoGroupListName.lastIndexOf(LIST_SUFFIX)).toLowerCase();
939 protected String getInAuthorityValue() {
940 String inAuthorityValue = getInAuthority();
941 if (Tools.notBlank(inAuthorityValue)) {
942 return inAuthorityValue;
944 return AuthorityResource.PARENT_WILDCARD;
949 public Map<String,String> getJDBCQueryParams() {
950 // FIXME: Get all of the following values from appropriate external constants.
951 // At present, these are duplicated in both RepositoryClientImpl
952 // and in AuthorityItemDocumentModelHandler.
953 final String TERM_GROUP_LIST_NAME = "TERM_GROUP_LIST_NAME";
954 final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
955 final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
957 Map<String,String> params = super.getJDBCQueryParams();
958 params.put(TERM_GROUP_LIST_NAME, getItemTermInfoGroupXPathBase());
959 params.put(TERM_GROUP_TABLE_NAME_PARAM, getTermGroupTableName());
960 params.put(IN_AUTHORITY_PARAM, getInAuthorityValue());