Java URI to Relative URI resolve(URI baseURI, String reference)

Here you can find the source of resolve(URI baseURI, String reference)

Description

Resolves a URI reference against a base URI.

License

Apache License

Parameter

Parameter Description
baseURI a parameter
reference a parameter

Exception

Parameter Description
URISyntaxException an exception

Return

the resolved URI

Declaration

public static URI resolve(URI baseURI, String reference) throws URISyntaxException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.regex.Pattern;

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

    /**/*from w w w .  j a  v a2  s. c om*/
     * Resolves a URI reference against a base URI. Work-around for bugs in
     * java.net.URI
     * (e.g.http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4708535)
     * 
     * @param baseURI
     * @param reference
     * @return the resolved {@code URI}
     * @throws URISyntaxException
     */
    public static URI resolve(URI baseURI, String reference) throws URISyntaxException {
        if (reference.isEmpty()) {
            return new URI(baseURI.getScheme(), baseURI.getSchemeSpecificPart(), null);
        }

        // A Windows path such as "C:\Users" is interpreted as a URI with
        // a scheme of "C". Use a regex that matches the colon-backslash
        // combination to handle this specifically as an absolute file URI.
        if (WINDOWS_FILE_PATTERN.matcher(reference).lookingAt()) {
            return new File(reference).toURI();
        }

        reference = reference.replace('\\', '/');
        URI refURI;
        try {
            refURI = new URI(reference);
        } catch (URISyntaxException e) {
            refURI = new URI(null, reference, null);
        }
        return baseURI.resolve(refURI);
    }
}

Related

  1. relativize(URI baseURI, URI uriToRelativize)
  2. relativizeFromBase(String uri, URI base)
  3. resolve(String baseURI, String connectorURI)
  4. resolve(String path, URI... relativeTo)
  5. resolve(URI base, URI child)
  6. resolveAbsoluteURI(final URI relativeURI)
  7. resolveFile(final URI relativeURI)
  8. resolveFileName(URI uri)
  9. resolveFileNameNoExt(URI uri)