/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999 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 org.ow2.jonas.lib.util.Log;

import org.objectweb.wssample.gen.google.GoogleSearchService;
import org.objectweb.wssample.gen.google.GoogleSearchPort;
import org.objectweb.wssample.gen.google.GoogleSearchResult;
import org.objectweb.wssample.gen.google.ResultElement;

/**
 * WebServices Client Servlet
 *
 * @author Guillaume Sauthier
 */
public class WsClientServlet extends HttpServlet {

    /**
     * Initializes the servlet.
     * @param config ServletConfig
     * @throws ServletException if super.init(config); fails
     */
    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 default servlet exception thrown
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        // output your page here
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Google WebService Response</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>");

        // Get and Display results
        try {
            // Get the Context
            Context ctx = new InitialContext();

            String key = (String) ctx.lookup("java:comp/env/key");

            // Lookup the binded service
            Object s = ctx.lookup("java:comp/env/service/google");
            GoogleSearchService google = (GoogleSearchService) s;

            // get the Port object
            GoogleSearchPort search = google.getGoogleSearchPort();

            // execute the query
            GoogleSearchResult result = search.doGoogleSearch(key, request.getParameter("search"), 0, // first
                                                                                                      // index
                    10, // maxresult
                    false, //filter
                    null, //restrict
                    false, // safesearch
                    null, //lr
                    null, //ie
                    null //oe
                    );

            out.println("<div class=\"titlepage\">Results</div>");
            out.println("<div class=\"links\">");

            // Display the results
            ResultElement[] elements = result.getResultElements();
            for (int i = 0; i < elements.length; i++) {
                out.println("<i><a href=\"" + elements[i].getURL() + "\">" + elements[i].getTitle() + "</a></i><br/>");
                out.println(elements[i].getSummary() + "<br/><br/>");
            }
            out.println("</div>");

        } catch (NamingException ne) {
            out.println("<div class=\"titlepage\">Error when looking for service-ref</div>");
            ne.printStackTrace(out);
        } catch (ServiceException se) {
            out.println("<div class=\"titlepage\">Error when performign service-ref</div>");
            se.printStackTrace(out);
        }

        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 "Servlet which is client of the WebServices API of Google";
    }

}
