-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathJsonResponseCallbackHandler.java
More file actions
63 lines (50 loc) · 1.91 KB
/
Copy pathJsonResponseCallbackHandler.java
File metadata and controls
63 lines (50 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.github.dockerjava.netty.handler;
import com.github.dockerjava.core.DockerClientConfig;
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<T> extends SimpleChannelInboundHandler<ByteBuf> {
private final ObjectMapper objectMapper;
private TypeReference<T> typeReference;
private ResultCallback<T> callback;
@Deprecated
public JsonResponseCallbackHandler(TypeReference<T> typeReference, ResultCallback<T> callback) {
this(
DockerClientConfig.getDefaultObjectMapper(),
typeReference,
callback
);
}
public JsonResponseCallbackHandler(ObjectMapper objectMapper, TypeReference<T> typeReference, ResultCallback<T> callback) {
this.objectMapper = objectMapper;
this.typeReference = typeReference;
this.callback = callback;
}
@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();
}
}