]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
42837f1f4b431ce541b945e9992c6fb417cb1f33
[tmp/jakarta-migration.git] /
1 /**
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:
5
6  *  http://www.collectionspace.org
7  *  http://wiki.collectionspace.org
8
9  *  Copyright 2009 University of California at Berkeley
10
11  *  Licensed under the Educational Community License (ECL), Version 2.0.
12  *  You may not use this file except in compliance with this License.
13
14  *  You may obtain a copy of the ECL 2.0 License at
15
16  *  https://source.collectionspace.org/collection-space/LICENSE.txt
17
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.
23  */
24 package org.collectionspace.services.nuxeo.client.java;
25
26 import java.io.InputStream;
27 import java.util.Collection;
28 import java.util.HashMap;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Map.Entry;
32 import java.util.Set;
33
34 import javax.ws.rs.WebApplicationException;
35 import javax.ws.rs.core.MediaType;
36 import javax.ws.rs.core.Response;
37
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;
49
50 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
51 import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
52
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;
57
58 import org.nuxeo.ecm.core.schema.types.Schema;
59
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
62 import org.w3c.dom.Document;
63
64 /**
65  * RemoteDocumentModelHandler
66  *
67  * $LastChangedRevision: $
68  * $LastChangedDate: $
69  * @param <T> 
70  * @param <TL> 
71  */
72 public abstract class RemoteDocumentModelHandlerImpl<T, TL>
73         extends DocumentModelHandler<T, TL> {
74
75     /** The logger. */
76     private final Logger logger = LoggerFactory.getLogger(RemoteDocumentModelHandlerImpl.class);
77
78     /* (non-Javadoc)
79      * @see org.collectionspace.services.common.document.AbstractDocumentHandlerImpl#setServiceContext(org.collectionspace.services.common.context.ServiceContext)
80      */
81     @Override
82     public void setServiceContext(ServiceContext ctx) {  //FIXME: Apply proper generics to ServiceContext<MultipartInput, MultipartOutput>
83         if (ctx instanceof MultipartServiceContext) {
84             super.setServiceContext(ctx);
85         } else {
86             throw new IllegalArgumentException("setServiceContext requires instance of "
87                     + MultipartServiceContext.class.getName());
88         }
89     }
90
91     /* (non-Javadoc)
92      * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#completeUpdate(org.collectionspace.services.common.document.DocumentWrapper)
93      */
94     @Override
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);
107         }
108     }
109
110     /**
111      * Adds the output part.
112      *
113      * @param unQObjectProperties the un q object properties
114      * @param schema the schema
115      * @param partMeta the part meta
116      * @throws Exception the exception
117      */
118     private void addOutputPart(Map<String, Object> unQObjectProperties, String schema, ObjectPartType partMeta)
119             throws Exception {
120         Document doc = DocumentUtils.buildDocument(partMeta, schema,
121                 unQObjectProperties);
122         if (logger.isDebugEnabled() == true) {
123             logger.debug(DocumentUtils.xmlToString(doc));
124         }
125         MultipartServiceContext ctx = (MultipartServiceContext) getServiceContext();
126         ctx.addOutputPart(schema, doc, partMeta.getContent().getContentType());
127     }
128
129     /**
130      * Extract paging info.
131      *
132      * @param commonsList the commons list
133      * @return the tL
134      * @throws Exception the exception
135      */
136     public TL extractPagingInfo(TL theCommonList, DocumentWrapper<DocumentModelList> wrapDoc)
137             throws Exception {
138         AbstractCommonList commonList = (AbstractCommonList) theCommonList;
139
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());
151
152         return (TL) commonList;
153     }
154
155     /* (non-Javadoc)
156      * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#extractAllParts(org.collectionspace.services.common.document.DocumentWrapper)
157      */
158     @Override
159     public void extractAllParts(DocumentWrapper<DocumentModel> wrapDoc)
160             throws Exception {
161
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
169             }
170             Map<String, Object> unQObjectProperties = extractPart(docModel, schema, partMeta);
171             addOutputPart(unQObjectProperties, schema, partMeta);
172         }
173     }
174
175     /* (non-Javadoc)
176      * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#fillAllParts(org.collectionspace.services.common.document.DocumentWrapper)
177      */
178     @Override
179     public void fillAllParts(DocumentWrapper<DocumentModel> wrapDoc, Action action) throws Exception {
180
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);
191         }
192
193         Map<String, ObjectPartType> partsMetaMap = getServiceContext().getPartsMetadata();
194
195         //iterate over parts received and fill those parts
196         List<InputPart> inputParts = input.getParts();
197         for (InputPart part : inputParts) {
198
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);
204             }
205
206             //skip if the part is not in metadata
207             ObjectPartType partMeta = partsMetaMap.get(partLabel);
208             if (partMeta == null) {
209                 continue;
210             }
211             fillPart(part, docModel, partMeta, action, ctx);
212         }//rof
213
214     }
215
216     /**
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
221      * @throws Exception
222      */
223     protected void fillPart(InputPart part, DocumentModel docModel,
224             ObjectPartType partMeta, Action action, ServiceContext ctx)
225             throws Exception {
226         InputStream payload = part.getBody(InputStream.class, null);
227
228         //check if this is an xml part
229         if (part.getMediaType().equals(MediaType.APPLICATION_XML_TYPE)) {
230             if (payload != null) {
231                 Document document = DocumentUtils.parseDocument(payload, partMeta,
232                         false /*don't validate*/);
233                 Map<String, Object> objectProps = DocumentUtils.parseProperties(partMeta, document, ctx);
234                 if (action == Action.UPDATE) {
235                     this.filterReadOnlyPropertiesForPart(objectProps, partMeta);
236                 }
237                 docModel.setProperties(partMeta.getLabel(), objectProps);
238             }
239         }
240     }
241
242     /**
243      * Filters out read only properties, so they cannot be set on update.
244      * TODO: add configuration support to do this generally
245      * @param objectProps the properties parsed from the update payload
246      * @param partMeta metadata for the object to fill
247      */
248     public void filterReadOnlyPropertiesForPart(
249             Map<String, Object> objectProps, ObjectPartType partMeta) {
250         // Currently a no-op, but can be overridden in Doc handlers.
251     }
252
253     /**
254      * extractPart extracts an XML object from given DocumentModel
255      * @param docModel
256      * @param schema of the object to extract
257      * @param partMeta metadata for the object to extract
258      * @throws Exception
259      */
260     protected Map<String, Object> extractPart(DocumentModel docModel, String schema, ObjectPartType partMeta)
261             throws Exception {
262         return extractPart(docModel, schema, partMeta, null);
263     }
264
265     /**
266      * extractPart extracts an XML object from given DocumentModel
267      * @param docModel
268      * @param schema of the object to extract
269      * @param partMeta metadata for the object to extract
270      * @throws Exception
271      */
272     protected Map<String, Object> extractPart(
273             DocumentModel docModel, String schema, ObjectPartType partMeta,
274             Map<String, Object> addToMap)
275             throws Exception {
276         Map<String, Object> result = null;
277
278         MediaType mt = MediaType.valueOf(partMeta.getContent().getContentType());
279         if (mt.equals(MediaType.APPLICATION_XML_TYPE)) {
280             Map<String, Object> objectProps = docModel.getProperties(schema);
281             //unqualify properties before sending the doc over the wire (to save bandwidh)
282             //FIXME: is there a better way to avoid duplication of a collection?
283             Map<String, Object> unQObjectProperties =
284                     (addToMap != null) ? addToMap : (new HashMap<String, Object>());
285             Set<Entry<String, Object>> qualifiedEntries = objectProps.entrySet();
286             for (Entry<String, Object> entry : qualifiedEntries) {
287                 String unqProp = getUnQProperty(entry.getKey());
288                 unQObjectProperties.put(unqProp, entry.getValue());
289             }
290             result = unQObjectProperties;
291         } //TODO: handle other media types
292
293         return result;
294     }
295
296     /* (non-Javadoc)
297      * @see org.collectionspace.services.nuxeo.client.java.DocumentModelHandler#getAuthorityRefs(org.collectionspace.services.common.document.DocumentWrapper, java.util.List)
298      */
299     @Override
300     public AuthorityRefList getAuthorityRefs(
301             DocumentWrapper<DocumentModel> docWrapper,
302             List<String> authRefFieldNames) throws PropertyException {
303
304         AuthorityRefList authRefList = new AuthorityRefList();
305         List<AuthorityRefList.AuthorityRefItem> list = authRefList.getAuthorityRefItem();
306         DocumentModel docModel = docWrapper.getWrappedObject();
307
308         try {
309             for (String authRefFieldName : authRefFieldNames) {
310
311                 // FIXME: Can use the schema to validate field existence,
312                 // to help avoid encountering PropertyExceptions.
313                 String schemaName = DocumentUtils.getSchemaNamePart(authRefFieldName);
314                 Schema schema = DocumentUtils.getSchemaFromName(schemaName);
315
316                 String descendantAuthRefFieldName = DocumentUtils.getDescendantAuthRefFieldName(authRefFieldName);
317                 if (descendantAuthRefFieldName != null && !descendantAuthRefFieldName.trim().isEmpty()) {
318                     authRefFieldName = DocumentUtils.getAncestorAuthRefFieldName(authRefFieldName);
319                 }
320
321                 String xpath = "//" + authRefFieldName;
322                 Property prop = docModel.getProperty(xpath);
323                 if (prop == null) {
324                     continue;
325                 }
326
327                 // If this is a single scalar field, with no children,
328                 // add an item with its values to the authRefs list.
329                 if (DocumentUtils.isSimpleType(prop)) {
330                     appendToAuthRefsList(prop.getValue(String.class), schemaName, authRefFieldName, list);
331
332                     // Otherwise, if this field has children, cycle through each child.
333                     //
334                     // Whenever we find instances of the descendant field among
335                     // these children, add an item with its values to the authRefs list.
336                     //
337                     // FIXME: When we increase maximum repeatability depth, that is, the depth
338                     // between ancestor and descendant, we'll need to use recursion here,
339                     // rather than making fixed assumptions about hierarchical depth.
340                 } else if ((DocumentUtils.isListType(prop) || DocumentUtils.isComplexType(prop))
341                         && prop.size() > 0) {
342                     
343                     Collection<Property> childProp = prop.getChildren();
344                     for (Property cProp : childProp) {
345                         if (DocumentUtils.isSimpleType(cProp) && cProp.getName().equals(descendantAuthRefFieldName)) {
346                             appendToAuthRefsList(cProp.getValue(String.class), schemaName, descendantAuthRefFieldName, list);
347                         } else if ((DocumentUtils.isListType(cProp) || DocumentUtils.isComplexType(cProp))
348                             && prop.size() > 0) {
349                             Collection<Property> grandChildProp = cProp.getChildren();
350                             for (Property gProp : grandChildProp) {
351                                 if (DocumentUtils.isSimpleType(gProp) && gProp.getName().equals(descendantAuthRefFieldName)) {
352                                     appendToAuthRefsList(gProp.getValue(String.class), schemaName, descendantAuthRefFieldName, list);
353                                 }
354                             }
355                         }
356                     }
357
358                 }
359
360             }
361
362             
363         } catch (PropertyException pe) {
364             String msg = "Attempted to retrieve value for invalid or missing authority field. "
365                     + "Check authority field properties in tenant bindings.";
366             logger.warn(msg, pe);
367             throw pe;
368         } catch (Exception e) {
369             if (logger.isDebugEnabled()) {
370                 logger.debug("Caught exception in getAuthorityRefs", e);
371             }
372             Response response = Response.status(
373                     Response.Status.INTERNAL_SERVER_ERROR).entity(
374                     "Failed to retrieve authority references").type(
375                     "text/plain").build();
376             throw new WebApplicationException(response);
377         }
378
379         return authRefList;
380     }
381
382     private void appendToAuthRefsList(String refName, String schemaName,
383             String fieldName, List<AuthorityRefList.AuthorityRefItem> list)
384             throws Exception {
385         if (refName == null || refName.trim().isEmpty()) {
386             return;
387         }
388         if (DocumentUtils.getSchemaNamePart(fieldName).isEmpty()) {
389             fieldName = DocumentUtils.appendSchemaName(schemaName, fieldName);
390         }
391         list.add(authorityRefListItem(fieldName, refName));
392     }
393
394     private AuthorityRefList.AuthorityRefItem authorityRefListItem(String authRefFieldName, String refName) {
395
396         AuthorityRefList.AuthorityRefItem ilistItem = new AuthorityRefList.AuthorityRefItem();
397         try {
398             RefNameUtils.AuthorityTermInfo termInfo = RefNameUtils.parseAuthorityTermInfo(refName);
399             ilistItem.setRefName(refName);
400             ilistItem.setAuthDisplayName(termInfo.inAuthority.displayName);
401             ilistItem.setItemDisplayName(termInfo.displayName);
402             ilistItem.setSourceField(authRefFieldName);
403             ilistItem.setUri(termInfo.getRelativeUri());
404         } catch (Exception e) {
405             // Do nothing upon encountering an Exception here.
406         }
407         return ilistItem;
408     }
409
410 }