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:eu.eubrazilcc.lvl.core.util.UrlUtils.java

/**
 * Returns a list of name-value pairs as built from the URI's query portion.
 * @param uri - input URI//from ww  w . ja va 2s  . co m
 * @return a list of name-value pairs as built from the URI's query portion.
 * @throws IllegalArgumentException If a malformed URI occurs.
 */
public static Map<String, String> getQueryParams(final URI uri) {
    checkArgument(uri != null, "Uninitialized URI");
    try {
        final URI nUri = uri.normalize();
        final URL url = nUri.isAbsolute() ? nUri.toURL()
                : new URL(new URL("http://example.org/"), nUri.toString());
        final String query = new URL(URLDecoder.decode(url.toString(), defaultCharset().name())).getQuery();
        final Map<String, String> map = newHashMap();
        final List<NameValuePair> pairs = URLEncodedUtils.parse(query, defaultCharset());
        final Iterator<NameValuePair> iterator = pairs.iterator();
        while (iterator.hasNext()) {
            final NameValuePair pair = iterator.next();
            map.put(pair.getName(), pair.getValue());
        }
        return map;
    } catch (MalformedURLException | UnsupportedEncodingException e) {
        throw new IllegalArgumentException("Malformed URI", e);
    }
}

From source file:com.msopentech.odatajclient.engine.utils.URIUtils.java

/**
 * Build URI starting from the given base and href.
 * <br/>//w ww.ja  v a 2 s .c o  m
 * If href is absolute or base is null then base will be ignored.
 *
 * @param base URI prefix.
 * @param href URI suffix.
 * @return built URI.
 */
public static URI getURI(final String base, final String href) {
    if (href == null) {
        throw new IllegalArgumentException("Null link provided");
    }

    URI uri = URI.create(href);

    if (!uri.isAbsolute() && base != null) {
        uri = URI.create(base + "/" + href);
    }

    return uri.normalize();
}

From source file:com.msopentech.odatajclient.engine.utils.URIUtils.java

/**
 * Build URI starting from the given base and href.
 * <br/>/* w  w  w .j av  a2s.  co  m*/
 * If href is absolute or base is null then base will be ignored.
 *
 * @param base URI prefix.
 * @param href URI suffix.
 * @return built URI.
 */
public static URI getURI(final URI base, final String href) {
    if (href == null) {
        throw new IllegalArgumentException("Null link provided");
    }

    URI uri = URI.create(href);

    if (!uri.isAbsolute() && base != null) {
        uri = URI.create(base.toASCIIString() + "/" + href);
    }

    return uri.normalize();
}

From source file:org.eel.kitchen.jsonschema.ref.JsonRef.java

/**
 * Build a JSON Reference from a URI// ww w . ja v a2 s  . co m
 *
 * @param uri the provided URI
 * @return the JSON Reference
 * @throws NullPointerException the provided URI is null
 */
public static JsonRef fromURI(final URI uri) {
    Preconditions.checkNotNull(uri, "URI must not be null");

    final URI normalized = uri.normalize();

    if (HASHONLY_URI.equals(normalized) || EMPTY_URI.equals(normalized))
        return EmptyJsonRef.getInstance();

    return "jar".equals(normalized.getScheme()) ? new JarJsonRef(normalized)
            : new HierarchicalJsonRef(normalized);
}

From source file:com.legstar.codegen.tasks.SourceToXsdCobolTask.java

/**
 * Converts a URI into a package name. We assume a hierarchical,
 * server-based URI with the following syntax:
 * [scheme:][//host[:port]][path][?query][#fragment]
 * The package name is derived from host, path and fragment.
 * /*  ww  w .j  a v  a 2  s. c om*/
 * @param namespaceURI the input namespace URI
 * @return the result package name
 */
