com.turbospaces.http.UrlUtils Maven / Gradle / Ivy
The newest version!
package com.turbospaces.http;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.message.BasicNameValuePair;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Multimap;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class UrlUtils {
public static URL addParams(String urlStr, Map params) throws URISyntaxException, MalformedURLException {
URL url = new URL(urlStr);
String urlWithoutQuery = urlStr.split("\\?")[0];
Multimap queryParams = decodeQuery(url.getQuery());
URIBuilder successUri = new URIBuilder(urlWithoutQuery);
queryParams.forEach(successUri::addParameter);
if (params != null) {
params.forEach(successUri::addParameter);
}
return successUri.build().toURL();
}
public static Multimap decodeQuery(String query) {
Multimap toReturn = HashMultimap.create();
if (StringUtils.isEmpty(query)) {
return toReturn;
}
List qparams = URLEncodedUtils.parse(query, StandardCharsets.UTF_8);
qparams.stream()
.filter(t -> StringUtils.isNotEmpty(t.getValue()))
.forEach(pair -> toReturn.put(pair.getName(), pair.getValue()));
return toReturn;
}
public static Optional getParam(String name, Multimap params) {
if (params.containsKey(name)) {
Collection l = params.get(name);
if (CollectionUtils.isNotEmpty(l)) {
return Optional.of(StringUtils.lowerCase(Iterables.getOnlyElement(l)));
}
}
return Optional.empty();
}
public static Optional getLastParam(String name, Multimap params) {
if (params.containsKey(name)) {
Collection l = params.get(name);
if (CollectionUtils.isNotEmpty(l)) {
return Optional.of(StringUtils.lowerCase(Iterables.getLast(l)));
}
}
return Optional.empty();
}
public static String toQuery(Multimap multimap) {
var params = multimap.entries().stream()
.map(e -> new BasicNameValuePair(e.getKey(), e.getValue()))
.collect(Collectors.toUnmodifiableList());
return toQuery(params);
}
public static String toQuery(List params) {
return URLEncodedUtils.format(params, StandardCharsets.UTF_8);
}
}