view src/fdl/test/topology/NodeManager.java @ 81:c001797f3fdb

connect bug fix
author one
date Mon, 23 Nov 2009 20:39:39 +0900
parents 805645cf5ec0
children
line wrap: on
line source

package fdl.test.topology;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;

import fdl.PSXLinda;
import fdl.MetaLinda;

public class NodeManager {
	public String hostName;
	public PSXLinda linda;
	private MetaLinda mLinda;
	private int port;
	private int manageId;
	private ArrayList<NodeManager> waitingNodes;
	private ArrayList<NodeManager> waitedNodes;
//	private ArrayList<NodeManager> sendNodes;

	public NodeManager(MetaLinda ml, int port, int manageId) {
		this.port = port;
		this.manageId = manageId;
		this.mLinda = ml;
		hostName = null;
		waitingNodes = new ArrayList<NodeManager>();
		waitedNodes = new ArrayList<NodeManager>();
//		sendNodes = new ArrayList<NodeManager>();
	}
	
	public void addConnection(NodeManager node) {
		waitingNodes.add(node);
		node.waitedNodes.add(this);
	}
	
	public void finishConnection(NodeManager node) {
		waitingNodes.remove(node);
		node.waitedNodes.remove(this);
//		sendNodes.add(node);
	}
	
	public void startUp(String hostName) {
		// 起動
		this.hostName = hostName;
		try {
			linda = mLinda.open(hostName, port);
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 起動待ちのノードに通知
		connectWaitedNodes();
	}
	
	public void connectWaitedNodes() {
		for (int i = 0; i < waitedNodes.size(); i++) {
			NodeManager node = waitedNodes.get(i);
			if (node.isRunning()) {
				node.connect(this);
				node.finishConnection(this);
				if (waitingNodes.contains(node)) {
					connect(node);
					finishConnection(node);
				}
			}
		}
		for (int i = 0; i < waitingNodes.size(); i++) {
			NodeManager node = waitingNodes.get(i);
			if (node.isRunning()) {
				connect(node);
				finishConnection(node);
				if (node.waitingNodes.contains(this)) {
					node.connect(this);
					node.finishConnection(this);
				}
			}
		}
	}
	
	public void connect(NodeManager node) {
		ByteBuffer data = ByteBuffer.wrap(node.hostName.getBytes());
		linda.out(manageId, data);
		try {
			linda.sync(1);
			System.out.println("[DEBUG] SendConnectTo: " + hostName + " to " + node.hostName);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public boolean isRunning() {
		return hostName != null;
	}
	
}