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.client5.testing.async;
28  
29  import java.io.ByteArrayOutputStream;
30  import java.nio.ByteBuffer;
31  import java.nio.channels.Channels;
32  import java.nio.channels.WritableByteChannel;
33  import java.nio.charset.StandardCharsets;
34  import java.util.LinkedHashMap;
35  import java.util.List;
36  import java.util.Map;
37  import java.util.Queue;
38  import java.util.Random;
39  import java.util.concurrent.ArrayBlockingQueue;
40  import java.util.concurrent.BlockingQueue;
41  import java.util.concurrent.ConcurrentLinkedQueue;
42  import java.util.concurrent.CountDownLatch;
43  import java.util.concurrent.ExecutorService;
44  import java.util.concurrent.Executors;
45  import java.util.concurrent.Future;
46  import java.util.concurrent.atomic.AtomicInteger;
47  import java.util.concurrent.atomic.AtomicReference;
48  
49  import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
50  import org.apache.hc.client5.http.protocol.HttpClientContext;
51  import org.apache.hc.core5.concurrent.FutureCallback;
52  import org.apache.hc.core5.http.ContentType;
53  import org.apache.hc.core5.http.HttpHost;
54  import org.apache.hc.core5.http.HttpResponse;
55  import org.apache.hc.core5.http.Message;
56  import org.apache.hc.core5.http.URIScheme;
57  import org.apache.hc.core5.http.nio.AsyncRequestProducer;
58  import org.apache.hc.core5.http.nio.support.AsyncRequestBuilder;
59  import org.apache.hc.core5.reactive.ReactiveEntityProducer;
60  import org.apache.hc.core5.reactive.ReactiveResponseConsumer;
61  import org.apache.hc.core5.testing.reactive.ReactiveTestUtils;
62  import org.apache.hc.core5.testing.reactive.ReactiveTestUtils.StreamDescription;
63  import org.apache.hc.core5.util.TextUtils;
64  import org.hamcrest.CoreMatchers;
65  import org.junit.Assert;
66  import org.junit.Test;
67  import org.reactivestreams.Publisher;
68  
69  import io.reactivex.Flowable;
70  import io.reactivex.functions.Consumer;
71  import io.reactivex.schedulers.Schedulers;
72  
73  public abstract class AbstractHttpReactiveFundamentalsTest<T extends CloseableHttpAsyncClient> extends AbstractIntegrationTestBase<T> {
74  
75      public AbstractHttpReactiveFundamentalsTest(final URIScheme scheme) {
76          super(scheme);
77      }
78  
79      @Override
80      protected final boolean isReactive() {
81          return true;
82      }
83  
84      @Test(timeout = 60_000)
85      public void testSequentialGetRequests() throws Exception {
86          final HttpHost target = start();
87          for (int i = 0; i < 3; i++) {
88              final ReactiveResponseConsumer consumer = new ReactiveResponseConsumer();
89  
90              httpclient.execute(AsyncRequestBuilder.get(target + "/random/2048").build(), consumer, null);
91  
92              final Message<HttpResponse, Publisher<ByteBuffer>> response = consumer.getResponseFuture().get();
93              Assert.assertThat(response, CoreMatchers.notNullValue());
94              Assert.assertThat(response.getHead().getCode(), CoreMatchers.equalTo(200));
95  
96              final String body = publisherToString(response.getBody());
97              Assert.assertThat(body, CoreMatchers.notNullValue());
98              Assert.assertThat(body.length(), CoreMatchers.equalTo(2048));
99          }
100     }
101 
102     @Test(timeout = 2000)
103     public void testSequentialHeadRequests() throws Exception {
104         final HttpHost target = start();
105         for (int i = 0; i < 3; i++) {
106             final ReactiveResponseConsumer consumer = new ReactiveResponseConsumer();
107 
108             httpclient.execute(AsyncRequestBuilder.head(target + "/random/2048").build(), consumer, null);
109 
110             final Message<HttpResponse, Publisher<ByteBuffer>> response = consumer.getResponseFuture().get();
111             Assert.assertThat(response, CoreMatchers.notNullValue());
112             Assert.assertThat(response.getHead().getCode(), CoreMatchers.equalTo(200));
113 
114             final String body = publisherToString(response.getBody());
115             Assert.assertThat(body, CoreMatchers.nullValue());
116         }
117     }
118 
119     @Test(timeout = 60_000)
120     public void testSequentialPostRequests() throws Exception {
121         final HttpHost target = start();
122         for (int i = 0; i < 3; i++) {
123             final byte[] b1 = new byte[1024];
124             final Random rnd = new Random(System.currentTimeMillis());
125             rnd.nextBytes(b1);
126             final Flowable<ByteBuffer> publisher = Flowable.just(ByteBuffer.wrap(b1));
127             final ReactiveResponseConsumer consumer = new ReactiveResponseConsumer();
128             final AsyncRequestProducer request = AsyncRequestBuilder.post(target + "/echo/")
129                 .setEntity(new ReactiveEntityProducer(publisher, -1, ContentType.APPLICATION_OCTET_STREAM, null))
130                 .build();
131 
132             httpclient.execute(request, consumer, HttpClientContext.create(), null);
133 
134             final Future<Message<HttpResponse, Publisher<ByteBuffer>>> responseFuture = consumer.getResponseFuture();
135             final Message<HttpResponse, Publisher<ByteBuffer>> responseMessage = responseFuture.get();
136             Assert.assertThat(responseMessage, CoreMatchers.notNullValue());
137             final HttpResponse response = responseMessage.getHead();
138             Assert.assertThat(response.getCode(), CoreMatchers.equalTo(200));
139             final byte[] b2 = publisherToByteArray(responseMessage.getBody());
140             Assert.assertThat(b1, CoreMatchers.equalTo(b2));
141         }
142     }
143 
144     @Test(timeout = 60_000)
145     public void testConcurrentPostRequests() throws Exception {
146         final HttpHost target = start();
147 
148         final int reqCount = 500;
149         final int maxSize = 128 * 1024;
150         final Map<Long, StreamingTestCase> testCases = StreamingTestCase.generate(reqCount, maxSize);
151         final BlockingQueue<StreamDescription> responses = new ArrayBlockingQueue<>(reqCount);
152 
153         for (final StreamingTestCase testCase : testCases.values()) {
154             final ReactiveEntityProducer producer = new ReactiveEntityProducer(testCase.stream, testCase.length,
155                     ContentType.APPLICATION_OCTET_STREAM, null);
156             final AsyncRequestProducer request = AsyncRequestBuilder.post(target + "/echo/")
157                     .setEntity(producer)
158                     .build();
159 
160             final ReactiveResponseConsumer consumer = new ReactiveResponseConsumer(new FutureCallback<Message<HttpResponse, Publisher<ByteBuffer>>>() {
161                 public void completed(final Message<HttpResponse, Publisher<ByteBuffer>> result) {
162                     final Flowable<ByteBuffer> flowable = Flowable.fromPublisher(result.getBody())
163                             .observeOn(Schedulers.io()); // Stream the data on an RxJava scheduler, not a client thread
164                     ReactiveTestUtils.consumeStream(flowable)
165                             .subscribe(new Consumer<StreamDescription>() {
166                                 @Override
167                                 public void accept(final StreamDescription streamDescription) {
168                                     responses.add(streamDescription);
169                                 }
170                             });
171                 }
172                 public void failed(final Exception ex) { }
173                 public void cancelled() { }
174             });
175             httpclient.execute(request, consumer, HttpClientContext.create(), null);
176         }
177 
178         for (int i = 0; i < reqCount; i++) {
179             final StreamDescription streamDescription = responses.take();
180             final StreamingTestCase streamingTestCase = testCases.get(streamDescription.length);
181             final long expectedLength = streamingTestCase.length;
182             final long actualLength = streamDescription.length;
183             Assert.assertEquals(expectedLength, actualLength);
184 
185             final String expectedHash = streamingTestCase.expectedHash.get();
186             final String actualHash = TextUtils.toHexString(streamDescription.md.digest());
187             Assert.assertEquals(expectedHash, actualHash);
188         }
189     }
190 
191     @Test(timeout = 60_000)
192     public void testRequestExecutionFromCallback() throws Exception {
193         final HttpHost target = start();
194         final int requestNum = 50;
195         final AtomicInteger count = new AtomicInteger(requestNum);
196         final Queue<Message<HttpResponse, Publisher<ByteBuffer>>> resultQueue = new ConcurrentLinkedQueue<>();
197         final CountDownLatch countDownLatch = new CountDownLatch(requestNum);
198 
199         final FutureCallback<Message<HttpResponse, Publisher<ByteBuffer>>> callback = new FutureCallback<Message<HttpResponse, Publisher<ByteBuffer>>>() {
200             @Override
201             public void completed(final Message<HttpResponse, Publisher<ByteBuffer>> result) {
202                 try {
203                     resultQueue.add(result);
204                     if (count.decrementAndGet() > 0) {
205                         final ReactiveResponseConsumer consumer = new ReactiveResponseConsumer(this);
206                         httpclient.execute(AsyncRequestBuilder.get(target + "/random/2048").build(), consumer, null);
207                     }
208                 } finally {
209                     countDownLatch.countDown();
210                 }
211             }
212 
213             @Override
214             public void failed(final Exception ex) {
215                 countDownLatch.countDown();
216             }
217 
218             @Override
219             public void cancelled() {
220                 countDownLatch.countDown();
221             }
222         };
223 
224         final int threadNum = 5;
225         final ExecutorService executorService = Executors.newFixedThreadPool(threadNum);
226         for (int i = 0; i < threadNum; i++) {
227             executorService.execute(new Runnable() {
228                 @Override
229                 public void run() {
230                     if (!Thread.currentThread().isInterrupted()) {
231                         final ReactiveResponseConsumer consumer = new ReactiveResponseConsumer(callback);
232                         httpclient.execute(AsyncRequestBuilder.get(target + "/random/2048").build(), consumer, null);
233                     }
234                 }
235             });
236         }
237 
238         Assert.assertThat(countDownLatch.await(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit()), CoreMatchers.equalTo(true));
239 
240         executorService.shutdownNow();
241         executorService.awaitTermination(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit());
242 
243         for (;;) {
244             final Message<HttpResponse, Publisher<ByteBuffer>> response = resultQueue.poll();
245             if (response == null) {
246                 break;
247             }
248             Assert.assertThat(response.getHead().getCode(), CoreMatchers.equalTo(200));
249         }
250     }
251 
252     @Test
253     public void testBadRequest() throws Exception {
254         final HttpHost target = start();
255         final AsyncRequestProducer request = AsyncRequestBuilder.get(target + "/random/boom").build();
256         final ReactiveResponseConsumer consumer = new ReactiveResponseConsumer();
257 
258         httpclient.execute(request, consumer, null);
259 
260         final Future<Message<HttpResponse, Publisher<ByteBuffer>>> future = consumer.getResponseFuture();
261         final HttpResponse response = future.get().getHead();
262         Assert.assertThat(response, CoreMatchers.notNullValue());
263         Assert.assertThat(response.getCode(), CoreMatchers.equalTo(400));
264     }
265 
266     static String publisherToString(final Publisher<ByteBuffer> publisher) throws Exception {
267         final byte[] bytes = publisherToByteArray(publisher);
268         if (bytes == null) {
269             return null;
270         }
271         return new String(bytes, StandardCharsets.UTF_8);
272     }
273 
274     static byte[] publisherToByteArray(final Publisher<ByteBuffer> publisher) throws Exception {
275         final ByteArrayOutputStream baos = new ByteArrayOutputStream();
276         try (WritableByteChannel channel = Channels.newChannel(baos)) {
277             final List<ByteBuffer> bufs = Flowable.fromPublisher(publisher)
278                 .toList()
279                 .blockingGet();
280             if (bufs.isEmpty()) {
281                 return null;
282             }
283             for (final ByteBuffer buf : bufs) {
284                 channel.write(buf);
285             }
286         }
287         return baos.toByteArray();
288     }
289 
290     private static final class StreamingTestCase {
291         final long length;
292         final AtomicReference<String> expectedHash;
293         final Flowable<ByteBuffer> stream;
294 
295         StreamingTestCase(final long length, final AtomicReference<String> expectedHash, final Flowable<ByteBuffer> stream) {
296             this.length = length;
297             this.expectedHash = expectedHash;
298             this.stream = stream;
299         }
300 
301         static Map<Long, StreamingTestCase> generate(final int numTestCases, final int maxSize) {
302             final Map<Long, StreamingTestCase> testCases = new LinkedHashMap<>();
303             int testCaseNum = 0;
304             while (testCases.size() < numTestCases) {
305                 final long seed = 198723L * testCaseNum++;
306                 final int length = 1 + new Random(seed).nextInt(maxSize);
307                 final AtomicReference<String> expectedHash = new AtomicReference<>(null);
308                 final Flowable<ByteBuffer> stream = ReactiveTestUtils.produceStream(length, expectedHash);
309                 final StreamingTestCase streamingTestCase = new StreamingTestCase(length, expectedHash, stream);
310                 testCases.put((long) length, streamingTestCase);
311             }
312             return testCases;
313         }
314     }
315 }