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

com.ovh.ws.jsonizer.api.http.UriBuilder Maven / Gradle / Ivy

The newest version!
/**
 * Copyright 2012, OVH. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and limitations under the License.
 */
package com.ovh.ws.jsonizer.api.http;

import java.net.URI;
import java.net.URL;

public class UriBuilder {

	private String protocol;
	private int port = -1;
	private String host;
	private StringBuilder path;

	/**
	 * Create a new instance initialized from an existing URL.
	 * 
	 * @param url
	 *            a URL that will be used to initialize the UriBuilder.
	 * @return a new UriBuilder
	 * @throws IllegalArgumentException
	 *             if url is null
	 */
	public static UriBuilder fromUrl(URL url) {
		UriBuilder b = new UriBuilder();
		b.url(url);
		return b;
	}

	private UriBuilder() {
		path = new StringBuilder();
	}

	public UriBuilder url(URL url) {
		if (url == null) {
			throw new IllegalArgumentException("URL parameter is null");
		}

		protocol = url.getProtocol();
		host = url.getHost();
		port = url.getPort();

		path.setLength(0);
		path.append(url.getPath());

		return this;
	}

	public UriBuilder protocol(String protocol) {
		if (protocol != null) {
			this.protocol = protocol;
		}
		return this;
	}

	/**
	 * Set the URI host.
	 */
	public UriBuilder host(String host) {
		if (host != null) {
			this.host = host;
		}
		return this;
	}

	/**
	 * Set the URI port.
	 */
	public UriBuilder port(int port) {
		this.port = port;
		return this;
	}

	/**
	 * Append path to the existing path.
	 */
	public UriBuilder path(String path) {
		appendPath(path);
		return this;
	}

	public URI build() {
		return URI.create(create());
	}

	private void appendPath(String segments) {
		final boolean pathEndsInSlash = path.charAt(path.length() - 1) == '/';

		if (!pathEndsInSlash) {
			path.append('/');
		}

		path.append(segments);
	}

	private String create() {
		StringBuilder sb = new StringBuilder();
		sb.append(protocol).append(':');
		sb.append("//").append(host);

		if (port != -1) {
			sb.append(':').append(port);
		}

		sb.append(path);

		return sb.toString();
	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy