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

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

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

    /**
     * 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, 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.
     */
    public void addConfiguredCluster(final Cluster cluster, String tomcatConfFile) {
        // General Cluster configuration
        setCluster(tomcatConfFile);

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

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

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

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

    /**
     * Enable the cluster feature.
     * @param tomcatConfFile Name of Tomcat configuration file.
     */
    private void setCluster(String tomcatConfFile) {
        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=\"org.apache.catalina.ha.session.DeltaManager\"\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);
    }
}
