Make a relative copy of a URI. - Java Network

Java examples for Network:URL

Description

Make a relative copy of a URI.

Demo Code

/* Licensed Materials - Property of IBM                              */
//package com.java2s;
import java.net.URI;

public class Main {
    /**// w  w w .jav a  2 s.c  o m
     * Make a relative copy of a URI.
     * 
     * <p>If makeRelative is false, this may return the original instance.
     * That should be OK because a URI is immutable.
     * 
     * @param original
     * @param makeRelative
     * @return
     */
    public static URI copy(URI original, boolean makeRelative) {
        URI uri = original;

        if (uri.isAbsolute() && makeRelative) {
            String rel = uri.getRawPath();
            if (uri.getQuery() != null) {
                rel += "?" + uri.getRawQuery();
            }
            uri = URI.create(rel);
        }

        return uri;
    }

    /**
     * Creates a new URI from a string.
     * 
     * <p>WARNING: If the input string is not a legal URI, this method
     * will throw an unchecked exception.
     * 
     * @param str
     * @param makeRelative
     * @return
     */
    public static URI create(String str, boolean makeRelative) {
        URI uri = URI.create(str);

        if (uri.isAbsolute() && makeRelative) {
            uri = copy(uri, true);
        }

        return uri;
    }
}

Related Tutorials