/*
 * $Header: /home/cvs/jakarta-tomcat-catalina/modules/cluster/src/share/org/apache/catalina/cluster/tcp/ReplicationTransmitter.java,v 1.14 2004/02/05 05:27:31 fhanik Exp $
 * $Revision: 1.14 $
 * $Date: 2004/02/05 05:27:31 $
 *
 * ====================================================================
 *
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 * [Additional notices, if required by prior licensing conditions]
 *
 */

package org.apache.catalina.cluster.tcp;

import org.apache.catalina.cluster.io.XByteBuffer;
import org.apache.catalina.cluster.Member;
import org.apache.catalina.cluster.ClusterSender;

 
public class ReplicationTransmitter implements ClusterSender
{
    private static org.apache.commons.logging.Log log =
        org.apache.commons.logging.LogFactory.getLog( ReplicationTransmitter.class );

    private java.util.HashMap map = new java.util.HashMap();
    public ReplicationTransmitter()
    {
    }

    private static long nrOfRequests = 0;
    private static long totalBytes = 0;
    private String replicationMode;
    private static synchronized void addStats(int length) {
        nrOfRequests++;
        totalBytes+=length;
        if ( (nrOfRequests % 100) == 0 ) {
            log.info("Nr of bytes sent="+totalBytes+" over "+nrOfRequests+" =="+(totalBytes/nrOfRequests)+" bytes/request");
        }

    }
    
    public void setReplicationMode(String mode) {
        String msg = IDataSenderFactory.validateMode(mode);
        if (msg == null) {
            log.debug("Setting replcation mode to " + mode);
            this.replicationMode = mode;
        }
        else
            throw new IllegalArgumentException(msg);

    }


    public synchronized void add(Member member)
    {
        try {
            IDataSender sender = IDataSenderFactory.getIDataSender(
                replicationMode, member);
            String key = sender.getAddress().getHostAddress() + ":" +
                sender.getPort();
            if (!map.containsKey(key))
                map.put(sender.getAddress().getHostAddress() + ":" +
                        sender.getPort(), sender);
        }catch ( java.io.IOException x ) {
            log.error("Unable to create and add a IDataSender object.",x);
        }
    }//add

    public synchronized void remove(Member member)
    {
        String key = member.getHost() + ":" + member.getPort();
        IDataSender toberemoved = (IDataSender) map.get(key);
        if (toberemoved == null)return;
        toberemoved.disconnect();
        map.remove(key);
    }

    public void start() throws java.io.IOException
    {
        //don't have to do shit, we connect on demand
    }

    public synchronized void stop()
    {
        java.util.Iterator i = map.entrySet().iterator();
        while ( i.hasNext() )
        {
            IDataSender sender = (IDataSender)((java.util.Map.Entry)i.next()).getValue();
            try { sender.disconnect(); } catch ( Exception x ){}
        }//while
    }//stop

    public IDataSender[] getSenders()
    {
        java.util.Iterator i = map.entrySet().iterator();
        java.util.Vector v = new java.util.Vector();
        while ( i.hasNext() )
        {
            IDataSender sender = (IDataSender)((java.util.Map.Entry)i.next()).getValue();
            if ( sender!=null) v.addElement(sender);
        }
        IDataSender[] result = new IDataSender[v.size()];
        v.copyInto(result);
        return result;
    }

    protected void sendMessageData(String sessionId, byte[] data, IDataSender sender) throws java.io.IOException  {
        if ( sender == null ) throw new java.io.IOException("Sender not available. Make sure sender information is available to the ReplicationTransmitter.");
        try
        {
            if (!sender.isConnected())
                sender.connect();
            sender.sendMessage(sessionId,data);
            sender.setSuspect(false);
            addStats(data.length);
        }catch ( Exception x)
        {
            if ( !sender.getSuspect() ) {
                log.warn("Unable to send replicated message, is server down?",
                         x);
            }
            sender.setSuspect(true);

        }

    }
    public void sendMessage(String sessionId, byte[] indata, Member member) throws java.io.IOException
    {
        byte[] data = XByteBuffer.createDataPackage(indata);
        String key = member.getHost()+":"+member.getPort();
        IDataSender sender = (IDataSender)map.get(key);
        sendMessageData(sessionId,data,sender);
    }

    public void sendMessage(String sessionId, byte[] indata) throws java.io.IOException
    {
         IDataSender[] senders = getSenders();
        byte[] data = XByteBuffer.createDataPackage(indata);
        for ( int i=0; i<senders.length; i++ )
        {

            IDataSender sender = senders[i];
            try
            {
                sendMessageData(sessionId,data,sender);
            }catch ( Exception x)
            {

                if ( !sender.getSuspect()) log.warn("Unable to send replicated message to "+sender+", is server down?",x);
                sender.setSuspect(true);
            }
        }//while
    }
    public String getReplicationMode() {
        return replicationMode;
    }
    
    public boolean getIsSenderSynchronized() {
        return IDataSenderFactory.SYNC_MODE.equals(replicationMode) ||
            IDataSenderFactory.POOLED_SYNC_MODE.equals(replicationMode);
    }



}
