cz.jalasoft.net.http.URIBuilder Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of HttpClient Show documentation
Show all versions of HttpClient Show documentation
API for communicating over HTTP.
The newest version!
package cz.jalasoft.net.http;
import java.net.URI;
import java.net.URISyntaxException;
/**
* A builder of URI
*
* Created by Honza Lastovicka on 23.4.15.
*/
public final class URIBuilder {
private static final int DEFAULT_PORT = 80;
private static final String URI_PATTERN = "%s://%s:%d%s";
/**
* Starts a process of URI creation.
* @return a buillder, never null
*/
public static URIBuilder http() {
return new URIBuilder("http", -1);
}
/**
* Gets a new URI builder from an existing URI.
* @param uri must not be null
* @return never null
*/
public static URIBuilder uri(URI uri) {
if (uri == null) {
throw new IllegalArgumentException("URI must not be null.");
}
URIBuilder builder = new URIBuilder(uri.getScheme(), uri.getPort())
.host(uri.getHost());
String path = uri.getPath();
if (path != null && !path.isEmpty()) {
builder.path(path);
}
return builder;
}
/**
* Gets a new URI builder from an existing URI as string.
* @param uriString must not be null or empty;
* @return never null
* @throws URISyntaxException if uriString does not match URI syntax
* @throws java.lang.IllegalArgumentException if uriString is null or empty
*/
public static URIBuilder uri(String uriString) throws URISyntaxException {
if (uriString == null || uriString.isEmpty()) {
throw new IllegalArgumentException("URI must not be null or empty.");
}
URI uri = new URI(uriString);
return uri(uri);
}
//-------------------------------------------------------------------------
//INSTANCE SCOPE
//-------------------------------------------------------------------------
private final String scheme;
private int port;
private String host;
private String path = "";
private URIBuilder(String scheme, int port) {
this.scheme = scheme;
this.port = port < 0 ? DEFAULT_PORT : port;
}
public URIBuilder host(String host) {
if (host == null || host.isEmpty()) {
throw new IllegalArgumentException("Host must not be null or empty.");
}
this.host = host;
return this;
}
public URIBuilder port(int port) {
if (port < 0) {
throw new IllegalArgumentException("Port must not be negative number.");
}
if (port > 65536) {
throw new IllegalArgumentException("Port must not be greater than 65536.");
}
this.port = port;
return this;
}
public URIBuilder path(String path) {
if (path == null || path.isEmpty()) {
throw new IllegalArgumentException("Path must not be null or empty.");
}
this.path = path;
return this;
}
public URI build() {
if (host == null) {
throw new IllegalStateException("Host has not been inserted.");
}
String uriAsString = String.format(URI_PATTERN, scheme, host, port, path);
return URI.create(uriAsString);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy