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:org.apache.gobblin.utils.HttpUtils.java

/**
 * Convert D2 URL template into a string used for throttling limiter
 *
 * Valid:/*from   www  .j  av a2s .c  o m*/
 *    d2://host/${resource-id}
 *
 * Invalid:
 *    d2://host${resource-id}, because we cannot differentiate the host
 */
public static String createR2ClientLimiterKey(Config config) {

    String urlTemplate = config.getString(HttpConstants.URL_TEMPLATE);
    try {
        String escaped = URIUtil.encodeQuery(urlTemplate);
        URI uri = new URI(escaped);
        if (uri.getHost() == null)
            throw new RuntimeException("Cannot get host part from uri" + urlTemplate);

        String key = uri.getScheme() + "/" + uri.getHost();
        if (uri.getPort() > 0) {
            key = key + "/" + uri.getPort();
        }
        log.info("Get limiter key [" + key + "]");
        return key;
    } catch (Exception e) {
        throw new RuntimeException("Cannot create R2 limiter key", e);
    }
}

From source file:com.spotify.helios.client.Endpoints.java

/**
 * Returns a list of {@link Endpoint}./*from w ww. ja  v a2 s  .  c om*/
 * @param uris A list of URIs.
 * @param dnsResolver An instance of {@link DnsResolver}
 * @return A list of Endpoints.
 */
static List<Endpoint> of(final List<URI> uris, final DnsResolver dnsResolver) {
    final ImmutableList.Builder<Endpoint> endpoints = ImmutableList.builder();
    for (final URI uri : uris) {
        try {
            for (final InetAddress ip : dnsResolver.resolve(uri.getHost())) {
                endpoints.add(new DefaultEndpoint(uri, ip));
            }
        } catch (UnknownHostException e) {
            log.warn("Unable to resolve hostname {} into IP address: {}", uri.getHost(), e);
        }
    }

    return endpoints.build();
}

From source file:com.netflix.spinnaker.orca.config.RedisConfiguration.java

@Deprecated // rz - Kept for backwards compat with old connection configs
public static JedisPool createPool(GenericObjectPoolConfig redisPoolConfig, String connection, int timeout,
        Registry registry, String poolName) {
    URI redisConnection = URI.create(connection);

    String host = redisConnection.getHost();
    int port = redisConnection.getPort() == -1 ? Protocol.DEFAULT_PORT : redisConnection.getPort();

    String redisConnectionPath = isNotEmpty(redisConnection.getPath()) ? redisConnection.getPath()
            : "/" + DEFAULT_DATABASE;
    int database = Integer.parseInt(redisConnectionPath.split("/", 2)[1]);

    String password = redisConnection.getUserInfo() != null ? redisConnection.getUserInfo().split(":", 2)[1]
            : null;/*ww w  .j a  v  a  2  s .c om*/

    JedisPool jedisPool = new JedisPool(
            redisPoolConfig != null ? redisPoolConfig : new GenericObjectPoolConfig(), host, port, timeout,
            password, database, null);
    final Field poolAccess;
    try {
        poolAccess = Pool.class.getDeclaredField("internalPool");
        poolAccess.setAccessible(true);
        GenericObjectPool<Jedis> pool = (GenericObjectPool<Jedis>) poolAccess.get(jedisPool);
        registry.gauge(registry.createId("redis.connectionPool.maxIdle", "poolName", poolName), pool,
                (GenericObjectPool<Jedis> p) -> Integer.valueOf(p.getMaxIdle()).doubleValue());
        registry.gauge(registry.createId("redis.connectionPool.minIdle", "poolName", poolName), pool,
                (GenericObjectPool<Jedis> p) -> Integer.valueOf(p.getMinIdle()).doubleValue());
        registry.gauge(registry.createId("redis.connectionPool.numActive", "poolName", poolName), pool,
                (GenericObjectPool<Jedis> p) -> Integer.valueOf(p.getNumActive()).doubleValue());
        registry.gauge(registry.createId("redis.connectionPool.numIdle", "poolName", poolName), pool,
                (GenericObjectPool<Jedis> p) -> Integer.valueOf(p.getMaxIdle()).doubleValue());
        registry.gauge(registry.createId("redis.connectionPool.numWaiters", "poolName", poolName), pool,
                (GenericObjectPool<Jedis> p) -> Integer.valueOf(p.getMaxIdle()).doubleValue());
        return jedisPool;
    } catch (NoSuchFieldException | IllegalAccessException e) {
        throw new BeanCreationException("Error creating Redis pool", e);
    }
}

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

