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

import java.io.File;

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 com.meterware.httpunit.HttpUnitOptions;
import com.meterware.httpunit.TableCell;
import com.meterware.httpunit.WebLink;
import com.meterware.httpunit.WebResponse;
import com.meterware.httpunit.WebTable;

/**
 * Class for testing application container in jonasAdmin
 * @author Paul Kemler
 *
 */
public class F_JonasAdminApplicationContainer extends JonasAdminTestCase {

    /**
     * URL of Application container
     */
    private static final String URL_JONASADMIN_APP_CONTAINER = "ListAppContainers.do";

    /**
     * URL of the ear tab
     */
    private static final String URL_JONASADMIN_EAR = "/jonasAdmin/EditEar.do";

    /**
     * URL of the web tab
     */
    private static final String URL_JONASADMIN_WEB = "/jonasAdmin/service/earWars.jsp";

    /**
     * URL of the ejb tab
     */
    private static final String URL_JONASADMIN_JAR = "/jonasAdmin/service/earJars.jsp";

    /**
     * URL of the resource adapter tab
     */
    private static final String URL_JONASADMIN_RAR = "/jonasAdmin/service/earRars.jsp";

    /**
     * URL of the deployment descriptor tab
     */
    private static final String URL_JONASADMIN_XML = "/jonasAdmin/service/earXmlDeployment.jsp";

    /**
     * number of tabs with war, jar and rar in the ear
     */
    private static final int NUMBER_OF_TABS_WITH_WAR_JAR_RAR = 6;

    /**
     * number of tabs without rar in the ear
     */
    private static final int NUMBER_OF_TABS_WITHOUT_RAR = 5;

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

