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

org.keycloak.util.UriUtils Maven / Gradle / Ivy

There is a newer version: 26.0.7
Show newest version
package org.keycloak.util;

import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLDecoder;
import java.util.regex.Pattern;

/**
 * @author Stian Thorgersen
 */
public class UriUtils {

    private static final Pattern originPattern = Pattern.compile("(http://|https://)[\\w-]+(\\.[\\w-]+)*(:[\\d]{2,5})?");

    public static String getOrigin(URI uri) {
        return getOrigin(uri.toString());
    }

    public static String getOrigin(String uri) {
        String u = uri.toString();
        int e = u.indexOf('/', 8);
        return e != -1 ? u.substring(0, u.indexOf('/', 8)) : u;
    }

    public static boolean isOrigin(String url) {
        return originPattern.matcher(url).matches();
    }

    public static MultivaluedHashMap decodeQueryString(String queryString) {
        MultivaluedHashMap map = new MultivaluedHashMap();
        if (queryString == null || queryString.equals("")) return map;

        String[] params = queryString.split("&");

        for (String param : params)
        {
            if (param.indexOf('=') >= 0)
            {
                String[] nv = param.split("=", 2);
                try
                {
                    String name = URLDecoder.decode(nv[0], "UTF-8");
                    String val = nv.length > 1 ? nv[1] : "";
                    map.add(name, URLDecoder.decode(val, "UTF-8"));
                }
                catch (UnsupportedEncodingException e)
                {
                    throw new RuntimeException(e);
                }
            }
            else
            {
                try
                {
                    String name = URLDecoder.decode(param, "UTF-8");
                    map.add(name, "");
                }
                catch (UnsupportedEncodingException e)
                {
                    throw new RuntimeException(e);
                }
            }
        }
        return map;
    }

    public static String stripQueryParam(String url, String name){
        return url.replaceFirst("[\\?&]"+name+"=[^&]*$|"+name+"=[^&]*&", "");
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy