View Javadoc
1   package ejava.examples.webtier.web;
2   
3   import java.io.IOException;
4   import java.util.ArrayList;
5   import java.util.HashMap;
6   import java.util.List;
7   import java.util.Map;
8   
9   import javax.persistence.EntityManager;
10  import javax.servlet.RequestDispatcher;
11  import javax.servlet.ServletException;
12  import javax.servlet.http.HttpServlet;
13  import javax.servlet.http.HttpServletRequest;
14  import javax.servlet.http.HttpServletResponse;
15  
16  import org.slf4j.Logger;
17  import org.slf4j.LoggerFactory;
18  
19  import ejava.examples.webtier.bl.Registrar;
20  import ejava.examples.webtier.bl.RegistrarException;
21  import ejava.examples.webtier.bl.RegistrarImpl;
22  import ejava.examples.webtier.bo.Student;
23  import ejava.examples.webtier.dao.StudentDAO;
24  import ejava.examples.webtier.jpa.StudentJPADAO;
25  
26  @SuppressWarnings("serial")
27  public class RegistrarHandlerServlet extends HttpServlet {
28      private Logger logger = LoggerFactory.getLogger(RegistrarHandlerServlet.class);
29      private Map<String, Handler> handlers = new HashMap<String, Handler>();
30  
31      public void init() {
32          String level = super.getServletConfig().getInitParameter("level");  
33          logger.info("level=" + level);
34          
35          //create proper handlers per role
36          if (level != null && "admin".equals(level)) {
37              handlers.put("Create Student", new CreateStudent());
38              handlers.put("Generate Students",  new GenerateStudents());
39              handlers.put("Find Students", new GetStudents());
40              handlers.put("Get Student", new GetStudent());
41              handlers.put("Remove Student", new RemoveStudent());
42          }
43          else if (level != null && "user".equals(level)) {
44              
45          }
46          else {
47              
48          }
49      }
50      
51      /**
52       * Create a new instance of the registrar per request so that we do not
53       * have two calling threads using the same instance. JPAFilter will return
54       * the same EntityManager instance to all calls within the same thread.
55       * @return
56       */
57      protected Registrar getRegistrar() {
58          EntityManager em = JPAFilter.getEntityManager();
59          StudentDAO studentDao = new StudentJPADAO();
60          ((StudentJPADAO)studentDao).setEntityManager(em);
61          Registrar registrar = new RegistrarImpl();
62          ((RegistrarImpl)registrar).setStudentDAO(studentDao);
63          return registrar;
64      }
65      
66      protected void doGet(HttpServletRequest request,
67              HttpServletResponse response) throws ServletException, IOException {
68          
69          String command = request.getParameter("command");
70          if (command != null) {
71              Handler handler = handlers.get(command);
72              if (handler != null) {
73                  handler.handle(request, response);
74              }
75              else {
76                  RequestDispatcher rd = getServletContext().getRequestDispatcher(
77                      "/WEB-INF/content/UnknownCommand.jsp");
78                      rd.forward(request, response);
79              }
80          }
81          else {
82              RequestDispatcher rd = getServletContext().getRequestDispatcher(
83                      "NoCommand.jsp");
84                      rd.forward(request, response);
85          }
86  
87          
88      }
89  
90      protected void doPost(HttpServletRequest request,
91              HttpServletResponse response) throws ServletException, IOException {
92          doGet(request, response);
93      }
94  
95      private abstract class Handler {
96          public abstract void handle(HttpServletRequest request,
97                                      HttpServletResponse response)
98                                      throws ServletException, IOException;
99      }
100     
101     private class CreateStudent extends Handler {
102         public void handle(HttpServletRequest request,
103                 HttpServletResponse response)
104                 throws ServletException, IOException {
105             Student student = new Student();
106             student.setFirstName(request.getParameter("firstName"));
107             student.setLastName(request.getParameter("lastName"));
108             
109             try {
110                 logger.debug("creating new student:" + student);
111                 Student newStudent = getRegistrar().addStudent(student);
112                 request.setAttribute("student", newStudent);
113                 logger.debug("new student created:" + student);
114                 
115                 RequestDispatcher rd = getServletContext().getRequestDispatcher(
116                         "/WEB-INF/content/DisplayStudent.jsp");
117                 rd.forward(request, response);
118             } catch (RegistrarException ex) {
119                 logger.error("error creating student:" + ex);
120                 request.setAttribute("exception", ex);
121                 RequestDispatcher rd = getServletContext().getRequestDispatcher(
122                     "DisplayException.jsp");
123                 rd.forward(request, response);
124             }
125             
126         }        
127     }
128     
129     private class GenerateStudents extends Handler {
130         public void handle(HttpServletRequest request,
131                 HttpServletResponse response)
132                 throws ServletException, IOException {
133             String countStr = request.getParameter("count");
134             int count = 100;
135             try { count = Integer.parseInt(countStr); }
136             catch(Exception ex) {}
137             
138             try {
139                 logger.debug("generating " + count + " students");
140                 List<Student> students = new ArrayList<Student>();
141                 for(int i=0; i<count; i++) {
142                     Student student = new Student();
143                     student.setFirstName("gen");
144                     student.setLastName("student" + i);
145                     @SuppressWarnings("unused")
146                     Student newStudent = getRegistrar().addStudent(student);
147                     students.add(student);
148                 }
149                 logger.debug("new students created");
150                 request.setAttribute("students", students);
151                 request.setAttribute("index", 0);
152                 request.setAttribute("count", count);
153                 request.setAttribute("nextIndex", 0);
154                 request.setAttribute("firstName", "%");
155                 request.setAttribute("lastName", "%");
156                 
157                 RequestDispatcher rd = getServletContext().getRequestDispatcher(
158                         "/WEB-INF/content/DisplayStudents.jsp");
159                 rd.forward(request, response);
160             } catch (RegistrarException ex) {
161                 logger.error("error generating students:" + ex);
162                 request.setAttribute("exception", ex);
163                 RequestDispatcher rd = getServletContext().getRequestDispatcher(
164                     "DisplayException.jsp");
165                 rd.forward(request, response);
166             }
167             
168         }        
169     }
170 
171     
172     private class GetStudents extends Handler {
173         public void handle(HttpServletRequest request,
174                 HttpServletResponse response)
175                 throws ServletException, IOException {
176             String indexStr = request.getParameter("index");
177             String countStr = request.getParameter("count");
178             String firstName = (String)request.getParameter("firstName");
179             firstName = (firstName == null ? "%" : firstName);
180             String lastName = (String)request.getParameter("lastName");
181             lastName = (lastName == null ? "%" : lastName);
182             
183             Map<String, Object> params = new HashMap<String, Object>();
184             params.put("firstName", firstName);
185             params.put("lastName", lastName);
186             
187             int index = 0;
188             try { index = Integer.parseInt(indexStr); }
189             catch(Exception ex) {
190                 logger.info("error in index format (" + indexStr +
191                         ") defaulting to " + index);
192             }
193             int count = 20;
194             try { count = Integer.parseInt(countStr); }
195             catch(Exception ex) {
196                 logger.info("error in count format (" + countStr +
197                         ") defaulting to " + count);
198             }            
199             
200             try {
201                 logger.debug("getting students(" + index + ", " + count + "):" +
202                         params);
203                 List<Student> students = 
204                     getRegistrar().getStudents("getStudentsByName", 
205                             params, index, count);
206                 int nextIndex = (students.size() < count) ?
207                         0 : index + count;
208                 request.setAttribute("students", students);
209                 request.setAttribute("index", index);
210                 request.setAttribute("count", count);
211                 request.setAttribute("nextIndex", nextIndex);
212                 request.setAttribute("firstName", firstName);
213                 request.setAttribute("lastName", lastName);
214                 logger.debug("students found:" + students.size());
215                 
216                 RequestDispatcher rd = getServletContext().getRequestDispatcher(
217                         "/WEB-INF/content/DisplayStudents.jsp");
218                 rd.forward(request, response);
219             } catch (RegistrarException ex) {
220                 logger.error("error getting students:" + ex);
221                 request.setAttribute("exception", ex);
222                 RequestDispatcher rd = getServletContext().getRequestDispatcher(
223                     "/WEB-INF/content/DisplayException.jsp");
224                 rd.forward(request, response);
225             }
226             
227         }        
228     }
229     
230     private class GetStudent extends Handler {
231         public void handle(HttpServletRequest request,
232                 HttpServletResponse response)
233                 throws ServletException, IOException {
234             String idStr = request.getParameter("id");
235             long id = 0;
236             try { id = Long.parseLong(idStr); }
237             catch(Exception ex) {
238                 logger.info("error in id format:" + idStr);
239                 request.setAttribute("exception", ex);
240                 RequestDispatcher rd = getServletContext().getRequestDispatcher(
241                     "/WEB-INF/content/DisplayException.jsp");
242                 rd.forward(request, response);
243             }
244             
245             
246             
247             try {
248                 logger.debug("getting student:");
249                 Student student = getRegistrar().getStudent(id);
250                 request.setAttribute("student", student);
251                 logger.debug("student found:" + student);
252                 
253                 RequestDispatcher rd = getServletContext().getRequestDispatcher(
254                         "/WEB-INF/content/DisplayStudent.jsp");
255                 rd.forward(request, response);
256             } catch (RegistrarException ex) {
257                 logger.error("error getting student:" + ex);
258                 request.setAttribute("exception", ex);
259                 RequestDispatcher rd = getServletContext().getRequestDispatcher(
260                     "/WEB-INF/content/DisplayException.jsp");
261                 rd.forward(request, response);
262             }
263             
264         }        
265     }
266 
267     
268     private class RemoveStudent extends Handler {
269         public void handle(HttpServletRequest request,
270                 HttpServletResponse response)
271                 throws ServletException, IOException {
272             String idStr = request.getParameter("id");
273             long id = 0;
274             try { id = Long.parseLong(idStr); }
275             catch(Exception ex) {
276                 logger.info("error in id format:" + idStr);
277                 request.setAttribute("exception", ex);
278                 RequestDispatcher rd = getServletContext().getRequestDispatcher(
279                     "/WEB-INF/content/DisplayException.jsp");
280                 rd.forward(request, response);
281             }
282             
283             
284             try {
285                 logger.debug("removing student:");
286                 Student student = getRegistrar().getStudent(id); 
287                 student = getRegistrar().dropStudent(student);
288                 request.setAttribute("student", student);
289                 request.setAttribute("removed", true);
290                 logger.debug("student removed:" + student);
291                 
292                 RequestDispatcher rd = getServletContext().getRequestDispatcher(
293                         "/WEB-INF/content/DisplayStudent.jsp");
294                 rd.forward(request, response);
295             } catch (RegistrarException ex) {
296                 logger.error("error getting student:" + ex);
297                 request.setAttribute("exception", ex);
298                 RequestDispatcher rd = getServletContext().getRequestDispatcher(
299                     "/WEB-INF/content/DisplayException.jsp");
300                 rd.forward(request, response);
301             }
302             
303         }        
304     }
305     
306 }