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 static org.hamcrest.MatcherAssert.assertThat;
30  
31  import java.net.InetAddress;
32  import java.net.URI;
33  import java.nio.charset.Charset;
34  import java.nio.charset.StandardCharsets;
35  import java.util.ArrayList;
36  import java.util.Arrays;
37  import java.util.Collections;
38  import java.util.List;
39  
40  import org.apache.hc.core5.http.HttpHost;
41  import org.apache.hc.core5.http.NameValuePair;
42  import org.apache.hc.core5.http.NameValuePairListMatcher;
43  import org.apache.hc.core5.http.URIScheme;
44  import org.apache.hc.core5.http.message.BasicNameValuePair;
45  import org.hamcrest.CoreMatchers;
46  import org.junit.jupiter.api.Assertions;
47  import org.junit.jupiter.api.Test;
48  
49  public class TestURIBuilder {
50  
51      private static final String CH_HELLO = "\u0047\u0072\u00FC\u0065\u007A\u0069\u005F\u007A\u00E4\u006D\u00E4";
52      private static final String RU_HELLO = "\u0412\u0441\u0435\u043C\u005F\u043F\u0440\u0438\u0432\u0435\u0442";
53  
54      static List<String> parsePath(final CharSequence s) {
55          return URIBuilder.parsePath(s, null);
56      }
57  
58      @Test
59      public void testParseSegments() throws Exception {
60          assertThat(parsePath("/this/that"), CoreMatchers.equalTo(Arrays.asList("this", "that")));
61          assertThat(parsePath("this/that"), CoreMatchers.equalTo(Arrays.asList("this", "that")));
62          assertThat(parsePath("this//that"), CoreMatchers.equalTo(Arrays.asList("this", "", "that")));
63          assertThat(parsePath("this//that/"), CoreMatchers.equalTo(Arrays.asList("this", "", "that", "")));
64          assertThat(parsePath("this//that/%2fthis%20and%20that"),
65                  CoreMatchers.equalTo(Arrays.asList("this", "", "that", "/this and that")));
66          assertThat(parsePath("this///that//"),
67                  CoreMatchers.equalTo(Arrays.asList("this", "", "", "that", "", "")));
68          assertThat(parsePath("/"), CoreMatchers.equalTo(Collections.singletonList("")));
69          assertThat(parsePath(""), CoreMatchers.equalTo(Collections.<String>emptyList()));
70      }
71  
72      static String formatPath(final String... pathSegments) {
73          final StringBuilder buf = new StringBuilder();
74          URIBuilder.formatPath(buf, Arrays.asList(pathSegments), false, null);
75          return buf.toString();
76      }
77  
78      @Test
79      public void testFormatSegments() throws Exception {
80          assertThat(formatPath("this", "that"), CoreMatchers.equalTo("/this/that"));
81          assertThat(formatPath("this", "", "that"), CoreMatchers.equalTo("/this//that"));
82          assertThat(formatPath("this", "", "that", "/this and that"),
83                  CoreMatchers.equalTo("/this//that/%2Fthis%20and%20that"));
84          assertThat(formatPath("this", "", "", "that", "", ""),
85                  CoreMatchers.equalTo("/this///that//"));
86          assertThat(formatPath(""), CoreMatchers.equalTo("/"));
87          assertThat(formatPath(), CoreMatchers.equalTo(""));
88      }
89  
90      static List<NameValuePair> parseQuery(final CharSequence s) {
91          return URIBuilder.parseQuery(s, null, false);
92      }
93  
94      @Test
95      public void testParseQuery() throws Exception {
96          assertThat(parseQuery(""), NameValuePairListMatcher.isEmpty());
97          assertThat(parseQuery("Name0"),
98                  NameValuePairListMatcher.equalsTo(new BasicNameValuePair("Name0", null)));
99          assertThat(parseQuery("Name1=Value1"),
100                 NameValuePairListMatcher.equalsTo(new BasicNameValuePair("Name1", "Value1")));
101         assertThat(parseQuery("Name2="),
102                 NameValuePairListMatcher.equalsTo(new BasicNameValuePair("Name2", "")));
103         assertThat(parseQuery(" Name3  "),
104                 NameValuePairListMatcher.equalsTo(new BasicNameValuePair("Name3", null)));
105         assertThat(parseQuery("Name4=Value%204%21"),
106                 NameValuePairListMatcher.equalsTo(new BasicNameValuePair("Name4", "Value 4!")));
107         assertThat(parseQuery("Name4=Value%2B4%21"),
108                 NameValuePairListMatcher.equalsTo(new BasicNameValuePair("Name4", "Value+4!")));
109         assertThat(parseQuery("Name4=Value%204%21%20%214"),
110                 NameValuePairListMatcher.equalsTo(new BasicNameValuePair("Name4", "Value 4! !4")));
111         assertThat(parseQuery("Name5=aaa&Name6=bbb"),
112                 NameValuePairListMatcher.equalsTo(
113                         new BasicNameValuePair("Name5", "aaa"),
114                         new BasicNameValuePair("Name6", "bbb")));
115         assertThat(parseQuery("Name7=aaa&Name7=b%2Cb&Name7=ccc"),
116                 NameValuePairListMatcher.equalsTo(
117                         new BasicNameValuePair("Name7", "aaa"),
118                         new BasicNameValuePair("Name7", "b,b"),
119                         new BasicNameValuePair("Name7", "ccc")));
120         assertThat(parseQuery("Name8=xx%2C%20%20yy%20%20%2Czz"),
121                 NameValuePairListMatcher.equalsTo(new BasicNameValuePair("Name8", "xx,  yy  ,zz")));
122         assertThat(parseQuery("price=10%20%E2%82%AC"),
123                 NameValuePairListMatcher.equalsTo(new BasicNameValuePair("price", "10 \u20AC")));
124         assertThat(parseQuery("a=b\"c&d=e"),
125                 NameValuePairListMatcher.equalsTo(
126                         new BasicNameValuePair("a", "b\"c"),
127                         new BasicNameValuePair("d", "e")));
128         assertThat(parseQuery("russian=" + PercentCodec.encode(RU_HELLO, StandardCharsets.UTF_8) +
129                         "&swiss=" + PercentCodec.encode(CH_HELLO, StandardCharsets.UTF_8)),
130                 NameValuePairListMatcher.equalsTo(
131                         new BasicNameValuePair("russian", RU_HELLO),
132                         new BasicNameValuePair("swiss", CH_HELLO)));
133     }
134 
135     static String formatQuery(final NameValuePair... params) {
136         final StringBuilder buf = new StringBuilder();
137         URIBuilder.formatQuery(buf, Arrays.asList(params), null, false);
138         return buf.toString();
139     }
140 
141     @Test
142     public void testFormatQuery() throws Exception {
143         assertThat(formatQuery(new BasicNameValuePair("Name0", null)), CoreMatchers.equalTo("Name0"));
144         assertThat(formatQuery(new BasicNameValuePair("Name1", "Value1")), CoreMatchers.equalTo("Name1=Value1"));
145         assertThat(formatQuery(new BasicNameValuePair("Name2", "")), CoreMatchers.equalTo("Name2="));
146         assertThat(formatQuery(new BasicNameValuePair("Name4", "Value 4&")),
147                 CoreMatchers.equalTo("Name4=Value%204%26"));
148         assertThat(formatQuery(new BasicNameValuePair("Name4", "Value+4&")),
149                 CoreMatchers.equalTo("Name4=Value%2B4%26"));
150         assertThat(formatQuery(new BasicNameValuePair("Name4", "Value 4& =4")),
151                 CoreMatchers.equalTo("Name4=Value%204%26%20%3D4"));
152         assertThat(formatQuery(
153                 new BasicNameValuePair("Name5", "aaa"),
154                 new BasicNameValuePair("Name6", "bbb")), CoreMatchers.equalTo("Name5=aaa&Name6=bbb"));
155         assertThat(formatQuery(
156                 new BasicNameValuePair("Name7", "aaa"),
157                 new BasicNameValuePair("Name7", "b,b"),
158                 new BasicNameValuePair("Name7", "ccc")
159         ), CoreMatchers.equalTo("Name7=aaa&Name7=b%2Cb&Name7=ccc"));
160         assertThat(formatQuery(new BasicNameValuePair("Name8", "xx,  yy  ,zz")),
161                 CoreMatchers.equalTo("Name8=xx%2C%20%20yy%20%20%2Czz"));
162         assertThat(formatQuery(
163                 new BasicNameValuePair("russian", RU_HELLO),
164                 new BasicNameValuePair("swiss", CH_HELLO)),
165                 CoreMatchers.equalTo("russian=" + PercentCodec.encode(RU_HELLO, StandardCharsets.UTF_8) +
166                         "&swiss=" + PercentCodec.encode(CH_HELLO, StandardCharsets.UTF_8)));
167     }
168 
169     @Test
170     public void testHierarchicalUri() throws Exception {
171         final URI uri = new URI("http", "stuff", "localhost", 80, "/some stuff", "param=stuff", "fragment");
172         final URIBuilder uribuilder = new URIBuilder(uri);
173         final URI result = uribuilder.build();
174         Assertions.assertEquals(new URI("http://stuff@localhost:80/some%20stuff?param=stuff#fragment"), result);
175     }
176 
177     @Test
178     public void testMutationToRelativeUri() throws Exception {
179         final URI uri = new URI("http://stuff@localhost:80/stuff?param=stuff#fragment");
180         final URIBuilder uribuilder = new URIBuilder(uri).setHost((String) null);
181         final URI result = uribuilder.build();
182         Assertions.assertEquals(new URI("http:///stuff?param=stuff#fragment"), result);
183     }
184 
185     @Test
186     public void testMutationRemoveFragment() throws Exception {
187         final URI uri = new URI("http://stuff@localhost:80/stuff?param=stuff#fragment");
188         final URI result = new URIBuilder(uri).setFragment(null).build();
189         Assertions.assertEquals(new URI("http://stuff@localhost:80/stuff?param=stuff"), result);
190     }
191 
192     @Test
193     public void testMutationRemoveUserInfo() throws Exception {
194         final URI uri = new URI("http://stuff@localhost:80/stuff?param=stuff#fragment");
195         final URI result = new URIBuilder(uri).setUserInfo(null).build();
196         Assertions.assertEquals(new URI("http://localhost:80/stuff?param=stuff#fragment"), result);
197     }
198 
199     @Test
200     public void testMutationRemovePort() throws Exception {
201         final URI uri = new URI("http://stuff@localhost:80/stuff?param=stuff#fragment");
202         final URI result = new URIBuilder(uri).setPort(-1).build();
203         Assertions.assertEquals(new URI("http://stuff@localhost/stuff?param=stuff#fragment"), result);
204     }
205 
206     @Test
207     public void testOpaqueUri() throws Exception {
208         final URI uri = new URI("stuff", "some-stuff", "fragment");
209         final URIBuilder uribuilder = new URIBuilder(uri);
210         final URI result = uribuilder.build();
211         Assertions.assertEquals(uri, result);
212     }
213 
214     @Test
215     public void testOpaqueUriMutation() throws Exception {
216         final URI uri = new URI("stuff", "some-stuff", "fragment");
217         final URIBuilder uribuilder = new URIBuilder(uri).setCustomQuery("param1&param2=stuff").setFragment(null);
218         Assertions.assertEquals(new URI("stuff:?param1&param2=stuff"), uribuilder.build());
219     }
220 
221     @Test
222     public void testHierarchicalUriMutation() throws Exception {
223         final URIBuilder uribuilder = new URIBuilder("/").setScheme("http").setHost("localhost").setPort(80).setPath("/stuff");
224         Assertions.assertEquals(new URI("http://localhost:80/stuff"), uribuilder.build());
225     }
226 
227     @Test
228    public void testLocalhost() throws Exception {
229        // Check that the URI generated by URI builder agrees with that generated by using URI directly
230        final String scheme="https";
231        final InetAddress host=InetAddress.getLocalHost();
232        final String specials="/abcd!$&*()_-+.,=:;'~@[]?<>|#^%\"{}\\\u00a3`\u00ac\u00a6xyz"; // N.B. excludes space
233        final URI uri = new URI(scheme, specials, host.getHostAddress(), 80, specials, specials, specials);
234 
235        final URI bld = URIBuilder.localhost()
236                .setScheme(scheme)
237                .setUserInfo(specials)
238                .setPath(specials)
239                .setCustomQuery(specials)
240                .setFragment(specials)
241                .build();
242 
243        Assertions.assertEquals(uri.getHost(), bld.getHost());
244 
245        Assertions.assertEquals(uri.getUserInfo(), bld.getUserInfo());
246 
247        Assertions.assertEquals(uri.getPath(), bld.getPath());
248 
249        Assertions.assertEquals(uri.getQuery(), bld.getQuery());
250 
251        Assertions.assertEquals(uri.getFragment(), bld.getFragment());
252    }
253 
254     @Test
255    public void testLoopbackAddress() throws Exception {
256        // Check that the URI generated by URI builder agrees with that generated by using URI directly
257        final String scheme="https";
258        final InetAddress host=InetAddress.getLoopbackAddress();
259        final String specials="/abcd!$&*()_-+.,=:;'~@[]?<>|#^%\"{}\\\u00a3`\u00ac\u00a6xyz"; // N.B. excludes space
260        final URI uri = new URI(scheme, specials, host.getHostAddress(), 80, specials, specials, specials);
261 
262        final URI bld = URIBuilder.loopbackAddress()
263                .setScheme(scheme)
264                .setUserInfo(specials)
265                .setPath(specials)
266                .setCustomQuery(specials)
267                .setFragment(specials)
268                .build();
269 
270        Assertions.assertEquals(uri.getHost(), bld.getHost());
271 
272        Assertions.assertEquals(uri.getUserInfo(), bld.getUserInfo());
273 
274        Assertions.assertEquals(uri.getPath(), bld.getPath());
275 
276        Assertions.assertEquals(uri.getQuery(), bld.getQuery());
277 
278        Assertions.assertEquals(uri.getFragment(), bld.getFragment());
279    }
280 
281     @Test
282     public void testEmpty() throws Exception {
283         final URIBuilder uribuilder = new URIBuilder();
284         final URI result = uribuilder.build();
285         Assertions.assertEquals(new URI(""), result);
286     }
287 
288     @Test
289     public void testEmptyPath() throws Exception {
290         final URIBuilder uribuilder = new URIBuilder("http://thathost");
291         Assertions.assertTrue(uribuilder.isPathEmpty());
292     }
293 
294     @Test
295     public void testRemoveParameter() throws Exception {
296         final URI uri = new URI("http", null, "localhost", 80, "/", "param=stuff&blah&blah", null);
297         final URIBuilder uribuilder = new URIBuilder(uri);
298         Assertions.assertFalse(uribuilder.isQueryEmpty());
299 
300         Assertions.assertThrows(NullPointerException.class, () -> uribuilder.removeParameter(null));
301 
302         uribuilder.removeParameter("DoesNotExist");
303         Assertions.assertEquals("stuff", uribuilder.getFirstQueryParam("param").getValue());
304         Assertions.assertNull(uribuilder.getFirstQueryParam("blah").getValue());
305 
306         uribuilder.removeParameter("blah");
307         Assertions.assertEquals("stuff", uribuilder.getFirstQueryParam("param").getValue());
308         Assertions.assertNull(uribuilder.getFirstQueryParam("blah"));
309 
310         uribuilder.removeParameter("param");
311         Assertions.assertNull(uribuilder.getFirstQueryParam("param"));
312         Assertions.assertTrue(uribuilder.isQueryEmpty());
313 
314         uribuilder.removeParameter("AlreadyEmpty");
315         Assertions.assertTrue(uribuilder.isQueryEmpty());
316         Assertions.assertEquals(new URI("http://localhost:80/"), uribuilder.build());
317     }
318 
319     @Test
320     public void testRemoveQuery() throws Exception {
321         final URI uri = new URI("http", null, "localhost", 80, "/", "param=stuff", null);
322         final URIBuilder uribuilder = new URIBuilder(uri).removeQuery();
323         final URI result = uribuilder.build();
324         Assertions.assertEquals(new URI("http://localhost:80/"), result);
325     }
326 
327     @Test
328     public void testSetAuthorityFromNamedEndpointHost() throws Exception {
329         final Host host = Host.create("localhost:88");
330         final URIBuilder uribuilder = new URIBuilder().setScheme(URIScheme.HTTP.id).setAuthority(host);
331         // Check builder
332         Assertions.assertNull(uribuilder.getUserInfo());
333         Assertions.assertEquals(host.getHostName(), uribuilder.getAuthority().getHostName());
334         Assertions.assertEquals(host.getHostName(), uribuilder.getHost());
335         // Check result
336         final URI result = uribuilder.build();
337         Assertions.assertEquals(host.getHostName(), result.getHost());
338         Assertions.assertEquals(host.getPort(), result.getPort());
339         Assertions.assertEquals(new URI("http://localhost:88"), result);
340     }
341 
342     @Test
343     public void testSetAuthorityFromNamedEndpointHttpHost() throws Exception {
344         final HttpHost httpHost = HttpHost.create("localhost:88");
345         final URIBuilder uribuilder = new URIBuilder().setScheme(URIScheme.HTTP.id).setAuthority(httpHost);
346         // Check builder
347         Assertions.assertNull(uribuilder.getUserInfo());
348         Assertions.assertEquals(httpHost.getHostName(), uribuilder.getAuthority().getHostName());
349         Assertions.assertEquals(httpHost.getHostName(), uribuilder.getHost());
350         // Check result
351         final URI result = uribuilder.build();
352         Assertions.assertEquals(httpHost.getHostName(), result.getHost());
353         Assertions.assertEquals(httpHost.getPort(), result.getPort());
354         Assertions.assertEquals(new URI("http://localhost:88"), result);
355     }
356 
357     @Test
358     public void testSetAuthorityFromURIAuthority() throws Exception {
359         final URIAuthority authority = URIAuthority.create("u:p@localhost:88");
360         final URIBuilder uribuilder = new URIBuilder().setScheme(URIScheme.HTTP.id).setAuthority(authority);
361         // Check builder
362         Assertions.assertEquals(authority.getUserInfo(), uribuilder.getAuthority().getUserInfo());
363         Assertions.assertEquals(authority.getHostName(), uribuilder.getAuthority().getHostName());
364         Assertions.assertEquals(authority.getHostName(), uribuilder.getHost());
365         // Check result
366         final URI result = uribuilder.build();
367         Assertions.assertEquals(authority.getUserInfo(), result.getUserInfo());
368         Assertions.assertEquals(authority.getHostName(), result.getHost());
369         Assertions.assertEquals(authority.getPort(), result.getPort());
370         Assertions.assertEquals(authority.toString(), result.getAuthority());
371         Assertions.assertEquals(new URI("http://u:p@localhost:88"), result);
372     }
373 
374     @Test
375     public void testSetParameter() throws Exception {
376         final URI uri = new URI("http", null, "localhost", 80, "/", "param=stuff&blah&blah", null);
377         final URIBuilder uribuilder = new URIBuilder(uri).setParameter("param", "some other stuff")
378                 .setParameter("blah", "blah")
379                 .setParameter("blah", "blah2");
380         final URI result = uribuilder.build();
381         Assertions.assertEquals(new URI("http://localhost:80/?param=some%20other%20stuff&blah=blah2"), result);
382     }
383 
384     @Test
385     public void testGetFirstNamedParameter() throws Exception {
386         final URI uri = new URI("http", null, "localhost", 80, "/", "param=stuff&blah&blah", null);
387         URIBuilder uribuilder = new URIBuilder(uri).setParameter("param", "some other stuff")
388             .setParameter("blah", "blah");
389         Assertions.assertEquals("some other stuff", uribuilder.getFirstQueryParam("param").getValue());
390         Assertions.assertEquals("blah", uribuilder.getFirstQueryParam("blah").getValue());
391         Assertions.assertNull(uribuilder.getFirstQueryParam("DoesNotExist"));
392         //
393         uribuilder = new URIBuilder("http://localhost:80/?param=some%20other%20stuff&blah=blah&blah=blah2");
394         Assertions.assertEquals("blah", uribuilder.getFirstQueryParam("blah").getValue());
395     }
396 
397     @Test
398     public void testSetParametersWithEmptyArrayArg() throws Exception {
399         final URI uri = new URI("http", null, "localhost", 80, "/test", "param=test", null);
400         final URIBuilder uribuilder = new URIBuilder(uri).setParameters();
401         final URI result = uribuilder.build();
402         Assertions.assertEquals(new URI("http://localhost:80/test"), result);
403     }
404 
405     @Test
406     public void testSetParametersWithNullArrayArg() throws Exception {
407         final URI uri = new URI("http", null, "localhost", 80, "/test", "param=test", null);
408         final URIBuilder uribuilder = new URIBuilder(uri).setParameters((NameValuePair[]) null);
409         final URI result = uribuilder.build();
410         Assertions.assertEquals(new URI("http://localhost:80/test"), result);
411     }
412 
413     @Test
414     public void testSetParametersWithEmptyList() throws Exception {
415         final URI uri = new URI("http", null, "localhost", 80, "/test", "param=test", null);
416         final URIBuilder uribuilder = new URIBuilder(uri).setParameters(Collections.emptyList());
417         final URI result = uribuilder.build();
418         Assertions.assertEquals(new URI("http://localhost:80/test"), result);
419     }
420 
421     @Test
422     public void testSetParametersWithNullList() throws Exception {
423         final URI uri = new URI("http", null, "localhost", 80, "/test", "param=test", null);
424         final URIBuilder uribuilder = new URIBuilder(uri).setParameters((List<NameValuePair>) null);
425         final URI result = uribuilder.build();
426         Assertions.assertEquals(new URI("http://localhost:80/test"), result);
427     }
428 
429     @Test
430     public void testParameterWithSpecialChar() throws Exception {
431         final URI uri = new URI("http", null, "localhost", 80, "/", "param=stuff", null);
432         final URIBuilder uribuilder = new URIBuilder(uri).addParameter("param", "1 + 1 = 2")
433             .addParameter("param", "blah&blah");
434         final URI result = uribuilder.build();
435         Assertions.assertEquals(new URI("http://localhost:80/?param=stuff&param=1%20%2B%201%20%3D%202&" +
436                 "param=blah%26blah"), result);
437     }
438 
439     @Test
440     public void testAddParameter() throws Exception {
441         final URI uri = new URI("http", null, "localhost", 80, "/", "param=stuff&blah&blah", null);
442         final URIBuilder uribuilder = new URIBuilder(uri).addParameter("param", "some other stuff")
443             .addParameter("blah", "blah");
444         final URI result = uribuilder.build();
445         Assertions.assertEquals(new URI("http://localhost:80/?param=stuff&blah&blah&" +
446                 "param=some%20other%20stuff&blah=blah"), result);
447     }
448 
449     @Test
450     public void testQueryEncoding() throws Exception {
451         final URI uri1 = new URI("https://somehost.com/stuff?client_id=1234567890" +
452                 "&redirect_uri=https%3A%2F%2Fsomehost.com%2Fblah%20blah%2F");
453         final URI uri2 = new URIBuilder("https://somehost.com/stuff")
454             .addParameter("client_id","1234567890")
455             .addParameter("redirect_uri","https://somehost.com/blah blah/").build();
456         Assertions.assertEquals(uri1, uri2);
457     }
458 
459     @Test
460     public void testQueryAndParameterEncoding() throws Exception {
461         final URI uri1 = new URI("https://somehost.com/stuff?param1=12345&param2=67890");
462         final URI uri2 = new URIBuilder("https://somehost.com/stuff")
463             .setCustomQuery("this&that")
464             .addParameter("param1","12345")
465             .addParameter("param2","67890").build();
466         Assertions.assertEquals(uri1, uri2);
467     }
468 
469     @Test
470     public void testPathEncoding() throws Exception {
471         final URI uri1 = new URI("https://somehost.com/some%20path%20with%20blanks/");
472         final URI uri2 = new URIBuilder()
473             .setScheme("https")
474             .setHost("somehost.com")
475             .setPath("/some path with blanks/")
476             .build();
477         Assertions.assertEquals(uri1, uri2);
478     }
479 
480     @Test
481     public void testAgainstURI() throws Exception {
482         // Check that the URI generated by URI builder agrees with that generated by using URI directly
483         final String scheme="https";
484         final String host="localhost";
485         final String specials="/abcd!$&*()_-+.,=:;'~@[]?<>|#^%\"{}\\\u00a3`\u00ac\u00a6xyz"; // N.B. excludes space
486         final URI uri = new URI(scheme, specials, host, 80, specials, specials, specials);
487 
488         final URI bld = new URIBuilder()
489                 .setScheme(scheme)
490                 .setHost(host)
491                 .setUserInfo(specials)
492                 .setPath(specials)
493                 .setCustomQuery(specials)
494                 .setFragment(specials)
495                 .build();
496 
497         Assertions.assertEquals(uri.getHost(), bld.getHost());
498 
499         Assertions.assertEquals(uri.getUserInfo(), bld.getUserInfo());
500 
501         Assertions.assertEquals(uri.getPath(), bld.getPath());
502 
503         Assertions.assertEquals(uri.getQuery(), bld.getQuery());
504 
505         Assertions.assertEquals(uri.getFragment(), bld.getFragment());
506 
507     }
508 
509     @Test
510     public void testBuildAddParametersUTF8() throws Exception {
511         assertAddParameters(StandardCharsets.UTF_8);
512     }
513 
514     @Test
515     public void testBuildAddParametersISO88591() throws Exception {
516         assertAddParameters(StandardCharsets.ISO_8859_1);
517     }
518 
519     public void assertAddParameters(final Charset charset) throws Exception {
520         final URI uri = new URIBuilder("https://somehost.com/stuff")
521                 .setCharset(charset)
522                 .addParameters(createParameterList()).build();
523 
524         assertBuild(charset, uri);
525         // null addParameters
526         final URI uri2 = new URIBuilder("https://somehost.com/stuff")
527                 .setCharset(charset)
528                 .addParameters(null).build();
529 
530         Assertions.assertEquals("https://somehost.com/stuff", uri2.toString());
531     }
532 
533     @Test
534     public void testBuildSetParametersUTF8() throws Exception {
535         assertSetParameters(StandardCharsets.UTF_8);
536     }
537 
538     @Test
539     public void testBuildSetParametersISO88591() throws Exception {
540         assertSetParameters(StandardCharsets.ISO_8859_1);
541     }
542 
543     public void assertSetParameters(final Charset charset) throws Exception {
544         final URI uri = new URIBuilder("https://somehost.com/stuff")
545                 .setCharset(charset)
546                 .setParameters(createParameterList()).build();
547 
548         assertBuild(charset, uri);
549     }
550 
551     public void assertBuild(final Charset charset, final URI uri) throws Exception {
552         final String encodedData1 = PercentCodec.encode("\"1\u00aa position\"", charset);
553         final String encodedData2 = PercentCodec.encode("Jos\u00e9 Abra\u00e3o", charset);
554 
555         final String uriExpected = String.format("https://somehost.com/stuff?parameter1=value1&parameter2=%s&parameter3=%s", encodedData1, encodedData2);
556 
557         Assertions.assertEquals(uriExpected, uri.toString());
558     }
559 
560     private List<NameValuePair> createParameterList() {
561         final List<NameValuePair> parameters = new ArrayList<>();
562         parameters.add(new BasicNameValuePair("parameter1", "value1"));
563         parameters.add(new BasicNameValuePair("parameter2", "\"1\u00aa position\""));
564         parameters.add(new BasicNameValuePair("parameter3", "Jos\u00e9 Abra\u00e3o"));
565         return parameters;
566     }
567 
568     @Test
569     public void testMalformedPath() throws Exception {
570         final String path = "@notexample.com/mypath";
571         final URI uri = new URIBuilder(path).setHost("example.com").build();
572         Assertions.assertEquals("example.com", uri.getHost());
573     }
574 
575     @Test
576     public void testRelativePath() throws Exception {
577         final URI uri = new URIBuilder("./mypath").build();
578         Assertions.assertEquals(new URI("./mypath"), uri);
579     }
580 
581     @Test
582     public void testRelativePathWithAuthority() throws Exception {
583         final URI uri = new URIBuilder("./mypath").setHost("somehost").setScheme("http").build();
584         Assertions.assertEquals(new URI("http://somehost/./mypath"), uri);
585     }
586 
587     @Test
588     public void testTolerateNullInput() throws Exception {
589         assertThat(new URIBuilder()
590                         .setScheme(null)
591                         .setHost("localhost")
592                         .setUserInfo(null)
593                         .setPort(8443)
594                         .setPath(null)
595                         .setCustomQuery(null)
596                         .setFragment(null)
597                         .build(),
598                 CoreMatchers.equalTo(URI.create("//localhost:8443")));
599     }
600 
601     @Test
602     public void testTolerateBlankInput() throws Exception {
603         assertThat(new URIBuilder()
604                         .setScheme("")
605                         .setHost("localhost")
606                         .setUserInfo("")
607                         .setPort(8443)
608                         .setPath("")
609                         .setPath("")
610                         .setCustomQuery("")
611                         .setFragment("")
612                         .build(),
613                 CoreMatchers.equalTo(URI.create("//localhost:8443")));
614     }
615 
616     @Test
617     public void testHttpHost() throws Exception {
618         final HttpHost httpHost = new HttpHost("http", "example.com", 1234);
619         final URIBuilder uribuilder = new URIBuilder();
620         uribuilder.setHttpHost(httpHost);
621         Assertions.assertEquals(URI.create("http://example.com:1234"), uribuilder.build());
622     }
623 
624     @Test
625     public void testSetHostWithReservedChars() throws Exception {
626         final URIBuilder uribuilder = new URIBuilder();
627         uribuilder.setScheme("http").setHost("!example!.com");
628         Assertions.assertEquals(URI.create("http://%21example%21.com"), uribuilder.build());
629     }
630 
631     @Test
632     public void testGetHostWithReservedChars() throws Exception {
633         final URIBuilder uribuilder = new URIBuilder("http://someuser%21@%21example%21.com/");
634         Assertions.assertEquals("!example!.com", uribuilder.getHost());
635         Assertions.assertEquals("someuser!", uribuilder.getUserInfo());
636     }
637 
638     @Test
639     public void testMultipleLeadingPathSlashes() throws Exception {
640         final URI uri = new URIBuilder()
641                 .setScheme("ftp")
642                 .setHost("somehost")
643                 .setPath("//blah//blah")
644                 .build();
645         assertThat(uri, CoreMatchers.equalTo(URI.create("ftp://somehost//blah//blah")));
646     }
647 
648     @Test
649     public void testNoAuthorityAndPath() throws Exception {
650         final URI uri = new URIBuilder()
651                 .setScheme("file")
652                 .setPath("/blah")
653                 .build();
654         assertThat(uri, CoreMatchers.equalTo(URI.create("file:/blah")));
655     }
656 
657     @Test
658     public void testSetPathSegmentList() throws Exception {
659         final URI uri = new URIBuilder()
660             .setScheme("https")
661             .setHost("somehost")
662             .setPathSegments(Arrays.asList("api", "products"))
663             .build();
664         assertThat(uri, CoreMatchers.equalTo(URI.create("https://somehost/api/products")));
665     }
666 
667     @Test
668     public void testSetPathSegmentsVarargs() throws Exception {
669         final URI uri = new URIBuilder()
670             .setScheme("https")
671             .setHost("somehost")
672             .setPathSegments("api", "products")
673             .build();
674         assertThat(uri, CoreMatchers.equalTo(URI.create("https://somehost/api/products")));
675     }
676 
677     @Test
678     public void testSetPathSegmentsRootlessList() throws Exception {
679         final URI uri = new URIBuilder()
680             .setScheme("file")
681             .setPathSegmentsRootless(Arrays.asList("dir", "foo"))
682             .build();
683         assertThat(uri, CoreMatchers.equalTo(URI.create("file:dir/foo")));
684     }
685 
686     @Test
687     public void testSetPathSegmentsRootlessVarargs() throws Exception {
688         final URI uri = new URIBuilder()
689             .setScheme("file")
690             .setPathSegmentsRootless("dir", "foo")
691             .build();
692         assertThat(uri, CoreMatchers.equalTo(URI.create("file:dir/foo")));
693     }
694 
695     @Test
696     public void testAppendToExistingPath() throws Exception {
697         final URI uri = new URIBuilder()
698             .setScheme("https")
699             .setHost("somehost")
700             .setPath("api")
701             .appendPath("v1/resources")
702             .appendPath("idA")
703             .build();
704         assertThat(uri, CoreMatchers.equalTo(URI.create("https://somehost/api/v1/resources/idA")));
705     }
706 
707     @Test
708     public void testAppendToNonExistingPath() throws Exception {
709         final URI uri = new URIBuilder()
710             .setScheme("https")
711             .setHost("somehost")
712             .appendPath("api/v2/customers")
713             .appendPath("idA")
714             .build();
715         assertThat(uri, CoreMatchers.equalTo(URI.create("https://somehost/api/v2/customers/idA")));
716     }
717 
718     @Test
719     public void testAppendNullToExistingPath() throws Exception {
720         final URI uri = new URIBuilder()
721             .setScheme("https")
722             .setHost("somehost")
723             .setPath("api")
724             .appendPath(null)
725             .build();
726         assertThat(uri, CoreMatchers.equalTo(URI.create("https://somehost/api")));
727     }
728 
729     @Test
730     public void testAppendNullToNonExistingPath() throws Exception {
731         final URI uri = new URIBuilder()
732             .setScheme("https")
733             .setHost("somehost")
734             .appendPath(null)
735             .build();
736         assertThat(uri, CoreMatchers.equalTo(URI.create("https://somehost")));
737     }
738 
739     @Test
740     public void testAppendSegmentsVarargsToExistingPath() throws Exception {
741         final URI uri = new URIBuilder()
742             .setScheme("https")
743             .setHost("myhost")
744             .setPath("api")
745             .appendPathSegments("v3", "products")
746             .appendPathSegments("idA")
747             .build();
748         assertThat(uri, CoreMatchers.equalTo(URI.create("https://myhost/api/v3/products/idA")));
749     }
750 
751     @Test
752     public void testAppendSegmentsVarargsToNonExistingPath() throws Exception {
753         final URI uri = new URIBuilder()
754             .setScheme("https")
755             .setHost("somehost")
756             .appendPathSegments("api", "v2", "customers")
757             .appendPathSegments("idA")
758             .build();
759         assertThat(uri, CoreMatchers.equalTo(URI.create("https://somehost/api/v2/customers/idA")));
760     }
761 
762     @Test
763     public void testAppendNullSegmentsVarargs() throws Exception {
764         final String pathSegment = null;
765         final URI uri = new URIBuilder()
766             .setScheme("https")
767             .setHost("somehost")
768             .appendPathSegments(pathSegment)
769             .build();
770         assertThat(uri, CoreMatchers.equalTo(URI.create("https://somehost/")));
771     }
772 
773     @Test
774     public void testAppendSegmentsListToExistingPath() throws Exception {
775         final URI uri = new URIBuilder()
776             .setScheme("http")
777             .setHost("myhost")
778             .setPath("api")
779             .appendPathSegments(Arrays.asList("v3", "products"))
780             .build();
781         assertThat(uri, CoreMatchers.equalTo(URI.create("http://myhost/api/v3/products")));
782     }
783 
784     @Test
785     public void testAppendSegmentsListToNonExistingPath() throws Exception {
786         final URI uri = new URIBuilder()
787             .setScheme("http")
788             .setHost("myhost")
789             .appendPathSegments(Arrays.asList("api", "v3", "customers"))
790             .build();
791         assertThat(uri, CoreMatchers.equalTo(URI.create("http://myhost/api/v3/customers")));
792     }
793 
794     @Test
795     public void testAppendNullSegmentsList() throws Exception {
796         final List<String> pathSegments = null;
797         final URI uri = new URIBuilder()
798             .setScheme("http")
799             .setHost("myhost")
800             .appendPathSegments(pathSegments)
801             .build();
802         assertThat(uri, CoreMatchers.equalTo(URI.create("http://myhost")));
803     }
804 
805     @Test
806     public void testNoAuthorityAndPathSegments() throws Exception {
807         final URI uri = new URIBuilder()
808                 .setScheme("file")
809                 .setPathSegments("this", "that")
810                 .build();
811         assertThat(uri, CoreMatchers.equalTo(URI.create("file:/this/that")));
812     }
813 
814     @Test
815     public void testNoAuthorityAndRootlessPath() throws Exception {
816         final URI uri = new URIBuilder()
817                 .setScheme("file")
818                 .setPath("blah")
819                 .build();
820         assertThat(uri, CoreMatchers.equalTo(URI.create("file:blah")));
821     }
822 
823     @Test
824     public void testNoAuthorityAndRootlessPathSegments() throws Exception {
825         final URI uri = new URIBuilder()
826                 .setScheme("file")
827                 .setPathSegmentsRootless("this", "that")
828                 .build();
829         assertThat(uri, CoreMatchers.equalTo(URI.create("file:this/that")));
830     }
831 
832     @Test
833     public void testOpaque() throws Exception {
834         final URIBuilder uriBuilder = new URIBuilder("http://host.com");
835         final URI uri = uriBuilder.build();
836         assertThat(uriBuilder.isOpaque(), CoreMatchers.equalTo(uri.isOpaque()));
837     }
838 
839     @Test
840     public void testAddParameterEncodingEquivalence() throws Exception {
841         final URI uri = new URI("http", null, "localhost", 80, "/",
842                 "param=stuff with spaces", null);
843         final URIBuilder uribuilder = new URIBuilder().setScheme("http").setHost("localhost").setPort(80).setPath("/").addParameter(
844                 "param", "stuff with spaces");
845         final URI result = uribuilder.build();
846         Assertions.assertEquals(uri, result);
847     }
848 
849     @Test
850     public void testSchemeSpecificPartParametersNull() throws Exception {
851        final URIBuilder uribuilder = new URIBuilder("http://host.com").setParameter("par", "parvalue")
852                .setSchemeSpecificPart("", (NameValuePair)null);
853        Assertions.assertEquals(new URI("http://host.com?par=parvalue"), uribuilder.build());
854     }
855 
856     @Test
857     public void testSchemeSpecificPartSetGet() throws Exception {
858        final URIBuilder uribuilder = new URIBuilder().setSchemeSpecificPart("specificpart");
859        Assertions.assertEquals("specificpart", uribuilder.getSchemeSpecificPart());
860     }
861 
862     /** Common use case: mailto: scheme. See https://tools.ietf.org/html/rfc6068#section-2 */
863     @Test
864     public void testSchemeSpecificPartNameValuePairByRFC6068Sample() throws Exception {
865        final URIBuilder uribuilder = new URIBuilder().setScheme("mailto")
866                .setSchemeSpecificPart("my@email.server", new BasicNameValuePair("subject", "mail subject"));
867        final String result = uribuilder.build().toString();
868        Assertions.assertTrue(result.contains("my@email.server"), "mail address as scheme specific part expected");
869        Assertions.assertTrue(result.contains("mail%20subject"), "correct parameter encoding expected for that scheme");
870     }
871 
872     /** Common use case: mailto: scheme. See https://tools.ietf.org/html/rfc6068#section-2 */
873     @Test
874     public void testSchemeSpecificPartNameValuePairListByRFC6068Sample() throws Exception {
875         final List<NameValuePair> parameters = new ArrayList<>();
876         parameters.add(new BasicNameValuePair("subject", "mail subject"));
877 
878        final URIBuilder uribuilder = new URIBuilder().setScheme("mailto").setSchemeSpecificPart("my@email.server", parameters);
879        final String result = uribuilder.build().toString();
880        Assertions.assertTrue(result.contains("my@email.server"), "mail address as scheme specific part expected");
881        Assertions.assertTrue(result.contains("mail%20subject"), "correct parameter encoding expected for that scheme");
882     }
883 
884     @Test
885     public void testNormalizeSyntax() throws Exception {
886         Assertions.assertEquals("example://a/b/c/%7Bfoo%7D",
887                 new URIBuilder("eXAMPLE://a/./b/../b/%63/%7bfoo%7d").normalizeSyntax().build().toASCIIString());
888         Assertions.assertEquals("http://www.example.com/%3C",
889                 new URIBuilder("http://www.example.com/%3c").normalizeSyntax().build().toASCIIString());
890         Assertions.assertEquals("http://www.example.com/",
891                 new URIBuilder("HTTP://www.EXAMPLE.com/").normalizeSyntax().build().toASCIIString());
892         Assertions.assertEquals("http://www.example.com/a%2F",
893                 new URIBuilder("http://www.example.com/a%2f").normalizeSyntax().build().toASCIIString());
894         Assertions.assertEquals("http://www.example.com/?a%2F",
895                 new URIBuilder("http://www.example.com/?a%2f").normalizeSyntax().build().toASCIIString());
896         Assertions.assertEquals("http://www.example.com/?q=%26",
897                 new URIBuilder("http://www.example.com/?q=%26").normalizeSyntax().build().toASCIIString());
898         Assertions.assertEquals("http://www.example.com/%23?q=%26",
899                 new URIBuilder("http://www.example.com/%23?q=%26").normalizeSyntax().build().toASCIIString());
900         Assertions.assertEquals("http://www.example.com/blah-%28%20-blah-%20%26%20-blah-%20%29-blah/",
901                 new URIBuilder("http://www.example.com/blah-%28%20-blah-%20&%20-blah-%20)-blah/").normalizeSyntax().build().toASCIIString());
902         Assertions.assertEquals("../../.././",
903                 new URIBuilder("../../.././").normalizeSyntax().build().toASCIIString());
904         Assertions.assertEquals("file:../../.././",
905                 new URIBuilder("file:../../.././").normalizeSyntax().build().toASCIIString());
906         Assertions.assertEquals("http://host/",
907                 new URIBuilder("http://host/../../.././").normalizeSyntax().build().toASCIIString());
908         Assertions.assertEquals("http:/",
909                 new URIBuilder("http:///../../.././").normalizeSyntax().build().toASCIIString());
910     }
911 
912     @Test
913     public void testIpv6Host() throws Exception {
914         final URIBuilder builder = new URIBuilder("https://[::1]:432/path");
915         final URI uri = builder.build();
916         Assertions.assertEquals(432, builder.getPort());
917         Assertions.assertEquals(432, uri.getPort());
918         Assertions.assertEquals("https", builder.getScheme());
919         Assertions.assertEquals("https", uri.getScheme());
920         Assertions.assertEquals("::1", builder.getHost());
921         Assertions.assertEquals("[::1]", uri.getHost());
922         Assertions.assertEquals("/path", builder.getPath());
923         Assertions.assertEquals("/path", uri.getPath());
924     }
925 
926     @Test
927     public void testIpv6HostWithPortUpdate() throws Exception {
928         // Updating the port clears URIBuilder.encodedSchemeSpecificPart
929         // and bypasses the fast/simple path which preserves input.
930         final URIBuilder builder = new URIBuilder("https://[::1]:432/path").setPort(123);
931         final URI uri = builder.build();
932         Assertions.assertEquals(123, builder.getPort());
933         Assertions.assertEquals(123, uri.getPort());
934         Assertions.assertEquals("https", builder.getScheme());
935         Assertions.assertEquals("https", uri.getScheme());
936         Assertions.assertEquals("::1", builder.getHost());
937         Assertions.assertEquals("[::1]", uri.getHost());
938         Assertions.assertEquals("/path", builder.getPath());
939         Assertions.assertEquals("/path", uri.getPath());
940     }
941 
942     @Test
943     public void testBuilderWithUnbracketedIpv6Host() throws Exception {
944         final URIBuilder builder = new URIBuilder().setScheme("https").setHost("::1").setPort(443).setPath("/path");
945         final URI uri = builder.build();
946         Assertions.assertEquals("https", builder.getScheme());
947         Assertions.assertEquals("https", uri.getScheme());
948         Assertions.assertEquals(443, builder.getPort());
949         Assertions.assertEquals(443, uri.getPort());
950         Assertions.assertEquals("::1", builder.getHost());
951         Assertions.assertEquals("[::1]", uri.getHost());
952         Assertions.assertEquals("/path", builder.getPath());
953         Assertions.assertEquals("/path", uri.getPath());
954     }
955 }