- Joined
- Jul 28, 2009
- Messages
- 339
- Reaction score
- 200
Code:
package chatservernew.util;
import chatservernew.net.Client;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.jboss.netty.buffer.ChannelBuffer;
/**
*
* @author Jay
*/
public class HandlerManager {
public static enum HandlerList {
CHAT("chatservernew.net.handlers.AuthHandler");
private final String className;
private HandlerList(String className) {
this.className = className;
}
public String getName() {
return className;
}
}
private static Map<Byte, Method> handlers = new HashMap<Byte, Method>();
static {
try {
initialize();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private static void initialize() throws ClassNotFoundException {
int count = 0;
for (HandlerList handler : HandlerList.values()) {
Class c = Class.forName(handler.getName());
for (Method method : c.getMethods()) {
PacketIdentifier annotation = method.getAnnotation(PacketIdentifier.class);
if (annotation != null) {
if (isValidMethod(method)) {
if (handlers.containsKey(annotation.packetId())) {
System.out.println("Duplicate handler for packetId: " + annotation.packetId());
} else {
count++;
handlers.put(annotation.packetId(), method);
}
} else {
System.out.println("Failed to add handler with method name of: " + method.getName() + " in " + handler.getName());
}
}
}
}
System.out.println(count + " handlers loaded.");
}
private static boolean isValidMethod(Method method) {
Class[] types = method.getParameterTypes();
return types.length == 2 && types[0].equals(Client.class) && types[1].equals(ChannelBuffer.class);
}
public static void handle(Client client, ChannelBuffer data, byte packetId) {
Method method = handlers.get(packetId);
try {
if (method != null) {
method.invoke(null, client, data);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
Code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package chatservernew.util;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*
* @author Jay
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface PacketIdentifier {
byte packetId();
}
Sample:
Code:
@PacketIdentifier(packetId = Opcodes.RECV_LOGIN)
public static void handleLogin(Client client, ChannelBuffer buffer) {
needs some changing for odin.
see: isValidMethod
Last edited:

