Example usage for io.vertx.core.net ProxyOptions ProxyOptions

List of usage examples for io.vertx.core.net ProxyOptions ProxyOptions

Introduction

In this page you can find the example usage for io.vertx.core.net ProxyOptions ProxyOptions.

Prototype

public ProxyOptions() 

Source Link

Document

Default constructor.

Usage

From source file:examples.HTTPExamples.java

License:Open Source License

public void example58(Vertx vertx) {

    HttpClientOptions options = new HttpClientOptions()
            .setProxyOptions(new ProxyOptions().setType(ProxyType.HTTP).setHost("localhost").setPort(3128)
                    .setUsername("username").setPassword("secret"));
    HttpClient client = vertx.createHttpClient(options);

}

From source file:examples.HTTPExamples.java

License:Open Source License

public void example59(Vertx vertx) {

    HttpClientOptions options = new HttpClientOptions()
            .setProxyOptions(new ProxyOptions().setType(ProxyType.SOCKS5).setHost("localhost").setPort(1080)
                    .setUsername("username").setPassword("secret"));
    HttpClient client = vertx.createHttpClient(options);

}

From source file:examples.NetExamples.java

License:Open Source License

public void example47(Vertx vertx) {
    NetClientOptions options = new NetClientOptions()
            .setProxyOptions(new ProxyOptions().setType(ProxyType.SOCKS5).setHost("localhost").setPort(1080)
                    .setUsername("username").setPassword("secret"));
    NetClient client = vertx.createNetClient(options);
}

From source file:io.gravitee.fetcher.http.HttpFetcher.java

License:Apache License

private CompletableFuture<Buffer> fetchContent() {
    CompletableFuture<Buffer> future = new VertxCompletableFuture<>(vertx);

    URI requestUri = URI.create(httpFetcherConfiguration.getUrl());
    boolean ssl = HTTPS_SCHEME.equalsIgnoreCase(requestUri.getScheme());

    final HttpClientOptions options = new HttpClientOptions().setSsl(ssl).setTrustAll(true).setMaxPoolSize(1)
            .setKeepAlive(false).setTcpKeepAlive(false).setConnectTimeout(httpClientTimeout);

    if (httpFetcherConfiguration.isUseSystemProxy()) {
        ProxyOptions proxyOptions = new ProxyOptions();
        proxyOptions.setType(ProxyType.valueOf(httpClientProxyType));
        if (HTTPS_SCHEME.equals(requestUri.getScheme())) {
            proxyOptions.setHost(httpClientProxyHttpsHost);
            proxyOptions.setPort(httpClientProxyHttpsPort);
            proxyOptions.setUsername(httpClientProxyHttpsUsername);
            proxyOptions.setPassword(httpClientProxyHttpsPassword);
        } else {// w  w w  .j av a  2  s  .  co  m
            proxyOptions.setHost(httpClientProxyHttpHost);
            proxyOptions.setPort(httpClientProxyHttpPort);
            proxyOptions.setUsername(httpClientProxyHttpUsername);
            proxyOptions.setPassword(httpClientProxyHttpPassword);
        }
        options.setProxyOptions(proxyOptions);
    }

    final HttpClient httpClient = vertx.createHttpClient(options);

    final int port = requestUri.getPort() != -1 ? requestUri.getPort()
            : (HTTPS_SCHEME.equals(requestUri.getScheme()) ? 443 : 80);

    try {
        HttpClientRequest request = httpClient.request(HttpMethod.GET, port, requestUri.getHost(),
                requestUri.toString());

        request.setTimeout(httpClientTimeout);

        request.handler(response -> {
            if (response.statusCode() == HttpStatusCode.OK_200) {
                response.bodyHandler(buffer -> {
                    future.complete(buffer);

                    // Close client
                    httpClient.close();
                });
            } else {
                future.complete(null);
            }
        });

        request.exceptionHandler(event -> {
            try {
                future.completeExceptionally(event);

                // Close client
                httpClient.close();
            } catch (IllegalStateException ise) {
                // Do not take care about exception when closing client
            }
        });

        request.end();
    } catch (Exception ex) {
        logger.error("Unable to fetch content using HTTP", ex);
        future.completeExceptionally(ex);
    }

    return future;
}

