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.fluent;
28  
29  import java.io.File;
30  import java.net.InetSocketAddress;
31  import java.net.URI;
32  import java.nio.charset.StandardCharsets;
33  
34  import org.apache.hc.client5.http.ClientProtocolException;
35  import org.apache.hc.client5.http.HttpResponseException;
36  import org.apache.hc.client5.http.fluent.Content;
37  import org.apache.hc.client5.http.fluent.Request;
38  import org.apache.hc.client5.testing.extension.sync.ClientProtocolLevel;
39  import org.apache.hc.client5.testing.extension.sync.TestClientResources;
40  import org.apache.hc.client5.testing.extension.sync.TestServer;
41  import org.apache.hc.core5.http.ContentType;
42  import org.apache.hc.core5.http.HttpEntity;
43  import org.apache.hc.core5.http.HttpHost;
44  import org.apache.hc.core5.http.HttpStatus;
45  import org.apache.hc.core5.http.URIScheme;
46  import org.apache.hc.core5.http.io.entity.EntityUtils;
47  import org.apache.hc.core5.http.io.entity.StringEntity;
48  import org.apache.hc.core5.util.Timeout;
49  import org.junit.jupiter.api.Assertions;
50  import org.junit.jupiter.api.BeforeEach;
51  import org.junit.jupiter.api.Test;
52  import org.junit.jupiter.api.extension.RegisterExtension;
53  
54  public class TestFluent {
55  
56      public static final Timeout TIMEOUT = Timeout.ofMinutes(1);
57  
58      @RegisterExtension
59      private TestClientResources testResources = new TestClientResources(URIScheme.HTTP, ClientProtocolLevel.STANDARD, TIMEOUT);
60  
61      @BeforeEach
62      public void setUp() throws Exception {
63          testResources.configureServer(bootstrap -> bootstrap
64                  .register("/", (request, response, context) ->
65                          response.setEntity(new StringEntity("All is well", ContentType.TEXT_PLAIN)))
66                  .register("/echo", (request, response, context) -> {
67                      HttpEntity responseEntity = null;
68                      final HttpEntity requestEntity = request.getEntity();
69                      if (requestEntity != null) {
70                          final String contentTypeStr = requestEntity.getContentType();
71                          final ContentType contentType = contentTypeStr == null ? ContentType.DEFAULT_TEXT : ContentType.parse(contentTypeStr);
72                          if (ContentType.TEXT_PLAIN.getMimeType().equals(contentType.getMimeType())) {
73                              responseEntity = new StringEntity(
74                                      EntityUtils.toString(requestEntity), ContentType.TEXT_PLAIN);
75                          }
76                      }
77                      if (responseEntity == null) {
78                          responseEntity = new StringEntity("echo", ContentType.TEXT_PLAIN);
79                      }
80                      response.setEntity(responseEntity);
81                  })
82                  // Handler for large content large message
83                  .register("/large-message", (request, response, context) -> {
84                      final String largeContent = generateLargeString(10000); // Large content string
85                      response.setEntity(new StringEntity(largeContent, ContentType.TEXT_PLAIN));
86                  })
87                  // Handler for large content large message with error
88                  .register("/large-message-error", (request, response, context) -> {
89                      final String largeContent = generateLargeString(10000); // Large content string
90                      response.setCode(HttpStatus.SC_REDIRECTION);
91                      response.setEntity(new StringEntity(largeContent, ContentType.TEXT_PLAIN));
92                  }));
93      }
94  
95      public HttpHost startServer() throws Exception {
96          final TestServer server = testResources.server();
97          final InetSocketAddress inetSocketAddress = server.start();
98          return new HttpHost(testResources.scheme().id, "localhost", inetSocketAddress.getPort());
99      }
100 
101     @Test
102     public void testGetRequest() throws Exception {
103         final HttpHost target = startServer();
104         final String baseURL = "http://localhost:" + target.getPort();
105         final String message = Request.get(baseURL + "/").execute().returnContent().asString();
106         Assertions.assertEquals("All is well", message);
107     }
108 
109     @Test
110     public void testGetRequestByName() throws Exception {
111         final HttpHost target = startServer();
112         final String baseURL = "http://localhost:" + target.getPort();
113         final String message = Request.create("GET", baseURL + "/").execute().returnContent().asString();
114         Assertions.assertEquals("All is well", message);
115     }
116 
117     @Test
118     public void testGetRequestByNameWithURI() throws Exception {
119         final HttpHost target = startServer();
120         final String baseURL = "http://localhost:" + target.getPort();
121         final String message = Request.create("GET", new URI(baseURL + "/")).execute().returnContent().asString();
122         Assertions.assertEquals("All is well", message);
123     }
124 
125     @Test
126     public void testGetRequestFailure() throws Exception {
127         final HttpHost target = startServer();
128         final String baseURL = "http://localhost:" + target.getPort();
129         Assertions.assertThrows(ClientProtocolException.class, () ->
130                 Request.get(baseURL + "/boom").execute().returnContent().asString());
131     }
132 
133     @Test
134     public void testPostRequest() throws Exception {
135         final HttpHost target = startServer();
136         final String baseURL = "http://localhost:" + target.getPort();
137         final String message1 = Request.post(baseURL + "/echo")
138                 .bodyString("what is up?", ContentType.TEXT_PLAIN)
139                 .execute().returnContent().asString();
140         Assertions.assertEquals("what is up?", message1);
141         final String message2 = Request.post(baseURL + "/echo")
142                 .bodyByteArray(new byte[]{1, 2, 3}, ContentType.APPLICATION_OCTET_STREAM)
143                 .execute().returnContent().asString();
144         Assertions.assertEquals("echo", message2);
145     }
146 
147     @Test
148     public void testContentAsStringWithCharset() throws Exception {
149         final HttpHost target = startServer();
150         final String baseURL = "http://localhost:" + target.getPort();
151         final Content content = Request.post(baseURL + "/echo").bodyByteArray("Ü".getBytes(StandardCharsets.UTF_8)).execute()
152                 .returnContent();
153         Assertions.assertEquals((byte)-61, content.asBytes()[0]);
154         Assertions.assertEquals((byte)-100, content.asBytes()[1]);
155         Assertions.assertEquals("Ü", content.asString(StandardCharsets.UTF_8));
156     }
157 
158     @Test
159     public void testConnectionRelease() throws Exception {
160         final HttpHost target = startServer();
161         final String baseURL = "http://localhost:" + target.getPort();
162         for (int i = 0; i < 20; i++) {
163             Request.get(baseURL + "/").execute().returnContent();
164             Request.get(baseURL + "/").execute().returnResponse();
165             Request.get(baseURL + "/").execute().discardContent();
166             Request.get(baseURL + "/").execute().handleResponse(response -> null);
167             final File tmpFile = File.createTempFile("test", ".bin");
168             try {
169                 Request.get(baseURL + "/").execute().saveContent(tmpFile);
170             } finally {
171                 tmpFile.delete();
172             }
173         }
174     }
175 
176     private String generateLargeString(final int size) {
177         final StringBuilder sb = new StringBuilder(size);
178         for (int i = 0; i < size; i++) {
179             sb.append("x");
180         }
181         return sb.toString();
182     }
183 
184     @Test
185     public void testLargeResponse() throws Exception {
186 
187         final HttpHost target = startServer();
188         final String baseURL = "http://localhost:" + target.getPort();
189 
190         final Content content = Request.get(baseURL + "/large-message").execute().returnContent();
191         Assertions.assertEquals(10000, content.asBytes().length);
192     }
193 
194     @Test
195     public void testLargeResponseError() throws Exception {
196         final HttpHost target = startServer();
197         final String baseURL = "http://localhost:" + target.getPort();
198 
199         try {
200             Request.get(baseURL + "/large-message-error").execute().returnContent();
201             Assertions.fail("Expected an HttpResponseException to be thrown");
202         } catch (final HttpResponseException e) {
203             // Check if the content of the exception is less than or equal to 256 bytes
204             final byte[] contentBytes = e.getContentBytes();
205             Assertions.assertNotNull(contentBytes, "Content bytes should not be null");
206             Assertions.assertTrue(contentBytes.length <= 256, "Content length should be less or equal to 256 bytes");
207         }
208     }
209 
210 }