view rep/handler/Dispatcher.java @ 385:1fca50ce3508

first-working-version
author one@firefly.cr.ie.u-ryukyu.ac.jp
date Mon, 10 Nov 2008 22:18:14 +0900
parents bcdf5476b8e4
children bba62c4ac323
line wrap: on
line source

package rep.handler;

import java.io.IOException;

import rep.PacketSet;
import rep.REPCommand;
import rep.ServerMainLoop;
import rep.Session;
import rep.SessionManager;
import rep.channel.REPSelectionKey;
import rep.channel.REPSocketChannel;

/**
 * @author kono
 *    Handle SessionManager incoming Channel
 *    SessionManager Command and Multiplexed Editor Command come here.
 *    Dispatch Editor command according to the session and the channel.
 */
public class Dispatcher extends Forwarder {

	public Dispatcher(SessionManager manager) {
		super(manager);
	}

	public void setQuit2(REPCommand cmd) {
		send(cmd);
	}

	public boolean manage(REPCommand command) {
		next.send(command);
		return true;
	}

	public String toString(){
		return ("Dispatcher:" + channel);
	}
	

	public void handle(REPSelectionKey<REPCommand> key) throws IOException {
		/*
		 * SessionManagerから来たコマンドは、Editor関係のコマンドは、
		 * sessionとeidを判定して、そのeditorにforwardしてやれば良い。
		 * 残りは、manager.manage() で処理する。
		 */
		REPSocketChannel<REPCommand> channel = key.channel1();
		REPCommand command = channel.read();
		ServerMainLoop.logger.writeLog("REPHandlerImpl.handle() : command = " + command);
		if (manager.sessionManage(this, command)) return;
		
		distpatchToEditor(channel, command);
	}

	private void distpatchToEditor(REPSocketChannel<REPCommand> channel,
			REPCommand command) throws IOException {
		Session s = manager.getSession(command.sid);
		if (s==null) throw new IOException();
		REPNode f = s.getForwarder(channel);
		if (f==null) throw new IOException();
		if (!f.isDirect()) {
			// another forwarder, pass it to the next session manager
			f.send(command); 
			return;
		}
		/*
		 * local editor case. 
		 */
		Editor editor = (Editor)f;
		editor.forwardedCommandManage(command);
	}


	public void setNext(REPNode f) {
		next = f;
	}

	public boolean isMerging() {
		return false;
	}

	@Override
	public void send(REPCommand command) {
		assert(command!=null);
		assert(channel!=null);
		REPCommand c = new REPCommand(command);
		manager.addWriteQueue(new PacketSet(channel,null,  c));
	}
}