]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
6efb988a71f3add81493c72a1332235b478d1cef
[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.HashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Map.Entry;
31 import java.util.Set;
32
33 import javax.ws.rs.WebApplicationException;
34 import javax.ws.rs.core.MediaType;
35 import javax.ws.rs.core.Response;
36
37 import org.collectionspace.services.common.authorityref.AuthorityRefList;
38 import org.collectionspace.services.common.context.MultipartServiceContext;
39 import org.collectionspace.services.common.context.ServiceContext;
40 import org.collectionspace.services.common.document.BadRequestException;
41 import org.collectionspace.services.common.document.DocumentUtils;
42 import org.collectionspace.services.common.document.DocumentWrapper;
43 import org.collectionspace.services.common.service.ObjectPartType;
44 import org.collectionspace.services.common.vocabulary.RefNameUtils;
45 import org.jboss.resteasy.plugins.providers.multipart.InputPart;
46 import org.jboss.resteasy.plugins.providers.multipart.MultipartInput;
47 import org.nuxeo.ecm.core.api.DocumentModel;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import org.w3c.dom.Document;
51
52 /**
53  * RemoteDocumentModelHandler
54  *
55  * $LastChangedRevision: $
56  * $LastChangedDate: $
57  */
58 public abstract class RemoteDocumentModelHandlerImpl<T, TL>
59         extends DocumentModelHandler<T, TL> {
60
61     private final Logger logger = LoggerFactory.getLogger(RemoteDocumentModelHandlerImpl.class);
62
63     @Override
64     public void setServiceContext(ServiceContext ctx) {
65         if(ctx instanceof MultipartServiceContext){
66             super.setServiceContext(ctx);
67         }else{
68             throw new IllegalArgumentException("setServiceContext requires instance of " +
69                     MultipartServiceContext.class.getName());
70         }
71     }
72
73     @Override
74     public void completeUpdate(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
75         DocumentModel docModel = wrapDoc.getWrappedObject();
76         //return at least those document part(s) that were received
77         Map<String, ObjectPartType> partsMetaMap = getServiceContext().getPartsMetadata();
78         MultipartServiceContext ctx = (MultipartServiceContext) getServiceContext();
79         List<InputPart> inputParts = ctx.getInput().getParts();
80         for(InputPart part : inputParts){
81             String partLabel = part.getHeaders().getFirst("label");
82             ObjectPartType partMeta = partsMetaMap.get(partLabel);
83             extractPart(docModel, partLabel, partMeta);
84         }
85     }
86
87     @Override
88     public void extractAllParts(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
89
90         DocumentModel docModel = wrapDoc.getWrappedObject();
91         String[] schemas = docModel.getDeclaredSchemas();
92         Map<String, ObjectPartType> partsMetaMap = getServiceContext().getPartsMetadata();
93         for(String schema : schemas){
94             ObjectPartType partMeta = partsMetaMap.get(schema);
95             if(partMeta == null){
96                 continue; //unknown part, ignore
97             }
98             extractPart(docModel, schema, partMeta);
99         }
100     }
101
102     @Override
103     public void fillAllParts(DocumentWrapper<DocumentModel> wrapDoc) throws Exception {
104
105         //TODO filling extension parts should be dynamic
106         //Nuxeo APIs lack to support stream/byte[] input, get/setting properties is
107         //not an ideal way of populating objects.
108         DocumentModel docModel = wrapDoc.getWrappedObject();
109         MultipartServiceContext ctx = (MultipartServiceContext) getServiceContext();
110         MultipartInput input = ctx.getInput();
111         if(input.getParts().isEmpty()){
112             String msg = "No payload found!";
113             logger.error(msg + "Ctx=" + getServiceContext().toString());
114             throw new BadRequestException(msg);
115         }
116
117         Map<String, ObjectPartType> partsMetaMap = getServiceContext().getPartsMetadata();
118
119         //iterate over parts received and fill those parts
120         List<InputPart> inputParts = input.getParts();
121         for(InputPart part : inputParts){
122
123             String partLabel = part.getHeaders().getFirst("label");
124             if (partLabel == null) {
125                 String msg = "Part label is missing or empty!";
126                 logger.error(msg + "Ctx=" + getServiceContext().toString());
127                 throw new BadRequestException(msg);
128             }
129             
130             //skip if the part is not in metadata
131             if(!partsMetaMap.containsKey(partLabel)){
132                 continue;
133             }
134             ObjectPartType partMeta = partsMetaMap.get(partLabel);
135             fillPart(part, docModel, partMeta);
136         }//rof
137
138     }
139
140     /**
141      * fillPart fills an XML part into given document model
142      * @param part to fill
143      * @param docModel for the given object
144      * @param partMeta metadata for the object to fill
145      * @throws Exception
146      */
147     protected void fillPart(InputPart part, DocumentModel docModel, ObjectPartType partMeta)
148             throws Exception {
149         InputStream payload = part.getBody(InputStream.class, null);
150
151         //check if this is an xml part
152         if(part.getMediaType().equals(MediaType.APPLICATION_XML_TYPE)){
153             if(payload != null){
154                 Document document = DocumentUtils.parseDocument(payload);
155                 //TODO: callback to handler if registered to validate the
156                 //document
157                 Map<String, Object> objectProps = DocumentUtils.parseProperties(document);
158                 docModel.setProperties(partMeta.getLabel(), objectProps);
159             }
160         }
161     }
162
163     /**
164      * extractPart extracts an XML object from given DocumentModel
165      * @param docModel
166      * @param schema of the object to extract
167      * @param partMeta metadata for the object to extract
168      * @throws Exception
169      */
170     protected void extractPart(DocumentModel docModel, String schema, ObjectPartType partMeta)
171             throws Exception {
172         MediaType mt = MediaType.valueOf(partMeta.getContent().getContentType());
173         if(mt.equals(MediaType.APPLICATION_XML_TYPE)){
174             Map<String, Object> objectProps = docModel.getProperties(schema);
175             //unqualify properties before sending the doc over the wire (to save bandwidh)
176             //FIXME: is there a better way to avoid duplication of a collection?
177             Map<String, Object> unQObjectProperties = new HashMap<String, Object>();
178             Set<Entry<String, Object>> qualifiedEntries = objectProps.entrySet();
179             for(Entry<String, Object> entry : qualifiedEntries){
180                 String unqProp = getUnQProperty(entry.getKey());
181                 unQObjectProperties.put(unqProp, entry.getValue());
182             }
183             Document doc = DocumentUtils.buildDocument(partMeta, schema, unQObjectProperties);
184             if(logger.isDebugEnabled()){
185                 DocumentUtils.writeDocument(doc, System.out);
186             }
187             MultipartServiceContext ctx = (MultipartServiceContext) getServiceContext();
188             ctx.addOutputPart(schema, doc, partMeta.getContent().getContentType());
189         } //TODO: handle other media types
190     }
191     
192     public AuthorityRefList getAuthorityRefs(
193                 DocumentWrapper<DocumentModel> docWrapper,
194                 String pathPrefix,
195                 List<String> authRefFields) {
196         AuthorityRefList authRefList = new AuthorityRefList();
197         try {
198             DocumentModel docModel = docWrapper.getWrappedObject();
199             List<AuthorityRefList.AuthorityRefItem> list = 
200                 authRefList.getAuthorityRefItem();
201
202             for(String field:authRefFields){
203                         String refName = (String)docModel.getPropertyValue(pathPrefix+field);
204                         if(refName==null)
205                                 continue;
206                 try{
207                         RefNameUtils.AuthorityTermInfo termInfo =
208                                 RefNameUtils.parseAuthorityTermInfo(refName);
209                         AuthorityRefList.AuthorityRefItem ilistItem = 
210                                 new AuthorityRefList.AuthorityRefItem();
211                         ilistItem.setRefName(refName);
212                         ilistItem.setAuthDisplayName(termInfo.inAuthority.displayName);
213                         ilistItem.setItemDisplayName(termInfo.displayName);
214                         ilistItem.setSourceField(field);
215                         ilistItem.setUri(termInfo.getRelativeUri());
216                     list.add(ilistItem);
217                 } catch( Exception e ) {
218                     if (logger.isDebugEnabled()) {
219                         logger.debug("Caught exception in getAuthorityRefs", e);
220                     }
221                 }
222             }
223         } catch (Exception e) {
224             if (logger.isDebugEnabled()) {
225                 logger.debug("Caught exception in getAuthorityRefs", e);
226             }
227             Response response = Response.status(
228                     Response.Status.INTERNAL_SERVER_ERROR).entity("Index failed").type("text/plain").build();
229             throw new WebApplicationException(response);
230         }
231         return authRefList;
232     }
233
234
235 }