package com.tarena.wangkai.shoppingCart.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.tarena.wangkai.shoppingCart.action.token.TokenUtil;
import com.tarena.wangkai.shoppingCart.entity.Cart;
import com.tarena.wangkai.shoppingCart.entity.Item;
import com.tarena.wangkai.shoppingCart.entity.Order;
import com.tarena.wangkai.shoppingCart.entity.Product;
import com.tarena.wangkai.shoppingCart.entity.User;
import com.tarena.wangkai.shoppingCart.service.ShoppingCartService;
import com.tarena.wangkai.shoppingCart.util.StringUtil;
/**
*
* @author wangkai
*
*/
public class ActionServlet extends HttpServlet {
private static final long serialVersionUID = -7762641632538749621L;
private ShoppingCartService service;
public void init() throws ServletException {
this.service = new ShoppingCartService();
}
public void execute(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String path = req.getServletPath();
path = path.substring(0, path.indexOf("."));
req.setCharacterEncoding("utf8");
resp.setContentType("text/html;charset=utf8");
if (path.equals("/login")) {
//
String targetURI = req.getParameter("targetURI").trim();
if (targetURI == null || targetURI.equals("")
|| targetURI.equals("null")) {
targetURI = "/myShoppingCart.jsp";
}
this.doLogin(req, resp, targetURI);
} else if (path.equals("/listProducts")) {
//
this.listProducts(req, resp, "/productsList.jsp");
} else if (path.equals("/generateOrder")) {
//
this.generateOrder(req, resp, "businessMessage.jsp");
} else if (path.equals("/checkUserName")) {
String userName = StringUtil.codeToUTF(req.getParameter("userName").trim());
if (checkUserName(userName)) {
PrintWriter out = resp.getWriter();
out.print("inuse");
}
} else if (path.equals("/regeditUser")) {
if (TokenUtil.isTokenValid(req)) {
if (regeditUser(req, resp)) {
resp.sendRedirect(req.getContextPath());
}else{
resp.sendRedirect(req.getContextPath() + "/regedit.jsp");
}
} else {
resp.sendRedirect(req.getContextPath() + "/regedit.jsp");
}
}else if(path.equals("/myOrders")){
this.getUserOrders(req, resp, "myOrders.jsp");
}
}
private void getUserOrders(HttpServletRequest req, HttpServletResponse resp,String forwardPage){
HttpSession session=req.getSession(false);
if(session!=null && session.getAttribute("user")!=null){
User user=(User)session.getAttribute("user");
Collection<Order> userOrders=null;
if((userOrders=service.getUserOrders(user)).size()>0){
req.setAttribute("userOrders", userOrders);
this.forward(req, resp, forwardPage);
}
}
}
private boolean regeditUser(HttpServletRequest req, HttpServletResponse resp) {
boolean state = false;
String userName = req.getParameter("username").trim();
String passWord = req.getParameter("password");
String address = req.getParameter("address");
String postCode = req.getParameter("postcode");
String email = req.getParameter("email");
String homePhone = req.getParameter("homephone");
String cellPhone = req.getParameter("cellphone");
String officePhone = req.getParameter("officephone");
if(userName==null || userName.equals("")||userName.equals("null")||passWord==null || passWord.equals("")||passWord.equals("null")){
return false;
}else{
User user = new User();
user.setName(userName);
user.setPassword(passWord);
user.setAddress(address);
user.setPostCode(postCode);
user.setEmail(email);
user.setHomePhone(homePhone);
user.setCellPhone(cellPhone);
user.setOfficePhone(officePhone);
if (service.regeditUser(user)) {
HttpSession session = req.getSession();
session.setAttribute("user", user);
state = true;
}
}
return state;
}
/**
* check if the userName has been used;
* @param userName
* @return
*/
private boolean checkUserName(String userName) {
return service.checkUserName(userName);
}
/**
*
* @param req
* @param resp
* @param forwardPage
*/
private void doLogin(HttpServletRequest req, HttpServletResponse resp,
String forwardPage) {
String userName = req.getParameter("userName").trim();
String passWord = req.getParameter("passWord").trim();
if (userName == null || passWord == null || userName.length() < 0
|| passWord.length() < 0) {
try {
System.out.println("username null");
resp.sendRedirect(req.getContextPath() + "/login.jsp");
} catch (IOException e) {
e.printStackTrace();
}
return;
} else {
User u = service.login(userName, passWord);
if (u != null) {
HttpSession session = req.getSession();
session.setAttribute("user", u);
try {
resp.sendRedirect(req.getContextPath() + forwardPage);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
System.out.println("username not null");
forward(req, resp, "/common/error.jsp");
}
}
}
/**
*
* @param req
* @param resp
* @param forwardPage
*/
private void listProducts(HttpServletRequest req, HttpServletResponse resp,
String forwardPage) {
Collection<Product> products = service.listProducts();
if (products != null) {
ServletContext application = getServletContext();
application.setAttribute("products", products);
}
this.forward(req, resp, forwardPage);
}
/**
*/
private void generateOrder(HttpServletRequest req,
HttpServletResponse resp, String forwardPage) {
HttpSession session = req.getSession(false);
if (session != null) {
Cart myCart = (Cart) session.getAttribute("myCart");
User user = (User) session.getAttribute("user");
if (myCart != null && !myCart.isEmpty()) {
HashMap<Product, Integer> items = myCart.getCartItem();
Set<Product> products = items.keySet();
Set<Item> orderItems = new HashSet<Item>();
Order order = new Order();
for (Product p : products) {
Item item = new Item();
item.setProduct(p);
item.setNumber(items.get(p));
item.setCost(p.getPrice() * items.get(p));
item.setOrder(order);
orderItems.add(item);
}
order.setItems(orderItems);
order.setStatus(-1);
order.setCost(myCart.getCost());
order.setUser(user);
int orderId = this.service.generateOrder(order);
if (orderId != -1) {
session.removeAttribute("myCart");
}
req.setAttribute("orderId", orderId);
this.forward(req, resp, forwardPage);
}
}
}
/**
* @param forwardPage
* */
private void forward(HttpServletRequest req, HttpServletResponse resp,
String forwardPage) {
RequestDispatcher dispatcher = req.getRequestDispatcher(forwardPage);
try {
dispatcher.forward(req, resp);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.execute(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
this.execute(req, resp);
}
}