2 * This document is a part of the source code and related artifacts
3 * for CollectionSpace, an open source collections management system
4 * for museums and related institutions:
6 * http://www.collectionspace.org
7 * http://wiki.collectionspace.org
9 * Copyright 2009 University of California at Berkeley
11 * Licensed under the Educational Community License (ECL), Version 2.0.
12 * You may not use this file except in compliance with this License.
14 * You may obtain a copy of the ECL 2.0 License at
16 * https://source.collectionspace.org/collection-space/LICENSE.txt
18 * Unless required by applicable law or agreed to in writing, software
19 * distributed under the License is distributed on an "AS IS" BASIS,
20 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21 * See the License for the specific language governing permissions and
22 * limitations under the License.
24 package org.collectionspace.services.common.vocabulary.nuxeo;
26 import org.collectionspace.services.client.AuthorityClient;
27 import org.collectionspace.services.client.IQueryManager;
28 import org.collectionspace.services.client.PoxPayloadIn;
29 import org.collectionspace.services.client.PoxPayloadOut;
30 import org.collectionspace.services.common.ResourceMap;
31 import org.collectionspace.services.common.UriTemplateRegistry;
32 import org.collectionspace.services.common.api.RefName;
33 import org.collectionspace.services.common.api.RefNameUtils;
34 import org.collectionspace.services.common.api.RefNameUtils.AuthorityTermInfo;
35 import org.collectionspace.services.common.api.Tools;
36 import org.collectionspace.services.common.api.RefNameUtils.AuthorityInfo;
37 import org.collectionspace.services.common.authorityref.AuthorityRefDocList;
38 import org.collectionspace.services.common.context.MultipartServiceContext;
39 import org.collectionspace.services.common.context.MultipartServiceContextImpl;
40 import org.collectionspace.services.common.context.ServiceContext;
41 import org.collectionspace.services.common.document.DocumentException;
42 import org.collectionspace.services.common.document.DocumentFilter;
43 import org.collectionspace.services.common.document.DocumentNotFoundException;
44 import org.collectionspace.services.common.document.DocumentWrapper;
45 import org.collectionspace.services.common.document.DocumentHandler.Action;
46 import org.collectionspace.services.common.repository.RepositoryClient;
47 import org.collectionspace.services.common.vocabulary.AuthorityJAXBSchema;
48 import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema;
49 import org.collectionspace.services.common.vocabulary.AuthorityResource;
50 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils;
51 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.AuthorityItemSpecifier;
52 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.Specifier;
53 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.SpecifierForm;
54 import org.collectionspace.services.config.service.ListResultField;
55 import org.collectionspace.services.config.service.ObjectPartType;
56 import org.collectionspace.services.nuxeo.client.java.NuxeoDocumentModelHandler;
57 import org.collectionspace.services.nuxeo.client.java.CoreSessionInterface;
58 import org.collectionspace.services.nuxeo.client.java.RepositoryClientImpl;
59 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
60 import org.collectionspace.services.relation.RelationsCommonList;
61 import org.collectionspace.services.vocabulary.VocabularyItemJAXBSchema;
62 import org.nuxeo.ecm.core.api.ClientException;
63 import org.nuxeo.ecm.core.api.DocumentModel;
64 import org.nuxeo.ecm.core.api.model.PropertyException;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
68 import javax.ws.rs.core.MultivaluedMap;
69 import javax.ws.rs.core.Response;
71 import java.util.ArrayList;
72 import java.util.Collections;
73 import java.util.HashMap;
74 import java.util.List;
76 import java.util.regex.Matcher;
77 import java.util.regex.Pattern;
78 import java.util.regex.PatternSyntaxException;
80 //import org.collectionspace.services.common.authority.AuthorityItemRelations;
82 * AuthorityItemDocumentModelHandler
84 * $LastChangedRevision: $
87 public abstract class AuthorityItemDocumentModelHandler<AICommon>
88 extends NuxeoDocumentModelHandler<AICommon> {
90 private final Logger logger = LoggerFactory.getLogger(AuthorityItemDocumentModelHandler.class);
92 protected String authorityCommonSchemaName;
93 protected String authorityItemCommonSchemaName;
94 private String authorityItemTermGroupXPathBase;
95 private boolean shouldUpdateParentRevNumber = true;
97 * inVocabulary is the parent Authority for this context
99 protected String inAuthority = null;
100 protected boolean wildcardedAuthorityRequest = false;
101 protected String authorityRefNameBase = null;
102 // Used to determine when the displayName changes as part of the update.
103 protected String oldDisplayNameOnUpdate = null;
104 private final static String LIST_SUFFIX = "List";
105 private final static String ZERO_OR_MORE_ANY_CHAR_REGEX = ".*";
107 public AuthorityItemDocumentModelHandler(String authorityCommonSchemaName, String authorityItemCommonSchemaName) {
108 this.authorityItemCommonSchemaName = authorityItemCommonSchemaName;
111 abstract public String getParentCommonSchemaName();
113 public boolean getShouldUpdateParentRevNumber() {
114 return this.shouldUpdateParentRevNumber;
117 public void setShouldUpdateParentRevNumber(boolean flag) {
118 this.shouldUpdateParentRevNumber = flag;
122 protected String getRefnameDisplayName(DocumentWrapper<DocumentModel> docWrapper) {
123 String result = null;
125 DocumentModel docModel = docWrapper.getWrappedObject();
126 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = this.getServiceContext();
127 RefName.AuthorityItem refname = (RefName.AuthorityItem)getRefName(ctx, docModel);
128 result = refname.getDisplayName();
134 * After calling this method successfully, the document model will contain an updated refname and short ID
136 * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#getRefName(org.collectionspace.services.common.context.ServiceContext, org.nuxeo.ecm.core.api.DocumentModel)
139 public RefName.RefNameInterface getRefName(ServiceContext ctx,
140 DocumentModel docModel) {
141 RefName.RefNameInterface refname = null;
144 String displayName = getPrimaryDisplayName(docModel, authorityItemCommonSchemaName,
145 getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
146 if (Tools.isEmpty(displayName)) {
147 throw new Exception("The displayName for this authority term was empty or not set.");
150 String shortIdentifier = (String) docModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
151 if (Tools.isEmpty(shortIdentifier)) {
152 // We didn't find a short ID in the payload request, so we need to synthesize one.
153 shortIdentifier = handleDisplayNameAsShortIdentifier(docModel); // updates the document model with the new short ID as a side-effect
156 String authorityRefBaseName = getAuthorityRefNameBase();
157 if (Tools.isEmpty(authorityRefBaseName)) {
158 throw new Exception("Could not create the refName for this authority term, because the refName for its authority parent was empty.");
161 // Create the items refname using the parent's as a base
162 RefName.Authority parentsRefName = RefName.Authority.parse(authorityRefBaseName);
163 refname = RefName.buildAuthorityItem(parentsRefName, shortIdentifier, displayName);
164 // Now update the document model with the refname value
165 String refNameStr = refname.toString();
166 docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REF_NAME, refNameStr); // REM - This field is deprecated now that the refName is part of the collection_space core schema
168 } catch (Exception e) {
169 logger.error(e.getMessage(), e);
175 public void setInAuthority(String inAuthority) {
176 this.inAuthority = inAuthority;
179 public String getInAuthority() {
180 return this.inAuthority;
183 /** Subclasses may override this to customize the URI segment. */
184 public String getAuthorityServicePath() {
185 return getServiceContext().getServiceName().toLowerCase(); // Laramie20110510 CSPACE-3932
189 public String getUri(DocumentModel docModel) {
190 // Laramie20110510 CSPACE-3932
191 String authorityServicePath = getAuthorityServicePath();
192 if(inAuthority==null) { // Only true with the first document model received, on queries to wildcarded authorities
193 wildcardedAuthorityRequest = true;
195 // If this search crosses multiple authorities, get the inAuthority value
196 // from each record, rather than using the cached value from the first record
197 if(wildcardedAuthorityRequest) {
199 inAuthority = (String) docModel.getProperty(authorityItemCommonSchemaName,
200 AuthorityItemJAXBSchema.IN_AUTHORITY);
201 } catch (ClientException pe) {
202 throw new RuntimeException("Could not get parent specifier for item!");
205 return "/" + authorityServicePath + '/' + inAuthority + '/' + AuthorityClient.ITEMS + '/' + getCsid(docModel);
208 protected String getAuthorityRefNameBase() {
209 return this.authorityRefNameBase;
212 public void setAuthorityRefNameBase(String value) {
213 this.authorityRefNameBase = value;
217 * Note: the Vocabulary service's VocabularyItemDocumentModelHandler class overrides this method.
219 protected ListResultField getListResultsDisplayNameField() {
220 ListResultField result = new ListResultField();
221 // Per CSPACE-5132, the name of this element remains 'displayName'
222 // for backwards compatibility, although its value is obtained
223 // from the termDisplayName field.
225 // Update: this name is now being changed to 'termDisplayName', both
226 // because this is the actual field name and because the app layer
227 // work to convert over to this field is underway. Per Patrick, the
228 // app layer treats lists, in at least some context(s), as sparse record
229 // payloads, and thus fields in list results must all be present in
230 // (i.e. represent a strict subset of the fields in) record schemas.
234 // In CSPACE-5134, these list results will change substantially
235 // to return display names for both the preferred term and for
236 // each non-preferred term (if any).
237 result.setElement(AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
238 result.setXpath(NuxeoUtils.getPrimaryXPathPropertyName(
239 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_DISPLAY_NAME));
245 * Note: the Vocabulary service's VocabularyItemDocumentModelHandler class overrides this method.
247 protected ListResultField getListResultsTermStatusField() {
248 ListResultField result = new ListResultField();
250 result.setElement(AuthorityItemJAXBSchema.TERM_STATUS);
251 result.setXpath(NuxeoUtils.getPrimaryXPathPropertyName(
252 authorityItemCommonSchemaName, getItemTermInfoGroupXPathBase(), AuthorityItemJAXBSchema.TERM_STATUS));
257 private boolean isTermDisplayName(String elName) {
258 return AuthorityItemJAXBSchema.TERM_DISPLAY_NAME.equals(elName) || VocabularyItemJAXBSchema.DISPLAY_NAME.equals(elName);
263 * @see org.collectionspace.services.nuxeo.client.java.DocHandlerBase#getListItemsArray()
265 * Note: We're updating the "global" service and tenant bindings instance here -the list instance here is
266 * a reference to the tenant bindings instance in the singleton ServiceMain.
269 public List<ListResultField> getListItemsArray() throws DocumentException {
270 List<ListResultField> list = super.getListItemsArray();
272 // One-time initialization for each authority item service.
273 if (isListItemArrayExtended() == false) {
274 synchronized(AuthorityItemDocumentModelHandler.class) {
275 if (isListItemArrayExtended() == false) {
276 int nFields = list.size();
277 // Ensure that each item in a list of Authority items includes
278 // a set of common fields, so we do not depend upon configuration
279 // for general logic.
280 List<Integer> termDisplayNamePositionsInList = new ArrayList<>();
281 boolean hasShortId = false;
282 boolean hasTermStatus = false;
283 for (int i = 0; i < nFields; i++) {
284 ListResultField field = list.get(i);
285 String elName = field.getElement();
286 if (isTermDisplayName(elName) == true) {
287 termDisplayNamePositionsInList.add(i);
288 } else if (AuthorityItemJAXBSchema.SHORT_IDENTIFIER.equals(elName)) {
290 } else if (AuthorityItemJAXBSchema.TERM_STATUS.equals(elName)) {
291 hasTermStatus = true;
295 ListResultField field;
297 // Certain fields in authority item list results
298 // are handled specially here
302 // Ignore (throw out) any configuration entries that
303 // specify how the termDisplayName field should be
304 // emitted in authority item lists. This field will
305 // be handled in a standardized manner (see block below).
306 if (termDisplayNamePositionsInList.isEmpty() == false) {
307 // Remove matching items starting at the end of the list
308 // and moving towards the start, so that reshuffling of
309 // list order doesn't alter the positions of earlier items
310 Collections.sort(termDisplayNamePositionsInList, Collections.reverseOrder());
311 for (int i : termDisplayNamePositionsInList) {
315 // termDisplayName values in authority item lists
316 // will be handled via code that emits display names
317 // for both the preferred term and all non-preferred
318 // terms (if any). The following is a placeholder
319 // entry that will trigger this code. See the
320 // getListResultValue() method in this class.
321 field = getListResultsDisplayNameField();
326 field = new ListResultField();
327 field.setElement(AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
328 field.setXpath(AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
333 if (!hasTermStatus) {
334 field = getListResultsTermStatusField();
340 setListItemArrayExtended(true);
341 } // end of synchronized block
347 // private PoxPayloadIn getPayloadIn(AuthorityItemSpecifier specifier) throws Exception {
348 // PoxPayloadIn result = null;
350 // ServiceContext parentCtx = new MultipartServiceContextImpl(this.getAuthorityServicePath());
351 // AuthorityClient client = (AuthorityClient) parentCtx.getClient();
352 // Response res = client.readItem(specifier.getParentSpecifier().value, specifier.getItemSpecifier().value);
354 // int statusCode = res.getStatus();
356 // // Check the status code of the response: does it match
357 // // the expected response(s)?
358 // if (logger.isDebugEnabled()) {
359 // logger.debug(client.getClass().getCanonicalName() + ": status = " + statusCode);
362 // result = new PoxPayloadIn((String)res.readEntity(getEntityResponseType())); // Get the entire response!
371 public boolean handleSync(DocumentWrapper<Object> wrapDoc) throws Exception {
372 boolean result = false;
373 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
374 AuthorityItemSpecifier authorityItemSpecifier = (AuthorityItemSpecifier) wrapDoc.getWrappedObject();
376 // Get the rev number of the authority item so we can compare with rev number of shared authority
378 DocumentModel itemDocModel = NuxeoUtils.getDocFromSpecifier(ctx, getRepositorySession(), getAuthorityItemCommonSchemaName(),
379 authorityItemSpecifier.getItemSpecifier());
380 if (itemDocModel == null) {
381 throw new DocumentNotFoundException(String.format("Could not find authority item resource with CSID='%s'",
382 authorityItemSpecifier.getItemSpecifier().value));
384 Long itemRev = (Long) NuxeoUtils.getProperyValue(itemDocModel, AuthorityItemJAXBSchema.REV);
385 String itemShortId = (String) NuxeoUtils.getProperyValue(itemDocModel, AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
386 String itemRefName = (String) NuxeoUtils.getProperyValue(itemDocModel, AuthorityItemJAXBSchema.REF_NAME);
388 // Now get the Authority (the parent) information
390 DocumentModel authorityDocModel = NuxeoUtils.getDocFromSpecifier(ctx, getRepositorySession(), authorityCommonSchemaName,
391 authorityItemSpecifier.getParentSpecifier());
392 Long authorityRev = (Long) NuxeoUtils.getProperyValue(authorityDocModel, AuthorityJAXBSchema.REV);
393 String authorityShortId = (String) NuxeoUtils.getProperyValue(authorityDocModel, AuthorityJAXBSchema.SHORT_IDENTIFIER);
394 String authorityRefName = (String) NuxeoUtils.getProperyValue(authorityDocModel, AuthorityJAXBSchema.REF_NAME);
395 AuthorityInfo authorityInfo = RefNameUtils.parseAuthorityInfo(authorityRefName);
397 // Using the short IDs of the local authority and item, create URN specifiers to retrieve the SAS authority item
399 Specifier sasAuthoritySpecifier = new Specifier(SpecifierForm.URN_NAME, RefNameUtils.createShortIdRefName(authorityShortId));
400 Specifier sasItemSpecifier = new Specifier(SpecifierForm.URN_NAME, RefNameUtils.createShortIdRefName(itemShortId));
401 AuthorityItemSpecifier sasAuthorityItemSpecifier = new AuthorityItemSpecifier(sasAuthoritySpecifier, sasItemSpecifier);
402 // Get the shared authority server's copy
403 PoxPayloadIn sasPayloadIn = AuthorityServiceUtils.getPayloadIn(sasAuthorityItemSpecifier,
404 getAuthorityServicePath(), getEntityResponseType());
406 Long sasRev = getRevision(sasPayloadIn);
407 if (sasRev > itemRev) {
408 ResourceMap resourceMap = ctx.getResourceMap();
409 String resourceName = this.getAuthorityServicePath();
410 AuthorityResource authorityResource = (AuthorityResource) resourceMap.get(resourceName);
411 PoxPayloadOut payloadOut = authorityResource.updateAuthorityItem(ctx,
414 authorityDocModel.getName(), // parent's CSID
415 itemDocModel.getName(), // item's CSID
416 sasPayloadIn, // the payload from the SAS
417 false); // don't update the parent's revision number
418 if (payloadOut != null) {
419 ctx.setOutput(payloadOut);
428 * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#handleCreate(org.collectionspace.services.common.document.DocumentWrapper)
431 public void handleCreate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
432 // first fill all the parts of the document, refname and short ID get set as well
433 super.handleCreate(wrapDoc);
434 // Ensure we have required fields set properly
435 handleInAuthority(wrapDoc.getWrappedObject());
439 * This method gets called after the primary update to an authority item has happened. If the authority item's refName
440 * has changed, then we need to updated all the records that use that refname with the new/updated version
443 * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#completeUpdate(org.collectionspace.services.common.document.DocumentWrapper)
445 public void completeUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
446 // Must call our super class' version first
447 super.completeUpdate(wrapDoc);
450 // Look for and update authority references with the updated refName
452 if (hasRefNameUpdate() == true) {
453 // We have work to do.
454 if (logger.isDebugEnabled()) {
455 final String EOL = System.getProperty("line.separator");
456 logger.debug("Need to find and update references to authority item." + EOL
457 + " Old refName" + oldRefNameOnUpdate + EOL
458 + " New refName" + newRefNameOnUpdate);
460 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = getServiceContext();
461 RepositoryClient<PoxPayloadIn, PoxPayloadOut> repoClient = getRepositoryClient(ctx);
462 CoreSessionInterface repoSession = this.getRepositorySession();
464 // Update all the existing records that have a field with the old refName in it
465 int nUpdated = RefNameServiceUtils.updateAuthorityRefDocs(ctx, repoClient, repoSession,
466 oldRefNameOnUpdate, newRefNameOnUpdate, getRefPropName());
468 // Finished so log a message.
469 if (logger.isDebugEnabled()) {
470 logger.debug("Updated " + nUpdated + " instances of oldRefName to newRefName");
476 * Note that the Vocabulary service's document-model for items overrides this method.
478 protected String getPrimaryDisplayName(DocumentModel docModel, String schema,
479 String complexPropertyName, String fieldName) {
480 String result = null;
482 result = getStringValueInPrimaryRepeatingComplexProperty(docModel, schema, complexPropertyName, fieldName);
488 * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#handleUpdate(org.collectionspace.services.common.document.DocumentWrapper)
491 // FIXME: Once we remove the refName field from the authority item schemas, we can remove this override method since our super does everthing for us now.
493 public void handleUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
494 // Must call our super's version first, this updates the core schema and the relationship records to deal with possible refName changes/update
495 super.handleUpdate(wrapDoc);
496 if (this.hasRefNameUpdate() == true) {
497 DocumentModel docModel = wrapDoc.getWrappedObject();
498 docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REF_NAME, this.newRefNameOnUpdate); // This field is deprecated since it is now a duplicate of what is in the collectionspace_core:refName field
502 public void fillAllParts(DocumentWrapper<DocumentModel> wrapDoc, Action action) throws Exception {
503 super.fillAllParts(wrapDoc, action);
505 // Update the record's revision number on both CREATE and UPDATE actions
507 updateRevNumbers(wrapDoc);
510 protected void updateRevNumbers(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
511 DocumentModel documentModel = wrapDoc.getWrappedObject();
512 Long rev = (Long)documentModel.getProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REV);
518 documentModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.REV, rev);
520 // Next, update the inAuthority (the parent's) rev number
522 if (this.shouldUpdateParentRevNumber == true) {
523 DocumentModel inAuthorityDocModel = NuxeoUtils.getDocFromCsid(getServiceContext(), getRepositorySession(), getInAuthority());
524 Long parentRev = (Long)inAuthorityDocModel.getProperty(getParentCommonSchemaName(), AuthorityJAXBSchema.REV);
525 if (parentRev == null) {
526 parentRev = new Long(0);
529 inAuthorityDocModel.setProperty(getParentCommonSchemaName(), AuthorityJAXBSchema.REV, parentRev);
530 getRepositorySession().saveDocument(inAuthorityDocModel);
535 * If no short identifier was provided in the input payload, generate a
536 * short identifier from the preferred term display name or term name.
538 private String handleDisplayNameAsShortIdentifier(DocumentModel docModel) throws Exception {
539 String result = (String) docModel.getProperty(authorityItemCommonSchemaName,
540 AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
542 if (Tools.isEmpty(result)) {
543 String termDisplayName = getPrimaryDisplayName(
544 docModel, authorityItemCommonSchemaName,
545 getItemTermInfoGroupXPathBase(),
546 AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
548 String termName = getPrimaryDisplayName(
549 docModel, authorityItemCommonSchemaName,
550 getItemTermInfoGroupXPathBase(),
551 AuthorityItemJAXBSchema.TERM_NAME);
553 String generatedShortIdentifier = AuthorityIdentifierUtils.generateShortIdentifierFromDisplayName(termDisplayName,
555 docModel.setProperty(authorityItemCommonSchemaName, AuthorityItemJAXBSchema.SHORT_IDENTIFIER,
556 generatedShortIdentifier);
557 result = generatedShortIdentifier;
564 * Generate a refName for the authority item from the short identifier
567 * All refNames for authority items are generated. If a client supplies
568 * a refName, it will be overwritten during create (per this method)
569 * or discarded during update (per filterReadOnlyPropertiesForPart).
571 * @see #filterReadOnlyPropertiesForPart(Map<String, Object>, org.collectionspace.services.common.service.ObjectPartType)
574 protected String updateRefnameForAuthorityItem(DocumentModel docModel,
575 String schemaName) throws Exception {
576 String result = null;
578 RefName.RefNameInterface refname = getRefName(getServiceContext(), docModel);
579 String refNameStr = refname.toString();
580 docModel.setProperty(schemaName, AuthorityItemJAXBSchema.REF_NAME, refNameStr);
587 * Check the logic around the parent pointer. Note that we only need do this on
588 * create, since we have logic to make this read-only on update.
592 * @throws Exception the exception
594 private void handleInAuthority(DocumentModel docModel) throws Exception {
595 if(inAuthority==null) { // Only happens on queries to wildcarded authorities
596 throw new IllegalStateException("Trying to Create an object with no inAuthority value!");
598 docModel.setProperty(authorityItemCommonSchemaName,
599 AuthorityItemJAXBSchema.IN_AUTHORITY, inAuthority);
602 public AuthorityRefDocList getReferencingObjects(
603 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
604 UriTemplateRegistry uriTemplateRegistry,
605 List<String> serviceTypes,
607 String itemcsid) throws Exception {
608 AuthorityRefDocList authRefDocList = null;
609 CoreSessionInterface repoSession = null;
610 boolean releaseRepoSession = false;
613 RepositoryClientImpl repoClient = (RepositoryClientImpl)this.getRepositoryClient(ctx);
614 repoSession = this.getRepositorySession();
615 if (repoSession == null) {
616 repoSession = repoClient.getRepositorySession(ctx);
617 releaseRepoSession = true;
619 DocumentFilter myFilter = getDocumentFilter();
622 DocumentWrapper<DocumentModel> wrapper = repoClient.getDoc(repoSession, ctx, itemcsid);
623 DocumentModel docModel = wrapper.getWrappedObject();
624 String refName = (String) NuxeoUtils.getProperyValue(docModel, AuthorityItemJAXBSchema.REF_NAME); //docModel.getPropertyValue(AuthorityItemJAXBSchema.REF_NAME);
625 authRefDocList = RefNameServiceUtils.getAuthorityRefDocs(
626 repoSession, ctx, uriTemplateRegistry, repoClient,
630 myFilter, true /*computeTotal*/);
631 } catch (PropertyException pe) {
633 } catch (DocumentException de) {
635 } catch (Exception e) {
636 if (logger.isDebugEnabled()) {
637 logger.debug("Caught exception ", e);
639 throw new DocumentException(e);
641 // If we got/aquired a new seesion then we're responsible for releasing it.
642 if (releaseRepoSession && repoSession != null) {
643 repoClient.releaseRepositorySession(ctx, repoSession);
646 } catch (Exception e) {
647 if (logger.isDebugEnabled()) {
648 logger.debug("Caught exception ", e);
650 throw new DocumentException(e);
653 return authRefDocList;
657 * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#extractPart(org.nuxeo.ecm.core.api.DocumentModel, java.lang.String, org.collectionspace.services.common.service.ObjectPartType)
660 protected Map<String, Object> extractPart(DocumentModel docModel, String schema, ObjectPartType partMeta)
662 Map<String, Object> unQObjectProperties = super.extractPart(docModel, schema, partMeta);
664 // Add the CSID to the common part, since they may have fetched via the shortId.
665 if (partMeta.getLabel().equalsIgnoreCase(authorityItemCommonSchemaName)) {
666 String csid = getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
667 unQObjectProperties.put("csid", csid);
670 return unQObjectProperties;
674 * Filters out selected values supplied in an update request.
676 * For example, filters out AuthorityItemJAXBSchema.IN_AUTHORITY, to ensure
677 * that the link to the item's parent remains untouched.
679 * @param objectProps the properties filtered out from the update payload
680 * @param partMeta metadata for the object to fill
683 public void filterReadOnlyPropertiesForPart(
684 Map<String, Object> objectProps, ObjectPartType partMeta) {
685 super.filterReadOnlyPropertiesForPart(objectProps, partMeta);
686 String commonPartLabel = getServiceContext().getCommonPartLabel();
687 if (partMeta.getLabel().equalsIgnoreCase(commonPartLabel)) {
688 objectProps.remove(AuthorityItemJAXBSchema.IN_AUTHORITY);
689 objectProps.remove(AuthorityItemJAXBSchema.CSID);
690 objectProps.remove(AuthorityJAXBSchema.SHORT_IDENTIFIER);
691 objectProps.remove(AuthorityItemJAXBSchema.REF_NAME);
696 * Returns the items in a list of term display names whose names contain
697 * a partial term (as might be submitted in a search query, for instance).
698 * @param termDisplayNameList a list of term display names.
699 * @param partialTerm a partial term display name; that is, a portion
700 * of a display name that might be expected to match 0-n terms in the list.
701 * @return a list of term display names that matches the partial term.
702 * Matches are case-insensitive. As well, before matching is performed, any
703 * special-purpose characters that may appear in the partial term (such as
704 * wildcards and anchor characters) are filtered out from both compared terms.
706 protected List<String> getPartialTermDisplayNameMatches(List<String> termDisplayNameList, String partialTerm) {
707 List<String> result = new ArrayList<>();
708 String partialTermMatchExpression = filterAnchorAndWildcardChars(partialTerm).toLowerCase();
710 for (String termDisplayName : termDisplayNameList) {
711 if (termDisplayName.toLowerCase()
712 .matches(partialTermMatchExpression) == true) {
713 result.add(termDisplayName);
716 } catch (PatternSyntaxException pse) {
717 logger.warn("Error in regex match pattern '%s' for term display names: %s",
718 partialTermMatchExpression, pse.getMessage());
724 * Filters user-supplied anchor and wildcard characters in a string,
725 * replacing them with equivalent regular expressions.
726 * @param term a term in which to filter anchor and wildcard characters.
727 * @return the term with those characters filtered.
729 protected String filterAnchorAndWildcardChars(String term) {
730 if (Tools.isBlank(term)) {
733 if (term.length() < 3) {
736 if (logger.isTraceEnabled()) {
737 logger.trace(String.format("Term = %s", term));
739 Boolean anchorAtStart = false;
740 Boolean anchorAtEnd = false;
742 StringBuilder filteredTermBuilder = new StringBuilder(term);
743 // Term contains no anchor or wildcard characters.
744 if ( (! term.contains(RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR))
745 && (! term.contains(RepositoryClientImpl.USER_SUPPLIED_WILDCARD)) ) {
748 // Term contains at least one such character.
750 // Filter the starting anchor or wildcard character, if any.
751 String firstChar = filteredTermBuilder.substring(0,1);
753 case RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR:
754 anchorAtStart = true;
756 case RepositoryClientImpl.USER_SUPPLIED_WILDCARD:
757 filteredTermBuilder.deleteCharAt(0);
760 if (logger.isTraceEnabled()) {
761 logger.trace(String.format("After first char filtering = %s", filteredTermBuilder.toString()));
763 // Filter the ending anchor or wildcard character, if any.
764 int lastPos = filteredTermBuilder.length() - 1;
765 String lastChar = filteredTermBuilder.substring(lastPos);
767 case RepositoryClientImpl.USER_SUPPLIED_ANCHOR_CHAR:
768 filteredTermBuilder.deleteCharAt(lastPos);
769 filteredTermBuilder.insert(filteredTermBuilder.length(), RepositoryClientImpl.ENDING_ANCHOR_CHAR);
772 case RepositoryClientImpl.USER_SUPPLIED_WILDCARD:
773 filteredTermBuilder.deleteCharAt(lastPos);
776 if (logger.isTraceEnabled()) {
777 logger.trace(String.format("After last char filtering = %s", filteredTermBuilder.toString()));
779 filteredTerm = filteredTermBuilder.toString();
780 // Filter all other wildcards, if any.
781 filteredTerm = filteredTerm.replaceAll(RepositoryClientImpl.USER_SUPPLIED_WILDCARD_REGEX, ZERO_OR_MORE_ANY_CHAR_REGEX);
782 if (logger.isTraceEnabled()) {
783 logger.trace(String.format("After replacing user wildcards = %s", filteredTerm));
785 } catch (Exception e) {
786 logger.warn(String.format("Error filtering anchor and wildcard characters from string: %s", e.getMessage()));
790 // Wrap the term in beginning and ending regex wildcards, unless a
791 // starting or ending anchor character was present.
792 return (anchorAtStart ? "" : ZERO_OR_MORE_ANY_CHAR_REGEX)
794 + (anchorAtEnd ? "" : ZERO_OR_MORE_ANY_CHAR_REGEX);
797 @SuppressWarnings("unchecked")
798 private List<String> getPartialTermDisplayNameMatches(DocumentModel docModel, // REM - CSPACE-5133
799 String schema, ListResultField field, String partialTerm) {
800 List<String> result = null;
802 String xpath = field.getXpath(); // results in something like "persons_common:personTermGroupList/[0]/termDisplayName"
803 int endOfTermGroup = xpath.lastIndexOf("/[0]/");
804 String propertyName = endOfTermGroup != -1 ? xpath.substring(0, endOfTermGroup) : xpath; // it may not be multivalued so the xpath passed in would be the property name
808 value = docModel.getProperty(schema, propertyName);
809 } catch (Exception e) {
810 logger.error("Could not extract term display name with property = "
814 if (value != null && value instanceof ArrayList) {
815 ArrayList<HashMap<String, Object>> termGroupList = (ArrayList<HashMap<String, Object>>)value;
816 int arrayListSize = termGroupList.size();
817 if (arrayListSize > 1) { // if there's only 1 element in the list then we've already matched the primary term's display name
818 List<String> displayNameList = new ArrayList<String>();
819 for (int i = 1; i < arrayListSize; i++) { // start at 1, skip the primary term's displayName since we will always return it
820 HashMap<String, Object> map = (HashMap<String, Object>)termGroupList.get(i);
821 String termDisplayName = (String) map.get(AuthorityItemJAXBSchema.TERM_DISPLAY_NAME);
822 displayNameList.add(i - 1, termDisplayName);
825 result = getPartialTermDisplayNameMatches(displayNameList, partialTerm);
833 protected Object getListResultValue(DocumentModel docModel, // REM - CSPACE-5133
834 String schema, ListResultField field) throws DocumentException {
835 Object result = null;
837 result = NuxeoUtils.getXPathValue(docModel, schema, field.getXpath());
840 // Special handling of list item values for authority items (only)
843 // If the list result field is the termDisplayName element,
844 // check whether a partial term matching query was made.
845 // If it was, emit values for both the preferred (aka primary)
846 // term and for all non-preferred terms, if any.
848 String elName = field.getElement();
849 if (isTermDisplayName(elName) == true) {
850 MultivaluedMap<String, String> queryParams = this.getServiceContext().getQueryParams();
851 String partialTerm = queryParams != null ? queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM) : null;
852 if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
853 String primaryTermDisplayName = (String)result;
854 List<String> matches = getPartialTermDisplayNameMatches(docModel, schema, field, partialTerm);
855 if (matches != null && matches.isEmpty() == false) {
856 matches.add(0, primaryTermDisplayName); // insert the primary term's display name at the beginning of the list
857 result = matches; // set the result to a list of matching term display names with the primary term's display name at the beginning
866 public void extractAllParts(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
867 MultipartServiceContext ctx = (MultipartServiceContext) getServiceContext();
868 super.extractAllParts(wrapDoc);
871 protected List<RelationsCommonList.RelationListItem> cloneList(List<RelationsCommonList.RelationListItem> inboundList) {
872 List<RelationsCommonList.RelationListItem> result = newRelationsCommonList();
873 for (RelationsCommonList.RelationListItem item : inboundList) {
880 /* don't even THINK of re-using this method.
881 * String example_uri = "/locationauthorities/7ec60f01-84ab-4908-9a6a/items/a5466530-713f-43b4-bc05";
884 private String extractInAuthorityCSID(String uri) {
885 String IN_AUTHORITY_REGEX = "/(.*?)/(.*?)/(.*)";
886 Pattern p = Pattern.compile(IN_AUTHORITY_REGEX);
887 Matcher m = p.matcher(uri);
889 if (m.groupCount() < 3) {
890 logger.warn("REGEX-WRONG-GROUPCOUNT looking in " + uri);
893 //String service = m.group(1);
894 String inauth = m.group(2);
895 //String theRest = m.group(3);
897 //print("service:"+service+", inauth:"+inauth+", rest:"+rest);
900 logger.warn("REGEX-NOT-MATCHED looking in " + uri);
905 //ensures CSPACE-4042
906 protected void uriPointsToSameAuthority(String thisURI, String inboundItemURI) throws Exception {
907 String authorityCSID = extractInAuthorityCSID(thisURI);
908 String authorityCSIDForInbound = extractInAuthorityCSID(inboundItemURI);
909 if (Tools.isBlank(authorityCSID)
910 || Tools.isBlank(authorityCSIDForInbound)
911 || (!authorityCSID.equalsIgnoreCase(authorityCSIDForInbound))) {
912 throw new Exception("Item URI " + thisURI + " must point to same authority as related item: " + inboundItemURI);
916 public String getItemTermInfoGroupXPathBase() {
917 return authorityItemTermGroupXPathBase;
920 public void setItemTermInfoGroupXPathBase(String itemTermInfoGroupXPathBase) {
921 authorityItemTermGroupXPathBase = itemTermInfoGroupXPathBase;
924 protected String getAuthorityItemCommonSchemaName() {
925 return authorityItemCommonSchemaName;
929 public boolean isJDBCQuery() {
930 boolean result = false;
932 MultivaluedMap<String, String> queryParams = getServiceContext().getQueryParams();
934 // Look the query params to see if we need to make a SQL query.
936 String partialTerm = queryParams.getFirst(IQueryManager.SEARCH_TYPE_PARTIALTERM);
937 if (partialTerm != null && partialTerm.trim().isEmpty() == false) {
944 // By convention, the name of the database table that contains
945 // repeatable term information group records is derivable from
946 // an existing XPath base value, by removing a suffix and converting
948 protected String getTermGroupTableName() {
949 String termInfoGroupListName = getItemTermInfoGroupXPathBase();
950 return termInfoGroupListName.substring(0, termInfoGroupListName.lastIndexOf(LIST_SUFFIX)).toLowerCase();
953 protected String getInAuthorityValue() {
954 String inAuthorityValue = getInAuthority();
955 if (Tools.notBlank(inAuthorityValue)) {
956 return inAuthorityValue;
958 return AuthorityResource.PARENT_WILDCARD;
963 public Map<String,String> getJDBCQueryParams() {
964 // FIXME: Get all of the following values from appropriate external constants.
965 // At present, these are duplicated in both RepositoryClientImpl
966 // and in AuthorityItemDocumentModelHandler.
967 final String TERM_GROUP_LIST_NAME = "TERM_GROUP_LIST_NAME";
968 final String TERM_GROUP_TABLE_NAME_PARAM = "TERM_GROUP_TABLE_NAME";
969 final String IN_AUTHORITY_PARAM = "IN_AUTHORITY";
971 Map<String,String> params = super.getJDBCQueryParams();
972 params.put(TERM_GROUP_LIST_NAME, getItemTermInfoGroupXPathBase());
973 params.put(TERM_GROUP_TABLE_NAME_PARAM, getTermGroupTableName());
974 params.put(IN_AUTHORITY_PARAM, getInAuthorityValue());