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;
28 import javax.ws.rs.core.Response;
30 import org.collectionspace.services.client.AuthorityClient;
31 import org.collectionspace.services.client.CollectionSpaceClient;
32 import org.collectionspace.services.client.PayloadInputPart;
33 import org.collectionspace.services.client.VocabularyClient;
34 import org.collectionspace.services.client.PoxPayloadIn;
35 import org.collectionspace.services.client.PoxPayloadOut;
36 import org.collectionspace.services.common.api.RefName;
37 import org.collectionspace.services.common.api.RefName.Authority;
38 import org.collectionspace.services.common.api.RefNameUtils;
39 import org.collectionspace.services.common.api.RefNameUtils.AuthorityInfo;
40 import org.collectionspace.services.common.api.Tools;
41 import org.collectionspace.services.common.context.ServiceContext;
42 import org.collectionspace.services.common.document.DocumentException;
43 import org.collectionspace.services.common.document.DocumentNotFoundException;
44 import org.collectionspace.services.common.document.DocumentWrapper;
45 import org.collectionspace.services.common.vocabulary.AuthorityItemJAXBSchema;
46 import org.collectionspace.services.common.vocabulary.AuthorityJAXBSchema;
47 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.Specifier;
48 import org.collectionspace.services.common.vocabulary.RefNameServiceUtils.SpecifierForm;
49 import org.collectionspace.services.config.service.ObjectPartType;
50 import org.collectionspace.services.nuxeo.client.java.NuxeoDocumentModelHandler;
51 import org.collectionspace.services.nuxeo.client.java.CoreSessionInterface;
52 import org.collectionspace.services.nuxeo.client.java.RepositoryClientImpl;
53 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
54 import org.dom4j.Document;
55 import org.dom4j.Element;
56 import org.nuxeo.ecm.core.api.ClientException;
57 import org.nuxeo.ecm.core.api.DocumentModel;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
60 import org.testng.Assert;
63 * AuthorityDocumentModelHandler
65 * $LastChangedRevision: $
68 public abstract class AuthorityDocumentModelHandler<AuthCommon>
69 extends NuxeoDocumentModelHandler<AuthCommon> {
71 private final Logger logger = LoggerFactory.getLogger(AuthorityDocumentModelHandler.class);
72 protected String authorityCommonSchemaName;
73 protected String authorityItemCommonSchemaName;
75 public AuthorityDocumentModelHandler(String authorityCommonSchemaName, String authorityItemCommonSchemaName) {
76 this.authorityCommonSchemaName = authorityCommonSchemaName;
77 this.authorityItemCommonSchemaName = authorityItemCommonSchemaName;
81 * The entity type expected from the JAX-RS Response object
83 public Class<String> getEntityResponseType() {
87 protected PayloadInputPart extractPart(Response res, String partLabel)
89 PoxPayloadIn input = new PoxPayloadIn((String)res.readEntity(getEntityResponseType()));
90 PayloadInputPart payloadInputPart = input.getPart(partLabel);
91 if (payloadInputPart == null) {
92 logger.error("Part " + partLabel + " was unexpectedly null.");
94 return payloadInputPart;
98 public void handleSync(DocumentWrapper<Specifier> wrapDoc) throws Exception {
100 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = this.getServiceContext();
101 Specifier specifier = wrapDoc.getWrappedObject();
103 // Get the rev number of the authority so we can compare with rev number of shared authority
105 DocumentModel docModel = NuxeoUtils.getDocFromSpecifier(ctx, getRepositorySession(), authorityCommonSchemaName, specifier);
106 Long rev = (Long) NuxeoUtils.getProperyValue(docModel, AuthorityItemJAXBSchema.REV);
107 String shortId = (String) NuxeoUtils.getProperyValue(docModel, AuthorityItemJAXBSchema.SHORT_IDENTIFIER);
108 String refName = (String) NuxeoUtils.getProperyValue(docModel, AuthorityItemJAXBSchema.REF_NAME);
109 AuthorityInfo authorityInfo = RefNameUtils.parseAuthorityInfo(refName);
111 // Using the short ID of the local authority, created a URN specifier to retrieve the SAS authority
113 Specifier sasSpecifier = new Specifier(SpecifierForm.URN_NAME, RefNameUtils.createShortIdRefName(shortId));
114 Long sasRev = getRevFromSASInstance(sasSpecifier);
116 AuthorityClient client = ctx.getAuthorityClient();
117 Response res = client.read(sasSpecifier.value);
119 int statusCode = res.getStatus();
121 // Check the status code of the response: does it match
122 // the expected response(s)?
123 if (logger.isDebugEnabled()) {
124 logger.debug(client.getClass().getCanonicalName() + ": status = " + statusCode);
127 PoxPayloadIn input = new PoxPayloadIn((String)res.readEntity(getEntityResponseType())); // Get the entire response!
129 PayloadInputPart payloadInputPart = extractPart(res, client.getCommonPartName());
130 if (payloadInputPart != null) {
131 // result = (client.getc) payloadInputPart.getBody();
133 Document document = input.getDOMDocument();
134 Element rootElement = document.getRootElement();
142 private Long getRevFromSASInstance(Specifier specifier) {
145 VocabularyClient client = new VocabularyClient();
146 String uri = getUri(specifier);
152 * Non standard injection of CSID into common part, since caller may access through
153 * shortId, and not know the CSID.
154 * @see org.collectionspace.services.nuxeo.client.java.RemoteDocumentModelHandlerImpl#extractPart(org.nuxeo.ecm.core.api.DocumentModel, java.lang.String, org.collectionspace.services.common.service.ObjectPartType)
157 protected Map<String, Object> extractPart(DocumentModel docModel, String schema, ObjectPartType partMeta)
159 Map<String, Object> unQObjectProperties = super.extractPart(docModel, schema, partMeta);
161 // Add the CSID to the common part
162 if (partMeta.getLabel().equalsIgnoreCase(authorityCommonSchemaName)) {
163 String csid = getCsid(docModel);//NuxeoUtils.extractId(docModel.getPathAsString());
164 unQObjectProperties.put("csid", csid);
167 return unQObjectProperties;
170 public void fillAllParts(DocumentWrapper<DocumentModel> wrapDoc, Action action) throws Exception {
171 super.fillAllParts(wrapDoc, action);
173 // Update the record's revision number on both CREATE and UPDATE actions
175 updateRevNumbers(wrapDoc);
178 protected void updateRevNumbers(DocumentWrapper<DocumentModel> wrapDoc) {
179 DocumentModel documentModel = wrapDoc.getWrappedObject();
180 Long rev = (Long)documentModel.getProperty(authorityCommonSchemaName, AuthorityJAXBSchema.REV);
186 documentModel.setProperty(authorityCommonSchemaName, AuthorityJAXBSchema.REV, rev);
190 public void handleCreate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
191 super.handleCreate(wrapDoc);
193 // Uncomment once debugged and App layer is read to integrate
194 // Experimenting with this uncommented now ...
195 handleDisplayNameAsShortIdentifier(wrapDoc.getWrappedObject(), authorityCommonSchemaName);
196 updateRefnameForAuthority(wrapDoc, authorityCommonSchemaName);//CSPACE-3178
199 protected String buildWhereForShortId(String name) {
200 return authorityCommonSchemaName
201 + ":" + AuthorityJAXBSchema.SHORT_IDENTIFIER
205 private boolean isUnique(DocumentModel docModel, String schemaName) throws DocumentException {
209 private boolean temp_isUnique(DocumentModel docModel, String schemaName) throws DocumentException {
210 boolean result = true;
212 ServiceContext ctx = this.getServiceContext();
213 String shortIdentifier = (String) docModel.getProperty(schemaName, AuthorityJAXBSchema.SHORT_IDENTIFIER);
214 String nxqlWhereClause = buildWhereForShortId(shortIdentifier);
216 DocumentWrapper<DocumentModel> searchResultWrapper = getRepositoryClient(ctx).findDoc(ctx, nxqlWhereClause);
217 if (searchResultWrapper != null) {
219 if (logger.isInfoEnabled() == true) {
220 DocumentModel searchResult = searchResultWrapper.getWrappedObject();
221 String debugMsg = String.format("Could not create a new authority with a short identifier of '%s', because one already exists with the same short identifer: CSID = '%s'",
222 shortIdentifier, searchResult.getName());
223 logger.trace(debugMsg);
226 } catch (DocumentNotFoundException e) {
227 // Not a problem, just means we couldn't find another authority with that short ID
234 * If no short identifier was provided in the input payload,
235 * generate a short identifier from the display name. Either way though,
236 * the short identifier needs to be unique.
238 private void handleDisplayNameAsShortIdentifier(DocumentModel docModel, String schemaName) throws Exception {
239 String shortIdentifier = (String) docModel.getProperty(schemaName, AuthorityJAXBSchema.SHORT_IDENTIFIER);
240 String displayName = (String) docModel.getProperty(schemaName, AuthorityJAXBSchema.DISPLAY_NAME);
241 String shortDisplayName = "";
242 String generateShortIdentifier = null;
243 if (Tools.isEmpty(shortIdentifier)) {
244 generateShortIdentifier = AuthorityIdentifierUtils.generateShortIdentifierFromDisplayName(displayName, shortDisplayName);
245 docModel.setProperty(schemaName, AuthorityJAXBSchema.SHORT_IDENTIFIER, shortIdentifier);
248 if (isUnique(docModel, schemaName) == false) {
249 String shortId = generateShortIdentifier == null ? shortIdentifier : generateShortIdentifier;
250 String errMsgVerb = generateShortIdentifier == null ? "supplied" : "generated";
251 String errMsg = String.format("The %s short identifier '%s' was not unique, so the new authority could not be created.",
252 errMsgVerb, shortId);
253 throw new DocumentException(errMsg);
258 * Generate a refName for the authority from the short identifier
261 * All refNames for authorities are generated. If a client supplies
262 * a refName, it will be overwritten during create (per this method)
263 * or discarded during update (per filterReadOnlyPropertiesForPart).
265 * @see #filterReadOnlyPropertiesForPart(Map<String, Object>, org.collectionspace.services.common.service.ObjectPartType)
268 protected void updateRefnameForAuthority(DocumentWrapper<DocumentModel> wrapDoc, String schemaName) throws Exception {
269 DocumentModel docModel = wrapDoc.getWrappedObject();
270 RefName.Authority authority = (Authority) getRefName(getServiceContext(), docModel);
271 String refName = authority.toString();
272 docModel.setProperty(schemaName, AuthorityJAXBSchema.REF_NAME, refName);
276 public RefName.RefNameInterface getRefName(ServiceContext ctx,
277 DocumentModel docModel) {
278 RefName.RefNameInterface refname = null;
281 String shortIdentifier = (String) docModel.getProperty(authorityCommonSchemaName, AuthorityJAXBSchema.SHORT_IDENTIFIER);
282 String displayName = (String) docModel.getProperty(authorityCommonSchemaName, AuthorityJAXBSchema.DISPLAY_NAME);
283 RefName.Authority authority = RefName.Authority.buildAuthority(ctx.getTenantName(),
284 ctx.getServiceName(),
285 null, // Only use shortId form!!!
289 } catch (Exception e) {
290 logger.error(e.getMessage(), e);
297 protected String getRefnameDisplayName(DocumentWrapper<DocumentModel> docWrapper) {
298 String result = null;
300 DocumentModel docModel = docWrapper.getWrappedObject();
301 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = this.getServiceContext();
302 RefName.Authority refname = (RefName.Authority)getRefName(ctx, docModel);
303 result = refname.getDisplayName();
308 public String getShortIdentifier(String authCSID, String schemaName) throws Exception {
309 String shortIdentifier = null;
310 CoreSessionInterface repoSession = null;
312 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx = this.getServiceContext();
313 RepositoryClientImpl nuxeoRepoClient = (RepositoryClientImpl)this.getRepositoryClient(ctx);
315 repoSession = nuxeoRepoClient.getRepositorySession(ctx);
316 DocumentWrapper<DocumentModel> wrapDoc = nuxeoRepoClient.getDocFromCsid(ctx, repoSession, authCSID);
317 DocumentModel docModel = wrapDoc.getWrappedObject();
318 shortIdentifier = (String) docModel.getProperty(schemaName, AuthorityJAXBSchema.SHORT_IDENTIFIER);
319 } catch (ClientException ce) {
320 throw new RuntimeException("AuthorityDocHandler Internal Error: cannot get shortId!", ce);
322 if (repoSession != null) {
323 nuxeoRepoClient.releaseRepositorySession(ctx, repoSession);
327 return shortIdentifier;
331 * Filters out selected values supplied in an update request.
333 * @param objectProps the properties filtered out from the update payload
334 * @param partMeta metadata for the object to fill
337 public void filterReadOnlyPropertiesForPart(
338 Map<String, Object> objectProps, ObjectPartType partMeta) {
339 super.filterReadOnlyPropertiesForPart(objectProps, partMeta);
340 String commonPartLabel = getServiceContext().getCommonPartLabel();
341 if (partMeta.getLabel().equalsIgnoreCase(commonPartLabel)) {
342 objectProps.remove(AuthorityJAXBSchema.CSID);
343 objectProps.remove(AuthorityJAXBSchema.SHORT_IDENTIFIER);
344 objectProps.remove(AuthorityJAXBSchema.REF_NAME);