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 * 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.client;
16
17 import io.netty5.channel.ChannelHandlerContext;
18 import io.netty5.channel.SimpleChannelInboundHandler;
19 import io.netty5.handler.codec.http2.Http2Settings;
20 import io.netty5.util.concurrent.Promise;
21
22 import java.util.concurrent.TimeUnit;
23
24 /**
25 * Reads the first {@link Http2Settings} object and notifies a {@link Promise}
26 */
27 public class Http2SettingsHandler extends SimpleChannelInboundHandler<Http2Settings> {
28 private final Promise<Void> 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(Promise<Void> 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 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.asFuture().asStage().await(timeout, unit)) {
49 throw new IllegalStateException("Timed out waiting for settings");
50 }
51 if (promise.isFailed()) {
52 throw new RuntimeException(promise.cause());
53 }
54 }
55
56 @Override
57 protected void messageReceived(ChannelHandlerContext ctx, Http2Settings msg) throws Exception {
58 promise.setSuccess(null);
59
60 // Only care about the first settings message
61 ctx.pipeline().remove(this);
62 }
63 }