/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2006-2011 Bull S.A.S.
 * 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$
 * --------------------------------------------------------------------------
 */
package org.ow2.jonas.antmodular.jonasbase.web.tomcat;

import org.ow2.jonas.antmodular.jonasbase.bootstrap.JReplace;
import org.ow2.jonas.antmodular.web.base.Cluster;
import org.ow2.jonas.antmodular.web.base.SessionReplication;
import org.ow2.jonas.antmodular.web.base.SessionReplicationAlgorithm;
import org.ow2.jonas.antmodular.web.base.WebContainer;


/**
 * Support Tomcat Connector Configuration.
 * Prefered order : http, director, ajp, https, cluster.
 *
 * @author Guillaume Sauthier
 */
public abstract class Tomcat extends WebContainer {

    /**
     * Info for the logger.
     */
    public static final String INFO = "[Tomcat] ";

    /**
     * Tomcat HTTPS Connector token.
     */
    private static final String JVM_ROUTE_TOKEN = "<Engine name=\"JOnAS\" defaultHost=\"localhost\">";

    /**
     * Tomcat Context manager token
     */
    public static final String CONTEXT_MANAGER_TOKEN = "<!--\n    <Manager pathname=\"\" />\n    -->";

    /**
     * Backup manager class name
     */
    public static final String SESSION_REPLICATION_BACKUP_MANAGER = "org.apache.catalina.ha.session.BackupManager";

    /**
     * Delta manager class name
     */
    public static final String SESSION_REPLICATION_DELTA_MANAGER = "org.apache.catalina.ha.session.DeltaManager";

    /**
     * Default Constructor.
     */
    public Tomcat() {
        super();
    }

    /**
     * Configure a Cluster HTTP Session.
     * @param cluster Cluster HTTP Session.
     */
    @Deprecated
    public abstract void addConfiguredCluster(final Cluster cluster);

    /**
     * Configure the tomcat session replication
     * @param sessionReplication {@link SessionReplication}
     */
    public abstract void addConfiguredSessionReplication(final SessionReplication sessionReplication);

    /**
     * Configure a jvmRoute.
     * @param jvmRoute jvm route name
     */
    public abstract void setJvmRoute(final String jvmRoute);

    /**
     * Configure a jvmRoute.
     * @param jvmRoute jvm route name
     * @param tomcatConfFile Name of Tomcat configuration file.
     */
    public void setJvmRoute(final String jvmRoute, final String tomcatConfFile) {
        JReplace propertyReplace = new JReplace();
        propertyReplace.setConfigurationFile(tomcatConfFile);
        propertyReplace.setToken(JVM_ROUTE_TOKEN);
        StringBuffer value = new StringBuffer();
        value.append("<Engine name=\"JOnAS\" defaultHost=\"localhost\" jvmRoute=\"" + jvmRoute + "\">");
        propertyReplace.setValue(value.toString());
        propertyReplace.setLogInfo(INFO + "Setting the jvmRoute to : " + jvmRoute);

        addTask(propertyReplace);
    }

    /**
     * Configure a Cluster HTTP Session.
     * @param cluster Cluster HTTP Session.
     * @param tomcatConfFile Name of Tomcat configuration file.
     */
    @Deprecated
    public void addConfiguredCluster(final Cluster cluster, String tomcatConfFile) {
        addConfiguredSessionReplication(cluster, tomcatConfFile);
    }

    /**
     * Configure an HTTP session replication.
     * @param sessionReplication Cluster HTTP Session.
     * @param tomcatConfFile Name of Tomcat configuration file.
     */
    public void addConfiguredSessionReplication(final SessionReplication sessionReplication, String tomcatConfFile) {
        // General Cluster configuration
        SessionReplicationAlgorithm sessionReplicationAlgorithm = sessionReplication.getAlgorithm();
        if (SessionReplicationAlgorithm.BACKUP_MANAGER.equals(sessionReplicationAlgorithm)) {
            setCluster(tomcatConfFile, SESSION_REPLICATION_BACKUP_MANAGER);
        } else {
            setCluster(tomcatConfFile, SESSION_REPLICATION_DELTA_MANAGER);
        }

        // Cluster name
        JReplace propertyReplace = new JReplace();
        propertyReplace.setConfigurationFile(tomcatConfFile);
        propertyReplace.setToken(SessionReplication.DEFAULT_CLUSTER_NAME);
        propertyReplace.setValue(sessionReplication.getName());
        propertyReplace.setLogInfo(INFO + "Setting Cluster name : " + sessionReplication.getName());
        addTask(propertyReplace);

        // Cluster listening port
        propertyReplace = new JReplace();
        propertyReplace.setConfigurationFile(tomcatConfFile);
        propertyReplace.setToken(SessionReplication.DEFAULT_LISTEN_PORT);
        propertyReplace.setValue(sessionReplication.getListenPort());
        propertyReplace.setLogInfo(INFO + "Setting Cluster listen port : " + sessionReplication.getListenPort());
        addTask(propertyReplace);

        // Cluster Multicast Address
        propertyReplace = new JReplace();
        propertyReplace.setConfigurationFile(tomcatConfFile);
        propertyReplace.setToken(SessionReplication.DEFAULT_MCAST_ADDR);
        propertyReplace.setValue(sessionReplication.getMcastAddr());
        propertyReplace.setLogInfo(INFO + "Setting Cluster multicast addr : " + sessionReplication.getMcastAddr());
        addTask(propertyReplace);

        // Cluster Multicast Port
        propertyReplace = new JReplace();
        propertyReplace.setConfigurationFile(tomcatConfFile);
        propertyReplace.setToken(SessionReplication.DEFAULT_MCAST_PORT);
        propertyReplace.setValue(sessionReplication.getMcastPort());
        propertyReplace.setLogInfo(INFO + "Setting Cluster multicast port : " + sessionReplication.getMcastPort());
        addTask(propertyReplace);
    }

