/**
 * 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.joram;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;

import junit.framework.TestSuite;

import org.objectweb.jonas.jonasadmin.test.util.JonasAdminAuth;
import org.objectweb.jonas.jonasadmin.test.util.JonasAdminFiles;
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.WebLink;
import com.meterware.httpunit.WebResponse;
import com.meterware.httpunit.WebTable;


/**
 * Define a class to test the JOnAS Admin console
 * Test properties of joram platform
 * @author kemlerp
 *
 */
public class F_JonasAdminJoramProperties extends JonasAdminTestCase {

    /**
     * URL of the Joram Platform
     */
    private static final String URL_JONASADMIN_JORAM = "EditJoramPlatform.do";

    /**
     * Name of the file of jonasAdmin test properties
     */
    private static final String JONASADMINTEST_PROPERTY_NAME = "jonasAdminTests";

    /**
     * Name of the property joram.version
     */
    private static final String JORAM_VERSION = "joram.version";

    /**
     * Name of the property joram.serverId
     */
    private static final String JORAM_SERVER_ID = "joram.serverId";

    /**
     * Name of the property joram.serverName
     */
    private static final String JORAM_SERVER_NAME = "joram.serverName";

    /**
     * Name of the property joram.collocated
     */
    private static final String JORAM_COLLOCATED = "joram.collocated";

    /**
     * Name of the property joram.persistent
     */
    private static final String JORAM_PERSISTENT = "joram.persistent";

    /**
     * Name of the property joram.connectingTimer
     */
    private static final String JORAM_CONNECTING_TIMER = "joram.connectingTimer";

    /**
     * Name of the property joram.connectionPendingTimer
     */
    private static final String JORAM_CONNECTION_PENDING_TIMER = "joram.connectionPendingTimer";

    /**
     * Name of the property joram.transactedSessionMaximumIdleness
     */
    private static final String JORAM_TRANSACTED_SESSION_MAXIMUM_IDLENESS = "joram.transactedSessionMaximumIdleness";

    /**
     * Name of the property joram.timeoutToAbortRequest
     */
    private static final String JORAM_TIMEOUT_TO_ABORT_REQUEST = "joram.timeoutToAbortRequest";

    /**
     * Name of the property joram.defaultThresholdForDMQ
     */
    private static final String JORAM_DEFAULT_THRESHOLD = "joram.defaultThresholdForDMQ";