From source file:io.gravitee.gateway.http.connector.VertxHttpClient.java

License:Apache License

@Override
protected void doStart() throws Exception {
    httpClientOptions = new HttpClientOptions();

    httpClientOptions.setPipelining(endpoint.getHttpClientOptions().isPipelining());
    httpClientOptions.setKeepAlive(endpoint.getHttpClientOptions().isKeepAlive());
    httpClientOptions.setIdleTimeout((int) (endpoint.getHttpClientOptions().getIdleTimeout() / 1000));
    httpClientOptions.setConnectTimeout((int) endpoint.getHttpClientOptions().getConnectTimeout());
    httpClientOptions.setUsePooledBuffers(true);
    httpClientOptions.setMaxPoolSize(endpoint.getHttpClientOptions().getMaxConcurrentConnections());
    httpClientOptions.setTryUseCompression(endpoint.getHttpClientOptions().isUseCompression());
    httpClientOptions.setLogActivity(true);

    // Configure proxy
    HttpProxy proxy = endpoint.getHttpProxy();
    if (proxy != null && proxy.isEnabled()) {
        ProxyOptions proxyOptions = new ProxyOptions();
        proxyOptions.setHost(proxy.getHost());
        proxyOptions.setPort(proxy.getPort());
        proxyOptions.setUsername(proxy.getUsername());
        proxyOptions.setPassword(proxy.getPassword());
        proxyOptions.setType(ProxyType.valueOf(proxy.getType().name()));

        httpClientOptions.setProxyOptions(proxyOptions);
    }/*w  ww  .  j a v  a 2s  .  c  o m*/

    URI target = URI.create(endpoint.getTarget());
    HttpClientSslOptions sslOptions = endpoint.getHttpClientSslOptions();

    if (HTTPS_SCHEME.equalsIgnoreCase(target.getScheme())) {
        // Configure SSL
        httpClientOptions.setSsl(true);

        if (sslOptions != null) {
            httpClientOptions.setVerifyHost(sslOptions.isHostnameVerifier())
                    .setTrustAll(sslOptions.isTrustAll());

            // Client trust configuration
            if (!sslOptions.isTrustAll() && sslOptions.getTrustStore() != null) {
                switch (sslOptions.getTrustStore().getType()) {
                case PEM:
                    PEMTrustStore pemTrustStore = (PEMTrustStore) sslOptions.getTrustStore();
                    PemTrustOptions pemTrustOptions = new PemTrustOptions();
                    if (pemTrustStore.getPath() != null && !pemTrustStore.getPath().isEmpty()) {
                        pemTrustOptions.addCertPath(pemTrustStore.getPath());
                    } else if (pemTrustStore.getContent() != null && !pemTrustStore.getContent().isEmpty()) {
                        pemTrustOptions
                                .addCertValue(io.vertx.core.buffer.Buffer.buffer(pemTrustStore.getContent()));
                    } else {
                        throw new EndpointException(
                                "Missing PEM certificate value for endpoint " + endpoint.getName());
                    }
                    this.httpClientOptions.setPemTrustOptions(pemTrustOptions);
                    break;
                case PKCS12:
                    PKCS12TrustStore pkcs12TrustStore = (PKCS12TrustStore) sslOptions.getTrustStore();
                    PfxOptions pfxOptions = new PfxOptions();
                    pfxOptions.setPassword(pkcs12TrustStore.getPassword());
                    if (pkcs12TrustStore.getPath() != null && !pkcs12TrustStore.getPath().isEmpty()) {
                        pfxOptions.setPath(pkcs12TrustStore.getPath());
                    } else if (pkcs12TrustStore.getContent() != null
                            && !pkcs12TrustStore.getContent().isEmpty()) {
                        pfxOptions.setValue(io.vertx.core.buffer.Buffer.buffer(pkcs12TrustStore.getContent()));
                    } else {
                        throw new EndpointException("Missing PKCS12 value for endpoint " + endpoint.getName());
                    }
                    this.httpClientOptions.setPfxTrustOptions(pfxOptions);
                    break;
                case JKS:
                    JKSTrustStore jksTrustStore = (JKSTrustStore) sslOptions.getTrustStore();
                    JksOptions jksOptions = new JksOptions();
                    jksOptions.setPassword(jksTrustStore.getPassword());
                    if (jksTrustStore.getPath() != null && !jksTrustStore.getPath().isEmpty()) {
                        jksOptions.setPath(jksTrustStore.getPath());
                    } else if (jksTrustStore.getContent() != null && !jksTrustStore.getContent().isEmpty()) {
                        jksOptions.setValue(io.vertx.core.buffer.Buffer.buffer(jksTrustStore.getContent()));
                    } else {
                        throw new EndpointException("Missing JKS value for endpoint " + endpoint.getName());
                    }
                    this.httpClientOptions.setTrustStoreOptions(jksOptions);
                    break;
                }
            }

            // Client authentication configuration
            if (sslOptions.getKeyStore() != null) {
                switch (sslOptions.getKeyStore().getType()) {
                case PEM:
                    PEMKeyStore pemKeyStore = (PEMKeyStore) sslOptions.getKeyStore();
                    PemKeyCertOptions pemKeyCertOptions = new PemKeyCertOptions();
                    if (pemKeyStore.getCertPath() != null && !pemKeyStore.getCertPath().isEmpty()) {
                        pemKeyCertOptions.setCertPath(pemKeyStore.getCertPath());
                    } else if (pemKeyStore.getCertContent() != null
                            && !pemKeyStore.getCertContent().isEmpty()) {
                        pemKeyCertOptions
                                .setCertValue(io.vertx.core.buffer.Buffer.buffer(pemKeyStore.getCertContent()));
                    }
                    if (pemKeyStore.getKeyPath() != null && !pemKeyStore.getKeyPath().isEmpty()) {
                        pemKeyCertOptions.setKeyPath(pemKeyStore.getKeyPath());
                    } else if (pemKeyStore.getKeyContent() != null && !pemKeyStore.getKeyContent().isEmpty()) {
                        pemKeyCertOptions
                                .setKeyValue(io.vertx.core.buffer.Buffer.buffer(pemKeyStore.getKeyContent()));
                    }
                    this.httpClientOptions.setPemKeyCertOptions(pemKeyCertOptions);
                    break;
                case PKCS12:
                    PKCS12KeyStore pkcs12KeyStore = (PKCS12KeyStore) sslOptions.getKeyStore();
                    PfxOptions pfxOptions = new PfxOptions();
                    pfxOptions.setPassword(pkcs12KeyStore.getPassword());
                    if (pkcs12KeyStore.getPath() != null && !pkcs12KeyStore.getPath().isEmpty()) {
                        pfxOptions.setPath(pkcs12KeyStore.getPath());
                    } else if (pkcs12KeyStore.getContent() != null && !pkcs12KeyStore.getContent().isEmpty()) {
                        pfxOptions.setValue(io.vertx.core.buffer.Buffer.buffer(pkcs12KeyStore.getContent()));
                    }
                    this.httpClientOptions.setPfxKeyCertOptions(pfxOptions);
                    break;
                case JKS:
                    JKSKeyStore jksKeyStore = (JKSKeyStore) sslOptions.getKeyStore();
                    JksOptions jksOptions = new JksOptions();
                    jksOptions.setPassword(jksKeyStore.getPassword());
                    if (jksKeyStore.getPath() != null && !jksKeyStore.getPath().isEmpty()) {
                        jksOptions.setPath(jksKeyStore.getPath());
                    } else if (jksKeyStore.getContent() != null && !jksKeyStore.getContent().isEmpty()) {
                        jksOptions.setValue(io.vertx.core.buffer.Buffer.buffer(jksKeyStore.getContent()));
                    }
                    this.httpClientOptions.setKeyStoreOptions(jksOptions);
                    break;
                }
            }
        }
    }

    printHttpClientConfiguration(httpClientOptions);
}

From source file:io.gravitee.gateway.http.vertx.VertxHttpClient.java

License:Apache License

@Override
protected void doStart() throws Exception {
    // TODO: Prepare HttpClientOptions according to the endpoint to improve performance when creating a new
    // instance of the Vertx client
    httpClientOptions = new HttpClientOptions();

    httpClientOptions.setPipelining(endpoint.getHttpClientOptions().isPipelining());
    httpClientOptions.setKeepAlive(endpoint.getHttpClientOptions().isKeepAlive());
    httpClientOptions.setIdleTimeout((int) (endpoint.getHttpClientOptions().getIdleTimeout() / 1000));
    httpClientOptions.setConnectTimeout((int) endpoint.getHttpClientOptions().getConnectTimeout());
    httpClientOptions.setUsePooledBuffers(true);
    httpClientOptions.setMaxPoolSize(endpoint.getHttpClientOptions().getMaxConcurrentConnections());
    httpClientOptions.setTryUseCompression(endpoint.getHttpClientOptions().isUseCompression());

    // Configure proxy
    HttpProxy proxy = endpoint.getHttpProxy();
    if (proxy != null && proxy.isEnabled()) {
        ProxyOptions proxyOptions = new ProxyOptions();
        proxyOptions.setHost(proxy.getHost());
        proxyOptions.setPort(proxy.getPort());
        proxyOptions.setUsername(proxy.getUsername());
        proxyOptions.setPassword(proxy.getPassword());
        proxyOptions.setType(ProxyType.valueOf(proxy.getType().name()));

        httpClientOptions.setProxyOptions(proxyOptions);
    }// w  w w  .java2s . c  o m

    URI target = URI.create(endpoint.getTarget());
    // Configure SSL
    HttpClientSslOptions sslOptions = endpoint.getHttpClientSslOptions();
    if (sslOptions != null && sslOptions.isEnabled()) {
        httpClientOptions.setSsl(sslOptions.isEnabled()).setVerifyHost(sslOptions.isHostnameVerifier())
                .setTrustAll(sslOptions.isTrustAll());

        if (sslOptions.getPem() != null && !sslOptions.getPem().isEmpty()) {
            httpClientOptions.setPemTrustOptions(new PemTrustOptions()
                    .addCertValue(io.vertx.core.buffer.Buffer.buffer(sslOptions.getPem())));
        }
    } else if (HTTPS_SCHEME.equalsIgnoreCase(target.getScheme())) {
        // SSL is not configured but the endpoint scheme is HTTPS so let's enable the SSL on Vert.x HTTP client
        // automatically
        httpClientOptions.setSsl(true).setTrustAll(true);
    }

    printHttpClientConfiguration(httpClientOptions);
}

