package com.kylin.tankwar.jgroups.factory;

import org.apache.log4j.Logger;
import org.jgroups.Channel;
import org.jgroups.JChannel;
import org.jgroups.ReceiverAdapter;

import com.kylin.tankwar.jgroups.TankWarCommunicationException;

public class JChannelDefaultFactory implements ChannelFactory {
	
	private static final Logger logger = Logger.getLogger(JChannelDefaultFactory.class);
	
	private static JChannelDefaultFactory instance = null;
	
	public static JChannelDefaultFactory newInstance() {
		if(null == instance) {
			instance = new JChannelDefaultFactory();
		}
		return instance ;
	}
	
	private JChannelDefaultFactory() {}
	
	String jgroupsProps = "tankwar-udp.xml";

	public JChannelDefaultFactory setJgroupsProps(String jgroupsProps) {
		this.jgroupsProps = jgroupsProps;
		return this ;
	}

	public Channel createChannel(String id) throws Exception {
		return null;
	}

	public ProtocolStackConfiguration getProtocolStackConfiguration() {
		// TODO Auto-generated method stub
		return null;
	}

	public JChannel createChannel(String name, String cluster, ReceiverAdapter reciever) {

		logger.info("Create JGroups Channel, name = " + name + ", cluster = " + cluster);
		
		try {
			JChannel channel = new JChannel(jgroupsProps);
			channel.setName(name);
			channel.setReceiver(reciever);
			channel.setDiscardOwnMessages(true);
			channel.connect(cluster);
			return channel ;
		} catch (Exception e) {
			throw new TankWarCommunicationException("connect to " + cluster + " error", e);
		}
		
	}

}

@@ -37,16 +37,54 @@
 ctory;%0A%0A
+import javax.management.MBeanServer;%0A%0A
 import o
@@ -199,16 +199,86 @@
 Adapter;
+%0Aimport org.jgroups.jmx.JmxConfigurator;%0Aimport org.jgroups.util.Util;
 %0A%0Aimport
@@ -1475,16 +1475,346 @@
 uster);%0A
+%09%09%09%0A%09%09%09MBeanServer server = Util.getMBeanServer();%0A%09        if(server == null)%7B%0A%09        %09throw new Exception(%22No MBeanServers found;%22 + %22%5CnTankWar needs to be run with an MBeanServer present%22);%0A%09        %7D%0A%09        JmxConfigurator.registerChannel((JChannel)channel, server, %22jgroups-tankwar%22, channel.getClusterName(), true);%0A%09%09%09%0A
 %09%09%09retur

add JMX management function to jgroups tankwar demo