Java URL Resolve resolve(URL base, String uri)

Here you can find the source of resolve(URL base, String uri)

Description

Resolves specified uri to a specified base URL.

License

Apache License

Parameter

Parameter Description
base base URL to use for resulution.
uri a relative or an absolute URI.

Exception

Parameter Description

Return

URL resolved relatively to the base URL.

Declaration

public static URL resolve(URL base, String uri) throws MalformedURLException 

Method Source Code

//package com.java2s;
/*/*  w  w  w. ja v a  2s .co m*/
 * Copyright 2006-2012 The Scriptella Project Team.
 *
 * 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.
 */

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

import java.util.regex.Pattern;

public class Main {
    private static final Pattern WINDOWS_PATH = Pattern.compile("[a-zA-Z]\\:/?([^/]|$).*");

    /**
     * Resolves specified uri to a specified base URL.
     * <p>This method use {@link URL#URL(URL,String)} constructor and handles additional checks
     * if URL cannot be resolved by a standard mechanism.
     * <p>Typical example is handling windows absolute paths with forward slashes.
     * These paths are malformed URIs, but Scriptella recognize them and converts to URL
     * if no protocol handler has been registered.
     * <p>In future we can add support for default URL stream handlers in addition to the ones
     * supported by the JRE.
     *
     * @param base base URL to use for resulution.
     * @param uri  a relative or an absolute URI.
     * @return URL resolved relatively to the base URL.
     * @throws java.net.MalformedURLException if specified URI cannot be resolved.
     */
    public static URL resolve(URL base, String uri) throws MalformedURLException {
        try {
            return new URL(base, uri);
        } catch (MalformedURLException e) {
            //if windows path, e.g. DRIVE:/, see CR #5029
            if (WINDOWS_PATH.matcher(uri).matches()) {
                //Add file:/ prefix and create URL
                return new URL("file:/" + uri);
            } else { //otherwise rethrow
                throw e;
            }

        }
    }
}

Related

  1. resolve(final URL url)
  2. resolve(URL base, String relUrl)
  3. resolveGoogleRedirect(String url)
  4. resolveHref(String baseUrl, String href)
  5. resolveManifestResources(final URL manifestUrl, final List resources)
  6. resolvePlatformUrl(String urlspec)