From source file:io.gravitee.gateway.services.healthcheck.http.HttpEndpointRuleHandler.java

License:Apache License

@Override
public void handle(Long timer) {
    HttpEndpoint endpoint = (HttpEndpoint) rule.endpoint();

    logger.debug("Running health-check for endpoint: {} [{}]", endpoint.getName(), endpoint.getTarget());

    // Run request for each step
    for (io.gravitee.definition.model.services.healthcheck.Step step : rule.steps()) {
        try {// w w w  .j  a va 2 s. co  m
            URI hcRequestUri = create(endpoint.getTarget(), step.getRequest());

            // Prepare HTTP client
            HttpClientOptions httpClientOptions = new HttpClientOptions().setMaxPoolSize(1).setKeepAlive(false)
                    .setTcpKeepAlive(false);

            if (endpoint.getHttpClientOptions() != null) {
                httpClientOptions
                        .setIdleTimeout((int) (endpoint.getHttpClientOptions().getIdleTimeout() / 1000))
                        .setConnectTimeout((int) endpoint.getHttpClientOptions().getConnectTimeout())
                        .setTryUseCompression(endpoint.getHttpClientOptions().isUseCompression());
            }

            // Configure HTTP proxy
            HttpProxy proxy = endpoint.getHttpProxy();
            if (proxy != null && proxy.isEnabled()) {
                ProxyOptions proxyOptions = new ProxyOptions().setHost(proxy.getHost()).setPort(proxy.getPort())
                        .setUsername(proxy.getUsername()).setPassword(proxy.getPassword())
                        .setType(ProxyType.valueOf(proxy.getType().name()));

                httpClientOptions.setProxyOptions(proxyOptions);
            }

            HttpClientSslOptions sslOptions = endpoint.getHttpClientSslOptions();

            if (HTTPS_SCHEME.equalsIgnoreCase(hcRequestUri.getScheme())) {
                // Configure SSL
                httpClientOptions.setSsl(true);

                if (sslOptions != null) {
                    httpClientOptions.setVerifyHost(sslOptions.isHostnameVerifier())
                            .setTrustAll(sslOptions.isTrustAll());

                    // Client trust configuration
                    if (!sslOptions.isTrustAll() && sslOptions.getTrustStore() != null) {
                        switch (sslOptions.getTrustStore().getType()) {
                        case PEM:
                            PEMTrustStore pemTrustStore = (PEMTrustStore) sslOptions.getTrustStore();
                            PemTrustOptions pemTrustOptions = new PemTrustOptions();
                            if (pemTrustStore.getPath() != null && !pemTrustStore.getPath().isEmpty()) {
                                pemTrustOptions.addCertPath(pemTrustStore.getPath());
                            } else if (pemTrustStore.getContent() != null
                                    && !pemTrustStore.getContent().isEmpty()) {
                                pemTrustOptions.addCertValue(
                                        io.vertx.core.buffer.Buffer.buffer(pemTrustStore.getContent()));
                            } else {
                                throw new EndpointException(
                                        "Missing PEM certificate value for endpoint " + endpoint.getName());
                            }
                            httpClientOptions.setPemTrustOptions(pemTrustOptions);
                            break;
                        case PKCS12:
                            PKCS12TrustStore pkcs12TrustStore = (PKCS12TrustStore) sslOptions.getTrustStore();
                            PfxOptions pfxOptions = new PfxOptions();
                            pfxOptions.setPassword(pkcs12TrustStore.getPassword());
                            if (pkcs12TrustStore.getPath() != null && !pkcs12TrustStore.getPath().isEmpty()) {
                                pfxOptions.setPath(pkcs12TrustStore.getPath());
                            } else if (pkcs12TrustStore.getContent() != null
                                    && !pkcs12TrustStore.getContent().isEmpty()) {
                                pfxOptions.setValue(
                                        io.vertx.core.buffer.Buffer.buffer(pkcs12TrustStore.getContent()));
                            } else {
                                throw new EndpointException(
                                        "Missing PKCS12 value for endpoint " + endpoint.getName());
                            }
                            httpClientOptions.setPfxTrustOptions(pfxOptions);
                            break;
                        case JKS:
                            JKSTrustStore jksTrustStore = (JKSTrustStore) sslOptions.getTrustStore();
                            JksOptions jksOptions = new JksOptions();
                            jksOptions.setPassword(jksTrustStore.getPassword());
                            if (jksTrustStore.getPath() != null && !jksTrustStore.getPath().isEmpty()) {
                                jksOptions.setPath(jksTrustStore.getPath());
                            } else if (jksTrustStore.getContent() != null
                                    && !jksTrustStore.getContent().isEmpty()) {
                                jksOptions.setValue(
                                        io.vertx.core.buffer.Buffer.buffer(jksTrustStore.getContent()));
                            } else {
                                throw new EndpointException(
                                        "Missing JKS value for endpoint " + endpoint.getName());
                            }
                            httpClientOptions.setTrustStoreOptions(jksOptions);
                            break;
                        }
                    }

                    // Client authentication configuration
                    if (sslOptions.getKeyStore() != null) {
                        switch (sslOptions.getKeyStore().getType()) {
                        case PEM:
                            PEMKeyStore pemKeyStore = (PEMKeyStore) sslOptions.getKeyStore();
                            PemKeyCertOptions pemKeyCertOptions = new PemKeyCertOptions();
                            if (pemKeyStore.getCertPath() != null && !pemKeyStore.getCertPath().isEmpty()) {
                                pemKeyCertOptions.setCertPath(pemKeyStore.getCertPath());
                            } else if (pemKeyStore.getCertContent() != null
                                    && !pemKeyStore.getCertContent().isEmpty()) {
                                pemKeyCertOptions.setCertValue(
                                        io.vertx.core.buffer.Buffer.buffer(pemKeyStore.getCertContent()));
                            }
                            if (pemKeyStore.getKeyPath() != null && !pemKeyStore.getKeyPath().isEmpty()) {
                                pemKeyCertOptions.setKeyPath(pemKeyStore.getKeyPath());
                            } else if (pemKeyStore.getKeyContent() != null
                                    && !pemKeyStore.getKeyContent().isEmpty()) {
                                pemKeyCertOptions.setKeyValue(
                                        io.vertx.core.buffer.Buffer.buffer(pemKeyStore.getKeyContent()));
                            }
                            httpClientOptions.setPemKeyCertOptions(pemKeyCertOptions);
                            break;
                        case PKCS12:
                            PKCS12KeyStore pkcs12KeyStore = (PKCS12KeyStore) sslOptions.getKeyStore();
                            PfxOptions pfxOptions = new PfxOptions();
                            pfxOptions.setPassword(pkcs12KeyStore.getPassword());
                            if (pkcs12KeyStore.getPath() != null && !pkcs12KeyStore.getPath().isEmpty()) {
                                pfxOptions.setPath(pkcs12KeyStore.getPath());
                            } else if (pkcs12KeyStore.getContent() != null
                                    && !pkcs12KeyStore.getContent().isEmpty()) {
                                pfxOptions.setValue(
                                        io.vertx.core.buffer.Buffer.buffer(pkcs12KeyStore.getContent()));
                            }
                            httpClientOptions.setPfxKeyCertOptions(pfxOptions);
                            break;
                        case JKS:
                            JKSKeyStore jksKeyStore = (JKSKeyStore) sslOptions.getKeyStore();
                            JksOptions jksOptions = new JksOptions();
                            jksOptions.setPassword(jksKeyStore.getPassword());
                            if (jksKeyStore.getPath() != null && !jksKeyStore.getPath().isEmpty()) {
                                jksOptions.setPath(jksKeyStore.getPath());
                            } else if (jksKeyStore.getContent() != null
                                    && !jksKeyStore.getContent().isEmpty()) {
                                jksOptions
                                        .setValue(io.vertx.core.buffer.Buffer.buffer(jksKeyStore.getContent()));
                            }
                            httpClientOptions.setKeyStoreOptions(jksOptions);
                            break;
                        }
                    }
                }
            }

            HttpClient httpClient = vertx.createHttpClient(httpClientOptions);

            final int port = hcRequestUri.getPort() != -1 ? hcRequestUri.getPort()
                    : (HTTPS_SCHEME.equals(hcRequestUri.getScheme()) ? 443 : 80);

            String relativeUri = (hcRequestUri.getRawQuery() == null) ? hcRequestUri.getRawPath()
                    : hcRequestUri.getRawPath() + '?' + hcRequestUri.getRawQuery();

            // Run health-check
            HttpClientRequest healthRequest = httpClient.request(
                    HttpMethod.valueOf(step.getRequest().getMethod().name().toUpperCase()), port,
                    hcRequestUri.getHost(), relativeUri);

            // Set timeout on request
            if (endpoint.getHttpClientOptions() != null) {
                healthRequest.setTimeout(endpoint.getHttpClientOptions().getReadTimeout());
            }

            // Prepare request
            if (step.getRequest().getHeaders() != null) {
                step.getRequest().getHeaders().forEach(
                        httpHeader -> healthRequest.headers().set(httpHeader.getName(), httpHeader.getValue()));
            }

            final EndpointStatus.Builder healthBuilder = EndpointStatus
                    .forEndpoint(rule.api(), endpoint.getName()).on(currentTimeMillis());

            long startTime = currentTimeMillis();

            Request request = new Request();
            request.setMethod(step.getRequest().getMethod());
            request.setUri(hcRequestUri.toString());

            healthRequest.handler(response -> response.bodyHandler(buffer -> {
                long endTime = currentTimeMillis();
                logger.debug("Health-check endpoint returns a response with a {} status code",
                        response.statusCode());

                String body = buffer.toString();

                EndpointStatus.StepBuilder stepBuilder = validateAssertions(step,
                        new EvaluableHttpResponse(response, body));
                stepBuilder.request(request);
                stepBuilder.responseTime(endTime - startTime);

                Response healthResponse = new Response();
                healthResponse.setStatus(response.statusCode());

                // If validation fail, store request and response data
                if (!stepBuilder.isSuccess()) {
                    request.setBody(step.getRequest().getBody());

                    if (step.getRequest().getHeaders() != null) {
                        HttpHeaders reqHeaders = new HttpHeaders();
                        step.getRequest().getHeaders().forEach(httpHeader -> reqHeaders
                                .put(httpHeader.getName(), Collections.singletonList(httpHeader.getValue())));
                        request.setHeaders(reqHeaders);
                    }

                    // Extract headers
                    HttpHeaders headers = new HttpHeaders();
                    response.headers().names().forEach(
                            headerName -> headers.put(headerName, response.headers().getAll(headerName)));
                    healthResponse.setHeaders(headers);

                    // Store body
                    healthResponse.setBody(body);
                }

                stepBuilder.response(healthResponse);

                // Append step stepBuilder
                healthBuilder.step(stepBuilder.build());

                report(healthBuilder.build());

                // Close client
                httpClient.close();
            }));

            healthRequest.exceptionHandler(event -> {
                long endTime = currentTimeMillis();

                EndpointStatus.StepBuilder stepBuilder = EndpointStatus.forStep(step.getName());
                stepBuilder.fail(event.getMessage());

                Response healthResponse = new Response();

                // Extract request information
                request.setBody(step.getRequest().getBody());
                if (step.getRequest().getHeaders() != null) {
                    HttpHeaders reqHeaders = new HttpHeaders();
                    step.getRequest().getHeaders().forEach(httpHeader -> reqHeaders.put(httpHeader.getName(),
                            Collections.singletonList(httpHeader.getValue())));
                    request.setHeaders(reqHeaders);
                }

                if (event instanceof ConnectTimeoutException) {
                    stepBuilder.fail(event.getMessage());
                    healthResponse.setStatus(HttpStatusCode.REQUEST_TIMEOUT_408);
                } else {
                    healthResponse.setStatus(HttpStatusCode.SERVICE_UNAVAILABLE_503);
                }

                Step result = stepBuilder.build();
                result.setResponse(healthResponse);
                result.setRequest(request);

                result.setResponseTime(endTime - startTime);

                // Append step result
                healthBuilder.step(result);

                report(healthBuilder.build());

                try {
                    // Close client
                    httpClient.close();
                } catch (IllegalStateException ise) {
                    // Do not take care about exception when closing client
                }
            });

            // Send request
            logger.debug("Execute health-check request: {}", healthRequest);
            if (step.getRequest().getBody() != null && !step.getRequest().getBody().isEmpty()) {
                healthRequest.end(step.getRequest().getBody());
            } else {
                healthRequest.end();
            }
        } catch (EndpointException ee) {
            logger.error("An error occurs while configuring the endpoint " + endpoint.getName()
                    + ". Healthcheck is skipped for this endpoint.", ee);
        } catch (Exception ex) {
            logger.error("An unexpected error occurs", ex);
        }
    }
}

