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

tech.ydb.core.utils.URITools Maven / Gradle / Ivy

There is a newer version: 2.3.0
Show newest version
package tech.ydb.core.utils;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.AbstractMap.SimpleImmutableEntry;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.google.common.base.Strings;

/**
 *
 * @author Aleksandr Gorshenin
 */
public class URITools {
    private URITools() { }

    public static Map> splitQuery(URI url) {
        if (Strings.isNullOrEmpty(url.getQuery())) {
            return Collections.emptyMap();
        }
        return Arrays.stream(url.getQuery().split("&"))
                .map(URITools::splitQueryParameter)
                .collect(Collectors.groupingBy(
                        SimpleImmutableEntry::getKey,
                        LinkedHashMap::new,
                        Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
    }

    private static String decode(String url) {
        try {
            return URLDecoder.decode(url, StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException ex) {
            return url;
        }
    }

    private static SimpleImmutableEntry splitQueryParameter(String it) {
        final int idx = it.indexOf("=");
        final String key = idx > 0 ? it.substring(0, idx) : it;
        final String value = idx > 0 && it.length() > idx + 1 ? it.substring(idx + 1) : null;
        return new SimpleImmutableEntry<>(decode(key), decode(value));
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy