Example usage for java.net URI getHost

List of usage examples for java.net URI getHost

Introduction

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

Prototype

public String getHost() 

Source Link

Document

Returns the host component of this URI.

Usage

From source file:com.google.cloud.hadoop.util.HttpTransportFactory.java

/**
 * Parse an HTTP proxy from a String address.
 * @param proxyAddress The address of the proxy of the form (https?://)HOST:PORT.
 * @return The URI of the proxy.//from www  .  ja  va  2s. com
 * @throws IllegalArgumentException If the address is invalid.
 */
@VisibleForTesting
static URI parseProxyAddress(@Nullable String proxyAddress) {
    if (Strings.isNullOrEmpty(proxyAddress)) {
        return null;
    }
    String uriString = proxyAddress;
    if (!uriString.contains("//")) {
        uriString = "//" + uriString;
    }
    try {
        URI uri = new URI(uriString);
        String scheme = uri.getScheme();
        String host = uri.getHost();
        int port = uri.getPort();
        if (!Strings.isNullOrEmpty(scheme) && !scheme.matches("https?")) {
            throw new IllegalArgumentException(
                    String.format("HTTP proxy address '%s' has invalid scheme '%s'.", proxyAddress, scheme));
        } else if (Strings.isNullOrEmpty(host)) {
            throw new IllegalArgumentException(String.format("Proxy address '%s' has no host.", proxyAddress));
        } else if (port == -1) {
            throw new IllegalArgumentException(String.format("Proxy address '%s' has no port.", proxyAddress));
        } else if (!uri.equals(new URI(scheme, null, host, port, null, null, null))) {
            throw new IllegalArgumentException(String.format("Invalid proxy address '%s'.", proxyAddress));
        }
        return uri;
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(String.format("Invalid proxy address '%s'.", proxyAddress), e);
    }
}

From source file:org.exoplatform.utils.ExoUtils.java

/**
 * Extract a name from a Server URL by keeping the 1st part of the FQDN,
 * between the protocol and the first dot or the end of the URL. It is then
 * capitalized. If an IP address is given instead, it is used as-is. Examples:
 * <ul>//from   w w  w .j a v  a 2 s .com
 * <li>http://int.exoplatform.com => Int</li>
 * <li>http://community.exoplatform.com => Community</li>
 * <li>https://mycompany.com => Mycompany</li>
 * <li>https://intranet.secure.mycompany.co.uk => Intranet</li>
 * <li>http://localhost => Localhost</li>
 * <li>http://192.168.1.15 => 192.168.1.15</li>
 * </ul>
 * 
 * @param url the Server URL
 * @param defaultName a default name in case it is impossible to extract
 * @return a name
 */
public static String getAccountNameFromURL(String url, String defaultName) {
    String finalName = defaultName;
    if (url != null && !url.isEmpty()) {
        if (!url.startsWith("http"))
            url = ExoConnectionUtils.HTTP + url;
        try {
            URI theURL = new URI(url);
            finalName = theURL.getHost();
            if (!isCorrectIPAddress(finalName)) {
                int firstDot = finalName.indexOf('.');
                if (firstDot > 0) {
                    finalName = finalName.substring(0, firstDot);
                }
                // else, no dot was found in the host,
                // return the hostname as is, e.g. localhost
            }
            // else, URL is an IP address, return it as is
        } catch (URISyntaxException e) {
            finalName = defaultName;
        } catch (IndexOutOfBoundsException e) {
            finalName = defaultName;
        }
    }
    return capitalize(finalName);
}

From source file:com.qwazr.cluster.manager.ClusterNode.java

private static URI toUri(String address) throws URISyntaxException {
    if (!address.contains("//"))
        address = "//" + address;
    URI u = new URI(address);
    return new URI(StringUtils.isEmpty(u.getScheme()) ? "http" : u.getScheme(), null, u.getHost(), u.getPort(),
            null, null, null);//w w w.  ja  v  a2s .co  m
}

From source file:com.meltmedia.cadmium.servlets.AbstractSecureRedirectStrategy.java

/**
 * Returns a new URI object, based on the specified URI template, with an updated port (scheme) and port.  If the port
 * number is -1, then the default port is used in the resulting URI. 
 * //from  w  w  w  . java 2 s  .  co  m
 * @param protocol the new protocol (scheme) in the resulting URI.
 * @param port the new port in the resulting URI, or the default port if -1 is provided.
 * @param template the source of all other values for the new URI.
 * @return a new URI object with the updated protocol and port.
 * @throws URISyntaxException 
 */
public static URI changeProtocolAndPort(String protocol, int port, URI template) throws URISyntaxException {
    return new URI(protocol, template.getUserInfo(), template.getHost(), port, template.getPath(),
            template.getQuery(), null);
}

From source file:core.com.qiniu.regions.RegionUtils.java

/**
 * Get the URI object for the given endpoint. URI class cannot correctly
 * parse the endpoint if it doesn't include protocol. This method will add
 * the protocol if this happens./*from   ww  w .j  a  va  2  s  .  c  om*/
 */
private static URI getUriByEndpoint(String endpoint) {
    URI targetEndpointUri = null;
    try {
        targetEndpointUri = new URI(endpoint);
        if (targetEndpointUri.getHost() == null) {
            targetEndpointUri = new URI("http://" + endpoint);
        }
    } catch (URISyntaxException e) {
        throw new RuntimeException("Unable to parse service endpoint: " + e.getMessage());
    }
    return targetEndpointUri;
}

From source file:org.apache.uima.examples.as.GetMetaRequest.java

/**
 * Connects to this service Broker's JMX Server. If unable to connect, this method
 * fails silently. The method uses default JMX Port number 1099 to create a connection
 * to the Broker's JMX MBean server. The default can be overridden via System 
 * property 'activemq.broker.jmx.port'. If connection cannot be established the 
 * method silently fails./*from  ww w .  j  a  va  2 s  .  com*/
 * 
 */
private static void attachToRemoteBrokerJMXServer(String brokerUri) throws Exception {
    //  Fetch AMQ jmx domain from system properties. This property is not required
    //  and the default AMQ jmx is used. The only exception is when the service is
    //  deployed in a jvm with multiple brokers deployed as it is the case with jUnit 
    //  tests. In such a case, each broker will register self with JMX using a different
    //  domain.
    String jmxAMQDomain = System.getProperty("activemq.broker.jmx.domain");
    if (jmxAMQDomain == null) {
        jmxAMQDomain = "org.apache.activemq"; // default
    }
    String brokerHostname = "";
    URI target = new URI(brokerUri);
    brokerHostname = target.getHost();
    initialize(jmxAMQDomain, brokerHostname, jmxPort);
}

From source file:org.springframework.cloud.stream.binder.rabbit.admin.RabbitManagementUtils.java

public static RestTemplate buildRestTemplate(String adminUri, String user, String password) {
    BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
    credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
            new UsernamePasswordCredentials(user, password));
    HttpClient httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
    // Set up pre-emptive basic Auth because the rabbit plugin doesn't currently support challenge/response for PUT
    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();
    // Generate BASIC scheme object and add it to the local; from the apache docs...
    // auth cache
    BasicScheme basicAuth = new BasicScheme();
    URI uri;
    try {//from w  ww.  j  ava  2s. c  om
        uri = new URI(adminUri);
    } catch (URISyntaxException e) {
        throw new RabbitAdminException("Invalid URI", e);
    }
    authCache.put(new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme()), basicAuth);
    // Add AuthCache to the execution context
    final HttpClientContext localContext = HttpClientContext.create();
    localContext.setAuthCache(authCache);
    RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient) {

        @Override
        protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
            return localContext;
        }

    });
    restTemplate.setMessageConverters(
            Collections.<HttpMessageConverter<?>>singletonList(new MappingJackson2HttpMessageConverter()));
    return restTemplate;
}

From source file:gobblin.util.ClustersNames.java

private static String normalizeClusterUrl(String clusterIdentifier) {
    try {/*from www .java2  s. co m*/
        URI uri = new URI(clusterIdentifier.trim());
        // URIs without protocol prefix
        if (!uri.isOpaque() && null != uri.getHost()) {
            clusterIdentifier = uri.getHost();
        } else {
            clusterIdentifier = uri.toString().replaceAll("[/:]", " ").trim().replaceAll(" ", "_");
        }
    } catch (URISyntaxException e) {
        //leave ID as is
    }

    return clusterIdentifier;
}

From source file:com.labs64.utils.swid.support.SwidUtils.java

/**
 * <p>/*from  w  w  w.  jav  a2  s.c  o  m*/
 * Revert given URL according to the <a href="http://en.wikipedia.org/wiki/Reverse_domain_name_notation">Reverse
 * domain name notation</a>
 * </p>
 * <p>
 * 
 * @see <a
 *      href="http://en.wikipedia.org/wiki/Reverse_domain_name_notation">http://en.wikipedia.org/wiki/Reverse_domain_name_notation</a>
 *      </p>
 * 
 * @param domainName
 *            the domain name to be reverted
 * @return reverted domain name
 */
public static String revertDomainName(final String domainName) {
    if (StringUtils.isBlank(domainName)) {
        throw new SwidException("domainName isn't defined");
    }

    try {
        URI uri = new URI(StringUtils.prependIfMissing(domainName, "http://", "https://"));
        String hostName = StringUtils.removeStart(uri.getHost(), "www.");

        String[] domainNameSplit = StringUtils.split(hostName, ".");
        CollectionUtils.reverseArray(domainNameSplit);
        return StringUtils.join(domainNameSplit, ".");
    } catch (URISyntaxException e) {
        throw new SwidException("Cannot revert domain name");
    }
}

From source file:com.baidubce.util.HttpUtils.java

/**
 * Returns a host header according to the specified URI. The host header is generated with the same logic used by
 * apache http client, that is, append the port to hostname only if it is not the default port.
 *
 * @param uri the URI/*from ww w .  jav a 2  s . c  om*/
 * @return a host header according to the specified URI.
 */
public static String generateHostHeader(URI uri) {
    String host = uri.getHost();
    if (isUsingNonDefaultPort(uri)) {
        host += ":" + uri.getPort();
    }
    return host;
}