From source file:org.apache.servicecomb.config.client.ConfigCenterClient.java

License:Apache License

private HttpClientOptions createHttpClientOptions() {
    HttpClientOptions httpClientOptions = new HttpClientOptions();
    if (ConfigCenterConfig.INSTANCE.isProxyEnable()) {
        ProxyOptions proxy = new ProxyOptions().setHost(ConfigCenterConfig.INSTANCE.getProxyHost())
                .setPort(ConfigCenterConfig.INSTANCE.getProxyPort())
                .setUsername(ConfigCenterConfig.INSTANCE.getProxyUsername())
                .setPassword(ConfigCenterConfig.INSTANCE.getProxyPasswd());
        httpClientOptions.setProxyOptions(proxy);
    }/* w  w w  .  j  a va  2  s  .  c  o m*/
    httpClientOptions.setConnectTimeout(CONFIG_CENTER_CONFIG.getConnectionTimeout());
    if (this.memberDiscovery.getConfigServer().toLowerCase().startsWith("https")) {
        LOGGER.debug("config center client performs requests over TLS");
        SSLOptionFactory factory = SSLOptionFactory.createSSLOptionFactory(SSL_KEY,
                ConfigCenterConfig.INSTANCE.getConcurrentCompositeConfiguration());
        SSLOption sslOption;
        if (factory == null) {
            sslOption = SSLOption.buildFromYaml(SSL_KEY,
                    ConfigCenterConfig.INSTANCE.getConcurrentCompositeConfiguration());
        } else {
            sslOption = factory.createSSLOption();
        }
        SSLCustom sslCustom = SSLCustom.createSSLCustom(sslOption.getSslCustomClass());
        VertxTLSBuilder.buildHttpClientOptions(sslOption, sslCustom, httpClientOptions);
    }
    return httpClientOptions;
}

