Example usage for io.vertx.core.http HttpClientOptions setConnectTimeout

List of usage examples for io.vertx.core.http HttpClientOptions setConnectTimeout

Introduction

In this page you can find the example usage for io.vertx.core.http HttpClientOptions setConnectTimeout.

Prototype

@Override
    public HttpClientOptions setConnectTimeout(int connectTimeout) 

Source Link

Usage

From source file:io.gravitee.am.identityprovider.github.authentication.spring.GithubAuthenticationProviderConfiguration.java

License:Apache License

@Bean
public HttpClient httpClient() {
    HttpClientOptions httpClientOptions = new HttpClientOptions();
    httpClientOptions
            .setConnectTimeout(/* w  w  w.jav a  2 s .co  m*/
                    Integer.valueOf(properties.getProperty("identities.github.http.connectionTimeout",
                            DEFAULT_CONNECTION_TIMEOUT)) * 1000)
            .setMaxPoolSize(Integer.valueOf(properties.getProperty(
                    "identities.github.http.pool.maxTotalConnection", DEFAULT_MAX_TOTAL_CONNECTION)));

    return vertx.createHttpClient(httpClientOptions);
}

From source file:io.gravitee.am.identityprovider.oauth2.authentication.spring.OAuth2GenericAuthenticationProviderConfiguration.java

License:Apache License

@Bean
public HttpClient httpClient() {
    HttpClientOptions httpClientOptions = new HttpClientOptions();
    httpClientOptions
            .setConnectTimeout(//from www  .j  a v a  2  s  .c  om
                    Integer.valueOf(properties.getProperty("identities.oauth2.http.connectionTimeout",
                            DEFAULT_CONNECTION_TIMEOUT)) * 1000)
            .setMaxPoolSize(Integer.valueOf(properties.getProperty(
                    "identities.oauth2.http.pool.maxTotalConnection", DEFAULT_MAX_TOTAL_CONNECTION)));

    return vertx.createHttpClient(httpClientOptions);
}

From source file:io.nitor.api.backend.NitorBackend.java

License:Apache License

