/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2008 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: JMSApplicationClient.java 13538 2008-04-07 12:01:32Z sauthieg $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.examples.ear.client;

import java.io.PrintStream;
import java.util.Collection;
import java.util.List;

import javax.jms.Message;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.naming.Context;
import javax.naming.InitialContext;

import org.ow2.jonas.examples.ear.entity.Author;
import org.ow2.jonas.examples.ear.entity.Book;
import org.ow2.jonas.examples.ear.init.Initializer;
import org.ow2.jonas.examples.ear.reader.RemoteReader;

/**
 * This application-client shows usage of JMS destinations to
 * interact with the server-side application.
 * @author Guillaume Sauthier
 */
public final class JMSApplicationClient {

    /**
     * Number of Books to be created.
     */
    private static final int ITERATION_NUMBER = 10;

    /**
     * Empty default constructor for utility class.
     */
    private JMSApplicationClient() {

    }

    /**
     * @param args Command line arguments
     * @throws Exception InitialContext creation failure / JMS Exception
     */
    public static void main(final String[] args) throws Exception {

        PrintStream out = System.out;

        // Print Header
        out.println("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");
        out.println("OW2 JOnAS :: EAR Sample :: Messager Application Client     ");
        out.println("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -");


        // Lookup the Remote Bean interface through JNDI
        Context initialContext = new InitialContext();

        // Init. data if needed
        out.print("Initialization ... ");
        Initializer bean = (Initializer) initialContext.lookup("myInitializerBean");
        bean.initializeEntities();
        out.println("Done.");

        // Get the JMS QueueConnectionFactory
        QueueConnectionFactory factory = null;
        factory = (QueueConnectionFactory) initialContext.lookup("java:comp/env/jms/QueueConnectionFactory");

        // Get the JMS Queue
        Queue queue = (Queue) initialContext.lookup("java:comp/env/jms/SampleQueue");

        // Send Book creation Messages
        QueueConnection connection = factory.createQueueConnection();
        QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        QueueSender sender = session.createSender(queue);

        for (int i = 0; i < ITERATION_NUMBER; i++) {
            String title = "Encyclopedia Universalis Vol." + i;
            Message message = session.createTextMessage(title);
            sender.send(message);
            out.println("Sended creation order for '" + title + "'");
        }

        // Close JMS objects
        sender.close();
        session.close();
        connection.close();

        // Wait for some time ...
        // Remember JMS is for asynchronous messages :)
        final long period = 2500;
        out.println("Wait for " + period + " ms...");
        Thread.sleep(period);

        // Get the Reader EJB to see the results
        String jndiName = "org.ow2.jonas.examples.ear.reader.ReaderBean"
                          + "_" + RemoteReader.class.getName() + "@Remote";
        out.println("Get Reader Bean ... ");
        RemoteReader readerBean = (RemoteReader) initialContext.lookup(jndiName);

        // List Authors and Books
        List<Author> authors = readerBean.listAllAuthors();
        for (Author author : authors) {
            out.println(" * " + author.getName());
            Collection<Book> books = author.getBooks();
            for (Book book : books) {
                out.println(" -> " + book.getTitle() + " [id: " + book.getId() + "]");
            }
        }

        out.println("Success.");

    }
}
