View Javadoc
1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  package org.apache.hc.core5.http2.examples;
28  
29  import java.util.List;
30  import java.util.concurrent.CountDownLatch;
31  import java.util.concurrent.Future;
32  import java.util.concurrent.TimeUnit;
33  
34  import org.apache.hc.core5.concurrent.FutureCallback;
35  import org.apache.hc.core5.http.Header;
36  import org.apache.hc.core5.http.HttpConnection;
37  import org.apache.hc.core5.http.HttpHost;
38  import org.apache.hc.core5.http.HttpResponse;
39  import org.apache.hc.core5.http.Message;
40  import org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester;
41  import org.apache.hc.core5.http.nio.AsyncClientEndpoint;
42  import org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer;
43  import org.apache.hc.core5.http.nio.support.AsyncRequestBuilder;
44  import org.apache.hc.core5.http.nio.support.BasicResponseConsumer;
45  import org.apache.hc.core5.http2.HttpVersionPolicy;
46  import org.apache.hc.core5.http2.config.H2Config;
47  import org.apache.hc.core5.http2.frame.RawFrame;
48  import org.apache.hc.core5.http2.impl.nio.H2StreamListener;
49  import org.apache.hc.core5.http2.impl.nio.bootstrap.H2RequesterBootstrap;
50  import org.apache.hc.core5.io.CloseMode;
51  import org.apache.hc.core5.reactor.IOReactorConfig;
52  import org.apache.hc.core5.util.Timeout;
53  
54  /**
55   * Example of HTTP/2 concurrent request execution using multiple streams.
56   */
57  public class H2MultiStreamExecutionExample {
58  
59      public static void main(final String[] args) throws Exception {
60  
61          // Create and start requester
62          final IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
63                  .setSoTimeout(5, TimeUnit.SECONDS)
64                  .build();
65  
66          final H2Config h2Config = H2Config.custom()
67                  .setPushEnabled(false)
68                  .setMaxConcurrentStreams(100)
69                  .build();
70  
71          final HttpAsyncRequester requester = H2RequesterBootstrap.bootstrap()
72                  .setIOReactorConfig(ioReactorConfig)
73                  .setVersionPolicy(HttpVersionPolicy.FORCE_HTTP_2)
74                  .setH2Config(h2Config)
75                  .setStreamListener(new H2StreamListener() {
76  
77                      @Override
78                      public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
79                          for (int i = 0; i < headers.size(); i++) {
80                              System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + headers.get(i));
81                          }
82                      }
83  
84                      @Override
85                      public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
86                          for (int i = 0; i < headers.size(); i++) {
87                              System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + headers.get(i));
88                          }
89                      }
90  
91                      @Override
92                      public void onFrameInput(final HttpConnection connection, final int streamId, final RawFrame frame) {
93                      }
94  
95                      @Override
96                      public void onFrameOutput(final HttpConnection connection, final int streamId, final RawFrame frame) {
97                      }
98  
99                      @Override
100                     public void onInputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
101                     }
102 
103                     @Override
104                     public void onOutputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
105                     }
106 
107                 })
108                 .create();
109         Runtime.getRuntime().addShutdownHook(new Thread(() -> {
110             System.out.println("HTTP requester shutting down");
111             requester.close(CloseMode.GRACEFUL);
112         }));
113         requester.start();
114 
115         final HttpHost target = new HttpHost("nghttp2.org");
116         final String[] requestUris = new String[] {"/httpbin/ip", "/httpbin/user-agent", "/httpbin/headers"};
117 
118         final Future<AsyncClientEndpoint> future = requester.connect(target, Timeout.ofSeconds(5));
119         final AsyncClientEndpoint clientEndpoint = future.get();
120 
121         final CountDownLatch latch = new CountDownLatch(requestUris.length);
122         for (final String requestUri: requestUris) {
123             clientEndpoint.execute(
124                     AsyncRequestBuilder.get()
125                             .setHttpHost(target)
126                             .setPath(requestUri)
127                             .build(),
128                     new BasicResponseConsumer<>(new StringAsyncEntityConsumer()),
129                     new FutureCallback<Message<HttpResponse, String>>() {
130 
131                         @Override
132                         public void completed(final Message<HttpResponse, String> message) {
133                             latch.countDown();
134                             final HttpResponse response = message.getHead();
135                             final String body = message.getBody();
136                             System.out.println(requestUri + "->" + response.getCode());
137                             System.out.println(body);
138                         }
139 
140                         @Override
141                         public void failed(final Exception ex) {
142                             latch.countDown();
143                             System.out.println(requestUri + "->" + ex);
144                         }
145 
146                         @Override
147                         public void cancelled() {
148                             latch.countDown();
149                             System.out.println(requestUri + " cancelled");
150                         }
151 
152                     });
153         }
154 
155         latch.await();
156 
157         // Manually release client endpoint when done !!!
158         clientEndpoint.releaseAndDiscard();
159 
160         System.out.println("Shutting down I/O reactor");
161         requester.initiateShutdown();
162     }
163 
164 }