CommandProcessor(Socket client) {
this.client = client;
}
public void run() {
long receiveTime = System.currentTimeMillis();
TaskHandlerExecutor executor = null;
CommandInterpreter.ProxyCommand readCommand = null;
try {
CommandInterpreter commandInterpreter = new CommandInterpreter();
readCommand = commandInterpreter.readCommand(client.getInputStream());
LOGGER.debug("Read Command : " + readCommand);
String pool = readCommand.getCommandParams().get("pool");
// Prepare the request Wrapper
TaskRequestWrapper taskRequestWrapper = new TaskRequestWrapper();
taskRequestWrapper.setData(readCommand.getCommandData());
taskRequestWrapper.setParams(readCommand.getCommandParams());
/*Try to execute command using ThreadPool, if "pool" is found in the command, else the command name */
if (pool != null) {
executor = (TaskHandlerExecutor) repository.getExecutor(readCommand.getCommand(), pool, taskRequestWrapper);
} else {
executor = (TaskHandlerExecutor) repository.getExecutor(readCommand.getCommand(), readCommand.getCommand(), taskRequestWrapper);
}
TaskResult result;
/* execute */
if (executor.getCallInvocationType() == TaskHandler.SYNC_CALL) {
result = executor.execute();
} else {
/* dont wait for the result. send back a response that the call has been dispatched for async execution */
executor.queue();
result = new TaskResult(true, TaskHandlerExecutor.ASYNC_QUEUED);
}
LOGGER.debug("The output is: " + result);
// write the results to the socket output
commandInterpreter.writeCommandExecutionResponse(client.getOutputStream(), result);
} catch (Exception e) {
throw new RuntimeException("Error in processing command : " + e.getMessage(), e);
} finally {
if (eventProducer != null) {
// Publishes event both in case of success and failure.
final Map<String, String> params = readCommand.getCommandParams();
ServiceProxyEvent.Builder eventBuilder;
if(executor==null)
eventBuilder = new ServiceProxyEvent.Builder(readCommand.getCommand(), COMMAND_HANDLER).withEventSource(getClass().getName());
else
eventBuilder = executor.getEventBuilder().withCommandData(executor).withEventSource(executor.getClass().getName());
eventBuilder.withRequestId(params.get("requestID")).withRequestReceiveTime(receiveTime);
if(params.containsKey("requestSentTime"))
eventBuilder.withRequestSentTime(Long.valueOf(params.get("requestSentTime")));
eventProducer.publishEvent(eventBuilder.build());