1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.codec.http2;
17
18 import io.netty.channel.ChannelHandlerContext;
19 import io.netty.channel.ChannelInboundHandlerAdapter;
20 import io.netty.handler.codec.http.FullHttpMessage;
21 import io.netty.handler.codec.http.HttpHeaders;
22 import io.netty.handler.codec.http.HttpScheme;
23
24
25
26
27 public class InboundHttpToHttp2Adapter extends ChannelInboundHandlerAdapter {
28 private final Http2Connection connection;
29 private final Http2FrameListener listener;
30
31 public InboundHttpToHttp2Adapter(Http2Connection connection, Http2FrameListener listener) {
32 this.connection = connection;
33 this.listener = listener;
34 }
35
36 private static int getStreamId(Http2Connection connection, HttpHeaders httpHeaders) {
37 return httpHeaders.getInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text(),
38 connection.remote().incrementAndGetNextStreamId());
39 }
40
41 @Override
42 public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
43 if (msg instanceof FullHttpMessage) {
44 handle(ctx, connection, listener, (FullHttpMessage) msg);
45 } else {
46 super.channelRead(ctx, msg);
47 }
48 }
49
50
51
52
53 static void handle(ChannelHandlerContext ctx, Http2Connection connection,
54 Http2FrameListener listener, FullHttpMessage message) throws Http2Exception {
55 try {
56 int streamId = getStreamId(connection, message.headers());
57 Http2Stream stream = connection.stream(streamId);
58 if (stream == null) {
59 stream = connection.remote().createStream(streamId, false);
60 }
61 message.headers().set(HttpConversionUtil.ExtensionHeaderNames.SCHEME.text(), HttpScheme.HTTP.name());
62 Http2Headers messageHeaders = HttpConversionUtil.toHttp2Headers(message, true);
63 boolean hasContent = message.content().isReadable();
64 boolean hasTrailers = !message.trailingHeaders().isEmpty();
65 listener.onHeadersRead(
66 ctx, streamId, messageHeaders, 0, !(hasContent || hasTrailers));
67 if (hasContent) {
68 listener.onDataRead(ctx, streamId, message.content(), 0, !hasTrailers);
69 }
70 if (hasTrailers) {
71 Http2Headers headers = HttpConversionUtil.toHttp2Headers(message.trailingHeaders(), true);
72 listener.onHeadersRead(ctx, streamId, headers, 0, true);
73 }
74 stream.closeRemoteSide();
75 } finally {
76 message.release();
77 }
78 }
79 }