From source file:org.apache.servicecomb.serviceregistry.client.http.HttpClientPool.java

License:Apache License

@Override
public HttpClientOptions createHttpClientOptions() {
    HttpVersion ver = ServiceRegistryConfig.INSTANCE.getHttpVersion();
    HttpClientOptions httpClientOptions = new HttpClientOptions();
    httpClientOptions.setProtocolVersion(ver);
    httpClientOptions.setConnectTimeout(ServiceRegistryConfig.INSTANCE.getConnectionTimeout());
    httpClientOptions.setIdleTimeout(ServiceRegistryConfig.INSTANCE.getIdleConnectionTimeout());
    if (ServiceRegistryConfig.INSTANCE.isProxyEnable()) {
        ProxyOptions proxy = new ProxyOptions();
        proxy.setHost(ServiceRegistryConfig.INSTANCE.getProxyHost());
        proxy.setPort(ServiceRegistryConfig.INSTANCE.getProxyPort());
        proxy.setUsername(ServiceRegistryConfig.INSTANCE.getProxyUsername());
        proxy.setPassword(ServiceRegistryConfig.INSTANCE.getProxyPasswd());
        httpClientOptions.setProxyOptions(proxy);
    }//  w  w w  . ja v  a  2s . com
    if (ver == HttpVersion.HTTP_2) {
        LOGGER.debug("service center client protocol version is HTTP/2");
        httpClientOptions.setHttp2ClearTextUpgrade(false);
    }
    if (ServiceRegistryConfig.INSTANCE.isSsl()) {
        LOGGER.debug("service center client performs requests over TLS");
        VertxTLSBuilder.buildHttpClientOptions(SSL_KEY, httpClientOptions);
    }
    return httpClientOptions;
}

