Example usage for java.net URI getAuthority

List of usage examples for java.net URI getAuthority

Introduction

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

Prototype

public String getAuthority() 

Source Link

Document

Returns the decoded authority component of this URI.

Usage

From source file:com.buaa.cfs.utils.SecurityUtil.java

/**
 * Construct the service key for a token
 *
 * @param uri of remote connection with a token
 *
 * @return "ip:port" or "host:port" depending on the value of hadoop.security.token.service.use_ip
 *//*from   w w w . java 2  s.  c o  m*/
public static Text buildTokenService(URI uri) {
    return buildTokenService(NetUtils.createSocketAddr(uri.getAuthority()));
}

From source file:com.microsoft.alm.common.utils.UrlHelper.java

public static String getHttpsUrlFromHttpUrl(final String httpUrl) {
    final URI uri = createUri(httpUrl);
    String httpsUrl = httpUrl;//from  w w w.j  a va 2  s. co m
    if (uri != null && StringUtils.equalsIgnoreCase(uri.getScheme(), "http")) {
        final URI httpsUri = createUri("https://" + uri.getAuthority() + uri.getPath());
        httpsUrl = httpsUri.toString();
    }

    if (StringUtils.startsWithIgnoreCase(httpsUrl, "https://")) {
        return httpsUrl;
    } else {
        return null;
    }
}

From source file:org.apache.impala.common.FileSystemUtil.java

/**
 * Returns true if Path 'p' is a descendant of Path 'parent', false otherwise.
 * This function relies on Path.equals() which requires paths to have the same
 * schema and authority to compare equal. So both 'p' and 'parent' should either
 * be qualified or unqualified paths for this function to behave as expected.
 *///from   w  ww . j a v a  2 s. c o m
public static boolean isDescendantPath(Path p, Path parent) {
    if (p == null || parent == null)
        return false;
    while (!p.isRoot() && p.depth() != parent.depth())
        p = p.getParent();
    if (p.isRoot())
        return false;
    boolean result = p.equals(parent);
    if (!result && LOG.isTraceEnabled()) {
        // Add a message to the log if 'p' and 'parent' have inconsistent qualification.
        URI pUri = p.toUri();
        URI parentUri = parent.toUri();
        boolean sameScheme = Objects.equal(pUri.getScheme(), parentUri.getScheme());
        boolean sameAuthority = Objects.equal(pUri.getAuthority(), parentUri.getAuthority());
        if (!sameScheme || !sameAuthority) {
            LOG.trace("Inconsistent schema or authority for paths: " + p.toString() + " " + parent.toString());
        }
    }
    return result;
}

From source file:org.apache.hadoop.fs.http.client.HttpFSUtils.java

/**
 * Convenience method that creates an HTTP <code>URL</code> for the
 * HttpFSServer file system operations./*from  w  ww  . ja va  2  s .c  o  m*/
 * <p/>
 *
 * @param path the file path.
 * @param params the query string parameters.
 * @param multiValuedParams multi valued parameters of the query string
 *
 * @return URL a <code>URL</code> for the HttpFSServer server,
 *
 * @throws IOException thrown if an IO error occurs.
 */
static URL createURL(Path path, Map<String, String> params, Map<String, List<String>> multiValuedParams)
        throws IOException {
    URI uri = path.toUri();
    String realScheme;
    if (uri.getScheme().equalsIgnoreCase(HttpFSFileSystem.SCHEME)) {
        realScheme = "http";
    } else if (uri.getScheme().equalsIgnoreCase(HttpsFSFileSystem.SCHEME)) {
        realScheme = "https";

    } else {
        throw new IllegalArgumentException(MessageFormat.format("Invalid scheme [{0}] it should be '"
                + HttpFSFileSystem.SCHEME + "' " + "or '" + HttpsFSFileSystem.SCHEME + "'", uri));
    }
    StringBuilder sb = new StringBuilder();
    sb.append(realScheme).append("://").append(uri.getAuthority()).append(SERVICE_PATH).append(uri.getPath());

    String separator = "?";
    for (Map.Entry<String, String> entry : params.entrySet()) {
        sb.append(separator).append(entry.getKey()).append("=")
                .append(URLEncoder.encode(entry.getValue(), "UTF8"));
        separator = "&";
    }
    if (multiValuedParams != null) {
        for (Map.Entry<String, List<String>> multiValuedEntry : multiValuedParams.entrySet()) {
            String name = URLEncoder.encode(multiValuedEntry.getKey(), "UTF8");
            List<String> values = multiValuedEntry.getValue();
            for (String value : values) {
                sb.append(separator).append(name).append("=").append(URLEncoder.encode(value, "UTF8"));
                separator = "&";
            }
        }
    }
    return new URL(sb.toString());
}

