com.github.dockerjava.netty.handler.JsonResponseCallbackHandler Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of org.apache.servicemix.bundles.docker-java
Show all versions of org.apache.servicemix.bundles.docker-java
This OSGi bundle wraps ${pkgArtifactId} ${pkgVersion} jar file.
package com.github.dockerjava.netty.handler;
import com.fasterxml.jackson.databind.SerializationFeature;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.dockerjava.api.async.ResultCallback;
/**
* Handler that decodes an incoming byte stream into objects of T and calls {@link ResultCallback#onNext(Object)}
*
* @author Marcus Linke
*/
public class JsonResponseCallbackHandler extends SimpleChannelInboundHandler {
private static ObjectMapper objectMapper = new ObjectMapper();
private TypeReference typeReference;
private ResultCallback callback;
public JsonResponseCallbackHandler(TypeReference typeReference, ResultCallback callback) {
this.typeReference = typeReference;
this.callback = callback;
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
byte[] buffer = new byte[msg.readableBytes()];
msg.readBytes(buffer);
msg.discardReadBytes();
T object = null;
try {
object = objectMapper.readValue(buffer, typeReference);
} catch (Exception e) {
callback.onError(e);
throw new RuntimeException(e);
}
callback.onNext(object);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
callback.onError(cause);
ctx.close();
}
}