package server;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import common.Marshaller;
import common.Request;
import common.Response;
public class Invoker {
private HashMap<Integer, Object> objectList =
new HashMap<Integer, Object>(10, 10);
private static Invoker instance;
private int currentId = 0;
public static Invoker getInstance() {
if (instance == null)
instance = new Invoker();
return instance;
}
public byte[] invoke(byte[] serializedRequest) {
Request request = (Request) Marshaller.deserialize(serializedRequest);
Response response = new Response();
int id = request.getAOR().getId();
String operation = request.getOperation();
Object[] arguments = request.getArguments();
Class<?>[] argTypes = new Class<?>[arguments.length];
for (int i = 0; i < arguments.length; i++)
argTypes[i] = arguments[i].getClass();
try {
Method method = objectList.get(id).getClass().getMethod(operation,
argTypes);
Object result = method.invoke(objectList.get(id), arguments);
response.setResult(result);
} catch (NoSuchMethodException | SecurityException |
IllegalAccessException | IllegalArgumentException |
InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return Marshaller.serialize(response);
}
public int register(Object object) {
this.objectList.put(currentId, object);
this.currentId = this.currentId + 1;
return (this.currentId - 1);
}
public void unregister(int objectId) {
this.objectList.remove(objectId);
}
}