001package co.codewizards.cloudstore.core.util;
002
003import java.net.MalformedURLException;
004import java.net.URL;
005
006public final class UrlUtil {
007
008        private UrlUtil() { }
009
010        public static URL canonicalizeURL(URL url) {
011                if (url == null)
012                        return null;
013
014                URL result = url;
015
016                String query = url.getQuery();
017                if (query != null && query.isEmpty()) {
018                        query = null;
019                        result = null;
020                }
021
022                String path = url.getPath();
023                while (path.endsWith("/")) {
024                         path = path.substring(0, path.length() - 1);
025                         result = null;
026                }
027
028                if (result == null) {
029                        String file = query == null ? path : path + '?' + query;
030                        try {
031                                result = new URL(url.getProtocol(), url.getHost(), url.getPort(), file);
032                        } catch (MalformedURLException e) {
033                                throw new RuntimeException(e);
034                        }
035                }
036                return result;
037        }
038
039}