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.Method;
41  import org.apache.hc.core5.http.impl.bootstrap.HttpAsyncRequester;
42  import org.apache.hc.core5.http.nio.AsyncClientEndpoint;
43  import org.apache.hc.core5.http.nio.entity.StringAsyncEntityConsumer;
44  import org.apache.hc.core5.http.nio.support.BasicRequestProducer;
45  import org.apache.hc.core5.http.nio.support.BasicResponseConsumer;
46  import org.apache.hc.core5.http2.HttpVersionPolicy;
47  import org.apache.hc.core5.http2.config.H2Config;
48  import org.apache.hc.core5.http2.frame.RawFrame;
49  import org.apache.hc.core5.http2.impl.nio.H2StreamListener;
50  import org.apache.hc.core5.http2.impl.nio.bootstrap.H2RequesterBootstrap;
51  import org.apache.hc.core5.io.CloseMode;
52  import org.apache.hc.core5.reactor.IOReactorConfig;
53  import org.apache.hc.core5.util.Timeout;
54  
55  /**
56   * Example of HTTP/2 concurrent request execution using multiple streams.
57   */
58  public class H2MultiStreamExecutionExample {
59  
60      public static void main(final String[] args) throws Exception {
61  
62          // Create and start requester
63          final IOReactorConfig ioReactorConfig = IOReactorConfig.custom()
64                  .setSoTimeout(5, TimeUnit.SECONDS)
65                  .build();
66  
67          final H2Config h2Config = H2Config.custom()
68                  .setPushEnabled(false)
69                  .setMaxConcurrentStreams(100)
70                  .build();
71  
72          final HttpAsyncRequester requester = H2RequesterBootstrap.bootstrap()
73                  .setIOReactorConfig(ioReactorConfig)
74                  .setVersionPolicy(HttpVersionPolicy.FORCE_HTTP_2)
75                  .setH2Config(h2Config)
76                  .setStreamListener(new H2StreamListener() {
77  
78                      @Override
79                      public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
80                          for (int i = 0; i < headers.size(); i++) {
81                              System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + headers.get(i));
82                          }
83                      }
84  
85                      @Override
86                      public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
87                          for (int i = 0; i < headers.size(); i++) {
88                              System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + headers.get(i));
89                          }
90                      }
91  
92                      @Override
93                      public void onFrameInput(final HttpConnection connection, final int streamId, final RawFrame frame) {
94                      }
95  
96                      @Override
97                      public void onFrameOutput(final HttpConnection connection, final int streamId, final RawFrame frame) {
98                      }
99  
100                     @Override
101                     public void onInputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
102                     }
103 
104                     @Override
105                     public void onOutputFlowControl(final HttpConnection connection, final int streamId, final int delta, final int actualSize) {
106                     }
107 
108                 })
109                 .create();
110         Runtime.getRuntime().addShutdownHook(new Thread() {
111             @Override
112             public void run() {
113                 System.out.println("HTTP requester shutting down");
114                 requester.close(CloseMode.GRACEFUL);
115             }
116         });
117         requester.start();
118 
119         final HttpHost target = new HttpHost("nghttp2.org");
120         final String[] requestUris = new String[] {"/httpbin/ip", "/httpbin/user-agent", "/httpbin/headers"};
121 
122         final Future<AsyncClientEndpoint> future = requester.connect(target, Timeout.ofSeconds(5));
123         final AsyncClientEndpoint clientEndpoint = future.get();
124 
125         final CountDownLatch latch = new CountDownLatch(requestUris.length);
126         for (final String requestUri: requestUris) {
127             clientEndpoint.execute(
128                     new BasicRequestProducer(Method.GET, target, requestUri),
129                     new BasicResponseConsumer<>(new StringAsyncEntityConsumer()),
130                     new FutureCallback<Message<HttpResponse, String>>() {
131 
132                         @Override
133                         public void completed(final Message<HttpResponse, String> message) {
134                             latch.countDown();
135                             final HttpResponse response = message.getHead();
136                             final String body = message.getBody();
137                             System.out.println(requestUri + "->" + response.getCode());
138                             System.out.println(body);
139                         }
140 
141                         @Override
142                         public void failed(final Exception ex) {
143                             latch.countDown();
144                             System.out.println(requestUri + "->" + ex);
145                         }
146 
147                         @Override
148                         public void cancelled() {
149                             latch.countDown();
150                             System.out.println(requestUri + " cancelled");
151                         }
152 
153                     });
154         }
155 
156         latch.await();
157 
158         // Manually release client endpoint when done !!!
159         clientEndpoint.releaseAndDiscard();
160 
161         System.out.println("Shutting down I/O reactor");
162         requester.initiateShutdown();
163     }
164 
165 }