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.nuxeo.client.java;
26 import java.io.InputStream;
27 import java.util.Collection;
28 import java.util.HashMap;
29 import java.util.List;
31 import java.util.Map.Entry;
34 import javax.ws.rs.WebApplicationException;
35 import javax.ws.rs.core.MediaType;
36 import javax.ws.rs.core.Response;
38 import org.collectionspace.services.jaxb.AbstractCommonList;
39 import org.collectionspace.services.common.authorityref.AuthorityRefList;
40 import org.collectionspace.services.common.context.MultipartServiceContext;
41 import org.collectionspace.services.common.context.ServiceContext;
42 import org.collectionspace.services.common.document.BadRequestException;
43 import org.collectionspace.services.common.document.DocumentUtils;
44 import org.collectionspace.services.common.document.DocumentWrapper;
45 import org.collectionspace.services.common.document.DocumentFilter;
46 import org.collectionspace.services.common.document.DocumentHandler.Action;
47 import org.collectionspace.services.common.service.ObjectPartType;
48 import org.collectionspace.services.common.vocabulary.RefNameUtils;
50 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
51 import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
53 import org.nuxeo.ecm.core.api.DocumentModel;
54 import org.nuxeo.ecm.core.api.DocumentModelList;
55 import org.nuxeo.ecm.core.api.model.Property;
56 import org.nuxeo.ecm.core.api.model.PropertyException;
58 import org.nuxeo.ecm.core.schema.types.Schema;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
62 import org.w3c.dom.Document;
65 * RemoteDocumentModelHandler
67 * $LastChangedRevision: $
72 public abstract class RemoteDocumentModelHandlerImpl<T, TL>
73 extends DocumentModelHandler<T, TL> {
76 private final Logger logger = LoggerFactory.getLogger(RemoteDocumentModelHandlerImpl.class);
79 * @see org.collectionspace.services.common.document.AbstractDocumentHandlerImpl#setServiceContext(org.collectionspace.services.common.context.ServiceContext)
82 public void setServiceContext(ServiceContext ctx) { //FIXME: Apply proper generics to ServiceContext<MultipartInput, MultipartOutput>
83 if (ctx instanceof MultipartServiceContext) {
84 super.setServiceContext(ctx);
86 throw new IllegalArgumentException("setServiceContext requires instance of "
87 + MultipartServiceContext.class.getName());
92 * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#completeUpdate(org.collectionspace.services.common.document.DocumentWrapper)
95 public void completeUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
96 DocumentModel docModel = wrapDoc.getWrappedObject();
97 //return at least those document part(s) that were received
98 Map<String, ObjectPartType> partsMetaMap = getServiceContext().getPartsMetadata();
99 MultipartServiceContext ctx = (MultipartServiceContext) getServiceContext();
100 List<InputPart> inputParts = ctx.getInput().getParts();
101 for (InputPart part : inputParts) {
102 String partLabel = part.getHeaders().getFirst("label");
103 ObjectPartType partMeta = partsMetaMap.get(partLabel);
104 // extractPart(docModel, partLabel, partMeta);
105 Map<String, Object> unQObjectProperties = extractPart(docModel, partLabel, partMeta);
106 addOutputPart(unQObjectProperties, partLabel, partMeta);
111 * Adds the output part.
113 * @param unQObjectProperties the un q object properties
114 * @param schema the schema
115 * @param partMeta the part meta
116 * @throws Exception the exception
118 private void addOutputPart(Map<String, Object> unQObjectProperties, String schema, ObjectPartType partMeta)
120 Document doc = DocumentUtils.buildDocument(partMeta, schema,
121 unQObjectProperties);
122 if (logger.isDebugEnabled() == true) {
123 logger.debug(DocumentUtils.xmlToString(doc));
125 MultipartServiceContext ctx = (MultipartServiceContext) getServiceContext();
126 ctx.addOutputPart(schema, doc, partMeta.getContent().getContentType());
130 * Extract paging info.
132 * @param commonsList the commons list
134 * @throws Exception the exception
136 protected TL extractPagingInfo(TL theCommonList, DocumentWrapper<DocumentModelList> wrapDoc)
138 AbstractCommonList commonList = (AbstractCommonList) theCommonList;
140 DocumentFilter docFilter = this.getDocumentFilter();
141 long pageSize = docFilter.getPageSize();
142 long pageNum = pageSize != 0 ? docFilter.getOffset() / pageSize : pageSize;
143 // set the page size and page number
144 commonList.setPageNum(pageNum);
145 commonList.setPageSize(pageSize);
146 DocumentModelList docList = wrapDoc.getWrappedObject();
147 // Set num of items in list. this is useful to our testing framework.
148 commonList.setItemsInPage(docList.size());
149 // set the total result size
150 commonList.setTotalItems(docList.totalSize());
152 return (TL) commonList;
156 * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#extractAllParts(org.collectionspace.services.common.document.DocumentWrapper)
159 public void extractAllParts(DocumentWrapper<DocumentModel> wrapDoc)
162 DocumentModel docModel = wrapDoc.getWrappedObject();
163 String[] schemas = docModel.getDeclaredSchemas();
164 Map<String, ObjectPartType> partsMetaMap = getServiceContext().getPartsMetadata();
165 for (String schema : schemas) {
166 ObjectPartType partMeta = partsMetaMap.get(schema);
167 if (partMeta == null) {
168 continue; // unknown part, ignore
170 Map<String, Object> unQObjectProperties = extractPart(docModel, schema, partMeta);
171 addOutputPart(unQObjectProperties, schema, partMeta);
176 * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#fillAllParts(org.collectionspace.services.common.document.DocumentWrapper)
179 public void fillAllParts(DocumentWrapper<DocumentModel> wrapDoc, Action action) throws Exception {
181 //TODO filling extension parts should be dynamic
182 //Nuxeo APIs lack to support stream/byte[] input, get/setting properties is
183 //not an ideal way of populating objects.
184 DocumentModel docModel = wrapDoc.getWrappedObject();
185 MultipartServiceContext ctx = (MultipartServiceContext) getServiceContext();
186 MultipartInput input = ctx.getInput();
187 if (input.getParts().isEmpty()) {
188 String msg = "No payload found!";
189 logger.error(msg + "Ctx=" + getServiceContext().toString());
190 throw new BadRequestException(msg);
193 Map<String, ObjectPartType> partsMetaMap = getServiceContext().getPartsMetadata();
195 //iterate over parts received and fill those parts
196 List<InputPart> inputParts = input.getParts();
197 for (InputPart part : inputParts) {
199 String partLabel = part.getHeaders().getFirst("label");
200 if (partLabel == null) {
201 String msg = "Part label is missing or empty!";
202 logger.error(msg + "Ctx=" + getServiceContext().toString());
203 throw new BadRequestException(msg);
206 //skip if the part is not in metadata
207 ObjectPartType partMeta = partsMetaMap.get(partLabel);
208 if (partMeta == null) {
211 fillPart(part, docModel, partMeta, action, ctx);
217 * fillPart fills an XML part into given document model
218 * @param part to fill
219 * @param docModel for the given object
220 * @param partMeta metadata for the object to fill
223 protected void fillPart(InputPart part, DocumentModel docModel,
224 ObjectPartType partMeta, Action action, ServiceContext ctx)
226 InputStream payload = part.getBody(InputStream.class, null);
228 // TODO for sub-docs - after we parse the doc, we need to look for elements that are configured as
229 // subitem lists, for this part (schema), pull them out, and set them aside for later processing.
231 //check if this is an xml part
232 if (part.getMediaType().equals(MediaType.APPLICATION_XML_TYPE)) {
233 if (payload != null) {
234 Document document = DocumentUtils.parseDocument(payload, partMeta,
235 false /*don't validate*/);
236 //TODO: callback to handler if registered to validate the
238 // Map<String, Object> objectProps = DocumentUtils.parseProperties(document.getFirstChild());
239 Map<String, Object> objectProps = DocumentUtils.parseProperties(partMeta, document, ctx);
240 if (action == Action.UPDATE) {
241 this.filterReadOnlyPropertiesForPart(objectProps, partMeta);
243 docModel.setProperties(partMeta.getLabel(), objectProps);
249 * Filters out read only properties, so they cannot be set on update.
250 * TODO: add configuration support to do this generally
251 * @param objectProps the properties parsed from the update payload
252 * @param partMeta metadata for the object to fill
254 public void filterReadOnlyPropertiesForPart(
255 Map<String, Object> objectProps, ObjectPartType partMeta) {
256 // Currently a no-op, but can be overridden in Doc handlers.
260 * extractPart extracts an XML object from given DocumentModel
262 * @param schema of the object to extract
263 * @param partMeta metadata for the object to extract
266 protected Map<String, Object> extractPart(DocumentModel docModel, String schema, ObjectPartType partMeta)
268 return extractPart(docModel, schema, partMeta, null);
272 * extractPart extracts an XML object from given DocumentModel
274 * @param schema of the object to extract
275 * @param partMeta metadata for the object to extract
278 protected Map<String, Object> extractPart(
279 DocumentModel docModel, String schema, ObjectPartType partMeta,
280 Map<String, Object> addToMap)
282 Map<String, Object> result = null;
284 MediaType mt = MediaType.valueOf(partMeta.getContent().getContentType());
285 if (mt.equals(MediaType.APPLICATION_XML_TYPE)) {
286 Map<String, Object> objectProps = docModel.getProperties(schema);
287 //unqualify properties before sending the doc over the wire (to save bandwidh)
288 //FIXME: is there a better way to avoid duplication of a collection?
289 Map<String, Object> unQObjectProperties =
290 (addToMap != null) ? addToMap : (new HashMap<String, Object>());
291 Set<Entry<String, Object>> qualifiedEntries = objectProps.entrySet();
292 for (Entry<String, Object> entry : qualifiedEntries) {
293 String unqProp = getUnQProperty(entry.getKey());
294 unQObjectProperties.put(unqProp, entry.getValue());
296 result = unQObjectProperties;
297 } //TODO: handle other media types
303 * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#getAuthorityRefs(org.collectionspace.services.common.document.DocumentWrapper, java.util.List)
306 public AuthorityRefList getAuthorityRefs(
307 DocumentWrapper<DocumentModel> docWrapper,
308 List<String> authRefFieldNames) throws PropertyException {
310 AuthorityRefList authRefList = new AuthorityRefList();
311 List<AuthorityRefList.AuthorityRefItem> list = authRefList.getAuthorityRefItem();
312 DocumentModel docModel = docWrapper.getWrappedObject();
315 for (String authRefFieldName : authRefFieldNames) {
317 // FIXME: Can use the schema to validate field existence,
318 // to help avoid encountering PropertyExceptions.
319 String schemaName = DocumentUtils.getSchemaNamePart(authRefFieldName);
320 Schema schema = DocumentUtils.getSchemaFromName(schemaName);
322 String descendantAuthRefFieldName = DocumentUtils.getDescendantAuthRefFieldName(authRefFieldName);
323 if (descendantAuthRefFieldName != null && !descendantAuthRefFieldName.trim().isEmpty()) {
324 authRefFieldName = DocumentUtils.getAncestorAuthRefFieldName(authRefFieldName);
327 String xpath = "//" + authRefFieldName;
328 Property prop = docModel.getProperty(xpath);
333 // If this is a single scalar field, with no children,
334 // add an item with its values to the authRefs list.
335 if (DocumentUtils.isSimpleType(prop)) {
336 appendToAuthRefsList(prop.getValue(String.class), schemaName, authRefFieldName, list);
338 // Otherwise, if this field has children, cycle through each child.
340 // Whenever we find instances of the descendant field among
341 // these children, add an item with its values to the authRefs list.
343 // FIXME: When we increase maximum repeatability depth, that is, the depth
344 // between ancestor and descendant, we'll need to use recursion here,
345 // rather than making fixed assumptions about hierarchical depth.
346 } else if ((DocumentUtils.isListType(prop) || DocumentUtils.isComplexType(prop))
347 && prop.size() > 0) {
349 Collection<Property> childProp = prop.getChildren();
350 for (Property cProp : childProp) {
351 if (DocumentUtils.isSimpleType(cProp) && cProp.getName().equals(descendantAuthRefFieldName)) {
352 appendToAuthRefsList(cProp.getValue(String.class), schemaName, descendantAuthRefFieldName, list);
353 } else if ((DocumentUtils.isListType(cProp) || DocumentUtils.isComplexType(cProp))
354 && prop.size() > 0) {
355 Collection<Property> grandChildProp = cProp.getChildren();
356 for (Property gProp : grandChildProp) {
357 if (DocumentUtils.isSimpleType(gProp) && gProp.getName().equals(descendantAuthRefFieldName)) {
358 appendToAuthRefsList(gProp.getValue(String.class), schemaName, descendantAuthRefFieldName, list);
369 } catch (PropertyException pe) {
370 String msg = "Attempted to retrieve value for invalid or missing authority field. "
371 + "Check authority field properties in tenant bindings.";
372 logger.warn(msg, pe);
374 } catch (Exception e) {
375 if (logger.isDebugEnabled()) {
376 logger.debug("Caught exception in getAuthorityRefs", e);
378 Response response = Response.status(
379 Response.Status.INTERNAL_SERVER_ERROR).entity(
380 "Failed to retrieve authority references").type(
381 "text/plain").build();
382 throw new WebApplicationException(response);
388 private void appendToAuthRefsList(String refName, String schemaName,
389 String fieldName, List<AuthorityRefList.AuthorityRefItem> list)
391 if (refName == null || refName.trim().isEmpty()) {
394 if (DocumentUtils.getSchemaNamePart(fieldName).isEmpty()) {
395 fieldName = DocumentUtils.appendSchemaName(schemaName, fieldName);
397 list.add(authorityRefListItem(fieldName, refName));
400 private AuthorityRefList.AuthorityRefItem authorityRefListItem(String authRefFieldName, String refName) {
402 AuthorityRefList.AuthorityRefItem ilistItem = new AuthorityRefList.AuthorityRefItem();
404 RefNameUtils.AuthorityTermInfo termInfo = RefNameUtils.parseAuthorityTermInfo(refName);
405 ilistItem.setRefName(refName);
406 ilistItem.setAuthDisplayName(termInfo.inAuthority.displayName);
407 ilistItem.setItemDisplayName(termInfo.displayName);
408 ilistItem.setSourceField(authRefFieldName);
409 ilistItem.setUri(termInfo.getRelativeUri());
410 } catch (Exception e) {
411 // Do nothing upon encountering an Exception here.