]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
b8c06b852e73a18ef2f93fb67b883237fddcddc8
[tmp/jakarta-migration.git] /
1 package org.collectionspace.hello.services;
2
3 import java.net.URI;
4 import java.util.List;
5 import javax.ws.rs.Consumes;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.POST;
8 import javax.ws.rs.PUT;
9 import javax.ws.rs.Path;
10 import javax.ws.rs.PathParam;
11 import javax.ws.rs.Produces;
12 import javax.ws.rs.WebApplicationException;
13 import javax.ws.rs.core.Response;
14 import java.util.Map;
15 import java.util.concurrent.ConcurrentHashMap;
16 import java.util.concurrent.atomic.AtomicLong;
17 import javax.ws.rs.DELETE;
18 import javax.ws.rs.core.Context;
19 import javax.ws.rs.core.UriBuilder;
20 import javax.ws.rs.core.UriInfo;
21 import javax.xml.bind.JAXBContext;
22 import javax.xml.bind.Marshaller;
23 import org.collectionspace.hello.Person;
24 import org.collectionspace.hello.Persons.PersonListItem;
25 import org.collectionspace.hello.Persons;
26 import org.slf4j.Logger;
27 import org.slf4j.LoggerFactory;
28
29 @Path("/persons")
30 @Consumes("application/xml")
31 @Produces("application/xml")
32 public class PersonResource {
33
34     final Logger logger = LoggerFactory.getLogger(PersonResource.class);
35     private Map<Long, Person> personDB = new ConcurrentHashMap<Long, Person>();
36     private AtomicLong idCounter = new AtomicLong();
37
38     public PersonResource() {
39     }
40
41     @POST
42     public Response createPerson(Person p) {
43         p.setId(idCounter.incrementAndGet());
44         p.setVersion(1);
45         personDB.put(p.getId(), p);
46         verbose("created person", p);
47         UriBuilder path = UriBuilder.fromResource(PersonResource.class);
48         path.path("" + p.getId());
49         Response response = Response.created(path.build()).build();
50         return response;
51     }
52
53     @GET
54     @Path("{id}")
55     public Person getPerson(@PathParam("id") Long id) {
56         Person p = personDB.get(id);
57         if (p == null) {
58             Response response = Response.status(Response.Status.NOT_FOUND).entity(
59                     "Get failed, the requested person ID:" + id + ": was not found.").type("text/plain").build();
60             throw new WebApplicationException(response);
61         }
62         verbose("get person", p);
63         return p;
64     }
65
66     @PUT
67     @Path("{id}")
68     public Person updatePerson(@PathParam("id") Long id, Person update) {
69         Person current = personDB.get(id);
70         if (current == null) {
71             Response response = Response.status(Response.Status.NOT_FOUND).entity(
72                     "Update failed, the person ID:" + id + ": was not found.").type("text/plain").build();
73             throw new WebApplicationException(response);
74         }
75         verbose("update person input", update);
76         //todo: intelligent merge needed
77         current.setFirstName(update.getFirstName());
78         current.setLastName(update.getLastName());
79         current.setStreet(update.getStreet());
80         current.setState(update.getState());
81         current.setZip(update.getZip());
82         current.setCountry(update.getCountry());
83         current.setVersion(current.getVersion() + 1);
84         verbose("update person output", current);
85         return current;
86     }
87
88     @GET
89     public Persons getPersons(@Context UriInfo ui) {
90         Persons persons = new Persons();
91         List<Persons.PersonListItem> list = persons.getPersonListItem();
92         // builder starts with current URI and has appended path of getPerson method
93         UriBuilder ub = ui.getAbsolutePathBuilder().path(this.getClass(), "getPerson");
94         for (Person p : personDB.values()) {
95             PersonListItem pli = new PersonListItem();
96             pli.setFirstName(p.getFirstName());
97             pli.setLastName(p.getLastName());
98             pli.setId(p.getId());
99             // builder has {id} variable that must be filled in for each customer
100             URI uri = ub.build(p.getId());
101             pli.setUri(uri.toString());
102             list.add(pli);
103         }
104         return persons;
105     }
106
107     @DELETE
108     @Path("{id}")
109     public void deletePerson(@PathParam("id") Long id) {
110         Person removed = personDB.remove(id);
111         if (removed == null) {
112             Response response = Response.status(Response.Status.NOT_FOUND).entity(
113                     "Delete failed, the person ID:" + id + ": was not found.").type("text/plain").build();
114             throw new WebApplicationException(response);
115         }
116         verbose("deleted person", removed);
117     }
118
119     private void verbose(String msg, Person p) {
120         try {
121             System.out.println("PersonResource : " + msg);
122             JAXBContext jc = JAXBContext.newInstance(Person.class);
123             Marshaller m = jc.createMarshaller();
124             m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,
125                     Boolean.TRUE);
126             m.marshal(p, System.out);
127         } catch (Exception e) {
128             e.printStackTrace();
129         }
130     }
131
132 //    @POST
133 //    @Consumes("application/xml")
134 //    public Response createPerson(InputStream is) {
135 //        Person p = readPerson(is);
136 //        p.setId(idCounter.incrementAndGet());
137 //        p.setVersion(1);
138 //        personDB.put(p.getId(), p);
139 //        try {
140 //            System.out.println("Created Person " + p.getId());
141 //            outputPerson(System.out, p);
142 //        } catch (IOException ioe) {
143 //            throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
144 //        }
145 //        return Response.created(URI.create("/persons/" + p.getId())).build();
146 //
147 //    }
148 //
149 //    @GET
150 //    @Path("{id}")
151 //    @Produces("application/xml")
152 //    public StreamingOutput getPerson(@PathParam("id") int id) {
153 //        final Person p = personDB.get(id);
154 //        if (p == null) {
155 //            throw new WebApplicationException(Response.Status.NOT_FOUND);
156 //        }
157 //        return new StreamingOutput() {
158 //
159 //            public void write(OutputStream outputStream) throws IOException, WebApplicationException {
160 //                outputPerson(outputStream, p);
161 //            }
162 //        };
163 //    }
164 //
165 //    @PUT
166 //    @Path("{id}")
167 //    @Consumes("application/xml")
168 //    @Produces("application/xml")
169 //    public StreamingOutput updatePerson(@PathParam("id") int id, InputStream is) {
170 //        Person update = readPerson(is);
171 //        Person current = personDB.get(id);
172 //        if (current == null) {
173 //            throw new WebApplicationException(Response.Status.NOT_FOUND);
174 //        }
175 //
176 //        current.setFirstName(update.getFirstName());
177 //        current.setLastName(update.getLastName());
178 //        current.setStreet(update.getStreet());
179 //        current.setState(update.getState());
180 //        current.setZip(update.getZip());
181 //        current.setCountry(update.getCountry());
182 //        current.setVersion(current.getVersion() + 1);
183 //        final Person scurrent = current;
184 //        return new StreamingOutput() {
185 //
186 //            public void write(OutputStream outputStream) throws IOException, WebApplicationException {
187 //                outputPerson(outputStream, scurrent);
188 //            }
189 //        };
190 //    }
191 //
192 //    protected void outputPerson(OutputStream os, Person p) throws IOException {
193 //        PrintStream writer = new PrintStream(os);
194 //        writer.println("<Person id=\"" + p.getId() + "\" version=\"" + p.getVersion() + "\">");
195 //        writer.println("   <first-name>" + p.getFirstName() + "</first-name>");
196 //        writer.println("   <last-name>" + p.getLastName() + "</last-name>");
197 //        writer.println("   <street>" + p.getStreet() + "</street>");
198 //        writer.println("   <city>" + p.getCity() + "</city>");
199 //        writer.println("   <state>" + p.getState() + "</state>");
200 //        writer.println("   <zip>" + p.getZip() + "</zip>");
201 //        writer.println("   <country>" + p.getCountry() + "</country>");
202 //        writer.println("</Person>");
203 //    }
204 //
205 //    protected Person readPerson(InputStream is) {
206 //        try {
207 //            DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
208 //            Document doc = builder.parse(is);
209 //            Element root = doc.getDocumentElement();
210 //            Person p = new Person();
211 //            if (root.getAttribute("id") != null && !root.getAttribute("id").trim().equals("")) {
212 //                p.setId(Integer.valueOf(root.getAttribute("id")));
213 //            }
214 //            if (root.getAttribute("version") != null && !root.getAttribute("version").trim().equals("")) {
215 //                p.setVersion(Integer.valueOf(root.getAttribute("version")));
216 //            }
217 //            NodeList nodes = root.getChildNodes();
218 //            for (int i = 0; i < nodes.getLength(); i++) {
219 //                Element element = (Element) nodes.item(i);
220 //                if (element.getTagName().equals("first-name")) {
221 //                    p.setFirstName(element.getTextContent());
222 //                } else if (element.getTagName().equals("last-name")) {
223 //                    p.setLastName(element.getTextContent());
224 //                } else if (element.getTagName().equals("street")) {
225 //                    p.setStreet(element.getTextContent());
226 //                } else if (element.getTagName().equals("city")) {
227 //                    p.setCity(element.getTextContent());
228 //                } else if (element.getTagName().equals("state")) {
229 //                    p.setState(element.getTextContent());
230 //                } else if (element.getTagName().equals("zip")) {
231 //                    p.setZip(element.getTextContent());
232 //                } else if (element.getTagName().equals("country")) {
233 //                    p.setCountry(element.getTextContent());
234 //                }
235 //            }
236 //            return p;
237 //        } catch (Exception e) {
238 //            throw new WebApplicationException(e, Response.Status.BAD_REQUEST);
239 //        }
240 //    }
241 }