    /**
     * Get a new TestSuite for this class
     * @return a new TestSuite for this class
     */
    public static TestSuite suite() {
        return new TestSuite(F_JonasAdminApplicationContainer.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 application container when an ear with a war, a jar and a rar is deployed
     * @throws Exception if error occurs
     *
     */
    public void testAddEarWithWarJarAndRar() throws Exception {

        WebResponse wr;
        WebLink link;
        WebTable table;
        WebTable tabTable;
        TableCell selectedCell;
        TableCell cell;
        String ear = "earsample";
        int selectedTab;
        int code;
        JonasAdminUtils utils = new JonasAdminUtils();

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

        // Test only if there are services ear, ejb and resource
        if (jProp.isEar() && jProp.isEjb() && jProp.isResource()) {
            // Add earsample.ear
            useEar(ear);

            // Go to application container
            wr = wc.getFrameContents(FRAME_TREE);
            link = wr.getFirstMatchingLink( WebLink.MATCH_URL_STRING, URL_JONASADMIN_APP_CONTAINER);
            link.click();
            wr = wc.getFrameContents(FRAME_CONTENT);

            // Go to earsample page
            link = wr.getFirstMatchingLink( WebLink.MATCH_URL_STRING, ear);
            link.click();
            wr = wc.getFrameContents(FRAME_CONTENT);
            selectedTab = 2;

            // Verify infos
            try {
                table = utils.getTable(wr, 0);
                cell = table.getTableCell(0,2);
                // File
                assertEquals("It is not the name of the ear file. ", ear + ".ear", cell.getText());
                // Path
                String path = System.getProperty("jonas.base") + File.separator + "apps" + File.separator + ear + ".ear";
                assertEquals("It is not the path of the ear file. ", path, table.getTableCell(1,2).getText());
            } catch (ArrayIndexOutOfBoundsException e) {
                throw new IllegalStateException("Cannot find a table in the content frame. ");
            }

            // Verify tabs
            tabTable = utils.getTabTable(wr);
            testTabs(tabTable, NUMBER_OF_TABS_WITH_WAR_JAR_RAR, selectedTab, "Problem in 'earsample.ear' tab.");
            // - links
            assertTrue("The link " + URL_JONASADMIN_APP_CONTAINER + " is not found in the first tab. ",
                    tabTable.getTableCell(0, 0).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_APP_CONTAINER));
            assertTrue("The link " + URL_JONASADMIN_WEB + " is not found in the third tab. ",
                    tabTable.getTableCell(0, 4).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_WEB));
            assertTrue("The link " + URL_JONASADMIN_JAR + " is not found in the fourth tab. ",
                    tabTable.getTableCell(0, 6).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_JAR));
            assertTrue("The link " + URL_JONASADMIN_RAR + " is not found in the fifth tab. ",
                    tabTable.getTableCell(0, 8).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_RAR));
            assertTrue("The link " + URL_JONASADMIN_XML + " is not found in the sixth tab. ",
                    tabTable.getTableCell(0, 10).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_XML));


            // Go to the Web tab
            link = wr.getFirstMatchingLink( WebLink.MATCH_URL_STRING, URL_JONASADMIN_WEB);
            link.click();
            wr = wc.getFrameContents(FRAME_CONTENT);
            selectedTab = 3;

            // Verify infos
            table = utils.getTable(wr, 0);

            // File
            cell = table.getTableCell(1, 0);
            if (cell.getText().equals("")) {
                if (jProp.isCatalina()) {
                    fail("It is not the name of the war file of 'earsample'. ");
                } else {
                    throw new IllegalStateException("Not implemented: JETTY. ");
                }
            } else {
                assertEquals("It is not the name of the war file. ", "earsample", cell.getText());
                // Link
                link = cell.getLinks()[0];
                code = wc.sendRequest(link.getRequest()).getResponseCode();
                assertTrue("The file link does not contain 'EditWebApp.do?on='. ", link.getURLString().indexOf("EditWebApp.do?on=") != -1);
                assertEquals("The link " + link.getURLString() + " is not found. ", 200, code);
            }

            // Path
            cell = table.getTableCell(1, 1);
            assertTrue("It is not the path of the war file. ", cell.getText().endsWith("earsample.war"));

            // Verify tabs
            tabTable = utils.getTabTable(wr);
            testTabs(tabTable, NUMBER_OF_TABS_WITH_WAR_JAR_RAR, selectedTab, "Problem in 'Web' tab.");
            // - links
            assertTrue("The link " + URL_JONASADMIN_APP_CONTAINER + " is not found in the first tab. ",
                    tabTable.getTableCell(0, 0).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_APP_CONTAINER));
            assertTrue("The link " + URL_JONASADMIN_EAR + " is not found in the second tab. ",
                    tabTable.getTableCell(0, 2).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_EAR));
            assertTrue("The link " + URL_JONASADMIN_JAR + " is not found in the fourth tab. ",
                    tabTable.getTableCell(0, 6).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_JAR));
            assertTrue("The link " + URL_JONASADMIN_RAR + " is not found in the fifth tab. ",
                    tabTable.getTableCell(0, 8).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_RAR));
            assertTrue("The link " + URL_JONASADMIN_XML + " is not found in the sixth tab. ",
                    tabTable.getTableCell(0, 10).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_XML));


            // Go to the Ejb tab
            link = wr.getFirstMatchingLink( WebLink.MATCH_URL_STRING, URL_JONASADMIN_JAR);
            link.click();
            wr = wc.getFrameContents(FRAME_CONTENT);
            selectedTab = 4;

            // Verify infos
            table = utils.getTable(wr, 0);
            cell = table.getTableCell(1, 0);
            // File
            assertEquals("It is not the name of the war file. ", "secusb", cell.getText());
            // Link
            link = cell.getLinks()[0];
            code = wc.sendRequest(link.getRequest()).getResponseCode();
            assertTrue("The file link does not contain 'EditContainer.do?select='. ", cell.getLinks()[0].getURLString().indexOf("EditContainer.do?select=") != -1);
            assertEquals("The link " + link.getURLString() + " is not found. ", 200, code);

            // Path
            cell = table.getTableCell(1, 1);
            assertTrue("It is not the path of the war file. ", cell.getText().endsWith("secusb.jar"));

            // Verify tabs
            tabTable = utils.getTabTable(wr);
            testTabs(tabTable, NUMBER_OF_TABS_WITH_WAR_JAR_RAR, selectedTab, "Problem in 'Ejb' tab.");
            // - links
            assertTrue("The link " + URL_JONASADMIN_APP_CONTAINER + " is not found in the first tab. ",
                    tabTable.getTableCell(0, 0).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_APP_CONTAINER));
            assertTrue("The link " + URL_JONASADMIN_EAR + " is not found in the second tab. ",
                    tabTable.getTableCell(0, 2).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_EAR));
            assertTrue("The link " + URL_JONASADMIN_WEB + " is not found in the third tab. ",
                    tabTable.getTableCell(0, 4).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_WEB));
            assertTrue("The link " + URL_JONASADMIN_RAR + " is not found in the fifth tab. ",
                    tabTable.getTableCell(0, 8).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_RAR));
            assertTrue("The link " + URL_JONASADMIN_XML + " is not found in the sixth tab. ",
                    tabTable.getTableCell(0, 10).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_XML));


            // Go to the RA tab
            link = wr.getFirstMatchingLink( WebLink.MATCH_URL_STRING, URL_JONASADMIN_RAR);
            link.click();
            wr = wc.getFrameContents(FRAME_CONTENT);
            selectedTab = 5;

            // Verify infos
            table = utils.getTable(wr, 0);
            cell = table.getTableCell(1, 0);
            // File
            assertEquals("It is not the name of the rar file. ", "earsample.ra-sample", cell.getText());
            // Link
            link = cell.getLinks()[0];
            code = wc.sendRequest(link.getRequest()).getResponseCode();
            assertTrue("The file link does not contain 'EditResourceAdapter.do?select='. ", cell.getLinks()[0].getURLString().indexOf("EditResourceAdapter.do?select=") != -1);
            assertEquals("The link " + link.getURLString() + " is not found. ", 200, code);

            // Path
            cell = table.getTableCell(1, 1);
            assertTrue("It is not the path of the rar file. ", cell.getText().endsWith("ra-sample.rar"));

            // Verify tabs
            tabTable = utils.getTabTable(wr);
            testTabs(tabTable, NUMBER_OF_TABS_WITH_WAR_JAR_RAR, selectedTab, "Problem in 'Resource Adapter' tab.");
            // - links
            assertTrue("The link " + URL_JONASADMIN_APP_CONTAINER + " is not found in the first tab. ",
                    tabTable.getTableCell(0, 0).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_APP_CONTAINER));
            assertTrue("The link " + URL_JONASADMIN_EAR + " is not found in the second tab. ",
                    tabTable.getTableCell(0, 2).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_EAR));
            assertTrue("The link " + URL_JONASADMIN_WEB + " is not found in the third tab. ",
                    tabTable.getTableCell(0, 4).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_WEB));
            assertTrue("The link " + URL_JONASADMIN_JAR + " is not found in the fourth tab. ",
                    tabTable.getTableCell(0, 6).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_JAR));
            assertTrue("The link " + URL_JONASADMIN_XML + " is not found in the sixth tab. ",
                    tabTable.getTableCell(0, 10).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_XML));


            // Go to the deployement descriptor tab
            link = wr.getFirstMatchingLink( WebLink.MATCH_URL_STRING, URL_JONASADMIN_XML);
            link.click();
            wr = wc.getFrameContents(FRAME_CONTENT);
            selectedTab = 6;

            // Verify tabs
            tabTable = utils.getTabTable(wr);
            testTabs(tabTable, NUMBER_OF_TABS_WITH_WAR_JAR_RAR, selectedTab, "Problem in 'Deployment descriptor' tab.");
            // - links
            assertTrue("The link " + URL_JONASADMIN_APP_CONTAINER + " is not found in the first tab. ",
                    tabTable.getTableCell(0, 0).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_APP_CONTAINER));
            assertTrue("The link " + URL_JONASADMIN_EAR + " is not found in the second tab. ",
                    tabTable.getTableCell(0, 2).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_EAR));
            assertTrue("The link " + URL_JONASADMIN_WEB + " is not found in the third tab. ",
                    tabTable.getTableCell(0, 4).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_WEB));
            assertTrue("The link " + URL_JONASADMIN_JAR + " is not found in the fourth tab. ",
                    tabTable.getTableCell(0, 6).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_JAR));
            assertTrue("The link " + URL_JONASADMIN_RAR + " is not found in the fifth tab. ",
                    tabTable.getTableCell(0, 8).getLinks()[0].getURLString().endsWith(URL_JONASADMIN_RAR));
        }
    }

    /**
     * Test application container without a deployed rar
     * @throws Exception if error occurs
     *
     */
    public void testAddEarWithoutRar() throws Exception {

        WebResponse wr;
        WebLink link;
        WebTable tabTable;
        String ear = "alarm";
        JonasAdminUtils utils = new JonasAdminUtils();

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

        // Test only if there are services ear and ejb
        if (jProp.isEar() && jProp.isEjb()) {
            // Add alarm.ear
            useEar(ear);

            // Go to application container
            wr = wc.getFrameContents(FRAME_TREE);
            link = wr.getFirstMatchingLink( WebLink.MATCH_URL_STRING, URL_JONASADMIN_APP_CONTAINER);
            link.click();
            wr = wc.getFrameContents(FRAME_CONTENT);

            // Go to alarm page
            link = wr.getFirstMatchingLink( WebLink.MATCH_URL_STRING, ear);
            link.click();
            wr = wc.getFrameContents(FRAME_CONTENT);

            // Verify tabs
            try {
                tabTable = utils.getTabTable(wr);
            }catch (ArrayIndexOutOfBoundsException e) {
                throw new IllegalStateException("annot find the tab table. ");
            }
            // - number of tabs
            assertEquals("There are not " + NUMBER_OF_TABS_WITHOUT_RAR + " tabs. ",
                    NUMBER_OF_TABS_WITHOUT_RAR, (tabTable.getColumnCount() + 1) / 2);


            // Go to the Web tab
            link = wr.getFirstMatchingLink( WebLink.MATCH_URL_STRING, URL_JONASADMIN_WEB);
            link.click();
            wr = wc.getFrameContents(FRAME_CONTENT);

            // Verify tabs
            tabTable = utils.getTabTable(wr);

            // - number of tabs
            assertEquals("There are not " + NUMBER_OF_TABS_WITHOUT_RAR + " tabs. ",
                    NUMBER_OF_TABS_WITHOUT_RAR, (tabTable.getColumnCount() + 1) / 2);


            // Go to the Ejb tab
            link = wr.getFirstMatchingLink( WebLink.MATCH_URL_STRING, URL_JONASADMIN_JAR);
            link.click();
            wr = wc.getFrameContents(FRAME_CONTENT);

            // Verify tabs
            tabTable = utils.getTabTable(wr);
            // - number of tabs
            assertEquals("There are not " + NUMBER_OF_TABS_WITHOUT_RAR + " tabs. ",
                    NUMBER_OF_TABS_WITHOUT_RAR, (tabTable.getColumnCount() + 1) / 2);


            // Go to the deployement descriptor tab
            link = wr.getFirstMatchingLink( WebLink.MATCH_URL_STRING, URL_JONASADMIN_XML);
            link.click();
            wr = wc.getFrameContents(FRAME_CONTENT);

            // Verify tabs
            tabTable = utils.getTabTable(wr);
            // - number of tabs
            assertEquals("There are not " + NUMBER_OF_TABS_WITHOUT_RAR + " tabs. ",
                    NUMBER_OF_TABS_WITHOUT_RAR, (tabTable.getColumnCount() + 1) / 2);
        }
    }

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

}