@Override
public void start() {
    vertx.exceptionHandler(e -> logger.error("Fallback exception handler got", e));

    HttpServerOptions httpServerOptions = SetupHttpServerOptions.createHttpServerOptions(config());

    Router router = Router.router(vertx);

    HttpClientOptions clientOptions = new HttpClientOptions();
    clientOptions.setConnectTimeout((int) SECONDS.toMillis(5));
    clientOptions.setIdleTimeout((int) SECONDS.toMillis(15));
    clientOptions.setSsl(true);/* w  ww  .  j  a  v  a  2s .  com*/
    HttpClient httpClient = vertx.createHttpClient(clientOptions);

    Map<String, String> injectedResponseHeaders = new HashMap<>();
    for (Entry<String, Object> defaultHeader : config().getJsonObject("defaultHeaders")) {
        injectedResponseHeaders.put(defaultHeader.getKey().toLowerCase(), defaultHeader.getValue().toString());
    }

    String publicURI = config().getString("publicURI",
            "http" + (httpServerOptions.isSsl() ? "s" : "") + "://localhost:" + listenPort);
    if (publicURI.endsWith("/")) {
        publicURI = publicURI.substring(0, publicURI.length() - 1);
    }
    publicURI = publicURI.toLowerCase(ROOT);

    boolean isOrigReqHttps = httpServerOptions.isSsl() || publicURI.startsWith("https:");
    boolean trustPreviousProxy = config().getBoolean("trustPreviousProxy",
            publicURI.startsWith("https:") && !httpServerOptions.isSsl());

    router.route().handler(new AccessLogHandler()::handle);
    router.route().handler(routingContext -> {
        HttpServerResponse resp = routingContext.response();
        if (isOrigReqHttps) {
            resp.putHeader("strict-transport-security", "max-age=31536000; includeSubDomains");
        }
        if (trustPreviousProxy) {
            String origHost = parseForwardedHeaders(routingContext.request().headers());
            if (origHost != null) {
                routingContext.put(REMOTE_ADDRESS, origHost);
            }
        }
        if (!injectedResponseHeaders.isEmpty()) {
            routingContext.addHeadersEndHandler(v -> {
                for (Entry<String, String> header : injectedResponseHeaders.entrySet()) {
                    if (!resp.headers().contains(header.getKey())) {
                        resp.putHeader(header.getKey(), header.getValue());
                    }
                }
            });
        }
        routingContext.next();
    });

    router.get("/healthCheck").handler(routingContext -> routingContext.response().setStatusCode(200).end());

    router.get("/certCheck").handler(routingContext -> {
        String resp;
        try {
            resp = "Certs: " + Arrays.toString(routingContext.request().peerCertificateChain());
        } catch (SSLPeerUnverifiedException e) {
            resp = "No client certs available:" + e.getMessage();
        }
        routingContext.response().setChunked(true).putHeader(CONTENT_TYPE, "text/plain; charset=utf-8")
                .write(resp).end();
    });

    JsonObject clientAuth = config().getJsonObject("clientAuth");
    if (clientAuth != null) {
        if (null != clientAuth.getString("clientChain")) {
            router.route(clientAuth.getString("route", "/*")).handler(routingContext -> {
                try {
                    routingContext.request().peerCertificateChain();
                    routingContext.next();
                } catch (SSLPeerUnverifiedException e) {
                    routingContext.response().setStatusCode(FORBIDDEN.code());
                    routingContext.response().end();
                    logger.info("Rejected request that was missing valid client certificate from ip {}: {}",
                            routingContext.request().remoteAddress(), e.getMessage());
                }
            });
        }
    }

    boolean virtualHost = config().getBoolean("virtualHost", false);
    if (virtualHost) {
        router.route().handler(ctx -> {
            ctx.put("host", getUriHostName(ctx.request().host()));
            ctx.next();
        });
    }

    JsonObject sessionConf = config().getJsonObject("session");
    CookieSessionHandler sessionHandler = sessionConf != null ? new CookieSessionHandler(sessionConf) : null;
    if (sessionHandler != null) {
        router.route().handler(CookieHandler.create());

        router.get("/proxyLogout").handler(routingContext -> {
            routingContext.cookies()
                    .forEach(cookie -> secureCookie(cookie, (int) DAYS.toSeconds(30)).setValue(""));
            routingContext.response().putHeader(CACHE_CONTROL, "no-cache, no-store, must-revalidate")
                    .putHeader(EXPIRES, "0").putHeader(CONTENT_TYPE, "text/plain; charset=utf-8")
                    .end("Logged out", "UTF-8");
        });
    }

    JsonObject adAuth = config().getJsonObject("adAuth");
    if (adAuth != null) {
        JsonObject openIdConfig = adAuth.getJsonObject("openIdConfig");
        if (openIdConfig == null || !openIdConfig.containsKey("authorization_endpoint")
                || !openIdConfig.containsKey("token_endpoint")) {
            String configURI = adAuth.getString("configurationURI");
            try {
                logger.info("Fetching configuration from " + configURI);
                URL url = URI.create(configURI).toURL();
                openIdConfig = new JsonObject(buffer(toBytes(url.openStream())));
            } catch (Exception e) {
                RuntimeException ex = new RuntimeException("Failed to fetch open id config from " + configURI,
                        e);
                logger.fatal("adAuth config failure", ex);
                throw ex;
            }
            logger.info(
                    "To speed up startup please define \"adAuth\": {\"openIdConfig\": {\"authorization_endpoint\": \""
                            + openIdConfig.getString("authorization_endpoint") + "\", \"token_endpoint\": \""
                            + openIdConfig.getString("token_endpoint") + "\" } }");
        }
        adAuth.put("openIdConfig", openIdConfig);
        SetupAzureAdConnectAuth.setupAzureAd(adAuth, router, publicURI, virtualHost, sessionHandler,
                httpClient);
    }

    JsonObject basicAuth = config().getJsonObject("basicAuth");
    if (basicAuth != null) {
        AuthHandler basicAuthHandler = BasicAuthHandler.create(
                new SimpleConfigAuthProvider(basicAuth.getJsonObject("users")),
                basicAuth.getString("realm", "nitor"));
        router.route(basicAuth.getString("route", "/*")).handler(basicAuthHandler);
    }

    if (sessionHandler != null) {
        router.get("/cookieCheck").handler(routingContext -> {
            Map<String, String> headers = sessionHandler.getSessionData(routingContext);
            StringBuilder sb = new StringBuilder(2048);
            if (headers == null) {
                sb.append("No valid session");
            } else {
                headers.forEach((key, value) -> {
                    sb.append(key).append('=');
                    if (key.startsWith(SECRET_DATA_PREFIX))
                        sb.append("<secret>");
                    else
                        sb.append(value);
                    sb.append('\n');
                });
            }
            routingContext.response().putHeader(CONTENT_TYPE, "text/plain; charset=utf-8").end(sb.toString());
        });
    }

    JsonArray customizeConf = config().getJsonArray("customize");
    if (customizeConf != null) {
        customizeConf.forEach(c -> {
            JsonObject conf = (JsonObject) c;
            InlineJS inlineJs = new InlineJS(vertx, conf.getString("jsFile", "custom.js"));
            router.route(conf.getString("route")).handler(ctx -> {
                inlineJs.call("handleRequest", ctx.request(), ctx);
                ctx.addHeadersEndHandler((v) -> inlineJs.call("handleResponse", ctx.response(), ctx));
                ctx.next();
            });
        });
    }

    setupServices(config(), httpServerOptions, router, new ServiceRouterBuilder(), httpClient, sessionHandler,
            adAuth, isOrigReqHttps);

    router.route().failureHandler(routingContext -> {
        String error = "ERROR";
        int statusCode = routingContext.statusCode();
        Throwable t = routingContext.failure();
        logger.info("Handling failure statusCode=" + statusCode, t);
        HttpServerResponse resp = routingContext.response();
        if (resp.ended()) {
            return;
        }
        if (resp.headWritten()) {
            resp.end();
            routingContext.request().connection().close();
            return;
        }
        if (t != null) {
            if (t instanceof ProxyException) {
                statusCode = ((ProxyException) t).statusCode;
            }
            error = "ERROR: " + t.toString();
        }
        resp.setStatusCode(statusCode != -1 ? statusCode : INTERNAL_SERVER_ERROR.code());
        resp.headers().set("Content-Type", "text/plain; charset=UTF-8");
        resp.headers().set("Content-Length", Integer.toString(error.length()));
        resp.end(error);
    });

    vertx.createHttpServer(httpServerOptions).requestHandler(router).listen(listenPort, listenHost);
}

