Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017 package org.ros.internal.node.service;
00018
00019 import com.google.common.base.Preconditions;
00020
00021 import org.jboss.netty.buffer.ChannelBuffer;
00022 import org.jboss.netty.channel.ChannelHandlerContext;
00023 import org.jboss.netty.channel.MessageEvent;
00024 import org.jboss.netty.channel.SimpleChannelHandler;
00025 import org.ros.exception.RemoteException;
00026 import org.ros.internal.node.response.StatusCode;
00027 import org.ros.message.MessageDeserializer;
00028 import org.ros.node.service.ServiceResponseListener;
00029
00030 import java.nio.charset.Charset;
00031 import java.util.Queue;
00032 import java.util.concurrent.ExecutorService;
00033
00039 class ServiceResponseHandler<ResponseType> extends SimpleChannelHandler {
00040
00041 private final Queue<ServiceResponseListener<ResponseType>> responseListeners;
00042 private final MessageDeserializer<ResponseType> deserializer;
00043 private final ExecutorService executorService;
00044
00045 public ServiceResponseHandler(Queue<ServiceResponseListener<ResponseType>> messageListeners,
00046 MessageDeserializer<ResponseType> deserializer, ExecutorService executorService) {
00047 this.responseListeners = messageListeners;
00048 this.deserializer = deserializer;
00049 this.executorService = executorService;
00050 }
00051
00052 @Override
00053 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
00054 final ServiceResponseListener<ResponseType> listener = responseListeners.poll();
00055 Preconditions.checkNotNull(listener, "No listener for incoming service response.");
00056 final ServiceServerResponse response = (ServiceServerResponse) e.getMessage();
00057 final ChannelBuffer buffer = response.getMessage();
00058 executorService.execute(new Runnable() {
00059 @Override
00060 public void run() {
00061 if (response.getErrorCode() == 1) {
00062 listener.onSuccess(deserializer.deserialize(buffer));
00063 } else {
00064 String message = Charset.forName("US-ASCII").decode(buffer.toByteBuffer()).toString();
00065 listener.onFailure(new RemoteException(StatusCode.ERROR, message));
00066 }
00067 }
00068 });
00069 }
00070 }