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.net;
28  
29  import java.net.InetAddress;
30  import java.net.URI;
31  import java.net.URLEncoder;
32  import java.nio.charset.Charset;
33  import java.nio.charset.StandardCharsets;
34  import java.util.ArrayList;
35  import java.util.Arrays;
36  import java.util.List;
37  
38  import org.apache.hc.core5.http.HttpHost;
39  import org.apache.hc.core5.http.NameValuePair;
40  import org.apache.hc.core5.http.message.BasicNameValuePair;
41  import org.hamcrest.CoreMatchers;
42  import org.junit.Assert;
43  import org.junit.Test;
44  
45  public class TestURIBuilder {
46  
47      @Test
48      public void testHierarchicalUri() throws Exception {
49          final URI uri = new URI("http", "stuff", "localhost", 80, "/some stuff", "param=stuff", "fragment");
50          final URIBuilder uribuilder = new URIBuilder(uri);
51          final URI result = uribuilder.build();
52          Assert.assertEquals(new URI("http://stuff@localhost:80/some%20stuff?param=stuff#fragment"), result);
53      }
54  
55      @Test
56      public void testMutationToRelativeUri() throws Exception {
57          final URI uri = new URI("http://stuff@localhost:80/stuff?param=stuff#fragment");
58          final URIBuilder uribuilder = new URIBuilder(uri).setHost((String) null);
59          final URI result = uribuilder.build();
60          Assert.assertEquals(new URI("http:///stuff?param=stuff#fragment"), result);
61      }
62  
63      @Test
64      public void testMutationRemoveFragment() throws Exception {
65          final URI uri = new URI("http://stuff@localhost:80/stuff?param=stuff#fragment");
66          final URI result = new URIBuilder(uri).setFragment(null).build();
67          Assert.assertEquals(new URI("http://stuff@localhost:80/stuff?param=stuff"), result);
68      }
69  
70      @Test
71      public void testMutationRemoveUserInfo() throws Exception {
72          final URI uri = new URI("http://stuff@localhost:80/stuff?param=stuff#fragment");
73          final URI result = new URIBuilder(uri).setUserInfo(null).build();
74          Assert.assertEquals(new URI("http://localhost:80/stuff?param=stuff#fragment"), result);
75      }
76  
77      @Test
78      public void testMutationRemovePort() throws Exception {
79          final URI uri = new URI("http://stuff@localhost:80/stuff?param=stuff#fragment");
80          final URI result = new URIBuilder(uri).setPort(-1).build();
81          Assert.assertEquals(new URI("http://stuff@localhost/stuff?param=stuff#fragment"), result);
82      }
83  
84      @Test
85      public void testOpaqueUri() throws Exception {
86          final URI uri = new URI("stuff", "some-stuff", "fragment");
87          final URIBuilder uribuilder = new URIBuilder(uri);
88          final URI result = uribuilder.build();
89          Assert.assertEquals(uri, result);
90      }
91  
92      @Test
93      public void testOpaqueUriMutation() throws Exception {
94          final URI uri = new URI("stuff", "some-stuff", "fragment");
95          final URIBuilder uribuilder = new URIBuilder(uri).setCustomQuery("param1&param2=stuff").setFragment(null);
96          Assert.assertEquals(new URI("stuff:?param1&param2=stuff"), uribuilder.build());
97      }
98  
99      @Test
100     public void testHierarchicalUriMutation() throws Exception {
101         final URIBuilder uribuilder = new URIBuilder("/").setScheme("http").setHost("localhost").setPort(80).setPath("/stuff");
102         Assert.assertEquals(new URI("http://localhost:80/stuff"), uribuilder.build());
103     }
104 
105     @Test
106    public void testLocalhost() throws Exception {
107        // Check that the URI generated by URI builder agrees with that generated by using URI directly
108        final String scheme="https";
109        final InetAddress host=InetAddress.getLocalHost();
110        final String specials="/abcd!$&*()_-+.,=:;'~@[]?<>|#^%\"{}\\\u00a3`\u00ac\u00a6xyz"; // N.B. excludes space
111        final URI uri = new URI(scheme, specials, host.getHostAddress(), 80, specials, specials, specials);
112 
113        final URI bld = URIBuilder.localhost()
114                .setScheme(scheme)
115                .setUserInfo(specials)
116                .setPath(specials)
117                .setCustomQuery(specials)
118                .setFragment(specials)
119                .build();
120 
121        Assert.assertEquals(uri.getHost(), bld.getHost());
122 
123        Assert.assertEquals(uri.getUserInfo(), bld.getUserInfo());
124 
125        Assert.assertEquals(uri.getPath(), bld.getPath());
126 
127        Assert.assertEquals(uri.getQuery(), bld.getQuery());
128 
129        Assert.assertEquals(uri.getFragment(), bld.getFragment());
130    }
131 
132     @Test
133    public void testLoopbackAddress() throws Exception {
134        // Check that the URI generated by URI builder agrees with that generated by using URI directly
135        final String scheme="https";
136        final InetAddress host=InetAddress.getLoopbackAddress();
137        final String specials="/abcd!$&*()_-+.,=:;'~@[]?<>|#^%\"{}\\\u00a3`\u00ac\u00a6xyz"; // N.B. excludes space
138        final URI uri = new URI(scheme, specials, host.getHostAddress(), 80, specials, specials, specials);
139 
140        final URI bld = URIBuilder.loopbackAddress()
141                .setScheme(scheme)
142                .setUserInfo(specials)
143                .setPath(specials)
144                .setCustomQuery(specials)
145                .setFragment(specials)
146                .build();
147 
148        Assert.assertEquals(uri.getHost(), bld.getHost());
149 
150        Assert.assertEquals(uri.getUserInfo(), bld.getUserInfo());
151 
152        Assert.assertEquals(uri.getPath(), bld.getPath());
153 
154        Assert.assertEquals(uri.getQuery(), bld.getQuery());
155 
156        Assert.assertEquals(uri.getFragment(), bld.getFragment());
157    }
158 
159     @Test
160     public void testEmpty() throws Exception {
161         final URIBuilder uribuilder = new URIBuilder();
162         final URI result = uribuilder.build();
163         Assert.assertEquals(new URI(""), result);
164     }
165 
166     @Test
167     public void testSetUserInfo() throws Exception {
168         final URI uri = new URI("http", null, "localhost", 80, "/", "param=stuff", null);
169         final URIBuilder uribuilder = new URIBuilder(uri).setUserInfo("user", "password");
170         final URI result = uribuilder.build();
171         Assert.assertEquals(new URI("http://user:password@localhost:80/?param=stuff"), result);
172     }
173 
174     @Test
175     public void testRemoveParameters() throws Exception {
176         final URI uri = new URI("http", null, "localhost", 80, "/", "param=stuff", null);
177         final URIBuilder uribuilder = new URIBuilder(uri).removeQuery();
178         final URI result = uribuilder.build();
179         Assert.assertEquals(new URI("http://localhost:80/"), result);
180     }
181 
182     @Test
183     public void testSetParameter() throws Exception {
184         final URI uri = new URI("http", null, "localhost", 80, "/", "param=stuff&blah&blah", null);
185         final URIBuilder uribuilder = new URIBuilder(uri).setParameter("param", "some other stuff")
186             .setParameter("blah", "blah");
187         final URI result = uribuilder.build();
188         Assert.assertEquals(new URI("http://localhost:80/?param=some+other+stuff&blah=blah"), result);
189     }
190 
191     @Test
192     public void testSetParametersWithEmptyArg() throws Exception {
193         final URI uri = new URI("http", null, "localhost", 80, "/test", "param=test", null);
194         final URIBuilder uribuilder = new URIBuilder(uri).setParameters();
195         final URI result = uribuilder.build();
196         Assert.assertEquals(new URI("http://localhost:80/test"), result);
197     }
198 
199     @Test
200     public void testSetParametersWithEmptyList() throws Exception {
201         final URI uri = new URI("http", null, "localhost", 80, "/test", "param=test", null);
202         final URIBuilder uribuilder = new URIBuilder(uri).setParameters(Arrays.<NameValuePair>asList());
203         final URI result = uribuilder.build();
204         Assert.assertEquals(new URI("http://localhost:80/test"), result);
205     }
206 
207     @Test
208     public void testParameterWithSpecialChar() throws Exception {
209         final URI uri = new URI("http", null, "localhost", 80, "/", "param=stuff", null);
210         final URIBuilder uribuilder = new URIBuilder(uri).addParameter("param", "1 + 1 = 2")
211             .addParameter("param", "blah&blah");
212         final URI result = uribuilder.build();
213         Assert.assertEquals(new URI("http://localhost:80/?param=stuff&param=1+%2B+1+%3D+2&" +
214                 "param=blah%26blah"), result);
215     }
216 
217     @Test
218     public void testAddParameter() throws Exception {
219         final URI uri = new URI("http", null, "localhost", 80, "/", "param=stuff&blah&blah", null);
220         final URIBuilder uribuilder = new URIBuilder(uri).addParameter("param", "some other stuff")
221             .addParameter("blah", "blah");
222         final URI result = uribuilder.build();
223         Assert.assertEquals(new URI("http://localhost:80/?param=stuff&blah&blah&" +
224                 "param=some+other+stuff&blah=blah"), result);
225     }
226 
227     @Test
228     public void testQueryEncoding() throws Exception {
229         final URI uri1 = new URI("https://somehost.com/stuff?client_id=1234567890" +
230                 "&redirect_uri=https%3A%2F%2Fsomehost.com%2Fblah+blah%2F");
231         final URI uri2 = new URIBuilder("https://somehost.com/stuff")
232             .addParameter("client_id","1234567890")
233             .addParameter("redirect_uri","https://somehost.com/blah blah/").build();
234         Assert.assertEquals(uri1, uri2);
235     }
236 
237     @Test
238     public void testQueryAndParameterEncoding() throws Exception {
239         final URI uri1 = new URI("https://somehost.com/stuff?param1=12345&param2=67890");
240         final URI uri2 = new URIBuilder("https://somehost.com/stuff")
241             .setCustomQuery("this&that")
242             .addParameter("param1","12345")
243             .addParameter("param2","67890").build();
244         Assert.assertEquals(uri1, uri2);
245     }
246 
247     @Test
248     public void testPathEncoding() throws Exception {
249         final URI uri1 = new URI("https://somehost.com/some%20path%20with%20blanks/");
250         final URI uri2 = new URIBuilder()
251             .setScheme("https")
252             .setHost("somehost.com")
253             .setPath("/some path with blanks/")
254             .build();
255         Assert.assertEquals(uri1, uri2);
256     }
257 
258     @Test
259     public void testAgainstURI() throws Exception {
260         // Check that the URI generated by URI builder agrees with that generated by using URI directly
261         final String scheme="https";
262         final String host="localhost";
263         final String specials="/abcd!$&*()_-+.,=:;'~@[]?<>|#^%\"{}\\\u00a3`\u00ac\u00a6xyz"; // N.B. excludes space
264         final URI uri = new URI(scheme, specials, host, 80, specials, specials, specials);
265 
266         final URI bld = new URIBuilder()
267                 .setScheme(scheme)
268                 .setHost(host)
269                 .setUserInfo(specials)
270                 .setPath(specials)
271                 .setCustomQuery(specials)
272                 .setFragment(specials)
273                 .build();
274 
275         Assert.assertEquals(uri.getHost(), bld.getHost());
276 
277         Assert.assertEquals(uri.getUserInfo(), bld.getUserInfo());
278 
279         Assert.assertEquals(uri.getPath(), bld.getPath());
280 
281         Assert.assertEquals(uri.getQuery(), bld.getQuery());
282 
283         Assert.assertEquals(uri.getFragment(), bld.getFragment());
284 
285     }
286 
287     @Test
288     public void testAgainstURIEncoded() throws Exception {
289         // Check that the encoded URI generated by URI builder agrees with that generated by using URI directly
290         final String scheme="https";
291         final String host="localhost";
292         final String specials="/ abcd!$&*()_-+.,=:;'~<>/@[]|#^%\"{}\\`xyz"; // N.B. excludes \u00a3\u00ac\u00a6
293         final URI uri = new URI(scheme, specials, host, 80, specials, specials, specials);
294 
295         final URI bld = new URIBuilder()
296                 .setScheme(scheme)
297                 .setHost(host)
298                 .setUserInfo(specials)
299                 .setPath(specials)
300                 .setCustomQuery(specials)
301                 .setFragment(specials)
302                 .build();
303 
304         Assert.assertEquals(uri.getHost(), bld.getHost());
305 
306         Assert.assertEquals(uri.getRawUserInfo(), bld.getRawUserInfo());
307 
308         Assert.assertEquals(uri.getRawPath(), bld.getRawPath());
309 
310         Assert.assertEquals(uri.getRawQuery(), bld.getRawQuery());
311 
312         Assert.assertEquals(uri.getRawFragment(), bld.getRawFragment());
313 
314     }
315 
316     @Test
317     public void testBuildAddParametersUTF8() throws Exception {
318         assertAddParameters(StandardCharsets.UTF_8);
319     }
320 
321     @Test
322     public void testBuildAddParametersISO88591() throws Exception {
323         assertAddParameters(StandardCharsets.ISO_8859_1);
324     }
325 
326     public void assertAddParameters(final Charset charset) throws Exception {
327         final URI uri = new URIBuilder("https://somehost.com/stuff")
328                 .setCharset(charset)
329                 .addParameters(createParameters()).build();
330 
331         assertBuild(charset, uri);
332     }
333 
334     @Test
335     public void testBuildSetParametersUTF8() throws Exception {
336         assertSetParameters(StandardCharsets.UTF_8);
337     }
338 
339     @Test
340     public void testBuildSetParametersISO88591() throws Exception {
341         assertSetParameters(StandardCharsets.ISO_8859_1);
342     }
343 
344     public void assertSetParameters(final Charset charset) throws Exception {
345         final URI uri = new URIBuilder("https://somehost.com/stuff")
346                 .setCharset(charset)
347                 .setParameters(createParameters()).build();
348 
349         assertBuild(charset, uri);
350     }
351 
352     public void assertBuild(final Charset charset, final URI uri) throws Exception {
353         final String encodedData1 = URLEncoder.encode("\"1\u00aa position\"", charset.displayName());
354         final String encodedData2 = URLEncoder.encode("Jos\u00e9 Abra\u00e3o", charset.displayName());
355 
356         final String uriExpected = String.format("https://somehost.com/stuff?parameter1=value1&parameter2=%s&parameter3=%s", encodedData1, encodedData2);
357 
358         Assert.assertEquals(uriExpected, uri.toString());
359     }
360 
361     private List<NameValuePair> createParameters() {
362         final List<NameValuePair> parameters = new ArrayList<>();
363         parameters.add(new BasicNameValuePair("parameter1", "value1"));
364         parameters.add(new BasicNameValuePair("parameter2", "\"1\u00aa position\""));
365         parameters.add(new BasicNameValuePair("parameter3", "Jos\u00e9 Abra\u00e3o"));
366         return parameters;
367     }
368 
369     @Test
370     public void testMalformedPath() throws Exception {
371         final String path = "@notexample.com/mypath";
372         final URI uri = new URIBuilder(path).setHost("example.com").build();
373         Assert.assertEquals("example.com", uri.getHost());
374     }
375 
376     @Test
377     public void testRelativePath() throws Exception {
378         final URI uri = new URIBuilder("./mypath").build();
379         Assert.assertEquals(new URI("./mypath"), uri);
380     }
381 
382     @Test
383     public void testRelativePathWithAuthority() throws Exception {
384         final URI uri = new URIBuilder("./mypath").setHost("somehost").setScheme("http").build();
385         Assert.assertEquals(new URI("http://somehost/./mypath"), uri);
386     }
387 
388     @Test
389     public void testTolerateNullInput() throws Exception {
390         Assert.assertThat(new URIBuilder()
391                         .setScheme(null)
392                         .setHost("localhost")
393                         .setUserInfo(null)
394                         .setPort(8443)
395                         .setPath(null)
396                         .setCustomQuery(null)
397                         .setFragment(null)
398                         .build(),
399                 CoreMatchers.equalTo(URI.create("//localhost:8443")));
400     }
401 
402     @Test
403     public void testTolerateBlankInput() throws Exception {
404         Assert.assertThat(new URIBuilder()
405                         .setScheme("")
406                         .setHost("localhost")
407                         .setUserInfo("")
408                         .setPort(8443)
409                         .setPath("")
410                         .setPath("")
411                         .setCustomQuery("")
412                         .setFragment("")
413                         .build(),
414                 CoreMatchers.equalTo(URI.create("//localhost:8443")));
415     }
416 
417     @Test
418     public void testHttpHost() throws Exception {
419         final HttpHost httpHost = new HttpHost("http", "example.com", 1234);
420         final URIBuilder uribuilder = new URIBuilder();
421         uribuilder.setHttpHost(httpHost);
422         final URI result = uribuilder.build();
423         Assert.assertEquals(URI.create(httpHost.toURI()), result);
424     }
425 
426 
427 }