/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 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 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
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.objectweb.jonas.jonasadmin.test.logging;

import junit.framework.TestSuite;

import org.objectweb.jonas.jonasadmin.test.util.JonasAdminAuth;
import org.objectweb.jonas.jonasadmin.test.util.JonasAdminTestCase;
import org.objectweb.jonas.jonasadmin.test.util.JonasAdminUtils;
import org.xml.sax.SAXException;

import com.meterware.httpunit.HttpUnitOptions;
import com.meterware.httpunit.SubmitButton;
import com.meterware.httpunit.WebConversation;
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 JOnAS Admin console
 * Test logging
 * @author Paul Kemler
 *
 */
public class F_JonasAdminLogger extends JonasAdminTestCase {

    /**
     * URL of Jonas Logger
     */
    private static final String URL_JONASADMIN_JONAS_LOGGER = "/EditLoggingJonas.do";

    /**
     * INPUT Checkbox
     */
    private static final String INPUT_CHECKBOX = "input type=\"checkbox\"";

    /**
     * Title logger type
     */
    private static final String TITLE_LOGGER_TYPE = "Logger type";

    /**
     * Title container type
     */
    private static final String TITLE_CONTAINER_TYPE = "Container type";

    /**
     * Title container name
     */
    private static final String TITLE_CONTAINER_NAME = "Container name (or path)";

    /**
     * A 2nd connection to jonasAdmin
     */
    private static WebConversation wc2 = new WebConversation();

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

    /**
     * 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 F_JonasAdminLogger(testtorun));
        }
    }

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

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

        if (wc.getCurrentPage().getURL() == null) {
            useWar("jonasAdmin");
            // login to jonas admin
            try {
                JonasAdminAuth.doValidAuth(wc, url);
            } catch (Exception e) {
                fail("authentification failed :  " + e);
            }
        } else {
            // if there was an error, the connection must be restablished
            try {
                wc.getFrameContents(FRAME_TREE);
            } catch (Exception e) {
                wc.getResponse(urlLogOut);
                // login to jonas admin
                try {
                    JonasAdminAuth.doValidAuth(wc, url);
                } catch (Exception auth) {
                    fail("authentification failed :  " + auth);
                }
            }
        }
    }

    /**
     * Test creation, modification et removal acces log valves
     * @throws Exception if error occurs
     *
     */
    public void testLoggers() throws Exception {

        WebResponse wr;
        WebLink link;
        WebTable table;
        WebForm form;
        String host = "localhost";
        int row;
        int columnLoggerType;
        JonasAdminUtils utils = new JonasAdminUtils();

        // Disable errors of javascript
        HttpUnitOptions.setExceptionsThrownOnScriptError(false);
        // Disable exception thrown on error status
        HttpUnitOptions.setExceptionsThrownOnErrorStatus(false);


        // OPEN A SECOND CONNECTION
        // login to jonas admin
        try {
            JonasAdminAuth.doValidAuth(wc2, url);
        } catch (Exception e) {
            fail("authentification failed :  " + e);
        }

        if (jProp.isCatalina()) {
            wr = LoggerUtils.getLoggerPage(wc);
            table = utils.getTable(wr, 3);

            if (table.getRowCount() == 2) {
                assertFalse("There is a remove button. ", wr.getText().indexOf("'remove'") != -1);
            } else {
                assertTrue("There is no remove button but there is no one and only one logger. ", wr.getText().indexOf("'remove'") != -1);
            }

            // 1-Create new loggers
            LoggerUtils.createNewEngineLogger(wc);
            // Verify
            wr = LoggerUtils.getLoggerPage(wc);
            table = utils.getTable(wr, 3);
            form = wr.getForms()[0];
            columnLoggerType = utils.getColumn(TITLE_LOGGER_TYPE, table).intValue();
            row = utils.getFirstRow("Access log valve engine", table, columnLoggerType).intValue();
            if (row == -1) {
                throw new IllegalThreadStateException("There is no row, which contains 'Access log valve engine'. ");
            }
            assertEquals("There is no the correct number of loggers. ", 3, table.getRowCount());
            assertTrue("There is no remove button. ", wr.getText().indexOf("'remove'") != -1);
            assertEquals("There is no the correct number of parameters in the form. ", 2, form.getParameterNames().length);
            assertTrue("There is no checkbox", wr.getText().indexOf(INPUT_CHECKBOX) != -1);
            assertEquals("The container type is not 'Engine'. ", "Engine", table.getTableCell(row, utils.getColumn(TITLE_CONTAINER_TYPE, table).intValue()).getText());
            assertEquals("The container name is not 'engine'. ", "engine", table.getTableCell(row, utils.getColumn(TITLE_CONTAINER_NAME, table).intValue()).getText());

            LoggerUtils.createNewHostLogger(wc);
            // Verify
            wr = LoggerUtils.getLoggerPage(wc);
            table = utils.getTable(wr, 3);
            form = wr.getForms()[0];
            row = utils.getFirstRow("Access log valve " + host, table, columnLoggerType).intValue();
            if (row == -1) {
                throw new IllegalThreadStateException("There is no row, which contains 'Access log valve " + host + "'. ");
            }
            assertEquals("There is no the correct number of loggers. ", 4, table.getRowCount());
            assertTrue("There is no remove button. ", wr.getText().indexOf("'remove'") != -1);
            assertEquals("There is no the correct number of parameters in the form. ", 2, form.getParameterNames().length);
            assertEquals("The container type is not 'Host'. ", "Host", table.getTableCell(row, utils.getColumn(TITLE_CONTAINER_TYPE, table).intValue()).getText());
            assertEquals("The container name is not '" + host + "'. ", host, table.getTableCell(row, utils.getColumn(TITLE_CONTAINER_NAME, table).intValue()).getText());

            // 2-Modify loggers
            LoggerUtils.modifyLogger(wc, null, "dir", "true", "false", ".suffix", "prefix_", "%v");
            // Verify
            wr = wc.getFrameContents(FRAME_CONTENT);
            verifyAccessLogValve(wr, "dir", "true", "false", ".suffix", "prefix_", "%v");

            LoggerUtils.modifyLogger(wc, host, "dir", "true", "false", ".suffix", "prefix_", "%v");
            // Verify
            wr = wc.getFrameContents(FRAME_CONTENT);
            verifyAccessLogValve(wr, "dir", "true", "false", ".suffix", "prefix_", "%v");


            // 3-Remove loggers
            LoggerUtils.deleteLogger(wc, null);
            // Verify
            wr = LoggerUtils.getLoggerPage(wc);
            table = utils.getTable(wr, 3);
            assertEquals("The number of loggers is not 2. ", 3, table.getRowCount());

            LoggerUtils.deleteLogger(wc, host);
            // Verify
            wr = LoggerUtils.getLoggerPage(wc);
            table = utils.getTable(wr, 3);
            assertEquals("The number of loggers is not 1. ", 2, table.getRowCount());
        }
    }

