View Javadoc
1   package ejava.examples.asyncmarket.web;
2   
3   import java.io.IOException;
4   import java.util.Calendar;
5   import java.util.HashMap;
6   import java.util.Map;
7   
8   import javax.ejb.EJB;
9   import javax.servlet.RequestDispatcher;
10  import javax.servlet.ServletContext;
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.asyncmarket.Seller;
20  import ejava.examples.asyncmarket.UserMgmt;
21  import ejava.examples.asyncmarket.bo.AuctionItem;
22  import ejava.examples.asyncmarket.bo.Person;
23  import ejava.examples.asyncmarket.ejb.SellerLocal;
24  import ejava.examples.asyncmarket.ejb.UserMgmtLocal;
25  
26  @SuppressWarnings("serial")
27  public class SellerHandlerServlet extends HttpServlet {
28      private static Logger log = LoggerFactory.getLogger(SellerHandlerServlet.class);
29      private Map<String, Handler> handlers = new HashMap<String, Handler>();
30      @EJB(beanInterface=SellerLocal.class)
31      private Seller seller;
32      @EJB(beanInterface=UserMgmtLocal.class)
33      private UserMgmt userMgmt;
34  
35      public static final String COMMAND_PARAM = "command";
36      public static final String EXCEPTION_PARAM = "exception";
37      public static final String HANDLER_TYPE_KEY = "type";
38      public static final String ADMIN_TYPE = "admin";
39      public static final String USER_TYPE = "user";
40      public static final String MAINMENU_COMMAND = "menu";
41      public static final String CREATEACCOUNT_COMMAND = "Create Account";        
42      public static final String SELLPRODUCT_COMMAND = "Sell Product";        
43      public static final String GETITEMS_COMMAND = "Get Items";        
44      public static final String LOGOUT_COMMAND = "logout";        
45      protected static final String DISPLAY_EXCEPTION_URL = 
46          "/WEB-INF/content/DisplayException.jsp";
47      private static final String UNKNOWN_COMMAND_URL = 
48          "/WEB-INF/content/UnknownCommand.jsp";
49  
50      public void init() throws ServletException {
51          log.debug("init() called, seller=" + seller + ", userMgmt=" + userMgmt);
52          JNDIHelper jndi = null;
53          try {
54              //build a list of handlers for individual commands
55              handlers.put(MAINMENU_COMMAND, new AdminMenu());
56              handlers.put(CREATEACCOUNT_COMMAND, new CreateAccount());
57              handlers.put(SELLPRODUCT_COMMAND, new SellProduct());
58              handlers.put(GETITEMS_COMMAND, new GetItems());
59              handlers.put(LOGOUT_COMMAND, new Logout());
60  
61              //verify local injected or replace with remote
62              jndi = new JNDIHelper();
63              if (seller == null) {
64                  seller = jndi.getSeller();
65              }        
66              if (userMgmt == null) {
67                  userMgmt = jndi.getUserMgmt();
68              }                    
69          }
70          catch (Exception ex) {
71              log.error("error initializing handler", ex);
72              throw new ServletException("error initializing handler", ex);
73          }
74          finally {
75              	if (jndi != null) {
76              		jndi.close();
77              	}
78          }
79      }
80  
81      protected void doGet(HttpServletRequest request, 
82                           HttpServletResponse response) 
83          throws ServletException, IOException {
84          log.debug("doGet() called");
85          String command = request.getParameter(COMMAND_PARAM);
86          log.debug("command=" + command);
87          try {            
88              if (command != null) {
89                  Handler handler = handlers.get(command);
90                  if (handler != null) {
91                      log.debug("handler=" + handler);
92                      handler.handle(request, response);
93                  }
94                  else {
95                      request.setAttribute("handlers", handlers);
96                      RequestDispatcher rd = 
97                          getServletContext().getRequestDispatcher(
98                              UNKNOWN_COMMAND_URL);
99                              rd.forward(request, response);
100                 }
101             }
102             else {
103                 throw new Exception("no " + COMMAND_PARAM + " supplied"); 
104             }
105         }
106         catch (Exception ex) {
107             request.setAttribute(EXCEPTION_PARAM, ex);
108             RequestDispatcher rd = getServletContext().getRequestDispatcher(
109                     UNKNOWN_COMMAND_URL);
110                     rd.forward(request, response);
111         }
112     }
113 
114     protected void doPost(HttpServletRequest request, 
115                           HttpServletResponse response) 
116         throws ServletException, IOException {
117         log.debug("doPost() called, calling doGet()");
118         doGet(request, response);
119     }
120 
121     public void destroy() {
122         log.debug("destroy() called");
123     }
124     
125     private abstract class Handler {
126         protected static final String RESULT_PARAM = "result";
127         protected static final String MAINMENU_URL = 
128             "/index.jsp";
129         protected static final String DISPLAYUSER_URL = 
130             "/WEB-INF/content/DisplayUser.jsp";
131         protected static final String DISPLAYITEM_URL = 
132             "/WEB-INF/content/DisplayItem.jsp";
133         protected static final String SELLERMENU_URL = 
134             "/WEB-INF/content/SellerMenu.jsp";
135         protected static final String ITEM = "item";
136         protected static final String USER = "user";
137         public abstract void handle(HttpServletRequest request, 
138                 HttpServletResponse response) 
139                 throws ServletException, IOException;        
140     }
141     
142     private class AdminMenu extends Handler {
143         public void handle(HttpServletRequest request, 
144                 HttpServletResponse response) 
145                 throws ServletException, IOException {
146             try {
147                 RequestDispatcher rd = 
148                   getServletContext().getRequestDispatcher(SELLERMENU_URL);
149                 rd.forward(request, response);                
150             }
151             catch (Exception ex) {
152                 request.setAttribute(EXCEPTION_PARAM, ex);
153                 RequestDispatcher rd = getServletContext().getRequestDispatcher(
154                     DISPLAY_EXCEPTION_URL);
155                 rd.forward(request, response);
156             }
157         }
158     }
159 
160     private class CreateAccount extends Handler {
161         public void handle(HttpServletRequest request, 
162                 HttpServletResponse response) 
163                 throws ServletException, IOException {
164             try {
165                 String name = request.getParameter("name");
166                 String userId = request.getParameter("userId");
167                 
168                 Person user = new Person();
169                 user.setName(name);
170                 user.setUserId(userId);
171                 
172                 userMgmt.createUser(userId, name);
173                 user = userMgmt.getUserByUserId(userId);
174                 request.setAttribute(USER, user);
175                 
176                 RequestDispatcher rd = 
177                   getServletContext().getRequestDispatcher(DISPLAYUSER_URL);
178                 rd.forward(request, response);                
179             }
180             catch (Exception ex) {
181                 request.setAttribute(EXCEPTION_PARAM, ex);
182                 RequestDispatcher rd = getServletContext().getRequestDispatcher(
183                     DISPLAY_EXCEPTION_URL);
184                 rd.forward(request, response);
185             }
186         }
187     }
188     
189     private class SellProduct extends Handler {
190         public void handle(HttpServletRequest request, 
191                 HttpServletResponse response) 
192                 throws ServletException, IOException {
193             try {
194                 log.debug("in sell product");
195                 String name = request.getParameter("name");
196                 String delayString = request.getParameter("delay");
197                 int delay = Integer.parseInt(delayString);
198                 String minBidString = request.getParameter("midBid");
199                 double minBid = Double.parseDouble(minBidString);
200                 String sellerId = request.getParameter("userId");
201                 
202                 AuctionItem item = new AuctionItem();
203                 item.setName(name);
204                 item.setMinBid(minBid);
205                 Calendar cal = Calendar.getInstance();
206                 item.setStartDate(cal.getTime());
207                 cal.add(Calendar.SECOND, delay);
208                 item.setEndDate(cal.getTime());
209                 
210                 log.debug("calling EJB");
211                 long itemId = seller.sellProduct(sellerId, item);
212                 item = seller.getItem(itemId);
213                 request.setAttribute(ITEM, item);
214                 log.debug("about to forward");
215                 
216                 RequestDispatcher rd = 
217                   getServletContext().getRequestDispatcher(DISPLAYITEM_URL);
218                 rd.forward(request, response);                
219             }
220             catch (Exception ex) {
221                 request.setAttribute(EXCEPTION_PARAM, ex);
222                 RequestDispatcher rd = getServletContext().getRequestDispatcher(
223                     DISPLAY_EXCEPTION_URL);
224                 rd.forward(request, response);
225             }
226         }
227     }
228 
229     private class GetItems extends Handler {
230         public void handle(HttpServletRequest request, 
231                 HttpServletResponse response) 
232                 throws ServletException, IOException {
233             try {
234                 String userId = request.getParameter("userId");
235                 
236                 Person user = userMgmt.getUserByUserId(userId);
237                 
238                 request.setAttribute(USER, user);
239                 
240                 RequestDispatcher rd = 
241                   getServletContext().getRequestDispatcher(DISPLAYUSER_URL);
242                 rd.forward(request, response);                
243             }
244             catch (Exception ex) {
245                 request.setAttribute(EXCEPTION_PARAM, ex);
246                 RequestDispatcher rd = getServletContext().getRequestDispatcher(
247                     DISPLAY_EXCEPTION_URL);
248                 rd.forward(request, response);
249             }
250         }
251     }
252 
253     private class Logout extends Handler {
254         public void handle(HttpServletRequest request, 
255                 HttpServletResponse response) 
256                 throws ServletException, IOException {
257             try {
258                 request.getSession().invalidate();
259                 
260                 RequestDispatcher rd = 
261                   getServletContext().getRequestDispatcher(MAINMENU_URL);
262                 rd.forward(request, response);                
263             }
264             catch (Exception ex) {
265                 request.setAttribute(EXCEPTION_PARAM, ex);
266                 RequestDispatcher rd = getServletContext().getRequestDispatcher(
267                     DISPLAY_EXCEPTION_URL);
268                 rd.forward(request, response);
269             }
270         }
271     }
272 }