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  
28  package org.apache.hc.core5.http.io.entity;
29  
30  import java.io.ByteArrayInputStream;
31  import java.io.InputStream;
32  import java.nio.charset.Charset;
33  import java.nio.charset.StandardCharsets;
34  import java.nio.charset.UnsupportedCharsetException;
35  import java.util.ArrayList;
36  import java.util.List;
37  
38  import org.apache.hc.core5.http.ContentType;
39  import org.apache.hc.core5.http.NameValuePair;
40  import org.apache.hc.core5.http.message.BasicNameValuePair;
41  import org.apache.hc.core5.net.URLEncodedUtils;
42  import org.junit.Assert;
43  import org.junit.Test;
44  
45  /**
46   * Unit tests for {@link EntityUtils}.
47   *
48   */
49  public class TestEntityUtils {
50  
51      @Test
52      public void testNullEntityToByteArray() throws Exception {
53          try {
54              EntityUtils.toByteArray(null);
55              Assert.fail("IllegalArgumentException should have been thrown");
56          } catch (final IllegalArgumentException ex) {
57              // expected
58          }
59      }
60  
61      @Test
62      public void testEmptyContentToByteArray() throws Exception {
63          try (final NullHttpEntity httpentity = new NullHttpEntity()) {
64              final byte[] bytes = EntityUtils.toByteArray(httpentity);
65              Assert.assertNull(bytes);
66          }
67      }
68  
69      @Test
70      public void testMaxIntContentToByteArray() throws Exception {
71          final byte[] content = "Message content".getBytes(StandardCharsets.ISO_8859_1);
72          try (final BasicHttpEntity httpentity = new BasicHttpEntity()) {
73              httpentity.setContent(new ByteArrayInputStream(content));
74              httpentity.setContentLength(Integer.MAX_VALUE + 100L);
75              try {
76                  EntityUtils.toByteArray(httpentity);
77                  Assert.fail("IllegalArgumentException should have been thrown");
78              } catch (final IllegalArgumentException ex) {
79                  // expected
80              }
81          }}
82  
83      @Test
84      public void testUnknownLengthContentToByteArray() throws Exception {
85          final byte[] bytes = "Message content".getBytes(StandardCharsets.ISO_8859_1);
86          try (final BasicHttpEntity httpentity = new BasicHttpEntity()) {
87              httpentity.setContent(new ByteArrayInputStream(bytes));
88              httpentity.setContentLength(-1L);
89              final byte[] bytes2 = EntityUtils.toByteArray(httpentity);
90              Assert.assertNotNull(bytes2);
91              Assert.assertEquals(bytes.length, bytes2.length);
92              for (int i = 0; i < bytes.length; i++) {
93                  Assert.assertEquals(bytes[i], bytes2[i]);
94              }
95          }
96      }
97  
98      @Test
99      public void testKnownLengthContentToByteArray() throws Exception {
100         final byte[] bytes = "Message content".getBytes(StandardCharsets.ISO_8859_1);
101         try (final BasicHttpEntity httpentity = new BasicHttpEntity()) {
102             httpentity.setContent(new ByteArrayInputStream(bytes));
103             httpentity.setContentLength(bytes.length);
104             final byte[] bytes2 = EntityUtils.toByteArray(httpentity);
105             Assert.assertNotNull(bytes2);
106             Assert.assertEquals(bytes.length, bytes2.length);
107             for (int i = 0; i < bytes.length; i++) {
108                 Assert.assertEquals(bytes[i], bytes2[i]);
109             }
110         }}
111 
112     @Test
113     public void testNullEntityToString() throws Exception {
114         try {
115             EntityUtils.toString(null);
116             Assert.fail("IllegalArgumentException should have been thrown");
117         } catch (final IllegalArgumentException ex) {
118             // expected
119         }
120     }
121 
122     @Test
123     public void testEmptyContentToString() throws Exception {
124         try (final NullHttpEntity httpentity = new NullHttpEntity()) {
125             final String s = EntityUtils.toString(httpentity);
126             Assert.assertNull(s);
127         }}
128 
129     @Test
130     public void testMaxIntContentToString() throws Exception {
131         final byte[] content = "Message content".getBytes(StandardCharsets.ISO_8859_1);
132         try (final BasicHttpEntity httpentity = new BasicHttpEntity()) {
133             httpentity.setContent(new ByteArrayInputStream(content));
134             httpentity.setContentLength(Integer.MAX_VALUE + 100L);
135             try {
136                 EntityUtils.toString(httpentity);
137                 Assert.fail("IllegalArgumentException should have been thrown");
138             } catch (final IllegalArgumentException ex) {
139                 // expected
140             }
141         }}
142 
143     @Test
144     public void testUnknownLengthContentToString() throws Exception {
145         final byte[] bytes = "Message content".getBytes(StandardCharsets.ISO_8859_1);
146         try (final BasicHttpEntity httpentity = new BasicHttpEntity()) {
147             httpentity.setContent(new ByteArrayInputStream(bytes));
148             httpentity.setContentLength(-1L);
149             final String s = EntityUtils.toString(httpentity, "ISO-8859-1");
150             Assert.assertEquals("Message content", s);
151         }}
152 
153     @Test
154     public void testKnownLengthContentToString() throws Exception {
155         final byte[] bytes = "Message content".getBytes(StandardCharsets.ISO_8859_1);
156         try (final BasicHttpEntity httpentity = new BasicHttpEntity()) {
157             httpentity.setContent(new ByteArrayInputStream(bytes));
158             httpentity.setContentLength(bytes.length);
159             final String s = EntityUtils.toString(httpentity, "ISO-8859-1");
160             Assert.assertEquals("Message content", s);
161         }}
162 
163     static final int SWISS_GERMAN_HELLO [] = {
164         0x47, 0x72, 0xFC, 0x65, 0x7A, 0x69, 0x5F, 0x7A, 0xE4, 0x6D, 0xE4
165     };
166 
167     static final int RUSSIAN_HELLO [] = {
168         0x412, 0x441, 0x435, 0x43C, 0x5F, 0x43F, 0x440, 0x438,
169         0x432, 0x435, 0x442
170     };
171 
172     private static String constructString(final int [] unicodeChars) {
173         final StringBuilder buffer = new StringBuilder();
174         if (unicodeChars != null) {
175             for (final int unicodeChar : unicodeChars) {
176                 buffer.append((char)unicodeChar);
177             }
178         }
179         return buffer.toString();
180     }
181 
182     @Test
183     public void testNoCharsetContentToString() throws Exception {
184         final String content = constructString(SWISS_GERMAN_HELLO);
185         final byte[] bytes = content.getBytes(StandardCharsets.ISO_8859_1);
186         try (final BasicHttpEntity httpentity = new BasicHttpEntity()) {
187             httpentity.setContent(new ByteArrayInputStream(bytes));
188             httpentity.setContentType("text/plain");
189             final String s = EntityUtils.toString(httpentity);
190             Assert.assertEquals(content, s);
191         }}
192 
193     @Test
194     public void testDefaultCharsetContentToString() throws Exception {
195         final String content = constructString(RUSSIAN_HELLO);
196         final byte[] bytes = content.getBytes(Charset.forName("KOI8-R"));
197         try (final BasicHttpEntity httpentity = new BasicHttpEntity()) {
198             httpentity.setContent(new ByteArrayInputStream(bytes));
199             httpentity.setContentType("text/plain");
200             final String s = EntityUtils.toString(httpentity, "KOI8-R");
201             Assert.assertEquals(content, s);
202         }}
203 
204     @Test
205     public void testContentWithContentTypeToString() throws Exception {
206         final String content = constructString(RUSSIAN_HELLO);
207         final byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
208         try (final BasicHttpEntity httpentity = new BasicHttpEntity()) {
209             httpentity.setContent(new ByteArrayInputStream(bytes));
210             httpentity.setContentType("text/plain; charset=UTF-8");
211             final String s = EntityUtils.toString(httpentity, "ISO-8859-1");
212             Assert.assertEquals(content, s);
213         }}
214 
215     @Test
216     public void testContentWithInvalidContentTypeToString() throws Exception {
217         final String content = constructString(RUSSIAN_HELLO);
218         final byte[] bytes = content.getBytes("UTF-8");
219         try (final BasicHttpEntity httpentity = new BasicHttpEntity()) {
220             httpentity.setContent(new ByteArrayInputStream(bytes));
221             httpentity.setContentType("text/plain; charset=nosuchcharset");
222             final String s = EntityUtils.toString(httpentity, "UTF-8");
223             Assert.assertEquals(content, s);
224         }}
225 
226     @Test
227     public void testExtractNullInput() throws Exception {
228         Assert.assertNull(EntityUtils.getContentType(null));
229     }
230 
231     @Test
232     public void testExtractNullContentType() throws Exception {
233         try (final BasicHttpEntity httpentity = new BasicHttpEntity()) {
234             httpentity.setContentType(null);
235             Assert.assertNull(EntityUtils.getContentType(httpentity));
236         }}
237 
238     @Test
239     public void testExtract() throws Exception {
240         try (final BasicHttpEntity httpentity = new BasicHttpEntity()) {
241             httpentity.setContentType("text/plain; charset = UTF-8");
242             final ContentType contentType = EntityUtils.getContentType(httpentity);
243             Assert.assertNotNull(contentType);
244             Assert.assertEquals("text/plain", contentType.getMimeType());
245             Assert.assertEquals(StandardCharsets.UTF_8, contentType.getCharset());
246         }}
247 
248     @Test
249     public void testExtractNoCharset() throws Exception {
250         try (final BasicHttpEntity httpentity = new BasicHttpEntity()) {
251             httpentity.setContentType("text/plain; param=yadayada");
252             final ContentType contentType = EntityUtils.getContentType(httpentity);
253             Assert.assertNotNull(contentType);
254             Assert.assertEquals("text/plain", contentType.getMimeType());
255             Assert.assertNull(contentType.getCharset());
256         }}
257 
258     @Test(expected = UnsupportedCharsetException.class)
259     public void testExtractInvalidCharset() throws Exception {
260         try (final BasicHttpEntity httpentity = new BasicHttpEntity()) {
261             httpentity.setContentType("text/plain; charset = stuff");
262             EntityUtils.getContentType(httpentity);
263         }}
264 
265     @Test
266     public void testExtracLenienttNullInput() throws Exception {
267         Assert.assertNull(EntityUtils.getContentTypeLenient(null));
268     }
269 
270     @Test
271     public void testExtractLenientNullContentType() throws Exception {
272         try (final BasicHttpEntity httpentity = new BasicHttpEntity()) {
273             httpentity.setContentType(null);
274             Assert.assertNull(EntityUtils.getContentTypeLenient(httpentity));
275         }}
276 
277     @Test
278     public void testLenientExtractInvalidCharset() throws Exception {
279         try (final BasicHttpEntity httpentity = new BasicHttpEntity()) {
280             httpentity.setContentType("text/plain; charset = stuff");
281             final ContentType contentType = EntityUtils.getContentTypeLenient(httpentity);
282             Assert.assertNotNull(contentType);
283             Assert.assertEquals("text/plain", contentType.getMimeType());
284             Assert.assertEquals(null, contentType.getCharset());
285         }}
286 
287     private static void assertNameValuePair (
288             final NameValuePair parameter,
289             final String expectedName,
290             final String expectedValue) {
291         Assert.assertEquals(parameter.getName(), expectedName);
292         Assert.assertEquals(parameter.getValue(), expectedValue);
293     }
294 
295     @Test
296     public void testParseEntity() throws Exception {
297         try (final StringEntity entity = new StringEntity("Name1=Value1")) {
298 
299             entity.setContentType(URLEncodedUtils.CONTENT_TYPE);
300             final List<NameValuePair> result = EntityUtils.parse(entity);
301             Assert.assertEquals(1, result.size());
302             assertNameValuePair(result.get(0), "Name1", "Value1");
303 
304             entity.setContentType("text/test");
305             Assert.assertTrue(EntityUtils.parse(entity).isEmpty());
306         }}
307 
308     @Test
309     public void testParseUTF8Entity() throws Exception {
310         final String ru_hello = constructString(RUSSIAN_HELLO);
311         final String ch_hello = constructString(SWISS_GERMAN_HELLO);
312         final List <NameValuePair> parameters = new ArrayList<>();
313         parameters.add(new BasicNameValuePair("russian", ru_hello));
314         parameters.add(new BasicNameValuePair("swiss", ch_hello));
315 
316         final String s = URLEncodedUtils.format(parameters, StandardCharsets.UTF_8);
317 
318         Assert.assertEquals("russian=%D0%92%D1%81%D0%B5%D0%BC_%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82" +
319                 "&swiss=Gr%C3%BCezi_z%C3%A4m%C3%A4", s);
320 
321         try (final StringEntity entity = new StringEntity(s,
322                 ContentType.create(URLEncodedUtils.CONTENT_TYPE, StandardCharsets.UTF_8))) {
323             final List<NameValuePair> result = EntityUtils.parse(entity);
324             Assert.assertEquals(2, result.size());
325             assertNameValuePair(result.get(0), "russian", ru_hello);
326             assertNameValuePair(result.get(1), "swiss", ch_hello);
327         }
328     }
329 
330     /**
331      * Helper class that returns {@code null} as the content.
332      */
333     public static class NullHttpEntity extends BasicHttpEntity {
334 
335         // default constructor
336         /**
337          * Obtains no content.
338          * This method disables the state checks in the base class.
339          *
340          * @return {@code null}
341          */
342         @Override
343         public InputStream getContent() {
344             return null;
345         }
346     }
347 
348 }