View Javadoc
1   /*
2    * Copyright 2014 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    * http://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.netty.example.http2.helloworld.client;
16  
17  import io.netty.channel.ChannelHandlerContext;
18  import io.netty.channel.ChannelPromise;
19  import io.netty.channel.SimpleChannelInboundHandler;
20  import io.netty.handler.codec.http2.Http2Settings;
21  
22  import java.util.concurrent.TimeUnit;
23  
24  /**
25   * Reads the first {@link Http2Settings} object and notifies a {@link io.netty.channel.ChannelPromise}
26   */
27  public class Http2SettingsHandler extends SimpleChannelInboundHandler<Http2Settings> {
28      private final ChannelPromise promise;
29  
30      /**
31       * Create new instance
32       *
33       * @param promise Promise object used to notify when first settings are received
34       */
35      public Http2SettingsHandler(ChannelPromise promise) {
36          this.promise = promise;
37      }
38  
39      /**
40       * Wait for this handler to be added after the upgrade to HTTP/2, and for initial preface
41       * handshake to complete.
42       *
43       * @param timeout Time to wait
44       * @param unit {@link java.util.concurrent.TimeUnit} for {@code timeout}
45       * @throws Exception if timeout or other failure occurs
46       */
47      public void awaitSettings(long timeout, TimeUnit unit) throws Exception {
48          if (!promise.awaitUninterruptibly(timeout, unit)) {
49              throw new IllegalStateException("Timed out waiting for settings");
50          }
51          if (!promise.isSuccess()) {
52              throw new RuntimeException(promise.cause());
53          }
54      }
55  
56      @Override
57      protected void channelRead0(ChannelHandlerContext ctx, Http2Settings msg) throws Exception {
58          promise.setSuccess();
59  
60          // Only care about the first settings message
61          ctx.pipeline().remove(this);
62      }
63  }