UrlUtils.java

/*
 * Copyright 2022 Global Crop Diversity Trust
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
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;
	}
}