/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2007 Bull S.A.S.
 * Contact: jonas-team@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 (at your option) 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 * $Id: ExampleServlet.java 12246 2007-12-09 21:42:38Z benoitf $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.examples.ear;

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

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

/**
 * Defines a servlet that is accessing the two entities through a local session
 * bean.
 * @author Florent Benoit
 */
public class ExampleServlet extends HttpServlet {

    /**
     * Serializable class uid.
     */
    private static final long serialVersionUID = -3172627111841538912L;

    /**
     * Called by the server (via the service method) to allow a servlet to
     * handle a GET request.
     * @param request an HttpServletRequest object that contains the request the
     *        client has made of the servlet
     * @param response an HttpServletResponse object that contains the response
     *        the servlet sends to the client
     * @throws IOException if an input or output error is detected when the
     *         servlet handles the GET request
     * @throws ServletException if the request for the GET could not be handled
     */
    @Override
    public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head>");
        out.println("<title>");
        out.println("Client of Local session bean - EAR example</title>");
        out.println("</head>");
        out.println("<body>");

        initAuthorBooks(out);
        out.println("<br /><br />");
        displayAuthors(out);

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

    /**
     * Init list of authors/books.
     * @param out the given writer
     */
    private void initAuthorBooks(final PrintWriter out) {
        out.println("Initialize authors and their books...<br/>");

        List<Author> authors;
        try {
            authors = getBean().listOfAuthors();
        } catch (Exception e) {
            displayException(out, "Cannot Access to the bean", e);
            return;
        }

        if (authors != null && authors.size() > 0) {
            out.println("Already initialized !<br/>");
            return;
        }

        try {
            getBean().init();
        } catch (Exception e) {
            displayException(out, "Cannot init list of authors with their books", e);
            return;
        }
    }

    /**
     * Display authors.
     * @param out the given writer
     */
    private void displayAuthors(final PrintWriter out) {
        out.println("Get authors");
        out.println("<br /><br />");

        // Get list of Authors
        List<Author> authors = null;
        try {
            authors = getBean().listOfAuthors();
        } catch (Exception e) {
            displayException(out, "Cannot call listeOfAuthors on the bean", e);
            return;
        }

        // List for each author, the name of books
        if (authors != null) {
            for (Author author : authors) {
                out.println("List of books with author '" + author.getName() + "' :");
                out.println("<ul>");
                Collection<Book> books = author.getBooks();
                if (books == null) {
                    out.println("<li>No book !</li>");
                } else {
                    for (Book book : books) {
                        out.println("<li>Title '" + book.getTitle() + "'.</li>");
                    }
                }
                out.println("</ul>");

            }
        } else {
            out.println("No author found !");
        }

    }

    /**
     * If there is an exception, print the exception.
     * @param out the given writer
     * @param errMsg the error message
     * @param e the content of the exception
     */
    private void displayException(final PrintWriter out, final String errMsg, final Exception e) {
        out.println("<p>Exception : " + errMsg);
        out.println("<pre>");
        e.printStackTrace(out);
        out.println("</pre></p>");
    }

    /**
     * Lookup the stateless bean and gets a reference on it.
     * @return the stateless bean business interface.
     * @throws Exception if the bean cannot be retrieved.
     */
    private StatelessLocal getBean() throws Exception {
        Context initialContext = new InitialContext();

        // Default name
        //Object o = initialContext.lookup("org.ow2.jonas.examples.ear.StatelessBean" + "_"
        //        + StatelessLocal.class.getName() + "@Local");

        // But with mappedName attribute
        Object o = initialContext.lookup("myStateless");

        if (o instanceof StatelessLocal) {
            StatelessLocal statelessBean = (StatelessLocal) o;
            return statelessBean;
        }
        throw new Exception("Cannot cast object into StatelessLocal");

    }

}
