UrlUtils.java

/*
 * Copyright 2026 Global Crop Diversity Trust
 * Licensed under the Apache License, Version 2.0
 * See LICENSE file in project root folder or http://www.apache.org/licenses/LICENSE-2.0
 */

package org.gringlobal.util;

import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.lang3.StringUtils;

/**
 * UrlUtils.
 */
public abstract class UrlUtils {

	/**
	 * Create a clean URL from string:
	 *
	 * - port == -1, if port is specified and is defaultPort
	 * - path without trailing /
	 * - no query if blank
	 *
	 * @param url
	 * @return
	 * @throws MalformedURLException
	 */
	public static URL toCleanUrl(String url) throws MalformedURLException {
		var u = new URL(url);
		var port = u.getPort() == u.getDefaultPort() ? -1 : u.getPort();
		var path = StringUtils.endsWith(u.getPath(), "/") ? StringUtils.substringBeforeLast(u.getPath(), "/") : u.getPath();
		var queryPart = u.getQuery() == null || u.getQuery().length() == 0 ? "" : "?" + u.getQuery();

		u = new URL(u.getProtocol(), u.getHost(), port, path + queryPart);
		return u;
	}
}