package org.gcube.portlets.user.geoportaldataviewer.server.util; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLDecoder; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * The Class URLUtil. * * @author Francesco Mangiacrapa at ISTI-CNR (francesco.mangiacrapa@isti.cnr.it) * * Oct 29, 2020 */ public class URLParserUtil { /** * Adds the parameter to query string. * * @param key the key * @param value the value * @param prefixAmpersand the prefix ampersand * @param suffixAmpersand the suffix ampersand * @return the string */ public static String addParameterToQueryString(String key, String value, boolean prefixAmpersand, boolean suffixAmpersand) { String queryParameter = ""; if (prefixAmpersand) queryParameter += "&"; queryParameter += key + "=" + value; if (suffixAmpersand) queryParameter += "&"; return queryParameter; } /** * Extract value of parameter from URL. * * @param paramName the param name * @param url the url * @return the string */ public static String extractValueOfParameterFromURL(String paramName, String url) { int index = url.toLowerCase().indexOf(paramName.toLowerCase() + "="); // ADDING CHAR "=" IN TAIL TO BE SURE THAT // IT // IS A PARAMETER String value = ""; if (index > -1) { int start = index + paramName.length() + 1; // add +1 for char '=' String sub = url.substring(start, url.length()); int indexOfSeparator = sub.indexOf("&"); int end = indexOfSeparator != -1 ? indexOfSeparator : sub.length(); value = sub.substring(0, end); } else return null; return value; } /** * Split query. * * @param url the url * @return the map * @throws UnsupportedEncodingException the unsupported encoding exception */ public static Map> splitQuery(URL url) throws UnsupportedEncodingException { final Map> query_pairs = new LinkedHashMap>(); final String[] pairs = url.getQuery().split("&"); for (String pair : pairs) { final int idx = pair.indexOf("="); final String key = idx > 0 ? URLDecoder.decode(pair.substring(0, idx), "UTF-8") : pair; if (!query_pairs.containsKey(key)) { query_pairs.put(key, new LinkedList()); } final String value = idx > 0 && pair.length() > idx + 1 ? URLDecoder.decode(pair.substring(idx + 1), "UTF-8") : null; query_pairs.get(key).add(value); } return query_pairs; } }