Example usage for java.net URI normalize

List of usage examples for java.net URI normalize

Introduction

In this page you can find the example usage for java.net URI normalize.

Prototype

public URI normalize() 

Source Link

Document

Normalizes this URI's path.

Usage

From source file:org.wso2.carbon.identity.provider.openid.util.OpenIDUtil.java

/**
 * Normalize the provided relying party URL
 *
 * @param rpUrl Relying party URL to be normalized
 * @return Normalized relying party URL/*from  w  ww  .  j a va  2 s.c  o m*/
 * @throws IdentityException
 */
public static String getRelyingPartyUrl(String rpUrl) throws IdentityException {
    URI uri = null;
    URL url = null;

    try {
        uri = new URI(rpUrl);
    } catch (URISyntaxException e) {
        log.error("Invalid relying party URL :" + rpUrl, e);
        throw new IdentityException("Invalid relying party URL");
    }

    try {
        url = uri.normalize().toURL();
        url = new URL(url.getProtocol().toLowerCase(), url.getHost().toLowerCase(), url.getPort(),
                url.getPath());
        return url.toString();
    } catch (MalformedURLException e) {
        log.error("Malformed relying party URL :" + rpUrl, e);
        throw new IdentityException("Malformed relying party URL");
    }
}

From source file:org.wso2.carbon.identity.provider.openid.OpenIDUtil.java

/**
 * Generate OpenID for a given user.//from w  w w . j a  v  a 2s .  c  om
 *
 * @param user User
 * @return Generated OpenID
 * @throws IdentityProviderException
 */
public static String generateOpenID(String user) throws IdentityProviderException {

    ServerConfiguration serverConfig = null;
    String openIDUserUrl = null;
    String openID = null;
    URI uri = null;
    URL url = null;
    String encodedUser = null;

    serverConfig = ServerConfiguration.getInstance();
    openIDUserUrl = getOpenIDServerURL();

    encodedUser = normalizeUrlEncoding(user);

    openID = String.format(openIDUserUrl, encodedUser);

    try {
        uri = new URI(openID);
    } catch (URISyntaxException e) {
        log.error("Invalid OpenID URL :" + openID, e);
        throw new IdentityProviderException("Invalid OpenID URL :" + openID, e);
    }

    try {
        url = uri.normalize().toURL();
        if (url.getQuery() != null || url.getRef() != null) {
            log.error("Invalid user name for OpenID :" + openID);
            throw new IdentityProviderException("Invalid user name for OpenID :" + openID);
        }
    } catch (MalformedURLException e) {
        log.error("Malformed OpenID URL :" + openID, e);
        throw new IdentityProviderException("Malformed OpenID URL :" + openID, e);
    }

    openID = url.toString();

    if (log.isDebugEnabled()) {
        log.debug("OpenID generated successfully : " + openID);
    }

    return openID;
}

From source file:org.wso2.carbon.identity.provider.openid.util.OpenIDUtil.java

/**
 * Generate OpenID for a given user.//from   w w w. j  a va2 s  . c o  m
 *
 * @param user User
 * @return Generated OpenID
 * @throws IdentityProviderException
 */
public static String generateOpenID(String user, String openIDUserUrl) throws IdentityException {
    String openID = null;
    URI uri = null;
    URL url = null;

    String normalizedUser = normalizeUrlEncoding(user);
    openID = String.format(openIDUserUrl, normalizedUser);

    try {
        uri = new URI(openID);
    } catch (URISyntaxException e) {
        log.error("Invalid OpenID URL :" + openID, e);
        throw new IdentityException("Invalid OpenID URL");
    }

    try {
        url = uri.normalize().toURL();
        if (url.getQuery() != null || url.getRef() != null) {
            log.error("Invalid user name for OpenID :" + openID);
            throw new IdentityException("Invalid user name for OpenID");
        }
    } catch (MalformedURLException e) {
        log.error("Malformed OpenID URL :" + openID, e);
        throw new IdentityException("Malformed OpenID URL");
    }

    openID = url.toString();

    if (log.isDebugEnabled()) {
        log.debug("OpenID generated successfully : " + openID);
    }

    return openID;
}

From source file:eu.asterics.mw.services.ResourceRegistry.java

