]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
f4cfce982c98d6ba8020fb178a9001bb23aea85f
[tmp/jakarta-migration.git] /
1 package org.collectionspace.hello.services;
2
3 import java.io.ByteArrayInputStream;
4 import java.io.ByteArrayOutputStream;
5 import java.io.IOException;
6 import java.util.Iterator;
7 import javax.ws.rs.Consumes;
8 import javax.ws.rs.GET;
9 import javax.ws.rs.Path;
10 import javax.ws.rs.Produces;
11 import javax.ws.rs.DELETE;
12 import javax.ws.rs.POST;
13 import javax.ws.rs.PUT;
14 import javax.ws.rs.PathParam;
15 import javax.ws.rs.WebApplicationException;
16 import javax.ws.rs.core.MediaType;
17 import javax.ws.rs.core.Response;
18 import javax.ws.rs.core.UriBuilder;
19 import javax.xml.bind.JAXBContext;
20 import javax.xml.bind.Marshaller;
21
22 import org.collectionspace.hello.PersonNuxeo;
23
24 import org.collectionspace.services.nuxeo.NuxeoConnector;
25 import org.collectionspace.world.DublincoreNuxeo;
26 import org.dom4j.Document;
27 import org.dom4j.Element;
28 import org.dom4j.io.SAXReader;
29 import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
30 import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataOutput;
31
32
33 import org.nuxeo.common.utils.IdUtils;
34 import org.nuxeo.ecm.core.api.CoreSession;
35 import org.nuxeo.ecm.core.api.DocumentModel;
36
37
38 import org.nuxeo.ecm.core.api.DocumentRef;
39 import org.nuxeo.ecm.core.api.IdRef;
40 import org.nuxeo.ecm.core.api.repository.RepositoryInstance;
41 import org.nuxeo.ecm.core.client.NuxeoClient;
42 import org.nuxeo.ecm.core.io.DocumentPipe;
43 import org.nuxeo.ecm.core.io.DocumentReader;
44 import org.nuxeo.ecm.core.io.DocumentWriter;
45 import org.nuxeo.ecm.core.io.impl.DocumentPipeImpl;
46 import org.nuxeo.ecm.core.io.impl.plugins.SingleDocumentReader;
47 import org.nuxeo.ecm.core.io.impl.plugins.XMLDocumentWriter;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 @Path("/multischema")
52 @Consumes("application/xml")
53 @Produces("application/xml")
54 public class MultischemaResource extends CollectionSpaceResource {
55
56     final Logger logger = LoggerFactory.getLogger(MultischemaResource.class);
57
58     public MultischemaResource() {
59     }
60
61     @POST
62     @Consumes("multipart/form-data")
63     public Response createPerson(MultipartFormDataInput multipart) {
64
65         PersonNuxeo personPart = new PersonNuxeo();
66         DublincoreNuxeo dcPart = new DublincoreNuxeo();
67         CoreSession repoSession = null;
68         RepositoryInstance repo = null;
69         try{
70             if(multipart.getFormData().containsKey("dublincore")){
71                 dcPart = multipart.getFormDataPart("dublincore", DublincoreNuxeo.class, null);
72             }
73             if(multipart.getFormData().containsKey("hello")){
74                 personPart = multipart.getFormDataPart("hello", PersonNuxeo.class, null);
75             }
76
77             repo = getRepository();
78             repoSession = repo.getSession();
79             DocumentRef nuxeoWspace = new IdRef(CS_PERSON_WORKSPACE_UID);
80             DocumentModel wspacePeople = repoSession.getDocument(nuxeoWspace);
81             String wspacePath = wspacePeople.getPathAsString();
82             String docType = "Hello";
83             String id = IdUtils.generateId("New " + docType);
84             //create document model
85             DocumentModel helloDoc = repoSession.createDocumentModel(wspacePath, id, docType);
86             fillDocument(personPart, helloDoc);
87             //create document with documentmodel
88             helloDoc = repoSession.createDocument(helloDoc);
89             repoSession.save();
90
91             personPart.setId(helloDoc.getId());
92
93         }catch(Exception e){
94             e.printStackTrace();
95             Response response = Response.status(Response.Status.NOT_FOUND).entity(
96                     "Create failed").type("text/plain").build();
97             throw new WebApplicationException(response);
98         }finally{
99             try{
100 //                repo.close(repoSession);
101             }catch(Exception e){
102                 logger.error("Could not close the repository session", e);
103                 throw new WebApplicationException();
104             }
105         }
106         if(logger.isDebugEnabled()){
107             verbosePerson("createPerson: person", personPart);
108             verboseDublin("createPerson: dublincore", dcPart);
109         }
110         UriBuilder path = UriBuilder.fromResource(MultischemaResource.class);
111         path.path("" + personPart.getId());
112         Response response = Response.created(path.build()).build();
113         return response;
114     }
115
116     @GET
117     @Path("{id}")
118     @Produces("multipart/form-data")
119     public MultipartFormDataOutput getPerson(@PathParam("id") String id) {
120
121         PersonNuxeo personPart = new PersonNuxeo();
122         DublincoreNuxeo dublinPart = new DublincoreNuxeo();
123         MultipartFormDataOutput output = new MultipartFormDataOutput();
124         RepositoryInstance repo = null;
125         CoreSession repoSession = null;
126
127         try{
128             repo = getRepository();
129             repoSession = repo.getSession();
130             DocumentRef helloDocRef = new IdRef(id);
131             DocumentModel helloDoc = repoSession.getDocument(helloDocRef);
132             Document doc = getDocument(repoSession, helloDoc);
133             Element root = doc.getRootElement();
134             //TODO: recognize schema thru namespace uri
135             //Namespace ns = new Namespace("hello", "http://collectionspace.org/hello");
136             Iterator<Element> siter = root.elementIterator("schema");
137             while(siter.hasNext()){
138
139                 Element s = siter.next();
140
141                 //TODO: recognize schema thru namespace uri
142                 if("hello".equals(s.attribute("name").getValue())){
143                     personPart.setId(id);
144                     Element ele = s.element("cversion");
145                     if(ele != null){
146                         personPart.setVersion((String) ele.getData());
147                     }
148                     ele = s.element("firstName");
149                     if(ele != null){
150                         personPart.setFirstName((String) ele.getData());
151                     }
152                     ele = s.element("lastName");
153                     if(ele != null){
154                         personPart.setLastName((String) ele.getData());
155                     }
156                     ele = s.element("city");
157                     if(ele != null){
158                         personPart.setCity((String) ele.getData());
159                     }
160                     ele = s.element("state");
161                     if(ele != null){
162                         personPart.setState((String) ele.getData());
163                     }
164                     ele = s.element("zip");
165                     if(ele != null){
166                         personPart.setZip((String) ele.getData());
167                     }
168                     ele = s.element("country");
169                     if(ele != null){
170                         personPart.setCountry((String) ele.getData());
171                     }
172                 }else if("dublincore".equals(s.attribute("name").getValue())){
173                     Element ele = s.element("title");
174                     if(ele != null){
175                         dublinPart.setTitle((String) ele.getData());
176                     }
177                 }
178             }//while
179             if(logger.isDebugEnabled()){
180                 verbosePerson("getPerson:hello:", personPart);
181                 verboseDublin("getPerson:dublincore:", dublinPart);
182             }
183             output.addFormData("hello", personPart, MediaType.APPLICATION_XML_TYPE);
184             output.addFormData("dublincore", dublinPart, MediaType.APPLICATION_XML_TYPE);
185
186         }catch(Exception e){
187             e.printStackTrace();
188             Response response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(
189                     "Get failed").type("text/plain").build();
190             throw new WebApplicationException(response);
191         }finally{
192             try{
193 //                repo.close(repoSession);
194             }catch(Exception e){
195                 logger.error("Could not close the repository session", e);
196                 throw new WebApplicationException();
197             }
198         }
199         if(personPart == null){
200             Response response = Response.status(Response.Status.NOT_FOUND).entity(
201                     "Get failed, the requested person ID:" + id + ": was not found.").type("text/plain").build();
202             throw new WebApplicationException(response);
203         }
204
205         return output;
206     }
207
208     @PUT
209     @Path("{id}")
210     public PersonNuxeo updatePerson(
211             @PathParam("id") String id,
212             PersonNuxeo personPart) {
213         if(logger.isDebugEnabled()){
214             verbosePerson("updating person input", personPart);
215         }
216         CoreSession repoSession = null;
217         RepositoryInstance repo = null;
218         try{
219             repo = getRepository();
220             repoSession = repo.getSession();
221             DocumentRef helloDocRef = new IdRef(id);
222             DocumentModel helloDoc = repoSession.getDocument(helloDocRef);
223             fillDocument(personPart, helloDoc);
224             repoSession.saveDocument(helloDoc);
225             repoSession.save();
226         }catch(Exception e){
227             //FIXME: NOT_FOUND?
228             Response response = Response.status(Response.Status.NOT_FOUND).entity(
229                     "Update failed ").type("text/plain").build();
230             throw new WebApplicationException(response);
231         }finally{
232             try{
233 //                repo.close(repoSession);
234             }catch(Exception e){
235                 logger.error("Could not close the repository session", e);
236                 throw new WebApplicationException();
237             }
238         }
239         return personPart;
240     }
241
242     @DELETE
243     @Path("{id}")
244     public void deletePerson(@PathParam("id") String id) {
245         if(logger.isDebugEnabled()){
246             logger.debug("deleting person with id=" + id);
247         }
248         CoreSession repoSession = null;
249         RepositoryInstance repo = null;
250         try{
251             repo = getRepository();
252             repoSession = repo.getSession();
253             DocumentRef helloDocRef = new IdRef(id);
254             repoSession.removeDocument(helloDocRef);
255             repoSession.save();
256         }catch(Exception e){
257             //FIXME: NOT_FOUND?
258             Response response = Response.status(Response.Status.NOT_FOUND).entity(
259                     "Delete failed ").type("text/plain").build();
260             throw new WebApplicationException(response);
261         }finally{
262             try{
263 //                repo.close(repoSession);
264             }catch(Exception e){
265                 logger.error("Could not close the repository session", e);
266                 throw new WebApplicationException();
267             }
268         }
269
270     }
271
272     synchronized private RepositoryInstance getRepository() throws Exception {
273         NuxeoConnector rmiClient = NuxeoConnector.getInstance();
274         rmiClient.initialize();
275         NuxeoClient client = rmiClient.getClient();
276         RepositoryInstance repo = client.openRepository();
277         if(logger.isDebugEnabled()){
278             logger.debug("deployNuxeo: repository root: " + repo.getRootDocument());
279         }
280         return repo;
281     }
282
283     private Document getDocument(CoreSession repoSession, DocumentModel helloDoc)
284             throws Exception {
285         Document doc = null;
286         DocumentWriter writer = null;
287         DocumentReader reader = null;
288         ByteArrayOutputStream baos = null;
289         ByteArrayInputStream bais = null;
290         try{
291             baos = new ByteArrayOutputStream();
292             reader = new SingleDocumentReader(repoSession,
293                     helloDoc);
294             writer = new XMLDocumentWriter(baos);
295             DocumentPipe pipe = new DocumentPipeImpl();
296
297             pipe.setReader(reader);
298             pipe.setWriter(writer);
299             pipe.run();
300             bais = new ByteArrayInputStream(baos.toByteArray());
301             SAXReader saxReader = new SAXReader();
302             doc = saxReader.read(bais);
303         }finally{
304             if(reader != null){
305                 reader.close();
306             }
307             if(writer != null){
308                 writer.close();
309             }
310             try{
311                 if(bais != null){
312                     bais.close();
313                 }
314                 if(baos != null){
315                     baos.close();
316                 }
317             }catch(IOException ioe){
318                 logger.error("Failed to close io streams with {}", ioe);
319                 throw new WebApplicationException();
320             }
321         }
322         return doc;
323     }
324
325     private void fillDocument(PersonNuxeo p, DocumentModel helloDoc) throws Exception {
326         if(p.getFirstName() != null){
327             helloDoc.setPropertyValue("dublincore:title", p.getFirstName() + " " + p.getLastName());
328             helloDoc.setPropertyValue("hello:firstName", p.getFirstName());
329         }
330         if(p.getLastName() != null){
331             helloDoc.setPropertyValue("hello:lastName", p.getLastName());
332         }
333         if(p.getStreet() != null){
334             helloDoc.setPropertyValue("hello:street", p.getStreet());
335         }
336         if(p.getCity() != null){
337             helloDoc.setPropertyValue("hello:city", p.getCity());
338         }
339         if(p.getState() != null){
340             helloDoc.setPropertyValue("hello:state", p.getState());
341         }
342         if(p.getZip() != null){
343             helloDoc.setPropertyValue("hello:zip", p.getZip());
344         }
345         if(p.getCountry() != null){
346             helloDoc.setPropertyValue("hello:country", p.getCountry());
347         }
348     }
349
350     private void verbosePerson(String msg, PersonNuxeo person) {
351         try{
352             if(logger.isDebugEnabled()){
353                 logger.debug(msg);
354             }
355             JAXBContext jc = JAXBContext.newInstance(
356                     PersonNuxeo.class);
357
358             Marshaller m = jc.createMarshaller();
359             m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
360                     Boolean.TRUE);
361             m.marshal(person, System.out);
362         }catch(Exception e){
363             e.printStackTrace();
364         }
365
366     }
367
368     private void verboseDublin(String msg, DublincoreNuxeo dubin) {
369         try{
370             if(logger.isDebugEnabled()){
371                 logger.debug(msg);
372             }
373             JAXBContext jc = JAXBContext.newInstance(
374                     DublincoreNuxeo.class);
375
376             Marshaller m = jc.createMarshaller();
377             m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
378                     Boolean.TRUE);
379             m.marshal(dubin, System.out);
380         }catch(Exception e){
381             e.printStackTrace();
382         }
383
384     }
385 }