/*
 * 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 1any 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
 *
 * Initial developer: Florent BENOIT
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.objectweb.jonas.examples.clients.alarm;

import junit.framework.TestSuite;

import org.objectweb.jonas.examples.util.JExampleTestCase;

import com.meterware.httpunit.AuthorizationRequiredException;
import com.meterware.httpunit.TableCell;
import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebLink;
import com.meterware.httpunit.WebResponse;
import com.meterware.httpunit.WebTable;

/**
 * Define a class to test the Alarm example
 * Test authentication, generate alarm and process alarms
 * @author Florent Benoit
 */
public class C_alarm extends JExampleTestCase {


    /**
     * URL of the alarm index
     */
    private static final String URL_ALARM = "/alarm/secured/list.jsp";

    /**
     * URL of the list of alarms
     */
    private static final String URL_ALARM_LIST = "/alarm/secured/setfilter.jsp?profil=all-I";

    /**
     * URL of the alarm generator
     */
    private static final String URL_ALARM_GENERATE = "/alarm/generator.html";

    /**
     * Main method
     * @param args the arguments
     */
    public static void main(String[] args) {

        String testtorun = null;
        // Get args
        for (int argn = 0; argn < args.length; argn++) {
            String sArg = args[argn];
            if (sArg.equals("-n")) {
                testtorun = args[++argn];
            }
        }

        if (testtorun == null) {
            junit.textui.TestRunner.run(suite());
        } else {
            junit.textui.TestRunner.run(new C_alarm(testtorun));
        }
    }

    /**
     * Get a new TestSuite for this class
     * @return a new TestSuite for this class
     */
    public static TestSuite suite() {
        return new TestSuite(C_alarm.class);
    }

    /**
     * Setup need for these tests
     * alarm is required
     * @throws Exception if it fails
     */
    protected void setUp() throws Exception {
        super.setUp();
        useEar("alarm");
    }

    /**
     * Constructor with a specified name
     * @param s name
     */
    public C_alarm(String s) {
        super(s, URL_ALARM);
    }


    /**
     * Try to log in without authentication
     * @throws Exception if an error occurs
     */
    public void testTryWithoutAuth() throws Exception {
        try {
            WebResponse wr = wc.getResponse(url);
            fail("Alarm is not protected");
        } catch (AuthorizationRequiredException e) {
            ;
        }
    }

    /**
     * Try to authenticate with a bad login/password
     * @throws Exception if an error occurs
     */
    public void testTryWithBadAuth() throws Exception {
        try {
            wc.setAuthorization("bad", "bad");
            WebResponse wr = wc.getResponse(url);
            fail("Alarm is not protected");
        } catch (AuthorizationRequiredException e) {
            ;
        }
    }

    /**
     * Try to authenticate with a right login/password (jetty)
     * @throws Exception if an error occurs
     */
    public void testTryWithJettyAuth() throws Exception {
        try {
            wc.setAuthorization("jetty", "jetty");
            WebResponse wr = wc.getResponse(url);
        } catch (AuthorizationRequiredException e) {
            fail("Alarm don't accept l/p jetty/jetty");
        }
    }

    /**
     * Try to authenticate with a right login/password (tomcat)
     * @throws Exception if an error occurs
     */
    public void testTryWithTomcatAuth() throws Exception {
        try {
            wc.setAuthorization("tomcat", "tomcat");
            WebResponse wr = wc.getResponse(url);
        } catch (AuthorizationRequiredException e) {
            fail("Alarm don't accept l/p tomcat/tomcat");
        }
    }
    /**
     * Try to generate alarms. One of each kind of alarm (severe, informative, warning)
     * @throws Exception if an error occurs
     */
    public void testGenerateAlarms() throws Exception {
        try {
            wc.setAuthorization("tomcat", "tomcat");
            WebResponse wr = wc.getResponse(getAbsoluteUrl(URL_ALARM_GENERATE));

            WebForm[] webForms = wr.getForms();

            WebForm webForm = webForms[0];
            assertNotNull("There must be a form in the html page", webForm);

            String[] levels = new String[] {"S", "W", "I"};

            for (int i = 0; i < 3; i++) {
                webForm.setParameter("message", "Automatic test" + i);
                webForm.setParameter("device", "aut" + i);
                webForm.setParameter("level", levels[i]);
                WebResponse wFormRes = webForm.submit();
                String txt = wFormRes.getText();
                if (txt.indexOf("Message sent") == -1) {
                    fail("The alarm was not generated : " + txt);
                }
            }

        } catch (AuthorizationRequiredException e) {
            fail("Alarm don't accept l/p tomcat/tomcat");
        }
    }

    /**
     * Try to process all alarms which were generated
     * @throws Exception if an error occurs
     */
    public void testProcessAlarms() throws Exception {
        try {
            // Wait a little if the previous alarms were not generated
            Thread.sleep(1000);

            wc.setAuthorization("tomcat", "tomcat");
            WebResponse wr = wc.getResponse(getAbsoluteUrl(URL_ALARM_LIST));
            WebTable[] webTables = wr.getTables();

            WebTable wTable = webTables[1];
            assertNotNull("There must be a table in the html page", wTable);

            int rows = wTable.getRowCount();
            int cols = wTable.getColumnCount();

            assertEquals("The tables must have 6 columns", 6, cols);

            // For each alarm
            for (int i = 1; i < rows; i++) {
                TableCell tableCell = wTable.getTableCell(i, cols - 1);
                assertNotNull("There must be a cell in this row", tableCell);
                WebLink[] links = tableCell.getLinks();
                assertNotNull("There must have links in this cell", links);
                for (int l = 0; l < links.length; l++) {
                   links[l].click();
                }
            }

            //Now check alarms are empty (rows = 1)
            wr = wc.getResponse(getAbsoluteUrl(URL_ALARM_LIST));
            webTables = wr.getTables();
            wTable = webTables[1];
            rows = wTable.getRowCount();
            assertEquals(1, rows);

        } catch (AuthorizationRequiredException e) {
            fail("Authentication failed");
        }
    }
}