public static String packageFromURI(final URI namespaceURI) {

    StringBuilder result = new StringBuilder();
    URI nURI = namespaceURI.normalize();
    boolean firstToken = true;

    /*
     * First part of package name is built from host with tokens in
     * reverse order.
     */
    if (nURI.getHost() != null && nURI.getHost().length() != 0) {
        Vector<String> v = new Vector<String>();
        StringTokenizer t = new StringTokenizer(nURI.getHost(), ".");
        while (t.hasMoreTokens()) {
            v.addElement(t.nextToken());
        }

        for (int i = v.size(); i > 0; i--) {
            if (!firstToken) {
                result.append('.');
            } else {
                firstToken = false;
            }
            result.append(v.get(i - 1));
        }
    }

    /* Next part of package is built from the path tokens */
    if (nURI.getPath() != null && nURI.getPath().length() != 0) {
        Vector<String> v = new Vector<String>();
        StringTokenizer t = new StringTokenizer(nURI.getPath(), "/");
        while (t.hasMoreTokens()) {
            v.addElement(t.nextToken());
        }

        for (int i = 0; i < v.size(); i++) {
            String token = v.get(i);
            /* ignore situations such as /./../ */
            if (token.equals(".") || token.equals("..")) {
                continue;
            }
            if (!firstToken) {
                result.append('.');
            } else {
                firstToken = false;
            }
            result.append(v.get(i));
        }
    }

    /* Finally append any fragment */
    if (nURI.getFragment() != null && nURI.getFragment().length() != 0) {
        if (!firstToken) {
            result.append('.');
        } else {
            firstToken = false;
        }
        result.append(nURI.getFragment());
    }

    /*
     * By convention, namespaces are lowercase and should not contain
     * invalid Java identifiers
     */
    String s = result.toString().toLowerCase();
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < s.length(); i++) {
        Character c = s.charAt(i);
        if (Character.isJavaIdentifierPart(c) || c.equals('.')) {
            sb.append(c);
        } else {
            sb.append("_");
        }
    }
    return sb.toString();
}

From source file:org.apache.pig.backend.hadoop.executionengine.physicalLayer.util.PlanHelper.java

/**
 * Creates a relative path that can be used to build a temporary
 * place to store the output from a number of map-reduce tasks.
 *///  www  .j  a v a 2 s  .  c  om
public static String makeStoreTmpPath(String orig) {
    Path path = new Path(orig);
    URI uri = path.toUri();
    uri.normalize();

    String pathStr = uri.getPath();
    if (path.isAbsolute()) {
        return new Path("abs" + pathStr).toString();
    } else {
        return new Path("rel/" + pathStr).toString();
    }
}

From source file:org.apache.openmeetings.web.pages.auth.SignInPage.java

public static String getRedirectUri(OAuthServer server, Component component) {
    String result = "";
    if (server.getId() != null) {
        try {//from   w w  w  .j a  v a2s.co  m
            String base = getBean(ConfigurationDao.class).getBaseUrl();
            URI uri = new URI(base
                    + component.urlFor(SignInPage.class, new PageParameters().add("oauthid", server.getId())));
            result = uri.normalize().toString();
        } catch (URISyntaxException e) {
            log.error("Unexpected error while getting redirect URL", e);
        }
    }
    return result;
}

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

/**
 * When the RP hosted Tomcat is behind an Apache serever, OpenID verification fails since
 * return_to url mismatches with the returning url. To avoid that - only when the Tomcat is
 * behind an Apache frontend we need to provide a host/port mapping in the web.xml.
 * //from   w ww . j  a va  2 s. co m
 * @param returnUrl
 * @param data
 * @return mapped returing irl
 * @throws RelyingPartyException
 */