From source file:io.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 (ver == HttpVersion.HTTP_2) {
        LOGGER.debug("service center client protocol version is HTTP/2");
        httpClientOptions.setHttp2ClearTextUpgrade(false);
    }//from  w  w  w  . j a va2s.  c  om
    if (ServiceRegistryConfig.INSTANCE.isSsl()) {
        LOGGER.debug("service center client performs requests over TLS");
        buildSecureClientOptions(httpClientOptions);
    }
    return httpClientOptions;
}

From source file:io.servicecomb.serviceregistry.client.http.WebsocketClientPool.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.getIdleWatchTimeout());
    if (ver == HttpVersion.HTTP_2) {
        LOGGER.debug("service center ws client protocol version is HTTP/2");
        httpClientOptions.setHttp2ClearTextUpgrade(false);
    }// w ww . j  a v  a 2 s. com
    if (ServiceRegistryConfig.INSTANCE.isSsl()) {
        LOGGER.debug("service center ws client performs requests over TLS");
        buildSecureClientOptions(httpClientOptions);
    }
    return httpClientOptions;
}

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);
    }//from  w  w w . ja  va  2 s.co 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);
    }/*from   ww  w . j  ava 2s.  c  om*/
    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.apache.servicecomb.serviceregistry.client.http.WebsocketClientPool.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.getIdleWatchTimeout());
    if (ver == HttpVersion.HTTP_2) {
        LOGGER.debug("service center ws client protocol version is HTTP/2");
        httpClientOptions.setHttp2ClearTextUpgrade(false);
    }//from  w w  w . j av a2  s . c  om
    if (ServiceRegistryConfig.INSTANCE.isSsl()) {
        LOGGER.debug("service center ws client performs requests over TLS");
        VertxTLSBuilder.buildHttpClientOptions(SSL_KEY, httpClientOptions);
    }
    return httpClientOptions;
}

From source file:org.folio.auth.login_module.impl.ModuleUserSource.java

@Override
public Future<UserResult> getUser(String username) {
    if (okapiUrl == null || vertx == null || requestToken == null || tenant == null) {
        throw new RuntimeException(
                "You must call setOkapiUrl, setVertx, setRequestToken and setTenant before calling this method");
    }/*from   w  ww .  j  ava  2 s  .  c om*/
    Future<UserResult> future = Future.future();
    HttpClientOptions options = new HttpClientOptions();
    options.setConnectTimeout(10);
    options.setIdleTimeout(10);
    HttpClient client = vertx.createHttpClient(options);
    JsonObject query = new JsonObject().put("username", username);
    String requestUrl = null;
    try {
        requestUrl = okapiUrl + "/users/?query=" + URLEncoder.encode(query.encode(), "UTF-8");
    } catch (Exception e) {
        future.fail(e);
        return future;
    }
    logger.debug("Requesting userdata from URL at " + requestUrl);
    client.getAbs(requestUrl, res -> {
        if (res.statusCode() != 200) {
            future.fail("Got status code " + res.statusCode());
        } else {
            res.bodyHandler(buf -> {
                logger.debug("Got content from server: " + buf.toString());
                JsonObject result = buf.toJsonObject();
                if (result.getInteger("total_records") > 1) {
                    future.fail("Not unique username");
                } else if (result.getInteger("total_records") == 0) {
                    UserResult userResult = new UserResult(username, false);
                    future.complete(userResult);
                } else {
                    UserResult userResult = new UserResult(username, true,
                            result.getJsonArray("users").getJsonObject(0).getBoolean("active"));
                    future.complete(userResult);
                }
            });
        }
    }).putHeader("X-Okapi-Tenant", tenant).putHeader("Authorization", "Bearer " + requestToken)
            .putHeader("Content-type", "application/json").putHeader("Accept", "application/json").end();
    return future;
}

From source file:santo.vertx.reproducer.WebService.java

@Override
public void start() {
    System.out.println("Starting WebService");
    Router router = Router.router(vertx);

    // Add body handler
    router.route().handler(BodyHandler.create().setBodyLimit(10 * 1024 * 1024));

    HttpClientOptions options = new HttpClientOptions();
    options.setConnectTimeout(7000);
    options.setDefaultHost("internal.objectstore.eu");
    options.setDefaultPort(443);//from  w w w.  ja  v a  2  s . c  o m
    options.setSsl(true);
    options.setTrustAll(true);
    HttpClient http = vertx.createHttpClient(options);

    TestHandler handler = TestHandler.create(this, http);
    router.route("/api/test").handler(handler);

    vertx.createHttpServer().requestHandler(router::accept).listen(7000);
    System.out.println("WebService listening on port 7000");
}