View Javadoc
1   package info.ejava.examples.jaxrs.todos.rs;
2   
3   import java.net.URI;
4   
5   import javax.ejb.EJB;
6   import javax.ws.rs.Consumes;
7   import javax.ws.rs.DELETE;
8   import javax.ws.rs.DefaultValue;
9   import javax.ws.rs.GET;
10  import javax.ws.rs.POST;
11  import javax.ws.rs.PUT;
12  import javax.ws.rs.Path;
13  import javax.ws.rs.PathParam;
14  import javax.ws.rs.Produces;
15  import javax.ws.rs.QueryParam;
16  import javax.ws.rs.core.Context;
17  import javax.ws.rs.core.MediaType;
18  import javax.ws.rs.core.Response;
19  import javax.ws.rs.core.Response.ResponseBuilder;
20  import javax.ws.rs.core.Response.Status;
21  import javax.ws.rs.core.UriInfo;
22  
23  import org.slf4j.Logger;
24  import org.slf4j.LoggerFactory;
25  
26  import info.ejava.examples.jaxrs.todos.dto.MessageDTO;
27  import info.ejava.examples.jaxrs.todos.dto.TodoItemDTO;
28  import info.ejava.examples.jaxrs.todos.dto.TodoListDTO;
29  import info.ejava.examples.jaxrs.todos.dto.TodoListListDTO;
30  import info.ejava.examples.jaxrs.todos.ejb.InternalErrorException;
31  import info.ejava.examples.jaxrs.todos.ejb.InvalidRequestException;
32  import info.ejava.examples.jaxrs.todos.ejb.ResourceNotFoundException;
33  import info.ejava.examples.jaxrs.todos.ejb.TodosMgmtRemote;
34  
35  @Path("todo_lists")
36  public class TodoListsResource {
37      private static final Logger logger = LoggerFactory.getLogger(TodoListsResource.class);
38      
39      @EJB
40      private TodosMgmtRemote todosMgmt;
41      @Context
42      private UriInfo uriInfo;
43      
44      @GET @Path("")
45      @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
46      public Response getTodoLists(
47              @QueryParam("offset") @DefaultValue("0") Integer offset, 
48              @QueryParam("limit") @DefaultValue("10") Integer limit) {
49          ResponseBuilder rb = null;
50          try {
51              TodoListListDTO entity = todosMgmt.getTodoLists(offset, limit);
52              rb = Response.ok(entity)
53                      .contentLocation(uriInfo.getAbsolutePath());
54          } catch (InternalErrorException ex) {
55              rb = Response.serverError().entity(ex.getMessage());
56          } catch (Exception ex) {
57              logger.info("Unexpected exception getting TodoLists", ex);
58              String msg = String.format("Unexpected error getting TodoLists: %s", ex.toString());
59              rb = Response.serverError()
60                      .entity(new MessageDTO(msg));
61          }
62          return rb.build();
63      }
64      
65      private ResponseBuilder getUndexpectedErrorResponse(String message, Exception ex) {
66          logger.info(message, ex);
67          String msg = String.format("%s: %s", message, ex.toString());
68          return Response.serverError()
69                  .entity(new MessageDTO(msg));        
70      }
71      private ResponseBuilder getInternalErrorResponse(Exception ex) {
72          logger.info(ex.getMessage());
73          return Response.serverError()
74                  .entity(new MessageDTO(ex.getMessage()));        
75      }
76      private ResponseBuilder getBadRequestResponse(Exception ex) {
77          logger.debug(ex.getMessage());
78          return Response.status(Status.BAD_REQUEST)
79                  .entity(new MessageDTO(ex.getMessage()));        
80      }
81      private ResponseBuilder getNotFoundResponse(Exception ex) {
82          logger.debug(ex.getMessage());
83          return Response.status(Status.NOT_FOUND)
84                  .entity(new MessageDTO(ex.getMessage()));        
85      }
86      
87      @POST
88      @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
89      @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
90      public Response createTodoList(TodoListDTO todoList) {
91          ResponseBuilder rb = null;
92          try {
93              TodoListDTO entity = todosMgmt.createTodoList(todoList);
94              URI location = uriInfo.getBaseUriBuilder()
95                      .path(TodoListsResource.class)
96                      .path(TodoListsResource.class, "getTodoList")
97                      .build(entity.getName());
98              rb = Response.created(location)                    
99                      .contentLocation(location)
100                     .entity(entity);
101         } catch (InvalidRequestException ex) {
102             rb = getBadRequestResponse(ex);
103         } catch (InternalErrorException ex) {
104             rb = getInternalErrorResponse(ex);
105         } catch (Exception ex) {
106             rb = getUndexpectedErrorResponse("Unexpected error creating TodoList", ex);
107         }
108         return rb.build();
109     }
110 
111     @GET @Path("{listName}")
112     @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
113     public Response getTodoList(@PathParam("listName") String listName) {
114         ResponseBuilder rb = null;
115         try {
116             TodoListDTO entity = todosMgmt.getTodoList(listName);
117             rb = Response.ok(entity)
118                     .contentLocation(uriInfo.getAbsolutePath());
119         } catch (ResourceNotFoundException ex) {
120             rb = getNotFoundResponse(ex);
121         } catch (InternalErrorException ex) {
122             rb = getInternalErrorResponse(ex);
123         } catch (Exception ex) {
124             rb = getUndexpectedErrorResponse("Unexpected error creating TodoList", ex);
125         }
126         return rb.build();        
127     }
128 
129     @POST @Path("{listName}")
130     @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
131     public Response renameTodoList(
132             @PathParam("listName") String oldName,
133             @QueryParam("name") String newName) {
134         ResponseBuilder rb = null;
135         try {
136             TodoListDTO entity = todosMgmt.renameTodoList(oldName, newName);
137             URI location = uriInfo.getBaseUriBuilder()
138                     .path(TodoListsResource.class, "getTodoList")
139                     .build(entity.getName());
140             rb = Response.ok(entity)
141                     .location(location)
142                     .contentLocation(location);
143         } catch (ResourceNotFoundException ex) {
144             rb = getNotFoundResponse(ex);
145         } catch (InternalErrorException ex) {
146             rb = getInternalErrorResponse(ex);
147         } catch (Exception ex) {
148             rb = getUndexpectedErrorResponse("Unexpected error creating TodoList", ex);
149         }
150         return rb.build();        
151     }
152     
153     @DELETE @Path("{listName}")
154     public Response deleteTodoList(@PathParam("listName") String listName) {
155         ResponseBuilder rb = null;
156         try {
157             todosMgmt.deleteTodoList(listName);
158             rb = Response.noContent();
159         } catch (ResourceNotFoundException ex) {
160             rb = getNotFoundResponse(ex);
161         } catch (InternalErrorException ex) {
162             rb = getInternalErrorResponse(ex);
163         } catch (Exception ex) {
164             rb = getUndexpectedErrorResponse("Unexpected error deleting TodoList", ex);
165         }
166         return rb.build();                
167     }
168 
169     
170     @DELETE
171     public Response deleteAllTodos() {
172         ResponseBuilder rb=null;
173         try {
174             todosMgmt.deleteAll();
175             rb=Response.ok();
176         } catch (InternalErrorException ex) {
177             rb = getInternalErrorResponse(ex);
178         } catch (Exception ex) {
179             rb = getUndexpectedErrorResponse("Unexpected error deleting all Todos", ex);
180         }
181         return rb.build();
182     }
183     
184 //========================    
185     
186     @POST @Path("{listName}/todo_items")
187     @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
188     @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
189     public Response addTodoItem(
190             @PathParam("listName") String listName, 
191             TodoItemDTO item) {
192         ResponseBuilder rb = null;
193         try {
194             todosMgmt.addTodoListItem(listName, item);
195             rb = Response.ok();
196         } catch (ResourceNotFoundException ex) {
197             rb = getNotFoundResponse(ex);
198         } catch (InvalidRequestException ex) {
199             rb = getBadRequestResponse(ex);
200         } catch (InternalErrorException ex) {
201             rb = getInternalErrorResponse(ex);
202         } catch (Exception ex) {
203             rb = getUndexpectedErrorResponse("Unexpected error adding TodoItem", ex);
204         }
205         return rb.build();                        
206     }
207 
208     
209     @PUT @Path("{listName}/todo_items/{itemName}")
210     @Consumes({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
211     @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
212     public Response updateTodoItem(
213             @PathParam("listName") String listName,
214             @PathParam("itemName") String itemName,
215             TodoItemDTO item) {
216         ResponseBuilder rb = null;
217         try {
218             TodoItemDTO entity = todosMgmt.updateTodoListItem(listName, itemName, item);
219             rb = Response.ok(entity);
220         } catch (ResourceNotFoundException ex) {
221             rb = getNotFoundResponse(ex);
222         } catch (InvalidRequestException ex) {
223             rb = getBadRequestResponse(ex);
224         } catch (InternalErrorException ex) {
225             rb = getInternalErrorResponse(ex);
226         } catch (Exception ex) {
227             rb = getUndexpectedErrorResponse("Unexpected error updating TodoItems", ex);
228         }
229         return rb.build();                                
230     }
231 
232     
233     @DELETE @Path("{listName}/todo_items/{itemName}")
234     public Response deleteTodoItem(
235             @PathParam("listName") String listName, 
236             @PathParam("itemName") String itemName) {
237         ResponseBuilder rb = null;
238         try {
239             todosMgmt.deleteTodoListItem(listName, itemName);
240             rb = Response.noContent();
241         } catch (ResourceNotFoundException ex) {
242             rb = getNotFoundResponse(ex);
243         } catch (InternalErrorException ex) {
244             rb = getInternalErrorResponse(ex);
245         } catch (Exception ex) {
246             rb = getUndexpectedErrorResponse("Unexpected error deleting TodoItem", ex);
247         }
248         return rb.build();                                
249     }
250 }