/**
 * Searches through all known regions to find one with any service at the
 * specified endpoint. If no region is found with a service at that
 * endpoint, an exception is thrown./* www .  j a va 2  s.  c  om*/
 *
 * @param endpoint The endpoint for any service residing in the desired
 *            region.
 * @return The region containing any service running at the specified
 *         endpoint, otherwise an exception is thrown if no region is found
 *         with a service at the specified endpoint.
 * @throws MalformedURLException If the given URL is malformed, or if the
 *             one of the service URLs on record is malformed.
 */
public static Region getRegionByEndpoint(String endpoint) {
    URI targetEndpointUri = getUriByEndpoint(endpoint);
    String targetHost = targetEndpointUri.getHost();

    for (Region region : getRegions()) {
        for (String serviceEndpoint : region.getServiceEndpoints().values()) {
            URI serviceEndpointUrl = getUriByEndpoint(serviceEndpoint);

            if (serviceEndpointUrl.getHost().equals(targetHost))
                return region;
        }
    }

    throw new IllegalArgumentException("No region found with any service for endpoint " + endpoint);
}

From source file:com.microsoft.azure.servicebus.samples.queueswithproxy.QueuesWithProxy.java

public static int runApp(String[] args, Function<String, Integer> run) {
    try {//  w  ww.j av  a2 s.  c  o  m

        String connectionString;
        String proxyHostName;
        String proxyPortString;
        int proxyPort;

        // Add command line options and create parser
        Options options = new Options();
        options.addOption(new Option("c", true, "Connection string"));
        options.addOption(new Option("n", true, "Proxy hostname"));
        options.addOption(new Option("p", true, "Proxy port"));

        CommandLineParser clp = new DefaultParser();
        CommandLine cl = clp.parse(options, args);

        // Pull variables from command line options or environment variables
        connectionString = getOptionOrEnv(cl, "c", SB_SAMPLES_CONNECTIONSTRING);
        proxyHostName = getOptionOrEnv(cl, "n", SB_SAMPLES_PROXY_HOSTNAME);
        proxyPortString = getOptionOrEnv(cl, "p", SB_SAMPLES_PROXY_PORT);

        // Check for bad input
        if (StringUtil.isNullOrEmpty(connectionString) || StringUtil.isNullOrEmpty(proxyHostName)
                || StringUtil.isNullOrEmpty(proxyPortString)) {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp("run jar with", "", options, "", true);
            return 2;
        }

        if (!NumberUtils.isCreatable(proxyPortString)) {
            System.err.println("Please provide a numerical value for the port");
        }
        proxyPort = Integer.parseInt(proxyPortString);

        // ProxySelector set up for an HTTP proxy
        final ProxySelector systemDefaultSelector = ProxySelector.getDefault();
        ProxySelector.setDefault(new ProxySelector() {
            @Override
            public List<Proxy> select(URI uri) {
                if (uri != null && uri.getHost() != null && uri.getHost().equalsIgnoreCase(proxyHostName)) {
                    List<Proxy> proxies = new LinkedList<>();
                    proxies.add(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHostName, proxyPort)));
                    return proxies;
                }
                return systemDefaultSelector.select(uri);
            }

            @Override
            public void connectFailed(URI uri, SocketAddress sa, IOException ioe) {
                if (uri == null || sa == null || ioe == null) {
                    throw new IllegalArgumentException("Arguments can't be null.");
                }
                systemDefaultSelector.connectFailed(uri, sa, ioe);
            }
        });

        return run.apply(connectionString);
    } catch (Exception e) {
        System.out.printf("%s", e.toString());
        return 3;
    }
}

From source file:oracle.custom.ui.utils.ServerUtils.java

