View Javadoc
1   /*
2    * JBoss, Home of Professional Open Source
3    * Copyright 2014, Red Hat, Inc. and/or its affiliates, and individual
4    * contributors by the @authors tag. See the copyright.txt in the
5    * distribution for a full listing of individual contributors.
6    *
7    * Licensed under the Apache License, Version 2.0 (the "License");
8    * you may not use this file except in compliance with the License.
9    * You may obtain a copy of the License at
10   * http://www.apache.org/licenses/LICENSE-2.0
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.jboss.as.quickstarts.tasksrs.service;
18  
19  import java.net.URI;
20  import java.security.Principal;
21  import java.util.List;
22  
23  import javax.inject.Inject;
24  import javax.ws.rs.DELETE;
25  import javax.ws.rs.DefaultValue;
26  import javax.ws.rs.GET;
27  import javax.ws.rs.POST;
28  import javax.ws.rs.Path;
29  import javax.ws.rs.PathParam;
30  import javax.ws.rs.Produces;
31  import javax.ws.rs.WebApplicationException;
32  import javax.ws.rs.core.Context;
33  import javax.ws.rs.core.Response;
34  import javax.ws.rs.core.SecurityContext;
35  import javax.ws.rs.core.UriBuilder;
36  import javax.ws.rs.core.UriInfo;
37  
38  import org.jboss.as.quickstarts.tasksrs.model.Task;
39  import org.jboss.as.quickstarts.tasksrs.model.TaskDao;
40  import org.jboss.as.quickstarts.tasksrs.model.User;
41  import org.jboss.as.quickstarts.tasksrs.model.UserDao;
42  
43  /**
44   * A JAX-RS resource for exposing REST endpoints for Task manipulation
45   */
46  @Path("/")
47  public class TaskResource {
48      @Inject
49      private UserDao userDao;
50  
51      @Inject
52      private TaskDao taskDao;
53  
54      @POST
55      @Path("tasks/{title}")
56      public Response createTask(@Context UriInfo info, @Context SecurityContext context,
57                                 @PathParam("title")  @DefaultValue("task") String taskTitle) {
58  
59          User user = getUser(context);
60          Task task = new Task(taskTitle);
61  
62          taskDao.createTask(user, task);
63  
64          // Construct the URI for the newly created resource and put in into the Location header of the response
65          // (assumes that there is only one occurrence of the task title in the request)
66          String rawPath = info.getAbsolutePath().getRawPath().replace(task.getTitle(), task.getId().toString());
67          UriBuilder uriBuilder = info.getAbsolutePathBuilder().replacePath(rawPath);
68          URI uri = uriBuilder.build();
69  
70          return Response.created(uri).build();
71      }
72  
73      @DELETE
74      @Path("tasks/{id}")
75      public void deleteTaskById(@Context SecurityContext context, @PathParam("id") Long id) {
76          Task task = getTaskById(context, id);
77  
78          taskDao.deleteTask(task);
79      }
80  
81      @GET
82      @Path("tasks/{id}")
83      // JSON: include "application/json" in the @Produces annotation to include json support
84      //@Produces({ "application/xml", "application/json" })
85      @Produces({ "application/xml" })
86      public Task getTaskById(@Context SecurityContext context, @PathParam("id") Long id) {
87          User user = getUser(context);
88  
89          return getTask(user, id);
90      }
91  
92      @GET
93      @Path("tasks/{title}")
94      // JSON: include "application/json" in the @Produces annotation to include json support
95      //@Produces({ "application/xml", "application/json" })
96      @Produces({ "application/xml" })
97      public List<Task> getTasksByTitle(@Context SecurityContext context, @PathParam("title") String title) {
98          return getTasks(getUser(context), title);
99      }
100 
101     @GET
102     @Path("tasks")
103     // JSON: include "application/json" in the @Produces annotation to include json support
104     //@Produces({ "application/xml", "application/json" })
105     @Produces({ "application/xml" })
106     public List<Task> getTasks(@Context SecurityContext context) {
107         return getTasks(getUser(context));
108     }
109 
110 
111     // Utility Methods
112 
113     private List<Task> getTasks(User user, String title) {
114         return taskDao.getForTitle(user, title);
115     }
116 
117     private List<Task> getTasks(User user) {
118         return taskDao.getAll(user);
119     }
120 
121     private Task getTask(User user, Long id) {
122         for (Task task : taskDao.getAll(user))
123             if (task.getId().equals(id))
124                 return task;
125 
126         throw new WebApplicationException(Response.Status.NOT_FOUND);
127     }
128 
129     private User getUser(SecurityContext context) {
130         Principal principal = null;
131 
132         if (context != null)
133             principal = context.getUserPrincipal();
134 
135         if (principal == null)
136             throw new WebApplicationException(Response.Status.UNAUTHORIZED);
137 
138         return getUser(principal.getName());
139     }
140 
141     private User getUser(String username) {
142 
143         try {
144             User user = userDao.getForUsername(username);
145 
146             if (user == null) {
147                 user = new User(username);
148 
149                 userDao.createUser(user);
150             }
151 
152             return user;
153         } catch (Exception e) {
154             throw new WebApplicationException(e);
155         }
156     }
157 }