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.acre.script.AcreFetch.java

private static boolean isInternal(String url) {
    try {//from   ww  w  .  j a  va  2 s . c o  m
        URI uri = new URI(url);
        String host = uri.getHost();
        return (ACRE_METAWEB_API_ADDR.equals(host) || ACRE_FREEBASE_SITE_ADDR.equals(host));
    } catch (URISyntaxException e) {
        // if the url parsing threw, it's safer to consider it an external URL
        // and let the proxy do the guarding job
        return false;
    }
}

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.
 * //from w  ww  . ja  va 2 s  .co  m
 * @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:com.aliyun.oss.integrationtests.TestUtils.java

public static String composeLocation(String endpoint, String bucketName, String key) {
    try {/*  w  ww  .  j  av a  2 s  . co  m*/
        URI baseUri = URI.create(endpoint);
        URI resultUri = new URI(baseUri.getScheme(), null, bucketName + "." + baseUri.getHost(),
                baseUri.getPort(), String.format("/%s", HttpUtil.urlEncode(key, DEFAULT_CHARSET_NAME)), null,
                null);
        return URLDecoder.decode(resultUri.toString(), DEFAULT_CHARSET_NAME);
    } catch (Exception e) {
        throw new IllegalArgumentException(e.getMessage(), e);
    }
}

From source file:org.springframework.xd.dirt.integration.bus.rabbit.RabbitBusCleaner.java

@VisibleForTesting
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;//from   w  ww.  ja  v  a  2s.  c  o  m
    try {
        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:com.microsoft.gittf.client.clc.connection.GitTFHTTPClientFactory.java

/**
 * Determines whether the given host should be proxied or not, based on the
 * pipe-separated list of wildcards to not proxy (generally taken from the
 * <code>http.nonProxyHosts</code> system property.)
 * //ww  w  . j  av a 2  s .c  o m
 * @param host
 *        the host to query (not <code>null</code>)
 * @param nonProxyHosts
 *        the pipe-separated list of hosts (or wildcards) that should not be
 *        proxied, or <code>null</code> if all hosts are proxied
 * @return <code>true</code> if the host should be proxied,
 *         <code>false</code> otherwise
 */
static boolean hostExcludedFromProxyProperties(URI serverURI, String nonProxyHosts) {
    if (serverURI == null || serverURI.getHost() == null || nonProxyHosts == null) {
        return false;
    }

    for (String nonProxyHost : nonProxyHosts.split("\\|")) //$NON-NLS-1$
    {
        /*
         * Note: for wildcards, the java specification says that the host
         * "may start OR end with a *" (emphasis: mine).
         */
        if (nonProxyHost.startsWith("*") && LocaleInvariantStringHelpers //$NON-NLS-1$
                .caseInsensitiveEndsWith(serverURI.getHost(), nonProxyHost.substring(1))) {
            return true;
        } else if (nonProxyHost.endsWith("*") && LocaleInvariantStringHelpers.caseInsensitiveStartsWith( //$NON-NLS-1$
                serverURI.getHost(), nonProxyHost.substring(0, nonProxyHost.length() - 1))) {
            return true;
        } else if (CollatorFactory.getCaseInsensitiveCollator().equals(serverURI.getHost(), nonProxyHost)) {
            return true;
        }
    }

    return false;
}

From source file:com.ibm.stocator.fs.common.Utils.java

/**
 * Extract host name from the URI//from  ww  w. j a v  a  2s.c o  m
 *
 * @param uri object store uri
 * @return host name
 */
public static String getHost(URI uri) {
    String host = uri.getHost();
    if (host != null) {
        return host;
    }
    host = uri.toString();
    int sInd = host.indexOf("//") + 2;
    host = host.substring(sInd);
    int eInd = host.indexOf("/");
    host = host.substring(0, eInd);
    return host;
}

From source file:com.microsoft.tfs.client.clc.CLCHTTPClientFactory.java

/**
 * Determines whether the given host should be proxied or not, based on the
 * pipe-separated list of wildcards to not proxy (generally taken from the
 * <code>http.nonProxyHosts</code> system property.)
 *
 * @param host//  www.  ja v a 2  s.co  m
 *        the host to query (not <code>null</code>)
 * @param nonProxyHosts
 *        the pipe-separated list of hosts (or wildcards) that should not be
 *        proxied, or <code>null</code> if all hosts are proxied
 * @return <code>true</code> if the host should be proxied,
 *         <code>false</code> otherwise
 */
static boolean hostExcludedFromProxyProperties(final URI serverURI, final String nonProxyHosts) {
    if (serverURI == null || serverURI.getHost() == null || nonProxyHosts == null) {
        return false;
    }

    for (final String nonProxyHost : nonProxyHosts.split("\\|")) //$NON-NLS-1$
    {
        /*
         * Note: for wildcards, the java specification says that the host
         * "may start OR end with a *" (emphasis: mine).
         */
        if (nonProxyHost.startsWith("*") //$NON-NLS-1$
                && LocaleInvariantStringHelpers.caseInsensitiveEndsWith(serverURI.getHost(),
                        nonProxyHost.substring(1))) {
            return true;
        } else if (nonProxyHost.endsWith("*") //$NON-NLS-1$
                && LocaleInvariantStringHelpers.caseInsensitiveStartsWith(serverURI.getHost(),
                        nonProxyHost.substring(0, nonProxyHost.length() - 1))) {
            return true;
        } else if (CollatorFactory.getCaseInsensitiveCollator().equals(serverURI.getHost(), nonProxyHost)) {
            return true;
        }
    }

    return false;
}

From source file:com.mymita.vaadlets.VaadletsBuilder.java

private static void setEmbeddedAttributes(final com.vaadin.ui.Component vaadinComponent,
        final com.mymita.vaadlets.core.Component vaadletsComponent) {
    if (vaadletsComponent instanceof com.mymita.vaadlets.ui.Embedded) {
        final String source = ((com.mymita.vaadlets.ui.Embedded) vaadletsComponent).getSource();
        if (source.startsWith("theme:")) {
            try {
                final URI uri = new URI(source);
                final String theme = uri.getHost();
                final String path = uri.getPath();
                final String resourceId = URLDecoder.decode(path.replaceFirst("/", ""),
                        Charsets.UTF_8.toString());
                ((com.vaadin.ui.Embedded) vaadinComponent).setSource(new ThemeResource(resourceId));
            } catch (final URISyntaxException e) {
            } catch (final UnsupportedEncodingException e) {
            }/*  www . ja  v  a 2s.  com*/
        }
    }
}

From source file:com.ibm.watson.developer_cloud.professor_languo.ingestion.RankerCreationUtil.java

/**
 * //www.j a  v a  2s.c om
 * @param uri
 * @param username
 * @param password
 * @return
 */
public static HttpClient createHttpClient(String uri, String username, String password) {
    final URI scopeUri = URI.create(uri);

    final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(scopeUri.getHost(), scopeUri.getPort()),
            new UsernamePasswordCredentials(username, password));

    final HttpClientBuilder builder = HttpClientBuilder.create().setMaxConnTotal(128).setMaxConnPerRoute(32)
            .setDefaultRequestConfig(
                    RequestConfig.copy(RequestConfig.DEFAULT).setRedirectsEnabled(true).build());
    builder.setDefaultCredentialsProvider(credentialsProvider);

    return builder.build();
}

