package ejb.contran5.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.ejb.EJB;
import javax.naming.InitialContext;
import javax.naming.NameNotFoundException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ejb.contran5.acc.SendingSessionAcc5;
import ejb.contran5.acc.TranEntityAcc5;

@EJB(name="ejb/SendingSessionAcc5", 
		beanInterface=SendingSessionAcc5.class,
	     beanName="SendingSessionAccBean5")
public class SendingSessionAcc5Servlet extends HttpServlet {

	/**
	 *                                  
	 */
	private static final long serialVersionUID = 1L;

	private SendingSessionAcc5 callingBean;
	
	private String sendingname = "New Data";

	int count = 0;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		PrintWriter out = resp.getWriter();
		out.println("<html>");
		try {
			setUp();
			callingBean.createEntity();
			callingBean.updateEntityWithSleep(sendingname);
			TranEntityAcc5 data = callingBean.getEntity();
			out.println(data.getName() + "<br/>");
			out.println("Test Completed!<br/>");
		} catch (Exception e) {
			out.println("<font color='red'>" + e.getMessage() + "</font>");
			e.printStackTrace();
		}
		out.println("</html>");
		out.close();
	}

	protected void setUp() throws Exception {
		while (count < 3) {
			try {
				InitialContext ctx = new InitialContext();
				callingBean = (SendingSessionAcc5)ctx
						.lookup("java:comp/env/ejb/SendingSessionAcc5");
				break;
			} catch (NameNotFoundException e) {
				count++;
				System.out
						.println("Not able to connect to ejb. Trying to connect again...");
				Thread.sleep(3000);
			} catch (Exception e) {
				e.printStackTrace();
				break;
			}
		}
	}
}