/**
 * Compares equalness of the given URIs. Before comparison the URIs are normalized.
 * @param first// w w  w  .  j  ava  2s .  c o m
 * @param second
 * @return
 */
public static boolean equalsNormalizedURIs(URI first, URI second) {
    URI fnorm = first.normalize();
    URI fsecond = second.normalize();
    return first.normalize().equals(second.normalize());
}

From source file:eu.asterics.mw.services.ResourceRegistry.java

/**
 * Checks if the given uri points to a subpath of the given baseURI URI. 
 * @param baseURI// w  ww.j  av a 2s  . com
 * @param toTest
 * @return
 */
public static boolean isSubURI(URI baseURI, URI toTest) {
    URI relativeURI = baseURI.normalize().relativize(toTest.normalize());
    return !relativeURI.isAbsolute();
}

From source file:org.apache.sentry.core.common.utils.PathUtils.java

/**
 * URI is a a special case. For URI's, /a implies /a/b.
 * Therefore the test is "/a/b".startsWith("/a");
 *//*from w  w w .j  a  va2 s .co m*/
public static boolean impliesURI(URI privilegeURI, URI requestURI) throws URISyntaxException {
    if (privilegeURI.getPath() == null || requestURI.getPath() == null) {
        return false;
    }
    // ensure that either both schemes are null or equal
    if (privilegeURI.getScheme() == null) {
        if (requestURI.getScheme() != null) {
            return false;
        }
    } else if (!privilegeURI.getScheme().equals(requestURI.getScheme())) {
        return false;
    }
    // request path does not contain relative parts /a/../b &&
    // request path starts with privilege path &&
    // authorities (nullable) are equal
    String requestPath = ensureEndsWithSeparator(requestURI.getPath()).replace("//", "/");
    String privilegePath = ensureEndsWithSeparator(privilegeURI.getPath()).replace("//", "/");
    if (requestURI.getPath().equals(requestURI.normalize().getPath()) && requestPath.startsWith(privilegePath)
            && Strings.nullToEmpty(privilegeURI.getAuthority())
                    .equals(Strings.nullToEmpty(requestURI.getAuthority()))) {
        return true;
    }
    return false;
}

From source file:net.sf.ufsc.AbstractSession.java

public AbstractSession(URI uri) {
    this.uri = uri.normalize();
}

From source file:fr.eolya.utils.http.HttpUtils.java

public static String urlNormalize(String url, String preferedHost) {

    String ret_url = url.trim();/* w  w  w.ja  v  a  2  s.  c  o m*/

    // Perform some url nomalizations described here : http://en.wikipedia.org/wiki/URL_normalization

    try {
        // Remove last "/" - NO !!!
        //if (ret_url.lastIndexOf("/") == ret_url.length()-1)
        //   ret_url = ret_url.substring(0, ret_url.length()-1); 

        // Remove final "?" if unique in url -     http://www.example.com/display? -> http://www.example.com/display 
        if (ret_url.lastIndexOf("?") == ret_url.length() - 1)
            ret_url = ret_url.substring(0, ret_url.length() - 1);

        // Fix "?&"
        int index = ret_url.indexOf("?&");
        //int l = ret_url.length()-2;
        if (index != -1) {
            if (index != ret_url.length() - 2) {
                ret_url = ret_url.substring(0, index + 1) + ret_url.substring(index + 2);
            } else {
                ret_url = ret_url.substring(0, ret_url.length() - 2);
            }
        }

        // Replace "&" by "&"
        ret_url = StringEscapeUtils.unescapeHtml4(ret_url);

        // Replace " " by "%20"
        ret_url = ret_url.replace(" ", "%20");

        // Replace "'" by "%27"
        ret_url = ret_url.replace("'", "%27");

        // Replace "%5F" by "_"
        ret_url = ret_url.replace("%5f", "_");
        ret_url = ret_url.replace("%5F", "_");

        // Remove dot-segments.
        // http://www.example.com/../a/b/../c/./d.html => http://www.example.com/a/c/d.html           
        URI uri = new URI(ret_url);
        uri = uri.normalize();
        ret_url = uri.toURL().toExternalForm();

        // Remove dot-segments at the beginning of the path
        // http://www.example.com/../a/d.html => http://www.example.com/a/d.html           
        URL tempUrl = new URL(ret_url);
        String path = tempUrl.getFile();
        String pattern = "";
        while (path.startsWith("/../")) {
            path = path.substring(3);
            pattern += "/..";
        }
        if (!pattern.equals("")) {
            index = ret_url.indexOf(pattern);
            ret_url = ret_url.substring(0, index) + ret_url.substring(index + pattern.length());
        }

        // Remove default port
        if (ret_url.indexOf("http://" + uri.getHost() + ":80") != -1) {
            ret_url = ret_url.replace("//" + uri.getHost() + ":80", "//" + uri.getHost());
        }
        if (ret_url.indexOf("https://" + uri.getHost() + ":443") != -1) {
            ret_url = ret_url.replace("//" + uri.getHost() + ":443", "//" + uri.getHost());
        }

        // translate to prefered host (www.site.com vs site.com)
        if (preferedHost != null && !"".equals(preferedHost)) {
            if (uri.getHost().equals("www." + preferedHost) || ("www." + uri.getHost()).equals(preferedHost)) {
                ret_url = ret_url.replace("//" + uri.getHost(), "//" + preferedHost);
            }
        }

        // Remove the fragment.
        // http://www.example.com/bar.html#section1 => http://www.example.com/bar.html 
        if (ret_url.indexOf("#") != -1)
            ret_url = ret_url.substring(0, ret_url.indexOf("#"));

        // Reorder parameters in query string
        //ret_url = urlReorderParameters (ret_url);

        return ret_url;
    } catch (Exception e) {
    }

    return ret_url;
}

