com.aeontronix.commons.URLUtils Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of aeon-commons-core Show documentation
Show all versions of aeon-commons-core Show documentation
Various utility classes. Except for very rare exceptions (annotation-based validation) this will not
require any dependencies beyond the JRE
The newest version!
/*
* Copyright (c) 2014 Kloudtek Ltd
*/
package com.aeontronix.commons;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
/**
* Various URL/URI related utility functions
*/
public class URLUtils {
public static URL url(String address, int port, int securePort, boolean secure) {
StringBuilder url = new StringBuilder("http");
if (secure) {
url.append('s');
}
url.append("://").append(address);
if ((secure && securePort != 443) || (!secure && port != 80)) {
url.append(':').append(secure ? securePort : port);
}
return url(url.toString());
}
public static URL url(String scheme, String address, int port, String path) {
StringBuilder url = new StringBuilder(scheme).append("://").append(address);
if (!(scheme.equals("http") && port == 80) && !(scheme.equals("https") && port == 443)) {
url.append(':').append(port);
}
if (!path.startsWith("/")) {
url.append("/");
}
url.append(path);
return url(url.toString());
}
public static URL url(String baseUrl, String... pathElements) {
try {
if (pathElements == null || pathElements.length == 0) {
return new URL(baseUrl);
} else {
final URLBuilder url = new URLBuilder(baseUrl);
for (String element : pathElements) {
url.pathEl(element);
}
return url.toURL();
}
} catch (MalformedURLException e) {
throw new IllegalArgumentException(e);
}
}
public static URLBuilder buildUrl(String baseUrl, String... pathElements) {
URLBuilder urlBuilder = new URLBuilder(baseUrl);
if (pathElements != null && pathElements.length > 0) {
Arrays.stream(pathElements).forEach(urlBuilder::pathEl);
}
return urlBuilder;
}
/**
* Concatenate various paths elements, making sure there is only one slash '/' between each one
*
* @param paths Path elements
* @return concatenated path elements
*/
public static String concatPaths(String... paths) {
StringBuilder tmp = new StringBuilder();
for (String p : paths) {
if (p == null || StringUtils.isBlank(p)) {
continue;
}
final int len = tmp.length();
if (len == 0) {
tmp.append(p);
} else {
final char c = tmp.charAt(len - 1);
final char pc = p.charAt(0);
if (c == '/' && pc == '/') {
tmp.append(p.substring(1));
} else if (c != '/' && pc != '/') {
tmp.append('/').append(p);
} else {
tmp.append(p);
}
}
}
return tmp.toString();
}
}