/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2003-2004 Bull S.A.
 * Contact: jonas-team@ow2.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 any 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: ApplyConnectorAction.java 16123 2009-01-08 12:46:35Z eyindanga $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.webapp.jonasadmin.catalina;

import java.io.IOException;
import java.net.InetAddress;

import javax.management.ObjectName;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ow2.jonas.lib.management.extensions.base.JonasManagementRepr;
import org.ow2.jonas.lib.management.extensions.base.mbean.CatalinaObjectName;
import org.ow2.jonas.webapp.jonasadmin.JonasAdminJmx;
import org.ow2.jonas.webapp.jonasadmin.WhereAreYou;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

/**
 * @author Michel-Ange ANTON
 * @author Adriana Danes - update to Tomact 5.0
 * Replace MBeanFactory usage with JOnAS CatalinaConnectorFactory MBean
 * in order to avoid class loader problems occuring with JRMP
 */
public class ApplyConnectorAction extends CatalinaBaseAction {

    /**
     * Signature for the <code>createStandardConnector</code> operation.
     */
    private String[] saCreateStandardConnectorTypes = {
        "java.lang.String", "java.lang.String", "int" // port
    };

// --------------------------------------------------------- Public Methods

    public ActionForward executeAction(ActionMapping p_Mapping, ActionForm p_Form
        , HttpServletRequest p_Request, HttpServletResponse p_Response)
        throws IOException, ServletException {
        // Current JOnAS server name
        String serverName = m_WhereAreYou.getCurrentJonasServerName();
        // Next forward
        String sForward = "Catalina Connector";
        // Identify the requested action
        ConnectorForm oForm = (ConnectorForm) p_Form;
        String sAction = oForm.getAction();
        String sObjectName = oForm.getObjectName();
        String sConnectorType = oForm.getConnectorType();

        // Populate
        try {
            // Perform a "Create Connector operation"
            if ("create".equals(sAction)) {
                String address = oForm.getAddress(); // IP address

                // Ensure that the requested connector name is unique
                ObjectName onConnector = CatalinaObjectName.catalinaConnector(
                        m_WhereAreYou.getCurrentCatalinaDomainName(),
                        oForm.getPortText());
                if (JonasAdminJmx.hasMBeanName(onConnector, serverName)) {
                    m_Errors.add("connector", new ActionMessage("error.catalina.connector.exists"));
                    saveErrors(p_Request, m_Errors);
                    return (new ActionForward(p_Mapping.getInput()));
                }

                Object values[] = new Object[3];
                String operation = null;

                // Look up the Catalina MBeanFactory
                ObjectName onFactory = CatalinaObjectName.catalinaFactory();
                values[0] = CatalinaObjectName.catalinaService(m_WhereAreYou.
                    getCurrentCatalinaDomainName()
                    , m_WhereAreYou.getCurrentCatalinaServiceName()).toString();
                values[1] = address;
                values[2] = new Integer(oForm.getPortText());

                if ("HTTP".equalsIgnoreCase(sConnectorType)) {
                    operation = "createHttpConnector"; // HTTP
                }
                else if ("HTTPS".equalsIgnoreCase(sConnectorType)) {
                    operation = "createHttpsConnector"; // HTTPS
                }
                else {
                    operation = "createAjpConnector"; // AJP(HTTP)
                }
                sObjectName = (String) JonasManagementRepr.invoke(onFactory, operation, values
                    , saCreateStandardConnectorTypes, serverName);

                if (sObjectName == null) {
                    saveErrors(p_Request, m_Errors);
                    return (p_Mapping.findForward("Global Error"));
                }
                // refresh tree
                refreshTree(p_Request);
                // Force the node selected in tree
                String nodeName = getTreeBranchName(DEPTH_SERVER)
                    + WhereAreYou.NODE_SEPARATOR + "protocols"
                    + WhereAreYou.NODE_SEPARATOR + "connectors";
                    //+ WhereAreYou.NODE_SEPARATOR + m_WhereAreYou.getCurrentCatalinaServiceName()
                    //+ WhereAreYou.NODE_SEPARATOR + oForm.getPortText();
                if (address != null) {
                    nodeName = nodeName
                    + WhereAreYou.NODE_SEPARATOR + address;
                }
                m_WhereAreYou.selectNameNode(nodeName, true);

            }

            ObjectName oObjectName = new ObjectName(sObjectName);

            setIntegerAttribute(oObjectName, "acceptCount", oForm.getAcceptCountText());
            String addressValue = oForm.getAddress();
            InetAddress inetAddress = InetAddress.getByName(addressValue);
            JonasManagementRepr.setAttribute(oObjectName, "address", inetAddress, serverName);
            setBooleanAttribute(oObjectName, "allowTrace", oForm.isAllowTrace());
            setIntegerAttribute(oObjectName, "connectionTimeout", oForm.getConnTimeOutText());
            setIntegerAttribute(oObjectName, "bufferSize", oForm.getBufferSizeText());
            setIntegerAttribute(oObjectName, "maxPostSize", oForm.getMaxPostSizeText());
            setBooleanAttribute(oObjectName, "enableLookups", oForm.isEnableLookups());
            setBooleanAttribute(oObjectName, "emptySessionPath", oForm.isEmptySessionPath());
            setBooleanAttribute(oObjectName, "xpoweredBy", oForm.isXpoweredBy());
            setBooleanAttribute(oObjectName, "tcpNoDelay", oForm.isTcpNoDelay());
            setBooleanAttribute(oObjectName, "useBodyEncodingForURI", oForm.isUseBodyEncodingForURI());
            setIntegerAttribute(oObjectName, "redirectPort", oForm.getRedirectPortText());
            setIntegerAttribute(oObjectName, "maxThreads", oForm.getMaxThreadsText());
            setIntegerAttribute(oObjectName, "minSpareThreads", oForm.getMinSpareThreadsText());
            setIntegerAttribute(oObjectName, "maxSpareThreads", oForm.getMaxSpareThreadsText());

            // proxy name and port do not exist for AJP connector
            if ("AJP".equalsIgnoreCase(sConnectorType) == false) {
                setStringAttribute(oObjectName, "proxyName", oForm.getProxyName());
                setIntegerAttribute(oObjectName, "proxyPort", oForm.getProxyPortText());
            }

            // HTTPS specific properties
            if ("HTTPS".equalsIgnoreCase(sConnectorType) == true) {
                setBooleanAttribute(oObjectName, "clientAuth", oForm.isClientAuth());
                setStringAttribute(oObjectName, "keystoreFile", oForm.getKeystoreFile());
                setStringAttribute(oObjectName, "keystorePass", oForm.getKeystorePass());
            }

            if ("create".equals(sAction) == true) {
                m_Session.removeAttribute(p_Mapping.getAttribute());
                sForward = "ActionListCatalinaConnectors";
            }

            // Save in configuration file
            if (oForm.isSave() == true) {
                oForm.setSave(false);
                p_Request.setAttribute("forward", sForward);
                sForward = "ActionEditServletServer";
                //ObjectName on = CatalinaObjectName.catalinaServer();
                //JonasManagementRepr.invoke(on, "store", null, null);
            }
        } catch (Throwable t) {
            addGlobalError(t);
            saveErrors(p_Request, m_Errors);
            return (p_Mapping.findForward("Global Error"));
        }

        // Forward to the connector display page or the list if create
        return p_Mapping.findForward(sForward);
    }
}
