All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cz.jalasoft.net.http.URIBuilder Maven / Gradle / Ivy

The newest version!
package cz.jalasoft.net.http;

import java.net.URI;

/**
 * A builder of URI
 *
 * Created by Honza Lastovicka on 23.4.15.
 */
public final class URIBuilder {

    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", 80);
    }

    //-------------------------------------------------------------------------
    //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;
    }

    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 - 2024 Weber Informatics LLC | Privacy Policy