/**
 * JaDOrT: JASMINe Deployment Orchestration Tool
 * Copyright (C) 2008-2009 Bull S.A.S.
 * Copyright (C) 2008-2009 France Telecom R&D
 * Contact: jasmine@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id: CartServlet.java 3074 2009-02-04 16:59:48Z alitokmen $
 * --------------------------------------------------------------------------
 */
package org.ow2.jasmine.jadort.samples;

import java.io.IOException;

import javax.ejb.EJB;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@EJB(name="ejb/MyStoreBean", beanInterface=MyStoreBean.class)
public class CartServlet extends HttpServlet {

	private static final long serialVersionUID = 404403088184771790L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession(true);
		MyStoreBean myStore = (MyStoreBean) session.getAttribute("myStore");
		if (myStore == null) {
			try {
				myStore = (MyStoreBean) new InitialContext().lookup("java:comp/env/ejb/MyStoreBean");
			} catch (NamingException e) {
				throw new ServletException("Cannot look up the MyStoreBean", e);
			}
			session.setAttribute("myStore", myStore);
		}

		myStore.addToCart(request.getParameter("buyItem"));
		myStore.removeFromCart(request.getParameter("removeItem"));

		request.setAttribute("products", myStore.getProducts());
		request.setAttribute("cartItems", myStore.getCartItems());
		request.setAttribute("cartValue", myStore.getCartTotal());

		RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/store.jsp");
		dispatcher.forward(request, response);
	}

}
