diff options
author | Bjørn Christian Seime <bjorncs@verizonmedia.com> | 2021-03-26 14:26:20 +0100 |
---|---|---|
committer | Bjørn Christian Seime <bjorncs@verizonmedia.com> | 2021-03-26 14:26:20 +0100 |
commit | 75fce53e614d1f30276c23ab0601a43337fb7f95 (patch) | |
tree | a1b4057d1297dee013a80c78edd55d7af2687697 /container-core/src/main/java/com/yahoo/restapi/UriBuilder.java | |
parent | 5c080930cfa4ecac4357dc977c86f2ced9db6477 (diff) |
Rename class 'Uri' to 'UriBuilder'
Diffstat (limited to 'container-core/src/main/java/com/yahoo/restapi/UriBuilder.java')
-rw-r--r-- | container-core/src/main/java/com/yahoo/restapi/UriBuilder.java | 64 |
1 files changed, 64 insertions, 0 deletions
diff --git a/container-core/src/main/java/com/yahoo/restapi/UriBuilder.java b/container-core/src/main/java/com/yahoo/restapi/UriBuilder.java new file mode 100644 index 00000000000..daebb147547 --- /dev/null +++ b/container-core/src/main/java/com/yahoo/restapi/UriBuilder.java @@ -0,0 +1,64 @@ +// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. +package com.yahoo.restapi; + +import java.net.URI; +import java.net.URISyntaxException; + +/** + * A Uri which provides convenience methods for creating various manipulated copies. + * This is immutable. + * + * @author bratseth + */ +public class UriBuilder { + + /** The URI instance wrapped by this */ + private final URI uri; + + public UriBuilder(URI uri) { + this.uri = uri; + } + + public UriBuilder(String uri) { + try { + this.uri = new URI(uri); + } + catch (URISyntaxException e) { + throw new IllegalArgumentException("Invalid URI", e); + } + } + + /** Returns a uri with the given path appended and all parameters removed */ + public UriBuilder append(String pathElement) { + return new UriBuilder(withoutParameters().withTrailingSlash() + pathElement); + } + + public UriBuilder withoutParameters() { + int parameterStart = uri.toString().indexOf("?"); + if (parameterStart < 0) + return new UriBuilder(uri.toString()); + else + return new UriBuilder(uri.toString().substring(0, parameterStart)); + } + + public UriBuilder withPath(String path) { + try { + return new UriBuilder(new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), + uri.getPort(), path, uri.getQuery(), uri.getFragment())); + } + catch (URISyntaxException e) { + throw new IllegalArgumentException("Could not add path '" + path + "' to " + this); + } + } + + public UriBuilder withTrailingSlash() { + if (toString().endsWith("/")) return this; + return new UriBuilder(toString() + "/"); + } + + public URI toURI() { return uri; } + + @Override + public String toString() { return uri.toString(); } + +} |