package com.eactive.eai.adapter.socket2.tool.monitor;

import com.eactive.eai.adapter.socket2.common.SimpleFuture;
import com.eactive.eai.adapter.socket2.config.SocketAdapterContext;
import com.eactive.eai.adapter.socket2.config.SocketAdapterFactory;
import com.eactive.eai.adapter.socket2.protocol.ISocketAdapter;

public class SocketMonitor {
	String hostname;
	int port;
	ISocketAdapter adapter;
	
	public SocketMonitor(String hostname, int port) throws Exception {
		this.hostname = hostname;
		this.port = port;
	}
	
	public String getConnectionList() throws Exception {
		start();
		try {
			byte[] result = (byte[]) adapter.sendMessage("monitor connection");
			return new String(result);
		} finally {
			stop();
		}
	}
	
	private void start() throws Exception {
		SocketAdapterContext adminContext = new SocketAdapterContext();
		adminContext.setProtocol("FIXED_LENGTH_HEADER");
		adminContext.setAdapterGroupName("AdminAdapterGroup");
		adminContext.setAdapterName("AdminAdapter");
		adminContext.setBoundUsage("IOBOUND");
		adminContext.setSocketType("CLIENT");
		adminContext.setHostName(hostname);
		adminContext.setPortNumber(port);
		adminContext.setAckSupport("N");
		adminContext.setLlFieldType("BIN");
		adminContext.setLlFieldLength(4);
		adminContext.setResponseType("SYNC");
		adminContext.setTimeout(10);
		adminContext.setMaxConnection(1);
		adminContext.setPermanent("Y");
		adminContext.setTraceLevel(adminContext.TRACE_LEVEL_DEFAULT);
		adapter = SocketAdapterFactory.createSocketAdapter(adminContext);
		SimpleFuture future = adapter.start();
		Object o = future.join(60000L);
		if (o instanceof Exception)
			throw (Exception) o;
	}
	
	private void stop() throws Exception {
		SimpleFuture future = adapter.stop();
		future.join();
	}
}
