Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package edu.jhu.bremon.servlet; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import com.google.gson.reflect.TypeToken; import edu.jhu.bremon.dao.AudiobookDao; import edu.jhu.bremon.dao.InMemoryAudiobookDao; import edu.jhu.bremon.dao.InMemoryUserAudiobookStatusDao; import edu.jhu.bremon.dao.InMemoryUserDao; import edu.jhu.bremon.dao.UserAudiobookStatusDao; import edu.jhu.bremon.dao.UserDao; import edu.jhu.bremon.model.business.AudiobookAttributeType; import edu.jhu.bremon.model.business.AudiobookListItem; import edu.jhu.bremon.model.business.AudiobookQueryType; import edu.jhu.bremon.model.business.AudiobookSearchDetails; import edu.jhu.bremon.model.business.ResultStatus; import edu.jhu.bremon.model.business.ServiceOperation; import edu.jhu.bremon.model.business.ServiceResults; import edu.jhu.bremon.model.business.ServiceUserInput; import edu.jhu.bremon.model.data.Audiobook; import edu.jhu.bremon.model.data.User; import edu.jhu.bremon.web.ServiceAction; import edu.jhu.bremon.web.ServiceActionFactory; import edu.jhu.bremon.web.UserUtil; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; /** * * @author montana */ public class Main extends HttpServlet { protected UserDao userDao; protected AudiobookDao audiobookDao; protected UserAudiobookStatusDao audiobookStatusDao; /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { User sessionUser = (User) request.getSession().getAttribute("sessionUser"); // Get user details for sign in, register, or update user User loginUser = new User(); loginUser.setPassword(request.getParameter("password")); loginUser.setEmail(request.getParameter("email")); loginUser.setAuthenticated(false); loginUser.setFname(request.getParameter("fname")); loginUser.setLname(request.getParameter("lname")); // Get the optional audiobook ID Integer audiobookId = null; String audiobookIdStr = request.getParameter("audiobookId"); if (audiobookIdStr != null && !audiobookIdStr.isEmpty()) { audiobookId = Integer.parseInt(audiobookIdStr); } // Load search terms from the params String[] queries = request.getParameterValues("query"); String[] attributes = request.getParameterValues("queryAttribute"); String[] queryTypes = request.getParameterValues("queryType"); List<AudiobookSearchDetails> searchDetailsList = new ArrayList<AudiobookSearchDetails>(); if (queries != null && attributes != null && queryTypes != null) { for (int i = 0; i < queries.length && i < attributes.length && i < queryTypes.length; i++) { AudiobookSearchDetails search = new AudiobookSearchDetails(); search.setQuery(queries[i]); search.setAttributeType(AudiobookAttributeType.valueOf(attributes[i])); search.setQueryType(AudiobookQueryType.valueOf(queryTypes[i])); searchDetailsList.add(search); } } // Load all details into ServiceUserInput object to send into logic layer ServiceUserInput serviceUserInput = new ServiceUserInput(); serviceUserInput.setAudiobookId(audiobookId); serviceUserInput.setSearchDetails(searchDetailsList); serviceUserInput.setUser(loginUser); // Determine the operation being applied to the input String operationTypeStr = request.getParameter("operation"); ServiceOperation op = ServiceOperation.HOME; if (operationTypeStr != null && !operationTypeStr.isEmpty()) { op = ServiceOperation.valueOf(operationTypeStr); } // Get the operation from the operation factory ServiceAction action = ServiceActionFactory.getInstance().getServiceAction(op, userDao, audiobookDao, audiobookStatusDao); // Perform the operation ServiceResults results = action.performOperation(serviceUserInput, sessionUser); List<AudiobookListItem> cart = null; List<AudiobookListItem> purchased = null; if (results.getSessionUser() != null) { cart = UserUtil.getInstance().getCart(this.getAudiobookDao(), this.getAudiobookStatusDao(), results.getSessionUser().getId()); purchased = UserUtil.getInstance().getPurchased(this.getAudiobookDao(), this.getAudiobookStatusDao(), results.getSessionUser().getId()); } // Optionally invalidate the session or update the session user, cart, and purchases if (results.isShouldInvalidateSession()) { request.getSession().invalidate(); } else if (results.getSessionUser() != null) { request.getSession().setAttribute("sessionUser", results.getSessionUser()); request.getSession().setAttribute("cart", cart); request.getSession().setAttribute("purchased", purchased); } String forwardedLocation = getForwardedLocation(op, results.getResultStatus(), results.isSuccess()); String outputType = request.getParameter("outputType"); if (outputType != null && outputType.equals("debugJson")) { response.setContentType("application/json"); PrintWriter out = response.getWriter(); try { JsonObject object = new JsonObject(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); object.add("results", gson.toJsonTree(results)); object.add("startSessionUser", gson.toJsonTree(sessionUser)); object.add("cart", gson.toJsonTree(cart, new TypeToken<List<AudiobookListItem>>() { }.getType())); object.add("purchased", gson.toJsonTree(purchased, new TypeToken<List<AudiobookListItem>>() { }.getType())); object.addProperty("forwardedLocation", forwardedLocation); out.println(gson.toJson(object)); } finally { out.close(); } } else { response.setContentType("text/html;charset=UTF-8"); request.setAttribute("results", results); request.setAttribute("searchResults", results.getSearchResults()); request.getRequestDispatcher(forwardedLocation).forward(request, response); } } catch (Exception e) { // Unknown system error, forward to index request.getRequestDispatcher("index.jsp").forward(request, response); } } public String getForwardedLocation(ServiceOperation operation, ResultStatus resultStatus, boolean isSuccess) { switch (operation) { case ADD_TO_CART: if (isSuccess) { return "./checkout.jsp"; } break; case HOME: if (isSuccess) { return "./index.jsp"; } break; case SIGN_OUT: if (isSuccess) { return "./index.jsp"; } break; case PURCHASE: if (isSuccess) { return "./listen.jsp"; } break; case QUERY_AUDIOBOOKS: if (isSuccess) { return "./search.jsp"; } break; case REGISTER: return "./register.jsp"; case REMOVE_FROM_CART: return "./checkout.jsp"; case SIGN_IN: if (isSuccess) { return "./index.jsp"; } else { return "./login.jsp"; } case UPDATE_USER: return "./index.jsp"; case VIEW_AUDIOBOOK: break; case VIEW_AUDIOBOOKS_IN_CART: return "./checkout.jsp"; default: break; } return "./unsupported.jsp"; } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> @Override public void init() throws ServletException { super.init(); setUserDao(new InMemoryUserDao()); setAudiobookDao(new InMemoryAudiobookDao()); setAudiobookStatusDao(new InMemoryUserAudiobookStatusDao()); try { InputStream defaultDataStream = this.getServletContext().getResourceAsStream("/WEB-INF/users.json"); String x = IOUtils.toString(defaultDataStream); IOUtils.closeQuietly(defaultDataStream); Gson gson = new Gson(); List<User> users = gson.fromJson(x, new TypeToken<List<User>>() { }.getType()); for (User user : users) { user.setPassword(UserUtil.getInstance().md5Encode(user.getPassword())); userDao.persistUser(user); } } catch (IOException ex) { ex.printStackTrace(); Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } try { InputStream defaultDataStream = this.getServletContext() .getResourceAsStream("/WEB-INF/audiobooks.json"); String x = IOUtils.toString(defaultDataStream); IOUtils.closeQuietly(defaultDataStream); Gson gson = new Gson(); List<Audiobook> audiobooks = gson.fromJson(x, new TypeToken<List<Audiobook>>() { }.getType()); for (Audiobook audiobook : audiobooks) { audiobookDao.persistAudiobook(audiobook); } } catch (IOException ex) { ex.printStackTrace(); Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } /* Audiobook audiobook1 = new Audiobook(); audiobook1.setTitle("Title"); audiobook1.setAuthor("John Doe"); audiobook1.setRunTimeSeconds(100); audiobookDao.persistAudiobook(audiobook1); User admin = new User(); admin.setAuthorizationLevel(AuthorizationLevel.ADMIN); admin.setEmail("admin@example.com"); admin.setPassword(UserUtil.getInstance().md5Encode("admin")); admin.setFname("admin"); admin.setLname("admin"); userDao.persistUser(admin); */ } public UserDao getUserDao() { return userDao; } public void setUserDao(UserDao userDao) { this.userDao = userDao; } public AudiobookDao getAudiobookDao() { return audiobookDao; } public void setAudiobookDao(AudiobookDao audiobookDao) { this.audiobookDao = audiobookDao; } public UserAudiobookStatusDao getAudiobookStatusDao() { return audiobookStatusDao; } public void setAudiobookStatusDao(UserAudiobookStatusDao audiobookStatusDao) { this.audiobookStatusDao = audiobookStatusDao; } }