/** * Create a builder from a URI string. This will be parsed using the java standard library. * * @param value a URI string * @return a new builder */ public static Builder url(String value) { URI uri = URI.create(value); return new Builder() .scheme(uri.getScheme()) .authority(uri.getAuthority()) .path(uri.getRawPath()) .rawQuery(uri.getRawQuery()) .fragment(uri.getFragment()); }
/** * Create a builder from a URI string. This will be parsed using the java standard library. * * @param value a URI string * @return a new builder */ public static Builder url(String value) { URI uri = URI.create(value); return new Builder() .scheme(uri.getScheme()) .authority(uri.getAuthority()) .path(uri.getRawPath()) .rawQuery(uri.getRawQuery()) .fragment(uri.getFragment()); }
@Test public void shouldCreateAValidUrlIfAuthorityIsMissing() { Url url = new Url.Builder() .scheme("https") .path("/") .build(); assertThat(url.toString(), is("/")); }
/** * Rewrites the URL of the request according to the rewrite rules. * * @param request a request * @return a rewritten request */ public HttpRequest rewrite(HttpRequest request) { String path = request.path(); String newPath = newPath(path); if (!Objects.equals(newPath, path)) { Url newUrl = request.url().newBuilder().path(newPath).build(); return request.newBuilder() .url(newUrl) .build(); } return request; }
/** * Rewrites the URL of the request according to the rewrite rules. * * @param request a request * @return a rewritten request */ public LiveHttpRequest rewrite(LiveHttpRequest request) { String path = request.path(); String newPath = newPath(path); if (!Objects.equals(newPath, path)) { Url newUrl = request.url().newBuilder().path(newPath).build(); return request.newBuilder() .url(newUrl) .build(); } return request; }
@Test public void canModifyAComponentOfTheUrl() { Url url = url("/somerandompath?withsomequery=noquery").build(); assertThat(url.newBuilder().path("/newpath").build(), is(url("/newpath?withsomequery=noquery").build())); }
@Test public void canEncodeTheModifiedUrl() throws Exception { Url url = url("/search.do?foo=a%2Bb%3Dc").build(); Url newUrl = url.newBuilder().path("/v1/search").build(); assertThat(newUrl.encodedUri(), is("/v1/search?foo=a%2Bb%3Dc")); }
@Test public void shouldCreateWithPath() throws CharacterCodingException { Url url = new Url.Builder() .scheme("http") .authority("example.com") .path("/landing/de3445") .build(); assertThat(url.toString(), is("http://example.com/landing/de3445")); }
@Test public void shouldCreateWithSchemeAndHost() throws CharacterCodingException { assertThat("http://example.com", is(new Url.Builder() .scheme("http") .authority("example.com") .path("") .build() .toString())); }