    /**
     * Test JOnAS logger
     * @throws Exception if error occurs
     */
    public void testJonasLogger() throws Exception {

        if (jProp.isCatalina()) {
            WebResponse wr;
            WebLink link;
            WebTable table;
            WebForm form;
            SubmitButton button = null;
            int row;
            int columnLevels;
            int columnTopics;
            JonasAdminUtils utils = new JonasAdminUtils();

            // Disable errors of javascript
            HttpUnitOptions.setExceptionsThrownOnScriptError(false);
            // Disable exception thrown on error status
            HttpUnitOptions.setExceptionsThrownOnErrorStatus(false);

            wr = LoggerUtils.getLoggerPage(wc);
            link = wr.getFirstMatchingLink(WebLink.MATCH_URL_STRING, URL_JONASADMIN_JONAS_LOGGER);
            if (link != null) {
                link.click();
            } else {
                throw new IllegalThreadStateException("The link " + URL_JONASADMIN_JONAS_LOGGER + " is not found. ");
            }

            // Verify topics
            wr = wc.getFrameContents(FRAME_CONTENT);
            table = utils.getTable(wr, 3);
            form = wr.getForms()[0];
            String[] topics = form.getOptions("topic");
            columnTopics = utils.getColumn("Topics", table).intValue();
            if (columnTopics == -1) {
                throw new IllegalThreadStateException("There is no column, which contains 'Topics'. ");
            }
            assertEquals("Number of topics is not the same in the select menu and in the table.", topics.length, table.getRowCount() - 1);
            for (int i = 0; i < topics.length; i++) {
                assertEquals("Topic " + topics[i] + " is not found in the table. ", topics[i], table.getTableCell(i+1, columnTopics).getText());
            }

            // Modify level of a topic
            columnLevels = utils.getColumn("Levels", table).intValue();
            if (columnLevels == -1) {
                throw new IllegalThreadStateException("There is no column, which contains 'Levels'. ");
            }
            String level = table.getTableCell(topics.length, columnLevels).getText();
            String topic = "org.objectweb.jonas.web";
            if (level.equals("WARN")) {
                level = "INFO";
            } else if (level.equals("INFO")) {
                level = "ERROR";
            } else if (level.equals("FATAL")) {
                level = "INHERIT";
            } else if (level.equals("INHERIT")) {
                level = "DEBUG";
            } else if (level.equals("DEBUG")) {
                level = "WARN";
            }

            form.setParameter("topic", topic);
            form.setParameter("level", level);

            button = form.getSubmitButtons()[0];
            button.click();

            // Verify topics
            wr = wc.getFrameContents(FRAME_CONTENT);
            table = utils.getTable(wr, 3);
            if (level.equals("ERROR")) {
                level = "FATAL";
            }
            row = utils.getFirstRow(topic, table, columnTopics).intValue();
            if (row == -1) {
                throw new IllegalThreadStateException("There is no row, which contains '" + topic + "' in the topic column. ");
            }
            assertEquals("The level of " + topic + " is not " + level + ". ", level, table.getTableCell(row, columnLevels).getText());
        }
    }

    /**
     * Verify access log valve properties
     * @param wr Content frame
     * @param directory value of the directory parameter
     * @param resolveHosts value of the resolveHosts parameter
     * @param rotatable value of the rotatable parameter
     * @param suffix value of the suffix parameter
     * @param prefix value of the prefix parameter
     * @param pattern value of the pattern parameter
     * @throws SAXException if an error occurs while form is got
     */
    private void verifyAccessLogValve(WebResponse wr, String directory, String resolveHosts,
            String rotatable, String suffix, String prefix, String pattern) throws SAXException {
        WebForm form = wr.getForms()[0];
        assertEquals("Directory value is not" + directory + ". ", directory, form.getParameterValue("directory"));
        assertEquals("Resolve hosts value is not" + resolveHosts + ". ", resolveHosts, form.getParameterValue("resolveHosts"));
        assertEquals("Rotatable value is not" + rotatable + ". ", rotatable, form.getParameterValue("rotatable"));
        assertEquals("Suffix value is not" + suffix + ". ", suffix, form.getParameterValue("suffix"));
        assertEquals("Prefix value is not" + prefix + ". ", prefix, form.getParameterValue("prefix"));
        assertEquals("Pattern value is not" + pattern + ". ", pattern, form.getParameterValue("pattern"));
    }

    /**
     * Tear Down cleanUp action
     * @throws Exception if an error occurs
     */
    public void tearDown() throws Exception {
        super.tearDown();
    }
}