From source file:org.schors.flibot.FliBot.java

License:Open Source License

@Override
public void start() {

    cm = new CommandManager().addCommand(new GetAuthorCommand()).addCommand(new GetBookCommand())
            .addCommand(new CatalogCommand()).addCommand(new RegisterUserCommand())
            .addCommand(new UnregisterUserCommand()).addCommand(new DownloadCommand())
            .addCommand(new DownloadZipCommand()).addCommand(new GetCmdCommand())
            .setDefaultCommand(new DefaultCommand());

    db = DBService.createProxy(vertx, "db-service");
    urlCache = CacheBuilder.newBuilder().maximumSize(1000).build();

    boolean usetor = config().getBoolean("usetor");

    HttpClientOptions httpOptions = new HttpClientOptions().setTrustAll(true).setIdleTimeout(50)
            .setMaxPoolSize(100).setDefaultHost(usetor ? rootOPDStor : rootOPDShttp).setDefaultPort(80)
            .setLogActivity(true);/*from w  ww .j ava2 s.  c  o  m*/

    if (usetor) {
        httpOptions.setProxyOptions(
                new ProxyOptions().setType(ProxyType.SOCKS5).setHost(config().getString("torhost"))
                        .setPort(Integer.valueOf(config().getString("torport"))));
    }
    httpclient = vertx.createHttpClient(httpOptions);

    TelegramOptions telegramOptions = new TelegramOptions().setBotName(config().getString("name"))
            .setBotToken(config().getString("token"));

    bot = TelegramBot.create(vertx, telegramOptions, cm).receiver(new LongPollingReceiver().onUpdate(update -> {
        if (update.hasMessage() && update.getMessage().hasText()) {
            sendBusy(update);
            String text = update.getMessage().getText();
            String userName = update.getMessage().getFrom().getUserName();
            log.warn("onUpdate: " + text + ", " + userName);
            db.isRegisterdUser(userName, registrationRes -> {
                if (registrationRes.succeeded() && registrationRes.result().getBoolean("res")) {
                    cm.execute(text, cm.createContext(update));
                } else {
                    sendReply(update, "I do not talk to strangers");
                }
            });
        }
    })).addFacility(Util.HTTP_CLIENT, httpclient).addFacility(Util.CACHE, urlCache)
            .addFacility(Util.SEARCHES, searches).addFacility(Util.DB, db).addFacility(Util.CONFIG, config())
            .start();
}