Java URI to Relative URI getRelativePath(URI targetURI, URI baseURI)

Here you can find the source of getRelativePath(URI targetURI, URI baseURI)

Description

Returns a relative path between basePath and targetPath if possible.

License

Open Source License

Parameter

Parameter Description
targetURI the target path
baseURI the base path

Return

a relative path from basePath to targetPath or the targetPath if a relative path is not possible

Declaration

public static URI getRelativePath(URI targetURI, URI baseURI) 

Method Source Code

//package com.java2s;
/*/*from  ww  w .j a  v a2  s . c  om*/
 * Copyright (c) 2012 Data Harmonisation Panel
 * 
 * All rights reserved. This program and the accompanying materials are made
 * available under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the License,
 * or (at your option) any later version.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this distribution. If not, see <http://www.gnu.org/licenses/>.
 * 
 * Contributors:
 *     HUMBOLDT EU Integrated Project #030962
 *     Data Harmonisation Panel <http://www.dhpanel.eu>
 */

import java.net.URI;
import java.net.URISyntaxException;

public class Main {
    /**
     * Returns a relative path between basePath and targetPath if possible.
     * 
     * Source: http://stackoverflow.com/a/1288584
     * 
     * @param targetURI the target path
     * @param baseURI the base path
     * @return a relative path from basePath to targetPath or the targetPath if
     *         a relative path is not possible
     */
    public static URI getRelativePath(URI targetURI, URI baseURI) {
        // nothing to do if one path is opaque or not absolute
        if (!targetURI.isAbsolute() || !baseURI.isAbsolute() || targetURI.isOpaque() || baseURI.isOpaque())
            return targetURI;
        // check scheme
        // XXX also check the other stuff (authority, host, port)?
        if (!targetURI.getScheme().equals(baseURI.getScheme()))
            return targetURI;

        // Only use path, strip leading '/'
        String basePath = baseURI.getPath().substring(1);
        String targetPath = targetURI.getPath().substring(1);

        // We need the -1 argument to split to make sure we get a trailing
        // "" token if the base ends in the path separator and is therefore
        // a directory. We require directory paths to end in the path
        // separator -- otherwise they are indistinguishable from files.
        String[] base = basePath.split("/", -1);
        String[] target = targetPath.split("/", 0);

        // First get all the common elements. Store them as a string,
        // and also count how many of them there are.
        StringBuffer buf = new StringBuffer();
        int commonIndex = 0;
        for (int i = 0; i < target.length && i < base.length; i++) {

            if (target[i].equals(base[i])) {
                buf.append(target[i]).append("/");
                commonIndex++;
            } else
                break;
        }

        String common = buf.toString();

        if (commonIndex == 0) {
            // Whoops -- not even a single common path element. This most
            // likely indicates differing drive letters, like C: and D:.
            // These paths cannot be relativized. Return the target path.
            return targetURI;
            // This should never happen when all absolute paths
            // begin with / as in *nix.
        }

        String relative = "";
        if (base.length == commonIndex) {
            // Comment this out if you prefer that a relative path not start
            // with ./
            //         relative = "./";
        } else {
            int numDirsUp = base.length - commonIndex - 1;
            // The number of directories we have to backtrack is the length of
            // the base path MINUS the number of common path elements, minus
            // one because the last element in the path isn't a directory.
            for (int i = 1; i <= (numDirsUp); i++) {
                relative += "../";
            }
        }
        relative += targetPath.substring(common.length());

        try {
            return new URI(null, null, relative, targetURI.getQuery(), targetURI.getFragment());
        } catch (URISyntaxException e) {
            return targetURI;
        }
    }
}

Related

  1. getRedirectUri(URI uri, String location)
  2. getRelativeLocalURI(String suffix)
  3. getRelativeName(File file, URI directory)
  4. getRelativePath(URI base, File file)
  5. getRelativePath(URI targetUri, URI baseUri)
  6. getRelativeURI(String href)
  7. getRelativeURI(URI base, URI uri)
  8. getRelativeURI(URI repositoryXml, URI bundleJar)
  9. getRelativeUri(URI rootURI, File file)