public static String getMappedReturningUrl(String returnUrl, OpenIDRelyingPartyData data)
        throws RelyingPartyException {

    URI uri = null;
    URL url = null;
    String hostName = null;
    int portNumber;

    try {
        uri = new URI(returnUrl);
    } catch (URISyntaxException e) {
        log.error("Return_to url is not in the correct syntax", e);
        throw new RelyingPartyException("Return_to url is not in the correct syntax", e);
    }

    try {
        url = uri.normalize().toURL();
    } catch (MalformedURLException e) {
        log.error("Return_to url is malformed", e);
        throw new RelyingPartyException("Return_to url is malformed", e);
    }

    hostName = url.getHost();
    portNumber = url.getPort();

    if (log.isDebugEnabled()) {
        log.debug("Hostname in the received return_to url:" + hostName);
        log.debug("Port number in the received return_to url:" + portNumber);
    }

    if (data != null) {

        if (log.isDebugEnabled()) {
            log.debug("Mapped host name facing Apache:" + data.getMappedHostName());
            log.debug("Mapped port number facing Apache:" + data.getMappedPortNumber());
            log.debug("Mapping host name facing Apache:" + data.getMappingHostName());
            log.debug("Mapping port number facing Apache:" + data.getMappingPortNumber());
        }

        if (data.getMappedHostName() != null && data.getMappingHostName() != null) {
            if (data.getMappingHostName().equals(url.getHost())) {
                hostName = data.getMappedHostName();
            }
        }

        if (data.getMappedPortNumber() != null && data.getMappingPortNumber() != null) {
            if (Integer.parseInt(data.getMappingPortNumber()) == url.getPort()) {
                portNumber = Integer.parseInt(data.getMappedPortNumber());
            }
        }
    }

    try {

        if ((url.getProtocol().toLowerCase().equals("http") && portNumber == 80)
                || (url.getProtocol().toLowerCase().equals("https") && portNumber == 443)) {
            url = new URL(url.getProtocol().toLowerCase(), hostName, url.getPath());
        } else {
            url = new URL(url.getProtocol().toLowerCase(), hostName, portNumber, url.getPath());
        }

        if (log.isDebugEnabled()) {
            log.debug("Formatted return_to url : " + url.toString());
        }

        return url.toString();
    } catch (MalformedURLException e) {
        log.error("Return_to url is malformed", e);
        throw new RelyingPartyException("Return_to url is malformed", e);
    }
}

From source file:org.wso2.carbon.identity.sso.saml.common.Util.java

/**
 * Generate OpenID for a given user.//from www . j av a  2  s.  c om
 *
 * @param user User
 * @return Generated OpenID
 * @throws org.wso2.carbon.identity.base.IdentityException
 */
public static String generateOpenID(String user) throws IdentityException {
    String openIDUserUrl = null;
    String openID = null;
    URI uri = null;
    URL url = null;
    openIDUserUrl = IdentityUtil.getProperty(IdentityConstants.ServerConfig.OPENID_USER_PATTERN);
    user = normalizeUrlEncoding(user);
    openID = openIDUserUrl + user;
    try {
        uri = new URI(openID);
    } catch (URISyntaxException e) {
        throw new IdentityException("Invalid OpenID URL :" + openID, e);
    }
    try {
        url = uri.normalize().toURL();
        if (url.getQuery() != null || url.getRef() != null) {
            throw new IdentityException("Invalid user name for OpenID :" + openID);
        }
    } catch (MalformedURLException e) {
        throw new IdentityException("Malformed OpenID URL :" + openID, e);
    }
    openID = url.toString();
    return openID;
}

From source file:org.omnaest.utils.download.URIHelper.java

/**
 * Creates a new {@link Uri} which is based on the given base address and a relative path
 * /*from  w w  w . j  av  a  2  s.com*/
 * @param baseAddress
 * @param relativePath
 * @return
 */
public static URI createUri(URI baseAddress, String relativePath) {
    //
    URI retval = null;

    //
    if (baseAddress != null && relativePath != null) {
        try {
            //
            String baseAddressAsString = baseAddress.toString();
            if (!baseAddressAsString.endsWith("/")) {
                baseAddress = new URI(baseAddress.toString() + "/");
            }

            //
            relativePath = StringUtils.removeStart(relativePath, "/");

            //
            retval = baseAddress.normalize().resolve(relativePath).normalize();
        } catch (Exception e) {
        }
    }

    //
    return retval;
}