    /**
     * Constructor with a specified name
     * @param s name
     */
    public F_JonasAdminJoramProperties(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_JonasAdminJoramProperties(testtorun));
        }
    }

    /**
     * Get a new TestSuite for this class
     * @return a new TestSuite for this class
     */
    public static TestSuite suite() {
        return new TestSuite(F_JonasAdminJoramProperties.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 properties of joram
     * @throws Exception if error occurs
     */
    public void testJoramProperties() throws Exception {

        JonasAdminUtils utils = new JonasAdminUtils();
        MBeanServerConnection server = getMBeanServer();

        if (jProp.isResource()) {
            // Joram platform is in jonas
            if (isRarLoaded("joram_for_jonas_ra")) {
                // Disable errors of javascript
                HttpUnitOptions.setExceptionsThrownOnScriptError(false);
                // Disable exception thrown on error status
                HttpUnitOptions.setExceptionsThrownOnErrorStatus(false);

                // READ joram properties from MBeans
                ObjectName on = ObjectName.getInstance("joramClient:type=JoramAdapter,*");
                ObjectName joramAdapterON = (ObjectName) server.queryNames(on, null).iterator().next();

                String version = joramAdapterON.getKeyProperty("version");
                String serverId = ((Short) server.getAttribute(joramAdapterON, "ServerId")).toString();
                String serverName = (String) server.getAttribute(joramAdapterON, "ServerName");
                String collocatedServer = "" + jProp.isJMSCollocated();
                String persistentServer = ((Boolean) server.getAttribute(joramAdapterON, "PersistentPlatform")).toString();
                String connectingTimer = ((Integer) server.getAttribute(joramAdapterON, "ConnectingTimer")).toString();
                String connectionPendingTimer = ((Integer) server.getAttribute(joramAdapterON, "CnxPendingTimer")).toString();
                String transactedSessionMaximumIdleness = ((Integer) server.getAttribute(joramAdapterON, "TxPendingTimer")).toString();
                String timeoutToAbortRequest = "" + ((Long) server.getAttribute(joramAdapterON, "TimeOutToAbortRequest")).longValue();
                String hostName =(String) server.getAttribute(joramAdapterON, "HostName");
                String portNumber = ((Integer) server.getAttribute(joramAdapterON, "ServerPort")).toString();
                String fileName =(String) server.getAttribute(joramAdapterON, "AdminFileXML");

                String defaultThreshold = "Not set";
                Object defaultDMQinstance = server.getAttribute(joramAdapterON, "DefaultDMQ");
                if (defaultDMQinstance != null) {
                    defaultThreshold = defaultDMQinstance.toString();
                }
                // Go to Joram Platform
                WebResponse wr = wc.getFrameContents(FRAME_TREE);
                WebLink link = wr.getFirstMatchingLink(WebLink.MATCH_URL_STRING, URL_JONASADMIN_JORAM);
                link.click();
                wr = wc.getFrameContents(FRAME_CONTENT);

                // Get table
                try {
                    WebTable versionTable = utils.getTable(wr, 0);
                    WebTable currentJoramTable = utils.getTable(wr, 3);
                    WebTable timerTable = utils.getTable(wr, 6);
                    WebTable dmqTable = utils.getTable(wr, 9);

                    // Get name of administration task file
                    //String fileName = currentJoramTable.getTableCell(6, 2).getText();

                     // Get server port from administration task file
                    //String serverPort = JonasAdminFiles.getJoramServerPort(fileName);

                    // Get host name from administration task file
                    //String hostName = JonasAdminFiles.getJoramHostName(fileName);

                    // Verify
                    assertEquals("It is not the expected joram version. ", version, versionTable.getTableCell(0, 2)
                            .getText());
                    assertEquals("It is not the expected joram local server id. ", serverId, currentJoramTable
                            .getTableCell(0, 2).getText());
                    assertEquals("It is not the expected joram local server name. ", serverName, currentJoramTable
                            .getTableCell(1, 2).getText());
                    assertEquals("It is not the expected joram local host name. ", hostName, currentJoramTable
                            .getTableCell(2, 2).getText());
                    assertEquals("It is not the expected joram local server port. ", portNumber, currentJoramTable
                            .getTableCell(3, 2).getText());
                    assertEquals("It is not the expected value of the collocated server attribut. ", collocatedServer,
                            currentJoramTable.getTableCell(4, 2).getText());
                    assertEquals("It is not the expected value of the persistent server attribut. ", persistentServer,
                            currentJoramTable.getTableCell(5, 2).getText());
                    assertEquals("It is not the expected joram configuration file name. ", fileName, currentJoramTable
                            .getTableCell(6, 2).getText());
                    assertEquals("It is not the expected connecting timer. ", connectingTimer, timerTable
                            .getTableCell(0, 2).getText());
                    assertEquals("It is not the expected connection pending timer. ", connectionPendingTimer, timerTable
                            .getTableCell(1, 2).getText());
                    assertEquals("It is not the expected transacted session maximum idleness. ",
                            transactedSessionMaximumIdleness, timerTable.getTableCell(2, 2).getText());
                    assertEquals("It is not the expected timeout to abort request. ", timeoutToAbortRequest, timerTable
                            .getTableCell(3, 2).getText());
                    assertEquals("It is not the expected default threshold for DMQ. ", defaultThreshold, dmqTable
                            .getTableCell(1, 2).getText());
                } catch (SAXException e) {
                    fail("Tables are not correct.");
                }
            }
        }

    }

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