From source file:org.apache.xml.security.c14n.implementations.Canonicalizer11.java

private static String joinURI(String baseURI, String relativeURI) throws URISyntaxException {
    String bscheme = null;//  w  ww.  j  av  a  2 s .com
    String bauthority = null;
    String bpath = "";
    String bquery = null;

    // pre-parse the baseURI
    if (baseURI != null) {
        if (baseURI.endsWith("..")) {
            baseURI = baseURI + "/";
        }
        URI base = new URI(baseURI);
        bscheme = base.getScheme();
        bauthority = base.getAuthority();
        bpath = base.getPath();
        bquery = base.getQuery();
    }

    URI r = new URI(relativeURI);
    String rscheme = r.getScheme();
    String rauthority = r.getAuthority();
    String rpath = r.getPath();
    String rquery = r.getQuery();
    String rfragment = null;

    String tscheme, tauthority, tpath, tquery, tfragment;
    if (rscheme != null && rscheme.equals(bscheme)) {
        rscheme = null;
    }
    if (rscheme != null) {
        tscheme = rscheme;
        tauthority = rauthority;
        tpath = removeDotSegments(rpath);
        tquery = rquery;
    } else {
        if (rauthority != null) {
            tauthority = rauthority;
            tpath = removeDotSegments(rpath);
            tquery = rquery;
        } else {
            if (rpath.length() == 0) {
                tpath = bpath;
                if (rquery != null) {
                    tquery = rquery;
                } else {
                    tquery = bquery;
                }
            } else {
                if (rpath.startsWith("/")) {
                    tpath = removeDotSegments(rpath);
                } else {
                    if (bauthority != null && bpath.length() == 0) {
                        tpath = "/" + rpath;
                    } else {
                        int last = bpath.lastIndexOf('/');
                        if (last == -1) {
                            tpath = rpath;
                        } else {
                            tpath = bpath.substring(0, last + 1) + rpath;
                        }
                    }
                    tpath = removeDotSegments(tpath);
                }
                tquery = rquery;
            }
            tauthority = bauthority;
        }
        tscheme = bscheme;
    }
    tfragment = rfragment;
    return new URI(tscheme, tauthority, tpath, tquery, tfragment).toString();
}

From source file:org.eclipse.orion.internal.server.servlets.file.ServletFileStoreHandler.java

public static JSONObject toJSON(IFileStore store, IFileInfo info, URI location) {
    JSONObject result = new JSONObject();
    try {/*w w w.  j av  a2  s  .c o  m*/
        result.put(ProtocolConstants.KEY_NAME, info.getName());
        result.put(ProtocolConstants.KEY_LOCAL_TIMESTAMP, info.getLastModified());
        result.put(ProtocolConstants.KEY_DIRECTORY, info.isDirectory());
        result.put(ProtocolConstants.KEY_LENGTH, info.getLength());
        if (location != null) {
            result.put(ProtocolConstants.KEY_LOCATION, location);
            if (info.isDirectory())
                try {
                    result.put(ProtocolConstants.KEY_CHILDREN_LOCATION, new URI(location.getScheme(),
                            location.getAuthority(), location.getPath(), "depth=1", location.getFragment())); //$NON-NLS-1$
                } catch (URISyntaxException e) {
                    throw new RuntimeException(e);
                }
        }
        result.put(ProtocolConstants.KEY_ATTRIBUTES, getAttributes(store, info));
    } catch (JSONException e) {
        //cannot happen because the key is non-null and the values are strings
        throw new RuntimeException(e);
    }
    return result;
}

From source file:mitm.common.util.URIUtils.java

/**
 * Checks whether the given identifier is a valid URI. If type is null, a FULL check will be done.
 * If identifier is null, false will be returned.
 *///from  w w  w .  j  a  v a 2 s  . c om
public static boolean isValidURI(String identifier, URIType type) {
    if (identifier == null) {
        return false;
    }

    if (type == null) {
        type = URIType.FULL;
    }

    boolean valid = false;

    try {
        URI uri = new URI(identifier);

        if (type == URIType.BASE) {
            /*
             * Only accepts URI of the form [scheme:][//authority][path]
             */
            if (StringUtils.isNotEmpty(uri.getScheme()) && StringUtils.isNotEmpty(uri.getHost())
                    && StringUtils.isEmpty(uri.getQuery()) && StringUtils.isEmpty(uri.getFragment())) {
                valid = true;
            }
        } else if (type == URIType.RELATIVE) {
            /*
             * Only accepts URI of the form [path][?query][#fragment] 
             */
            if (StringUtils.isEmpty(uri.getScheme()) && StringUtils.isEmpty(uri.getAuthority())
                    && StringUtils.isEmpty(uri.getHost())) {
                valid = true;
            }
        } else if (type == URIType.FULL) {
            /*
             * Only accepts URI of the form [scheme:][//authority][path][?query][#fragment] 
             */
            if (StringUtils.isNotEmpty(uri.getScheme()) && StringUtils.isNotEmpty(uri.getHost())) {
                valid = true;
            }
        } else {
            valid = true;
        }

    } catch (URISyntaxException e) {
        // ignore
    }

    return valid;
}

