package com.hohai.juncao;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hohai.juncao.SendingSessionStdHome;
import com.hohai.juncao.SendingSessionStdLocal;
import com.hohai.juncao.TranEntityStd;

public class SendingSessionStdServlet extends HttpServlet {
//	static String serverIiopPort = System.getProperty("serverIiop");

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

	public void setUp() throws Exception {

		InitialContext ctx = new InitialContext();
		Object o = ctx.lookup("java:comp/env/ejb/SendingSessionStdBean");
		SendingSessionStdHome callingBeanHome = (SendingSessionStdHome) PortableRemoteObject
				.narrow(o, SendingSessionStdHome.class);
		for (int i = 0; i < 10; i++) {
			callingBean = callingBeanHome.create();
		}

	}

	public List<String> testHello() throws Exception {
		
		List<String> rt = new ArrayList<String>();
		setUp();
		TranEntityStd data = new TranEntityStd();
		callingBean.createEntity();
		data = callingBean.updateEntityWithSleep(sendingname);
		try {
			Thread.sleep(70000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		callingBean.mergeEntity(data);
		data = callingBean.getEntity();

		rt.add(data.getName());
		rt.add("Test Completed!");

		return rt;
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		PrintWriter out = resp.getWriter();
		out.println("<html>");
		List<String> rt;
		out.println("=====================<br/>");
		try {
			rt = testHello();
			for(String str : rt) {
				out.println(str + "<br/>");
			}
		} catch (Exception e) {
			out.println("<font color='red'>" + e.getMessage() + "</font><br/>");
			e.printStackTrace();
		}
		out.println("=====================<br/>");
		out.println("</html>");
		out.close();
	}

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

}
