View Javadoc
1   /*
2    * Copyright 2020 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License, version 2.0 (the
5    * "License"); you may not use this file except in compliance with the License. You may obtain a
6    * copy of the License at:
7    *
8    * https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software distributed under the License
11   * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
12   * or implied. See the License for the specific language governing permissions and limitations under
13   * the License.
14   */
15  package io.netty5.example.http2.helloworld.frame.client;
16  
17  import io.netty5.channel.ChannelHandlerContext;
18  import io.netty5.channel.SimpleChannelInboundHandler;
19  import io.netty5.handler.codec.http2.Http2DataFrame;
20  import io.netty5.handler.codec.http2.Http2HeadersFrame;
21  import io.netty5.handler.codec.http2.Http2StreamFrame;
22  
23  import java.util.concurrent.CountDownLatch;
24  import java.util.concurrent.TimeUnit;
25  
26  /**
27   * Handles HTTP/2 stream frame responses. This is a useful approach if you specifically want to check
28   * the main HTTP/2 response DATA/HEADERs, but in this example it's used purely to see whether
29   * our request (for a specific stream id) has had a final response (for that same stream id).
30   */
31  public final class Http2ClientStreamFrameResponseHandler extends SimpleChannelInboundHandler<Http2StreamFrame> {
32  
33      private final CountDownLatch latch = new CountDownLatch(1);
34  
35      @Override
36      protected void messageReceived(ChannelHandlerContext ctx, Http2StreamFrame msg) {
37          System.out.println("Received HTTP/2 'stream' frame: " + msg);
38  
39          // isEndStream() is not from a common interface, so we currently must check both
40          if (msg instanceof Http2DataFrame && ((Http2DataFrame) msg).isEndStream()) {
41              latch.countDown();
42          } else if (msg instanceof Http2HeadersFrame && ((Http2HeadersFrame) msg).isEndStream()) {
43              latch.countDown();
44          }
45      }
46  
47      /**
48       * Waits for the latch to be decremented (i.e. for an end of stream message to be received), or for
49       * the latch to expire after 5 seconds.
50       * @return true if a successful HTTP/2 end of stream message was received.
51       */
52      public boolean responseSuccessfullyCompleted() {
53          try {
54              return latch.await(5, TimeUnit.SECONDS);
55          } catch (InterruptedException ie) {
56              System.err.println("Latch exception: " + ie.getMessage());
57              return false;
58          }
59      }
60  
61  }