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