view rep/Forwarder.java @ 355:98607350f7d1

*** empty log message ***
author kono
date Fri, 17 Oct 2008 22:11:34 +0900
parents 0d47ff22ee0e
children 034acadc0cdc
line wrap: on
line source

package rep;

import java.io.IOException;


import rep.channel.REPLogger;
import rep.channel.REPSelectionKey;
import rep.channel.REPSocketChannel;
import rep.handler.PacketSet;
import rep.handler.REPHandler;

public class Forwarder extends EditorPlus implements REPHandler {
	int seq = 0;
	Forwarder next;
	// REPCommands we sent to the next editor
	final int limit=100;
	REPLogger ns = REPLogger.singleton();
	SessionManager manager;
	public REP mode = null;
	
	public Forwarder(SessionManager manager) {
		this.manager = manager;
	}

	public int seq() {
		return seq++;
	}
	
	public void send(REPCommand command) {
		assert(command!=null);
		REPCommand c = new REPCommand(command);
		manager.addWriteQueue(new PacketSet(channel,null,  c));
	}
	
	public REPSocketChannel<REPCommand> getChannel() {
		return channel;
	}
	
	public void setChannel(REPSocketChannel<REPCommand> channel) {
		this.channel = channel;
	}

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

	public void setNext(Forwarder next) {
		this.next = next;
	}
	
	public Forwarder getNextForwarder() {
		return next;
	}

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

	public String toString(){
		return ("Forwarder:" + channel);
	}
	
	public String getLocalHostName() {
		return channel.getLocalHostName();
	}

	public void cancel(REPSocketChannel<REPCommand> socketChannel) {
		manager.remove(socketChannel);
	}

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

	public void setMode(REP cmd) {
		mode = cmd;
	}

	public boolean isEditor() {
		return mode==REP.SMCMD_JOIN||mode==REP.SMCMD_PUT;
	}
	
	public boolean isForwarder() {
		return mode==REP.SMCMD_SM_JOIN||mode==REP.SMCMD_SM_JOIN_ACK;
	}


}