/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2005 Bull S.A.
 * Contact: jonas-team@objectweb.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$
 * --------------------------------------------------------------------------
 */
package org.objectweb.wssample.servlets.wsclient;

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

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.rpc.ServiceException;
import javax.xml.rpc.Stub;

import org.objectweb.wssample.gen.jaxrpc.JaxRpcEndpointInterface;
import org.objectweb.wssample.gen.jaxrpc.JaxRpcEndpointInterfaceService;

/**
 * @author Guillaume Sauthier
 */
public class JOnASJaxRpcClientServlet extends HttpServlet {

    /**
     * Initializes the servlet.
     * @param config ServletConfig
     * @throws ServletException thrown by super.init(config);
     */
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    /**
     * Destroys the servlet.
     */
    public void destroy() {

    }

    /**
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     *
     * @throws ServletException default servlet exception thrown
     * @throws IOException servlet exception thrown
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        out.println("<html>");
        out.println("<head>");
        out.println("<title>JOnAS JaxRpc WebService Test Page</title>");
        out.println("<style type=\"text/css\"> @import \"style/ow_jonas.css\"; </style>");
        out.println("</head>");
        out.println("<body class=\"bodywelcome\">");

        out.println("<div class=\"logos\">");
        out.println("<a href=\"http://jakarta.apache.org\"><img title=\"Jakarta Tomcat\" alt=\"Jakarta Tomcat\" src=\"images/tomcat.gif\" /></a>");
        out.println("<a href=\"http://jetty.mortbay.org/jetty/\"><img title=\"Mortbay Jetty\" alt=\"Mortbay Jetty\" src=\"images/jetty.gif\" /></a>");
        out.println("<a href=\"http://jonas.objectweb.org\"><img title=\"JOnAS WebSite\" alt=\"JOnAS WebSite\" src=\"images/ow_jonas_logo.gif\" /></a>");
        out.println("</div>");

        // do we need to use the encrypted endpoint or not ?
        boolean encrypt = false;
        if ("true".equalsIgnoreCase(request.getParameter("encrypt"))) {
            encrypt = true;
        }

        try {

            // Get the service instance
            //---------------------------------------------
            Context ctx = new InitialContext();
            JaxRpcEndpointInterfaceService service = null;
            JaxRpcEndpointInterface port = null;

            // We can use the same service because the 2 ws use the same interface
            // Get the port where execute methods

            if (encrypt) {
                service = (JaxRpcEndpointInterfaceService) ctx.lookup("java:comp/env/service/crypted-jaxrpc");
                //---------------------------------------------
                port = service.getEncryptedJaxRpcEndpoint();
            } else {
                service = (JaxRpcEndpointInterfaceService) ctx.lookup("java:comp/env/service/jaxrpc");
                //---------------------------------------------
                port = service.getJaxRpcEndpoint1();
            }

            // Use the context username for WSS4JHandler
            ((Stub) port)._setProperty("user", request.getUserPrincipal().getName());

            // Execute Methods :
            String hello = port.sayHello(request.getParameter("name"));
            int cotes = port.getCotes();

            if (encrypt) {
                out.println("<div class=\"titlepage\">Results With Encryption</div>");
            } else {
                out.println("<div class=\"titlepage\">Results</div>");
            }
            out.println("<div class=\"links\">");

            // Display results :
            out.println("Working with URL : <i>" + ((Stub) port)._getProperty(Stub.ENDPOINT_ADDRESS_PROPERTY)
                    + "</i><br/>");
            out.println("<b>result of sayHello(name) method :</b><i>" + hello + "</i><br/>");
            out.println("<b>result of getCotes() method :</b><i>" + cotes + "</i><br/>");

            out.println("</div>");
        } catch (ServiceException se) {
            out.println("<div class=\"titlepage\">Something goes wrong when calling the WebService<br/>");
            se.printStackTrace(out);
            out.println("</div>");
        } catch (NamingException ne) {
            out.println("<div class=\"titlepage\">Exception while retrieving InitialContext<br/>");
            ne.printStackTrace(out);
            out.println("</div>");
        }

        out.println("</body>");
        out.println("</html>");

        out.close();
    }

    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     *
     * @throws ServletException default servlet exception thrown
     * @throws IOException default servlet exception thrown
     */
    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 default servlet exception thrown
     * @throws IOException default servlet exception thrown
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        processRequest(request, response);
    }

    /**
     * @return Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }

}