From source file:org.apache.distributedlog.util.DLUtils.java

/**
 * Normalize the uri.//from   ww  w .  ja v a2s  .c  o m
 *
 * @param uri the distributedlog uri.
 * @return the normalized uri
 */
public static URI normalizeURI(URI uri) {
    checkNotNull(uri, "DistributedLog uri is null");
    String scheme = uri.getScheme();
    checkNotNull(scheme, "Invalid distributedlog uri : " + uri);
    scheme = scheme.toLowerCase();
    String[] schemeParts = StringUtils.split(scheme, '-');
    checkArgument(Objects.equal(DistributedLogConstants.SCHEME_PREFIX, schemeParts[0].toLowerCase()),
            "Unknown distributedlog scheme found : " + uri);
    URI normalizedUri;
    try {
        normalizedUri = new URI(schemeParts[0], // remove backend info
                uri.getAuthority(), uri.getPath(), uri.getQuery(), uri.getFragment());
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("Invalid distributedlog uri found : " + uri, e);
    }
    return normalizedUri;
}

From source file:org.opencms.site.xmlsitemap.CmsXmlSitemapGenerator.java

/**
 * Replaces the protocol/host/port of a link with the ones from the given server URI, if it's not empty.<p>
 *
 * @param link the link to change/*from  w  w  w.j  av  a 2s  .com*/
 * @param server the server URI string
        
 * @return the changed link
 */
public static String replaceServerUri(String link, String server) {

    String serverUriStr = server;

    if (CmsStringUtil.isEmptyOrWhitespaceOnly(serverUriStr)) {
        return link;
    }
    try {
        URI serverUri = new URI(serverUriStr);
        URI linkUri = new URI(link);
        URI result = new URI(serverUri.getScheme(), serverUri.getAuthority(), linkUri.getPath(),
                linkUri.getQuery(), linkUri.getFragment());
        return result.toString();
    } catch (URISyntaxException e) {
        LOG.error(e.getLocalizedMessage(), e);
        return link;
    }

}

From source file:org.apache.pulsar.common.net.ServiceURI.java

/**
 * Create a service uri instance from a {@link URI} instance.
 *
 * @param uri {@link URI} instance/* ww w . j  a va2s .  c o m*/
 * @return a service uri instance
 * @throws NullPointerException if {@code uriStr} is null
 * @throws IllegalArgumentException if the given string violates RFC&nbsp;2396
 */
public static ServiceURI create(URI uri) {
    checkNotNull(uri, "service uri instance is null");

    String serviceName;
    final String[] serviceInfos;
    String scheme = uri.getScheme();
    if (null != scheme) {
        scheme = scheme.toLowerCase();
        final String serviceSep = "+";
        String[] schemeParts = StringUtils.split(scheme, serviceSep);
        serviceName = schemeParts[0];
        serviceInfos = new String[schemeParts.length - 1];
        System.arraycopy(schemeParts, 1, serviceInfos, 0, serviceInfos.length);
    } else {
        serviceName = null;
        serviceInfos = new String[0];
    }

    String userAndHostInformation = uri.getAuthority();
    checkArgument(!Strings.isNullOrEmpty(userAndHostInformation),
            "authority component is missing in service uri : " + uri);

    String serviceUser;
    List<String> serviceHosts;
    int atIndex = userAndHostInformation.indexOf('@');
    Splitter splitter = Splitter.on(CharMatcher.anyOf(",;"));
    if (atIndex > 0) {
        serviceUser = userAndHostInformation.substring(0, atIndex);
        serviceHosts = splitter.splitToList(userAndHostInformation.substring(atIndex + 1));
    } else {
        serviceUser = null;
        serviceHosts = splitter.splitToList(userAndHostInformation);
    }
    serviceHosts = serviceHosts.stream().map(host -> validateHostName(serviceName, serviceInfos, host))
            .collect(Collectors.toList());

    String servicePath = uri.getPath();
    checkArgument(null != servicePath, "service path component is missing in service uri : " + uri);

    return new ServiceURI(serviceName, serviceInfos, serviceUser,
            serviceHosts.toArray(new String[serviceHosts.size()]), servicePath, uri);
}