From source file:com.evolveum.midpoint.prism.schema.CatalogImpl.java

/**
 * This fixes catalog items. When launched as spring boot fat jar, catalog by default resolve URIs like
 * <p>//from   w  w w . j  av  a  2  s. c o m
 * jar:file:/SOME_ABSOLUTE_PATH/midpoint.war!/WEB-INF/lib/schema-3.7-SNAPSHOT.jar!/META-INF/../xml/ns/public/common/common-core-3.xsd
 * <p>
 * which looks at first sight, but correct working version is:
 * <p>
 * jar:file:/SOME_ABSOLUTE_PATH/midpoint.war!/WEB-INF/lib/schema-3.7-SNAPSHOT.jar!/xml/ns/public/common/common-core-3.xsd
 * <p>
 * This catalog impl is enabled only when in spring boot fat jar is launched through main() using:
 * <p>
 * System.setProperty("xml.catalog.className", CatalogImpl.class.getName());
 */
@Override
protected String makeAbsolute(String sysid) {
    String absolute = super.makeAbsolute(sysid);

    if (absolute == null) {
        return null;
    }

    String[] array = absolute.split("!/");
    if (array.length <= 1) {
        return absolute;
    }

    String[] normalized = new String[array.length];
    for (int i = 0; i < array.length; i++) {
        String part = array[i];

        URI uri = java.net.URI.create(part);
        uri = uri.normalize();

        normalized[i] = uri.toString();
    }

    String newAbsolute = StringUtils.join(normalized, "!/");

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Normalized absolute path from '{}' to '{}'", absolute, newAbsolute);
    }

    return newAbsolute;
}

From source file:org.xenmaster.web.TemplateHook.java

@Override
public void handle(RequestBundle rb) throws IOException {
    if (rb.getPathParts().length < 1) {
        return;//from w ww.  j  a v  a  2s.  c  o m
    }
    String path = "";
    try {
        String concat = StringUtils.join(rb.getPathParts(), '/');
        URI uri = new URI(concat);
        uri = uri.normalize();
        path = uri.getPath();
    } catch (URISyntaxException ex) {
        Logger.getLogger(getClass()).error(ex);
    }
    if (path.isEmpty()) {
        return;
    }

    path = Settings.getInstance().getString("WebContentPath") + "/" + this.getSelector() + "/" + path;
    File f = new File(path);
    if (f.exists() && f.isDirectory()) {
        Path p = f.toPath();
        JsonObject contentTree = new JsonObject();
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(p)) {
            for (Path file : stream) {
                if (file.toFile().isFile() && !file.startsWith(".")) {
                    contentTree.addProperty(FilenameUtils.getBaseName(file.toString()),
                            IOUtils.toString(new FileInputStream(file.toFile())));
                }
            }
        }
        Gson gson = new Gson();
        rb.replyWithString(gson.toJson(contentTree));
    }
}