public static PublicKey getServerPublicKey(String domainName) throws Exception {
    HttpClient client = getClient(domainName);
    PublicKey key = null;// w w w .j  a v  a 2s. c  om
    String url = getIDCSBaseURL(domainName) + "/admin/v1/SigningCert/jwk";
    URI uri = new URI(url);
    HttpHost host = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
    HttpGet httpGet = new HttpGet(uri);
    httpGet.addHeader("Authorization", "Bearer " + AccessTokenUtils.getAccessToken(domainName));
    HttpResponse response = client.execute(host, httpGet);
    try {
        HttpEntity entity2 = response.getEntity();
        String res = EntityUtils.toString(entity2);
        EntityUtils.consume(entity2);
        ObjectMapper mapper = new ObjectMapper();
        System.out.println("result is " + res);
        SigningKeys signingKey = mapper.readValue(res, SigningKeys.class);

        String base64Cert = signingKey.getKeys().get(0).getX5c().get(0);
        byte encodedCert[] = Base64.getDecoder().decode(base64Cert);
        ByteArrayInputStream inputStream = new ByteArrayInputStream(encodedCert);

        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(inputStream);
        key = cert.getPublicKey();
    } finally {
        if (response instanceof CloseableHttpResponse) {
            ((CloseableHttpResponse) response).close();
        }
    }
    return key;
}

From source file:com.ibm.watson.retrieveandrank.app.rest.UtilityFunctions.java

public static HttpClientBuilder createHTTPBuilder(URI uri, String username, String password) {
    final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(uri.getHost(), uri.getPort()),
            new UsernamePasswordCredentials(username, password));

    final HttpClientBuilder builder = HttpClientBuilder.create().setMaxConnTotal(128).setMaxConnPerRoute(32)
            .setDefaultRequestConfig(// www.  jav a2 s.  c o m
                    RequestConfig.copy(RequestConfig.DEFAULT).setRedirectsEnabled(true).build());
    builder.setDefaultCredentialsProvider(credentialsProvider);
    builder.addInterceptorFirst(new PreemptiveAuthInterceptor());
    return builder;
}

From source file:org.projecthdata.social.api.connect.HDataServiceProvider.java

private static StringBuilder getBaseUrl(String ehrUrl) {
    URI uri = URIBuilder.fromUri(ehrUrl).build();
    StringBuilder builder = new StringBuilder();
    builder.append(uri.getScheme()).append("://");
    builder.append(uri.getHost());
    if (uri.getPort() >= 0) {
        builder.append(":").append(uri.getPort());
    }/*from  w  w w  . j  av  a  2s  .  co m*/
    if (uri.getPath() != null) {
        StringTokenizer tokenizer = new StringTokenizer(uri.getPath(), "/");
        // if there is more than one path element, then the first one should
        // be the webapp name
        if (tokenizer.countTokens() > 1) {
            builder.append("/").append(tokenizer.nextToken());
        }
    }
    return builder;
}

From source file:URIUtil.java

/**
 * Get the parent URI of the supplied URI
 * @param uri The input URI for which the parent URI is being requrested.
 * @return The parent URI.  Returns a URI instance equivalent to "../" if
 * the supplied URI path has no parent.//from  ww w. j a va  2s  .  c  o m
 * @throws URISyntaxException Failed to reconstruct the parent URI.
 */
public static URI getParent(URI uri) throws URISyntaxException {

    String parentPath = new File(uri.getPath()).getParent();

    if (parentPath == null) {
        return new URI("../");
    }

    return new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(),
            parentPath.replace('\\', '/'), uri.getQuery(), uri.getFragment());
}

From source file:com.aurel.track.master.ModuleBL.java

public static Cookie cretaeCookie(String cookieValue, String path, String url) {
    Cookie myCookie = new Cookie("JSESSIONID", cookieValue);
    myCookie.setPath(path);/*from   w ww. j a v a2  s  .c o  m*/
    URI uri;
    try {
        uri = new URI(url);
        String domain = uri.getHost();
        myCookie.setDomain(domain);
    } catch (URISyntaxException e) {
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    return myCookie;
}