/**
 * 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 javax.management.Query;
import javax.management.QueryExp;

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

/**
 * Class for testing Joram User
 * @author Paul Kemler
 *
 */
public class F_JonasAdminJoramUser extends JonasAdminTestCase {

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

    /**
     * URL of the Joram Servers
     */
    private static final String URL_JONASADMIN_JORAM_SERVERS = "joramplatform/joramservers.jsp";

    /**
     * URL of the Joram Users
     */
    private static final String URL_JONASADMIN_JORAM_USERS = "joramplatform/joramusers.jsp";

    /**
     * URL of "Create Jms User"
     */
    private static final String URL_JONASADMIN_JORAM_CREATE_USER = "CreateJoramUser.do";

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

    /**
     * Get a new TestSuite for this class
     * @return a new TestSuite for this class
     */
    public static TestSuite suite() {
        return new TestSuite(F_JonasAdminJoramUser.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 to create a local user
     * @throws Exception if error occurs
     *
     */
    public void testSuccessfulCreateLocalUser() throws Exception {

        WebResponse wr;
        WebLink link;
        WebTable table;
        String createUserPage;
        /*
         * To get some utils for WebTable
         */
        JonasAdminUtils utils = new JonasAdminUtils();

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


        if (jProp.isResource()) {
            // Joram platform is in jonas
            if (isRarLoaded("joram_for_jonas_ra")) {
                // Go to Joram Platform
                wr = wc.getFrameContents(FRAME_TREE);
                link = wr.getFirstMatchingLink(WebLink.MATCH_URL_STRING, URL_JONASADMIN_JORAM);
                link.click();
                wr = wc.getFrameContents(FRAME_CONTENT);

                // Go to Joram Servers
                link = wr.getFirstMatchingLink(WebLink.MATCH_URL_STRING, URL_JONASADMIN_JORAM_SERVERS);
                link.click();
                wr = wc.getFrameContents(FRAME_CONTENT);

                // Go to Local Server
                WebTable localTable = utils.getTable(wr, 1);
                link = localTable.getTableCell(0, 0).getLinks()[0];
                if (link == null) {
                    throw new IllegalStateException("No link was found to a local server in the 'Joram servers' page. ");
                }
                link.click();
                wr = wc.getFrameContents(FRAME_CONTENT);

                // Go to Joram Users
                link = wr.getFirstMatchingLink(WebLink.MATCH_URL_STRING, URL_JONASADMIN_JORAM_USERS);
                link.click();
                wr = wc.getFrameContents(FRAME_CONTENT);

                // Go to Create JMS User
                link = wr.getFirstMatchingLink(WebLink.MATCH_URL_STRING, URL_JONASADMIN_JORAM_CREATE_USER);
                link.click();
                wr = wc.getFrameContents(FRAME_CONTENT);

                createUserPage = wr.getText();    // For comparing with the forwarded page after the creation
                // Find a name
                String userName = "new_user_";
                int userId = 0;
                boolean found = false;
                while (!found) {
                    if (!isUser(userName + userId)) {
                        userName = userName + userId;
                        found = true;
                    }
                    userId++;
                }

                // Create a new user
                createUser(wr, userName, userName);

                wr = wc.getFrameContents(FRAME_CONTENT);

                // Verify user is created
                assertTrue("The '" + userName + "' topic was not created. ", isUser(userName));

                // Verify the forwarded page
                assertEquals("The 'New User' page has changed. ", createUserPage, wr.getText());

            }
        }

    }

    /**
     * Test to create a local user that already exists
     * @throws Exception if error occurs
     *
     */
    public void testCreateUserAlreadyExists() throws Exception {

        WebResponse wr;
        WebLink link;
        WebTable table;
        /*
         * To get some utils for WebTable
         */
        JonasAdminUtils utils = new JonasAdminUtils();

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


        if (jProp.isResource()) {
            // Joram platform is in jonas
            if (isRarLoaded("joram_for_jonas_ra")) {

                // Find a name
                String userName = "new_user_";
                int userId = 0;
                boolean found = false;
                while (!found) {
                    if (!isUser(userName + userId)) {
                        userName = userName + userId;
                        found = true;
                    }
                    userId++;
                }

                // Create Jms User
                createLocalJmsUser(userName, userName);

                // Go to Joram Platform
                wr = wc.getFrameContents(FRAME_TREE);
                link = wr.getFirstMatchingLink(WebLink.MATCH_URL_STRING, URL_JONASADMIN_JORAM);
                link.click();
                wr = wc.getFrameContents(FRAME_CONTENT);

                // Go to Joram Servers
                link = wr.getFirstMatchingLink(WebLink.MATCH_URL_STRING, URL_JONASADMIN_JORAM_SERVERS);
                link.click();
                wr = wc.getFrameContents(FRAME_CONTENT);

                // Go to Local Server
                WebTable localTable = utils.getTable(wr, 1);
                link = localTable.getTableCell(0, 0).getLinks()[0];
                if (link == null) {
                    throw new IllegalStateException("No link was found to a local server in the 'Joram servers' page. ");
                }
                link.click();
                wr = wc.getFrameContents(FRAME_CONTENT);

                // Go to Joram Users
                link = wr.getFirstMatchingLink(WebLink.MATCH_URL_STRING, URL_JONASADMIN_JORAM_USERS);
                link.click();
                wr = wc.getFrameContents(FRAME_CONTENT);

                // Go to Create JMS User
                link = wr.getFirstMatchingLink(WebLink.MATCH_URL_STRING, URL_JONASADMIN_JORAM_CREATE_USER);
                link.click();
                wr = wc.getFrameContents(FRAME_CONTENT);

                // Create a new user
                createUser(wr, userName, "password");

                wr = wc.getFrameContents(FRAME_CONTENT);
                String errorPage = wr.getText();
                // Verify error because user already exists
                assertTrue("The value of the body class is not 'errors'. ", errorPage.indexOf("<body class=\"errors\">") != -1);
                assertTrue("There is no the message: 'User [" + userName + "] already exists but with a different password' in the error page. ", errorPage.indexOf("User [" + userName + "] already exists but with a different password.") != -1);

            }
        }

    }

    /**
     * Test the user list :
     * Create a local user and verify if the user is added to the local user list
     * and verify the id of the user.
     * @throws Exception if error occurs
     *
     */
    public void testUserList() throws Exception {

        WebResponse wr;
        WebLink link;
        WebTable table;
        /*
         * To get some utils for WebTable
         */
        JonasAdminUtils utils = new JonasAdminUtils();

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


        if (jProp.isResource()) {
            // Joram platform is in jonas
            if (isRarLoaded("joram_for_jonas_ra")) {

                // Find a name
                String userName = "new_user_";
                int userId = 0;
                boolean found = false;
                while (!found) {
                    if (!isUser(userName + userId)) {
                        userName = userName + userId;
                        found = true;
                    }
                    userId++;
                }

                // Create Jms User
                createLocalJmsUser(userName, userName);

                // Go to Joram Platform
                wr = wc.getFrameContents(FRAME_TREE);
                link = wr.getFirstMatchingLink(WebLink.MATCH_URL_STRING, URL_JONASADMIN_JORAM);
                link.click();
                wr = wc.getFrameContents(FRAME_CONTENT);

                // Go to Joram Servers
                link = wr.getFirstMatchingLink(WebLink.MATCH_URL_STRING, URL_JONASADMIN_JORAM_SERVERS);
                link.click();
                wr = wc.getFrameContents(FRAME_CONTENT);

                // Go to Local Server
                WebTable localTable = utils.getTable(wr, 1);
                link = localTable.getTableCell(0, 0).getLinks()[0];
                if (link == null) {
                    throw new IllegalStateException("No link was found to a local server in the 'Joram servers' page. ");
                }
                link.click();
                wr = wc.getFrameContents(FRAME_CONTENT);

                // Go to Joram Users
                link = wr.getFirstMatchingLink(WebLink.MATCH_URL_STRING, URL_JONASADMIN_JORAM_USERS);
                link.click();
                wr = wc.getFrameContents(FRAME_CONTENT);

                // Verify user is in the list
                table = utils.getTable(wr, 3);
                int userRow = utils.getRow(userName, table).intValue();
                if (userRow == -1) {
                    fail("'" + userName + "' was not found in the local user list. ");
                }
                String jmsUserId = getJmsUserId(userName);
                assertEquals("", jmsUserId, table.getTableCell(userRow, 1).getText());
            }
        }

    }

    /**
     * User exists
     * @param name the name of the user
     * @return true if the user exists, false else
     * @throws Exception if an error occurs
     */
    private boolean isUser(String name) throws Exception {
        MBeanServerConnection server = getMBeanServer();
        ObjectName on = ObjectName.getInstance("joramClient:type=User,*");
        QueryExp exp = Query.match(Query.attr("Name"), Query.value(name));

        return !server.queryNames(on, exp).isEmpty();
    }

    /**
     * Get the id of the Jms User
     * @param name the name of the user
     * @return the id
     * @throws Exception if an error occurs
     */
    private String getJmsUserId(String name) throws Exception {
        MBeanServerConnection server = getMBeanServer();
        ObjectName on = ObjectName.getInstance("joramClient:type=User,*");
        QueryExp exp = Query.match(Query.attr("Name"), Query.value(name));

        ObjectName joramUserON = (ObjectName) (server.queryNames(on, exp).iterator().next());
        return (String) server.getAttribute(joramUserON, "ProxyId");
    }

    /**
     * Create a jms user
     * @param wr the content frame in the 'New User' page
     * @param name the name of the user
     * @param password the password of the user
     * @throws Exception if an error occurs
     */
    private void createUser(WebResponse wr, String name, String password) throws Exception {
        SubmitButton button;
        WebForm form = wr.getForms()[0];
        form.setParameter("password", password);
        form.setParameter("name", name);

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

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

}