From source file:com.cloud.utils.UriUtils.java

public static String getUpdateUri(String url, boolean encrypt) {
    String updatedPath = null;/*  w  w w.  j  ava  2s . c om*/
    try {
        String query = URIUtil.getQuery(url);
        URIBuilder builder = new URIBuilder(url);
        builder.removeQuery();

        StringBuilder updatedQuery = new StringBuilder();
        List<NameValuePair> queryParams = getUserDetails(query);
        ListIterator<NameValuePair> iterator = queryParams.listIterator();
        while (iterator.hasNext()) {
            NameValuePair param = iterator.next();
            String value = null;
            if ("password".equalsIgnoreCase(param.getName()) && param.getValue() != null) {
                value = encrypt ? DBEncryptionUtil.encrypt(param.getValue())
                        : DBEncryptionUtil.decrypt(param.getValue());
            } else {
                value = param.getValue();
            }

            if (updatedQuery.length() == 0) {
                updatedQuery.append(param.getName()).append('=').append(value);
            } else {
                updatedQuery.append('&').append(param.getName()).append('=').append(value);
            }
        }

        String schemeAndHost = "";
        URI newUri = builder.build();
        if (newUri.getScheme() != null) {
            schemeAndHost = newUri.getScheme() + "://" + newUri.getHost();
        }

        updatedPath = schemeAndHost + newUri.getPath() + "?" + updatedQuery;
    } catch (URISyntaxException e) {
        throw new CloudRuntimeException("Couldn't generate an updated uri. " + e.getMessage());
    }

    return updatedPath;
}