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

org.marvelution.jira.plugins.jenkins.utils.URIUtils Maven / Gradle / Ivy

/*
 * Copyright (c) 2012-present Marvelution B.V.
 *
 * 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.marvelution.jira.plugins.jenkins.utils;

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

import org.apache.commons.lang.StringUtils;

import static org.apache.commons.lang.StringUtils.stripEnd;

/**
 * URI Utils
 *
 * @author Mark Rekveld
 * @since 1.0.0
 */
public class URIUtils {

	private static final Pattern REDUNDANT_SLASHES = Pattern.compile("//+");

	/**
	 * Encode an url using a specific charset, also all + chars are replaced by %20
	 *
	 * @param url     the url to encode
	 * @param charset the charset to use
	 * @return the encoded url
	 * @throws UnsupportedEncodingException
	 */
	public static String encode(String url, String charset) throws UnsupportedEncodingException {
		String encoded = URLEncoder.encode(url, charset);
		return StringUtils.replace(encoded, "+", "%20");
	}

	/**
	 * Append the given paths to the base {@link URI}
	 *
	 * @param base  the {@link URI} base
	 * @param paths the paths to add
	 * @return the new {@link URI}
	 */
	@Deprecated
	public static URI appendPathsToURI(URI base, String... paths) {
		StringBuilder builder = new StringBuilder();
		for (String path : paths) {
			try {
				builder.append("/").append(encode(path, "UTF-8"));
			} catch (UnsupportedEncodingException e) {
				throw new IllegalStateException("Failed to append paths to " + base.toASCIIString(), e);
			}
		}
		return URI.create(stripEnd(base.toASCIIString(), "/") + REDUNDANT_SLASHES.matcher(builder.append("/").toString()).replaceAll("/"));
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy