package lbms.plugins.mldht.kad.messages;
import java.io.IOException;
import java.net.InetSocketAddress;
import lbms.plugins.mldht.kad.DHT;
import lbms.plugins.mldht.kad.Key;
/**
* Base class for all RPC messages.
*
* @author Damokles
*/
public abstract class MessageBase {
protected byte[] mtid;
protected Method method;
protected Type type;
protected Key id;
protected InetSocketAddress origin;
protected String version;
public MessageBase (byte[] mtid, Method m, Type type, Key id) {
this.mtid = mtid;
this.method = m;
this.type = type;
this.id = id;
}
/**
* When this message arrives this function will be called upon the DHT.
* The message should then call the appropriate DHT function (double dispatch)
* @param dh_table Pointer to DHT
*/
public void apply (DHT dh_table) {
}
/**
* Print the message for debugging purposes.
*/
//virtual void print() = 0;
/**
* BEncode the message.
* @return Data array
*/
public abstract byte[] encode () throws IOException;
/// Set the origin (i.e. where the message came from)
public void setOrigin (InetSocketAddress o) {
origin = o;
}
/// Get the origin
public InetSocketAddress getOrigin () {
return origin;
}
/// Set the origin (i.e. where the message came from)
public void setDestination (InetSocketAddress o) {
origin = o;
}
/// Get the origin
public InetSocketAddress getDestination () {
return origin;
}
/// Get the MTID
public byte[] getMTID () {
return mtid;
}
/// Set the MTID
public void setMTID (byte[] m) {
mtid = m;
}
public void setMTID (short m) {
mtid = new byte[] {(byte)(m>>8),(byte)(m&0xff)};
}
public String getVersion () {
return version;
}
public void setVersion (String version) {
this.version = version;
}
/// Get the id of the sender
public Key getID () {
return id;
}
/// Get the type of the message
public Type getType () {
return type;
}
/// Get the message it's method
public Method getMethod () {
return method;
}
@Override
public String toString() {
return " Method:" + method + " Type:" + type + " MessageID:" + new String(mtid)+(version != null ? " version:"+version : "")+" ";
}
public static enum Type {
REQ_MSG, RSP_MSG, ERR_MSG, INVALID
};
public static enum Method {
PING, FIND_NODE, GET_PEERS, ANNOUNCE_PEER, NONE
};
}