view src/pathfinder/BlockingQnoSeMa/EditorSimulator.java @ 105:6c209de0dd99

*** empty log message ***
author kent
date Sat, 22 Dec 2007 21:11:01 +0900
parents 0a483aa8cf71
children 2e649cd44078
line wrap: on
line source

package pathfinder.BlockingQnoSeMa;

import java.util.Queue;

import remoteeditor.command.REPCommand;
import remoteeditor.network.REP;
import sample.merge.Translater;
import sample.merge.TranslaterImp1;

public class EditorSimulator extends Thread{
	private int eid;
	private int seq;
	private boolean isOwner;
	private NetworkSimulator<REPCommand> ns;
	private ChannelSimulator<REPCommand> cs;
	private Queue<REPCommand> CmdList;
	private TranslaterImp1 translater;
	private Text text;
	private boolean running=true;

	public EditorSimulator(int _eid, NetworkSimulator<REPCommand> _ns, Queue<REPCommand> q, String _name) {
		super(_name);
		eid = _eid;
		ns = _ns;
		CmdList = q;
		translater = new TranslaterImp1(_eid);
		text = new Text();
		cs = ns.connect();
	}

	public void setOwner(boolean f){
		isOwner = f;
	}
	synchronized public void finish(){
		running = false;
	}

	public void run(){
		System.out.println("Editor"+eid+" start.");

		// Send All Command that is included CmdList.
		sendAllCommand();

		// MainLoop, 
		while(running){
			REPCommand cmd = cs.read();
			REPCommand[] cmds;

			//終了条件
			if (cmd.eid==eid && cmd.cmd==REP.SMCMD_QUIT){
				System.out.println("\tEditor"+eid+" catch QUIT command emited by itself.");
				translater.transReceiveCmd(cmd);
				running=false; break;
			}
			System.out.println("\tEditor"+eid+" catch command:>> "+cmd.toString());
			cmds = translater.transReceiveCmd(cmd);
			if (cmds==null) continue;

			for (int i=0; i<cmds.length; i++){
				cmd = cmds[i];
				if (isOwner) cmd.setThroughMaster(true);
				text.edit(cmd);
				cs.write(cmd);
			}
		}

		System.out.println("Editor"+eid+" finish.");
	}

	private void sendAllCommand() {
		for (REPCommand cmd: CmdList){
			cmd.seq = seq;
			cmd.eid = eid;
			cmd.setString("this is inserted or replaced by Editor"+eid+":"+seq);
			cmd = translater.transSendCmd(cmd);
			if (isOwner) cmd.setThroughMaster(true);
			text.edit(cmd);
			cs.write(cmd);
			seq++;
		}
		// Send Quit Command
		cs.write( translater.transSendCmd( new REPCommand(REP.SMCMD_QUIT, 0, eid, seq++, 0, 0, "QUIT by Editor"+eid)));
	}
/*
	private boolean checkQuit(REPCommand cmd) {
		// 最初に全部のコマンドを送信するから、自分のQUITが来るのは最後
		return (cmd.eid==eid && cmd.cmd==REP.SMCMD_QUIT);
	}
*/
	public Text getText(){
		return text;
	}
}