    /**
     * Enable the cluster feature.
     * @param tomcatConfFile Name of Tomcat configuration file.
     * @param sessionManagerClassName Name of the implementation class of the session manager
     */
    private void setCluster(final String tomcatConfFile, final String sessionManagerClassName) {
        JReplace propertyReplace = new JReplace();
        propertyReplace.setConfigurationFile(tomcatConfFile);
        propertyReplace.setToken("</Host>");
        StringBuffer value = new StringBuffer("\n");
        value.append("        <Cluster className=\"org.apache.catalina.ha.tcp.SimpleTcpCluster\"\n");
        value.append("            channelSendOptions=\"8\">\n");
        value.append("            <Manager className=\"" + sessionManagerClassName + "\"\n");
        value.append("                expireSessionsOnShutdown=\"false\"\n");
        value.append("                notifyListenersOnReplication=\"true\"/>\n");
        value.append("            <Channel className=\"org.apache.catalina.tribes.group.GroupChannel\">\n");
        value.append("                <Membership\n");
        value.append("                    className=\"org.apache.catalina.tribes.membership.McastService\"\n");
        value.append("                    addr=\"" + Cluster.DEFAULT_MCAST_ADDR + "\"\n");
        value.append("                    port=\"" + Cluster.DEFAULT_MCAST_PORT + "\"\n");
        value.append("                    frequency=\"500\"\n");
        value.append("                    dropTime=\"3000\" />\n");
        value.append("                <Receiver\n");
        value.append("                    className=\"org.apache.catalina.tribes.transport.nio.NioReceiver\"\n");
        value.append("                    address=\"auto\"\n");
        value.append("                    port=\"" + Cluster.DEFAULT_LISTEN_PORT + "\"\n");
        value.append("                    autoBind=\"100\"\n");
        value.append("                    selectorTimeout=\"100\"\n");
        value.append("                    maxThread=\"6\" />\n");
        value.append("                <Sender\n");
        value.append("                    className=\"org.apache.catalina.tribes.transport.ReplicationTransmitter\">\n");
        value.append("                    <Transport\n");
        value.append("                        className=\"org.apache.catalina.tribes.transport.nio.PooledParallelSender\"/>\n");
        value.append("                </Sender>\n");
        value.append("                <Interceptor className=\"org.apache.catalina.tribes.group.interceptors.TcpFailureDetector\"/>\n");
        value.append("                <Interceptor className=\"org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor\"/>\n");
        value.append("            </Channel>\n");
        value.append("            <Valve className=\"org.apache.catalina.ha.tcp.ReplicationValve\"\n");
        value.append("                 filter=\".*\\.gif;.*\\.js;.*\\.jpg;.*\\.png;.*\\.htm;.*\\.html;.*\\.css;.*\\.txt;\" />\n");
        value.append("            <Valve className=\"org.apache.catalina.ha.session.JvmRouteBinderValve\"/>\n");
                //              "          <Deployer className=\"org.apache.catalina.cluster.deploy.FarmWarDeployer\"" + "\n" +
                //              "                    tempDir=\"/tmp/war-temp/\"" + "\n" +
                //              "                    deployDir=\"/tmp/war-deploy/\"" + "\n" +
                //              "                    watchDir=\"/tmp/war-listen/\"" + "\n" +
                //              "                    watchEnabled=\"false\"/>" +"\n" +
        value.append("            <ClusterListener className=\"org.apache.catalina.ha.session.JvmRouteSessionIDBinderListener\"/>\n");
        value.append("            <ClusterListener className=\"org.apache.catalina.ha.session.ClusterSessionListener\"/>\n");
        value.append("        </Cluster>\n");
        value.append("      </Host>");
        propertyReplace.setValue(value.toString());
        propertyReplace.setLogInfo(INFO + "Setting Cluster");
        addTask(propertyReplace);
    }

    /**
     * Configure a Cluster HTTP Session.
     * @param tomcatSessionManager {@link TomcatSessionManager}
     * @param tomcatConfFile Name of Tomcat configuration file.
     */
    public void addConfiguredSessionManager(final TomcatSessionManager tomcatSessionManager, final String tomcatConfFile) {
        JReplace propertyReplace = new JReplace();
        propertyReplace.setConfigurationFile(tomcatConfFile);
        propertyReplace.setToken(CONTEXT_MANAGER_TOKEN);
        StringBuffer value = new StringBuffer();
        String maxActiveSessions = tomcatSessionManager.getMaxActiveSessions();
        if (maxActiveSessions != null) {
            value.append("<Manager maxActiveSessions=\"" + tomcatSessionManager.getMaxActiveSessions() + "\"/>");
        } else {
            value.append("<Manager/>");
        }
        propertyReplace.setValue(value.toString());
        propertyReplace.setLogInfo(INFO + "Setting the maxActiveSessions to : " + tomcatSessionManager.getMaxActiveSessions());
        addTask(propertyReplace);
    }

    /**
     * Configure a Cluster HTTP Session.
     * @param tomcatSessionManager {@link TomcatSessionManager}
     */
    public abstract void addConfiguredSessionManager(final TomcatSessionManager tomcatSessionManager);
}
