1 package ejava.examples.ejbwar.inventory.rs;
2
3 import javax.inject.Inject;
4 import javax.ws.rs.DELETE;
5 import javax.ws.rs.DefaultValue;
6 import javax.ws.rs.GET;
7 import javax.ws.rs.Path;
8 import javax.ws.rs.PathParam;
9 import javax.ws.rs.Produces;
10 import javax.ws.rs.QueryParam;
11 import javax.ws.rs.core.Context;
12 import javax.ws.rs.core.MediaType;
13 import javax.ws.rs.core.Request;
14 import javax.ws.rs.core.Response;
15 import javax.ws.rs.core.UriInfo;
16
17 import org.slf4j.Logger;
18 import org.slf4j.LoggerFactory;
19
20 import ejava.examples.ejbwar.inventory.bo.Categories;
21 import ejava.examples.ejbwar.inventory.bo.Category;
22 import ejava.examples.ejbwar.inventory.ejb.InventoryMgmtEJB;
23
24
25
26
27
28
29 @Path("categories")
30 public class CategoriesResource {
31 private static final Logger log = LoggerFactory.getLogger(CategoriesResource.class);
32
33 @Inject
34 private InventoryMgmtEJB ejb;
35 @Context
36 private Request request;
37 @Context
38 private UriInfo uriInfo;
39
40
41
42
43
44
45
46
47
48 @GET @Path("")
49 @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
50 public Response findCategoriesByName(
51 @QueryParam("name") @DefaultValue("") String name,
52 @QueryParam("offset") @DefaultValue("0") int offset,
53 @QueryParam("limit") @DefaultValue("0") int limit) {
54 log.debug(String.format("%s %s", request.getMethod(), uriInfo.getAbsolutePath()));
55
56 try {
57 Categories categories = ejb.findCategoryByName(name, offset, limit);
58
59 return Response.ok(categories)
60 .build();
61 } catch (Exception ex) {
62 return ResourceHelper.serverError(log, "get categories", ex).build();
63 }
64 }
65
66
67
68
69
70
71
72
73 @GET @Path("{id}")
74 @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
75 public Response getCategory(@PathParam("id")int id) {
76 log.debug(String.format("%s %s", request.getMethod(), uriInfo.getAbsolutePath()));
77
78 try {
79 Category category = ejb.getCategory(id);
80 if (category != null) {
81 return Response.ok(category)
82 .tag("" + category.getVersion())
83 .build();
84 }
85 else {
86 return Response.status(Response.Status.NOT_FOUND)
87 .entity(String.format("unable to locate category %d", id))
88 .type(MediaType.TEXT_PLAIN)
89 .build();
90 }
91 } catch (Exception ex) {
92 return ResourceHelper.serverError(log, "get category", ex).build();
93 }
94 }
95
96
97
98
99
100
101
102 @DELETE @Path("{id}")
103 public Response deleteCategory(@PathParam("id")int id) {
104 log.debug(String.format("%s %s", request.getMethod(), uriInfo.getAbsolutePath()));
105
106 try {
107 ejb.deleteCategory(id);
108 return Response.noContent().build();
109 } catch (Exception ex) {
110 return ResourceHelper.serverError(log, "delete category", ex).build();
111 }
112 }
113
114 }