io.vertx.ext.web.client.WebClientOptions Java Examples

The following examples show how to use io.vertx.ext.web.client.WebClientOptions. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Service.java    From xyz-hub with Apache License 2.0 7 votes vote down vote up
/**
 * The service entry point.
 */
public static void main(String[] arguments) {
  Configurator.initialize("default", CONSOLE_LOG_CONFIG);
  final ConfigStoreOptions fileStore = new ConfigStoreOptions().setType("file").setConfig(new JsonObject().put("path", "config.json"));
  final ConfigStoreOptions envConfig = new ConfigStoreOptions().setType("env");
  final ConfigStoreOptions sysConfig = new ConfigStoreOptions().setType("sys");
  final ConfigRetrieverOptions options = new ConfigRetrieverOptions().addStore(fileStore).addStore(envConfig).addStore(sysConfig);
  boolean debug = Arrays.asList(arguments).contains("--debug");

  final VertxOptions vertxOptions = new VertxOptions()
    .setWorkerPoolSize(NumberUtils.toInt(System.getenv(VERTX_WORKER_POOL_SIZE), 128))
    .setPreferNativeTransport(true);

  if (debug) {
    vertxOptions
        .setBlockedThreadCheckInterval(TimeUnit.MINUTES.toMillis(1))
        .setMaxEventLoopExecuteTime(TimeUnit.MINUTES.toMillis(1))
        .setMaxWorkerExecuteTime(TimeUnit.MINUTES.toMillis(1))
        .setWarningExceptionTime(TimeUnit.MINUTES.toMillis(1));
  }

  vertx = Vertx.vertx(vertxOptions);
  webClient = WebClient.create(Service.vertx, new WebClientOptions().setUserAgent(XYZ_HUB_USER_AGENT));
  ConfigRetriever retriever = ConfigRetriever.create(vertx, options);
  retriever.getConfig(Service::onConfigLoaded);
}
 
Example #2
Source File: BaseValidationHandlerTest.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@BeforeEach
public void setUp(Vertx vertx, VertxTestContext testContext) {
  router = Router.router(vertx);
  ValidationTestUtils.mountRouterFailureHandler(router);

  schemaRouter = SchemaRouter.create(vertx, new SchemaRouterOptions());
  parser = Draft7SchemaParser.create(schemaRouter);

  client = WebClient.create(vertx, new WebClientOptions().setDefaultPort(9000).setDefaultHost("localhost"));
  server = vertx
    .createHttpServer()
    .requestHandler(router)
    .listen(9000, testContext.succeeding(h -> {
      testContext.completeNow();
    }));
}
 
Example #3
Source File: WebClientOptionsFactory.java    From ethsigner with Apache License 2.0 6 votes vote down vote up
private void applyTrustOptions(
    final WebClientOptions webClientOptions,
    final Optional<Path> knownServerFile,
    final boolean caAuthEnabled) {

  if (knownServerFile.isPresent()) {
    try {
      webClientOptions.setTrustOptions(whitelistServers(knownServerFile.get(), caAuthEnabled));
    } catch (RuntimeException e) {
      throw new InitializationException("Failed to load known server file.", e);
    }
  }

  if (knownServerFile.isEmpty() && !caAuthEnabled) {
    throw new InitializationException(
        "Must specify a known-server file if CA-signed option is disabled");
  }
  // otherwise knownServerFile is empty and caAuthEnabled is true which is the default situation
}
 
Example #4
Source File: HttpRequestImpl.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
HttpRequestImpl(WebClientInternal client, HttpMethod method, SocketAddress serverAddress, String protocol, Boolean ssl, Integer port, String host, String
        uri, BodyCodec<T> codec, WebClientOptions options) {
  this.client = client;
  this.method = method;
  this.protocol = protocol;
  this.codec = codec;
  this.port = port;
  this.host = host;
  this.uri = uri;
  this.ssl = ssl;
  this.serverAddress = serverAddress;
  this.followRedirects = options.isFollowRedirects();
  this.options = options;
  if (options.isUserAgentEnabled()) {
    headers = HttpHeaders.set(HttpHeaders.USER_AGENT, options.getUserAgent());
  }
}
 
Example #5
Source File: WebClientOptionsFactory.java    From ethsigner with Apache License 2.0 6 votes vote down vote up
private void applyTlsOptions(final WebClientOptions webClientOptions, final Config config) {
  final Optional<ClientTlsOptions> optionalClientTlsOptions = config.getClientTlsOptions();
  if (optionalClientTlsOptions.isEmpty()) {
    return;
  }

  webClientOptions.setSsl(true);

  final ClientTlsOptions clientTlsOptions = optionalClientTlsOptions.get();

  applyTrustOptions(
      webClientOptions,
      clientTlsOptions.getKnownServersFile(),
      clientTlsOptions.isCaAuthEnabled());
  applyKeyStoreOptions(webClientOptions, clientTlsOptions.getKeyStoreOptions());
}
 
Example #6
Source File: HttpSink.java    From smallrye-reactive-messaging with Apache License 2.0 6 votes vote down vote up
HttpSink(Vertx vertx, HttpConnectorOutgoingConfiguration config) {
    WebClientOptions options = new WebClientOptions(JsonHelper.asJsonObject(config.config()));
    url = config.getUrl();
    if (url == null) {
        throw ex.illegalArgumentUrlNotSet();
    }
    method = config.getMethod();
    client = WebClient.create(vertx, options);
    converterClass = config.getConverter().orElse(null);

    subscriber = ReactiveStreams.<Message<?>> builder()
            .flatMapCompletionStage(m -> send(m)
                    .onItem().produceCompletionStage(v -> m.ack())
                    .onItem().apply(x -> m)
                    .subscribeAsCompletionStage())
            .ignore();
}
 
Example #7
Source File: HttpKafkaProducer.java    From client-examples with Apache License 2.0 6 votes vote down vote up
@Override
public void start(Future<Void> startFuture) throws Exception {
    log.info("HTTP Kafka producer starting with config {}", this.config);

    WebClientOptions options = new WebClientOptions()
            .setDefaultHost(this.config.getHostname())
            .setDefaultPort(this.config.getPort());
    this.client = WebClient.create(vertx, options);

    this.sendTimer = vertx.setPeriodic(this.config.getSendInterval(), t -> {
        Tracer tracer = GlobalTracer.get();
        Span span = tracer.buildSpan("send").withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_CLIENT).start();

        this.send(this.config.getTopic(), span).setHandler(ar -> {
            if (ar.succeeded()) {
                log.info("Sent {}", ar.result());
            }
            span.finish();
        });
    });
    startFuture.complete();
}
 
Example #8
Source File: HttpKafkaConsumer.java    From client-examples with Apache License 2.0 6 votes vote down vote up
@Override
public void start(Future<Void> startFuture) throws Exception {
    log.info("HTTP Kafka consumer starting with config {}", this.config);

    WebClientOptions options = new WebClientOptions()
            .setDefaultHost(this.config.getHostname())
            .setDefaultPort(this.config.getPort())
            .setPipelining(this.config.isPipelining())
            .setPipeliningLimit(this.config.getPipeliningLimit());
    this.client = WebClient.create(vertx, options);
    
    this.createConsumer()
    .compose(consumer -> this.subscribe(consumer, this.config.getTopic()))
    .compose(v -> {
        this.pollTimer = vertx.setPeriodic(this.config.getPollInterval(), t -> {
            this.poll().setHandler(ar -> {
                if (ar.succeeded()) {
                    log.info("Received {}", ar.result());
                }
            });
        });
        startFuture.complete();
    }, startFuture);
}
 
Example #9
Source File: PokemonHandler.java    From vertx-in-production with MIT License 6 votes vote down vote up
public PokemonHandler(Vertx vertx) {
    WebClientOptions options = new WebClientOptions().setKeepAlive(true).setSsl(true);
    this.webClient = WebClient.create(vertx, options);

    CircuitBreakerOptions circuitBreakerOptions = new CircuitBreakerOptions()
            .setMaxFailures(3)
            .setTimeout(1000)
            .setFallbackOnFailure(true)
            .setResetTimeout(60000);

    this.circuitBreaker = CircuitBreaker.create("pokeapi", vertx, circuitBreakerOptions);
    this.circuitBreaker.openHandler(v -> logger.info("{} circuit breaker is open", "pokeapi"));
    this.circuitBreaker.closeHandler(v -> logger.info("{} circuit breaker is closed", "pokeapi"));
    this.circuitBreaker.halfOpenHandler(v -> logger.info("{} circuit breaker is half open", "pokeapi"));

    this.healthChecks = HealthChecks.create(vertx);
    healthChecks.register("pokeApiHealthcheck", 1000, future -> {
        if (circuitBreaker.state().equals(CircuitBreakerState.CLOSED)) {
            future.complete(Status.OK());
        } else {
            future.complete(Status.KO());
        }
    });
}
 
Example #10
Source File: VertxJobsService.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@PostConstruct
void initialize() {
    DatabindCodec.mapper().disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
    DatabindCodec.mapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);             
    DatabindCodec.mapper().registerModule(new JavaTimeModule());
    DatabindCodec.mapper().findAndRegisterModules();
    
    DatabindCodec.prettyMapper().registerModule(new JavaTimeModule());
    DatabindCodec.prettyMapper().findAndRegisterModules();
    DatabindCodec.prettyMapper().disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
    DatabindCodec.prettyMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

    if (providedWebClient.isResolvable()) {
        this.client = providedWebClient.get();
        LOGGER.debug("Using provided web client instance");
    } else {
        final URI jobServiceURL = getJobsServiceUri();
        this.client = WebClient.create(vertx,
                                       new WebClientOptions()
                                               .setDefaultHost(jobServiceURL.getHost())
                                               .setDefaultPort(jobServiceURL.getPort()));
        LOGGER.debug("Creating new instance of web client for host {} and port {}", jobServiceURL.getHost(), jobServiceURL.getPort());
    }
}
 
Example #11
Source File: Http2TestCase.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@Test
public void testHttp2EnabledSsl() throws ExecutionException, InterruptedException {
    Assumptions.assumeTrue(JdkSSLEngineOptions.isAlpnAvailable()); //don't run on JDK8
    Vertx vertx = Vertx.vertx();
    try {
        WebClientOptions options = new WebClientOptions()
                .setUseAlpn(true)
                .setProtocolVersion(HttpVersion.HTTP_2)
                .setSsl(true)
                .setKeyStoreOptions(
                        new JksOptions().setPath("src/test/resources/client-keystore.jks").setPassword("password"))
                .setTrustStoreOptions(
                        new JksOptions().setPath("src/test/resources/client-truststore.jks").setPassword("password"));

        WebClient client = WebClient.create(vertx, options);
        int port = sslUrl.getPort();

        runTest(client, port);

    } finally {
        vertx.close();
    }
}
 
Example #12
Source File: ApiTest.java    From redpipe with Apache License 2.0 6 votes vote down vote up
@Before
public void prepare(TestContext context) throws IOException {
	Async async = context.async();

	server = new Server();
	server.start(//new JsonObject().put("mode", "prod"), 
			TestResource.class)
	.subscribe(() -> {
		webClient = WebClient.create(server.getVertx(),
				new WebClientOptions().setDefaultHost("localhost").setDefaultPort(9000));
		async.complete();
	}, x -> {
		x.printStackTrace();
		context.fail(x);
		async.complete();
	});
}
 
Example #13
Source File: DiscoveryTest.java    From redpipe with Apache License 2.0 6 votes vote down vote up
@Before
public void prepare(TestContext context) throws IOException {
	Async async = context.async();

	server = new Server();
	server.start(TestResource.class)
	.subscribe(() -> {
		webClient = WebClient.create(server.getVertx(),
				new WebClientOptions().setDefaultHost("localhost").setDefaultPort(9000));
		async.complete();
	}, x -> {
		x.printStackTrace();
		context.fail(x);
		async.complete();
	});
}
 
Example #14
Source File: ApiTest.java    From redpipe with Apache License 2.0 6 votes vote down vote up
@Before
public void prepare(TestContext context) throws IOException {
	Async async = context.async();

	JsonObject config = new JsonObject().put("db_url", "jdbc:hsqldb:mem:testdb;shutdown=true")
			.put("db_max_pool_size", 4)
			.put("security_definitions", "classpath:wiki-users.properties")
			.put("scan", new JsonArray().add(AppResource.class.getPackage().getName()))
			.put("keystore", new JsonObject()
					.put("path", "keystore.jceks")
					.put("type", "jceks")
					.put("password", "secret"));
			
	server = new WikiServer();
	server.start(config)
	.subscribe(() -> {
		webClient = WebClient.create(server.getVertx(),
				new WebClientOptions().setDefaultHost("localhost").setDefaultPort(9000));
		async.complete();
	}, x -> {
		x.printStackTrace();
		context.fail(x);
		async.complete();
	});
}
 
Example #15
Source File: MyResource.java    From redpipe with Apache License 2.0 6 votes vote down vote up
@Path("6")
@GET
public void hello6(@Suspended final AsyncResponse asyncResponse,
	      // Inject the Vertx instance
	      @Context Vertx vertx){
	io.vertx.reactivex.core.Vertx rxVertx = io.vertx.reactivex.core.Vertx.newInstance(vertx);
	System.err.println("Creating client");
	WebClientOptions options = new WebClientOptions();
	options.setSsl(true);
	options.setTrustAll(true);
	options.setVerifyHost(false);
	WebClient client = WebClient.create(rxVertx, options);
	Single<HttpResponse<io.vertx.reactivex.core.buffer.Buffer>> responseHandler = client.get(443,
			"www.google.com", 
			"/robots.txt").rxSend();

	responseHandler
		.doAfterTerminate(() -> client.close())
		.subscribe(body -> {
		System.err.println("Got body");
		asyncResponse.resume(Response.ok(body.body().toString()).build());
	});
	
	System.err.println("Created client");
}
 
Example #16
Source File: MyResource.java    From redpipe with Apache License 2.0 6 votes vote down vote up
@Path("7")
@GET
public CompletionStage<String> hello7(@Context Vertx vertx){
	io.vertx.reactivex.core.Vertx rxVertx = io.vertx.reactivex.core.Vertx.newInstance(vertx);
	System.err.println("Creating client");
	WebClientOptions options = new WebClientOptions();
	options.setSsl(true);
	options.setTrustAll(true);
	options.setVerifyHost(false);
	WebClient client = WebClient.create(rxVertx, options);
	Single<HttpResponse<io.vertx.reactivex.core.buffer.Buffer>> responseHandler = client.get(443,
			"www.google.com", 
			"/robots.txt").rxSend();

	CompletableFuture<String> ret = new CompletableFuture<>();
	responseHandler
		.doAfterTerminate(() -> client.close())
		.subscribe(body -> {
		System.err.println("Got body");
		ret.complete(body.body().toString());
	});
	
	System.err.println("Created client");
	return ret;
}
 
Example #17
Source File: MyResource.java    From redpipe with Apache License 2.0 6 votes vote down vote up
@Path("7error")
@GET
public CompletionStage<String> hello7Error(@Context Vertx vertx){
	io.vertx.reactivex.core.Vertx rxVertx = io.vertx.reactivex.core.Vertx.newInstance(vertx);
	System.err.println("Creating client");
	WebClientOptions options = new WebClientOptions();
	options.setSsl(true);
	options.setTrustAll(true);
	options.setVerifyHost(false);
	WebClient client = WebClient.create(rxVertx, options);
	Single<HttpResponse<io.vertx.reactivex.core.buffer.Buffer>> responseHandler = client.get(443,
			"www.google.com", 
			"/robots.txt").rxSend();

	CompletableFuture<String> ret = new CompletableFuture<>();
	responseHandler
		.doAfterTerminate(() -> client.close())
		.subscribe(body -> {
		System.err.println("Got body");
		
		ret.completeExceptionally(new MyException());
	});
	System.err.println("Created client");
	return ret;
}
 
Example #18
Source File: MyResource.java    From redpipe with Apache License 2.0 6 votes vote down vote up
@Path("8user")
@Produces("text/json")
@GET
public Single<DataClass> hello8User(@Context io.vertx.reactivex.core.Vertx rxVertx){
	System.err.println("Creating client");
	WebClientOptions options = new WebClientOptions();
	options.setSsl(true);
	options.setTrustAll(true);
	options.setVerifyHost(false);
	WebClient client = WebClient.create(rxVertx, options);
	Single<HttpResponse<io.vertx.reactivex.core.buffer.Buffer>> responseHandler = client.get(443,
			"www.google.com", 
			"/robots.txt").rxSend();

	System.err.println("Created client");
	return responseHandler.map(body -> {
		System.err.println("Got body");
		return new DataClass(body.body().toString());
	}).doAfterTerminate(() -> client.close());
}
 
Example #19
Source File: MyResource.java    From redpipe with Apache License 2.0 6 votes vote down vote up
@Path("8error")
@GET
public Single<String> hello8Error(@Context io.vertx.reactivex.core.Vertx rxVertx){
	System.err.println("Creating client");
	WebClientOptions options = new WebClientOptions();
	options.setSsl(true);
	options.setTrustAll(true);
	options.setVerifyHost(false);
	WebClient client = WebClient.create(rxVertx, options);
	Single<HttpResponse<io.vertx.reactivex.core.buffer.Buffer>> responseHandler = client.get(443,
			"www.google.com", 
			"/robots.txt").rxSend();

	System.err.println("Created client");
	return responseHandler
			.doAfterTerminate(() -> client.close())
			.map(body -> {
		System.err.println("Got body");
		throw new MyException();
	});
}
 
Example #20
Source File: MyResource.java    From redpipe with Apache License 2.0 6 votes vote down vote up
@Path("coroutines/1")
@GET
public Single<Response> helloAsync(@Context io.vertx.reactivex.core.Vertx rxVertx){
	return Fibers.fiber(() -> {
		System.err.println("Creating client");
		WebClientOptions options = new WebClientOptions();
		options.setSsl(true);
		options.setTrustAll(true);
		options.setVerifyHost(false);
		WebClient client = WebClient.create(rxVertx, options);
		Single<HttpResponse<io.vertx.reactivex.core.buffer.Buffer>> responseHandler = client.get(443,
				"www.google.com", 
				"/robots.txt").rxSend();

		System.err.println("Got response");

		HttpResponse<io.vertx.reactivex.core.buffer.Buffer> httpResponse = Fibers.await(responseHandler);
		System.err.println("Got body");
		client.close();
		
		return Response.ok(httpResponse.body().toString()).build();
	});
}
 
Example #21
Source File: SwaggerApiTest.java    From redpipe with Apache License 2.0 6 votes vote down vote up
@Before
public void prepare(TestContext context) throws IOException {
    Async async = context.async();

    server = new Server();
    server.start(ReactiveController.class)
            .subscribe(() -> {
                webClient = WebClient.create(server.getVertx(),
                        new WebClientOptions().setDefaultHost("localhost").setDefaultPort(9000));
                async.complete();
            }, x -> {
                x.printStackTrace();
                context.fail(x);
                async.complete();
            });
}
 
Example #22
Source File: ValidationHandlerTest.java    From vertx-starter with Apache License 2.0 6 votes vote down vote up
private void doTest(Vertx vertx, VertxTestContext testContext, ValidationHandler validator, MultiMap params, String extension, Handler<HttpResponse<Buffer>> handler) {
  Router router = Router.router(vertx);
  router.route().handler(validator).handler(rc -> {
    VertxProject vertProject = rc.get(WebVerticle.VERTX_PROJECT_KEY);
    rc.response().end(Json.encodePrettily(vertProject));
  });

  vertx.createHttpServer(new HttpServerOptions().setPort(0))
    .requestHandler(router)
    .listen(testContext.succeeding(server -> {

      WebClientOptions options = new WebClientOptions().setDefaultPort(server.actualPort());
      WebClient webClient = WebClient.create(vertx, options);

      HttpRequest<Buffer> request = webClient.get("/starter" + extension);
      request.queryParams().addAll(params);

      request.send(testContext.succeeding(handler));
    }));
}
 
Example #23
Source File: HttpAuthenticationProviderConfiguration.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Bean
@Qualifier("idpHttpAuthWebClient")
public WebClient httpClient() {
    WebClientOptions httpClientOptions = new WebClientOptions();
    httpClientOptions
            .setUserAgent(DEFAULT_USER_AGENT)
            .setConnectTimeout(configuration.getConnectTimeout())
            .setMaxPoolSize(configuration.getMaxPoolSize());

    if (configuration.getAuthenticationResource().getBaseURL() != null
            && configuration.getAuthenticationResource().getBaseURL().startsWith("https://")) {
        httpClientOptions.setSsl(true);
        httpClientOptions.setTrustAll(true);
    }

    return WebClient.create(vertx, httpClientOptions);
}
 
Example #24
Source File: HttpUserProviderConfiguration.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Bean
@Qualifier("idpHttpUsersWebClient")
public WebClient httpClient() {
    WebClientOptions httpClientOptions = new WebClientOptions();
    httpClientOptions
            .setUserAgent(DEFAULT_USER_AGENT)
            .setConnectTimeout(configuration.getConnectTimeout())
            .setMaxPoolSize(configuration.getMaxPoolSize());

    if (configuration.getUsersResource().getBaseURL() != null
            && configuration.getUsersResource().getBaseURL().startsWith("https://")) {
        httpClientOptions.setSsl(true);
        httpClientOptions.setTrustAll(true);
    }

    return WebClient.create(vertx, httpClientOptions);
}
 
Example #25
Source File: AbstractAdapterConfig.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Creates a new instance of {@link ResourceLimitChecks} based on prometheus metrics data.
 *
 * @return A ResourceLimitChecks instance.
 */
@Bean
@ConditionalOnClass(name = "io.micrometer.prometheus.PrometheusMeterRegistry")
@ConditionalOnProperty(name = "hono.resource-limits.prometheus-based.host")
public ResourceLimitChecks resourceLimitChecks() {
    final PrometheusBasedResourceLimitChecksConfig config = resourceLimitChecksConfig();
    final WebClientOptions webClientOptions = new WebClientOptions();
    webClientOptions.setDefaultHost(config.getHost());
    webClientOptions.setDefaultPort(config.getPort());
    webClientOptions.setTrustOptions(config.getTrustOptions());
    webClientOptions.setKeyCertOptions(config.getKeyCertOptions());
    webClientOptions.setSsl(config.isTlsEnabled());
    return new PrometheusBasedResourceLimitChecks(
            WebClient.create(vertx(), webClientOptions),
            config,
            newCaffeineCache(config.getCacheMinSize(), config.getCacheMaxSize()),
            getTracer());
}
 
Example #26
Source File: HttpBridgeTestBase.java    From strimzi-kafka-bridge with Apache License 2.0 6 votes vote down vote up
@BeforeAll
static void beforeAll(VertxTestContext context) {
    kafkaCluster.start();
    vertx = Vertx.vertx();

    LOGGER.info("Environment variable EXTERNAL_BRIDGE:" + BRIDGE_EXTERNAL_ENV);

    if ("FALSE".equals(BRIDGE_EXTERNAL_ENV)) {
        bridgeConfig = BridgeConfig.fromMap(config);
        httpBridge = new HttpBridge(bridgeConfig, new MetricsReporter(jmxCollectorRegistry, meterRegistry));
        httpBridge.setHealthChecker(new HealthChecker());

        LOGGER.info("Deploying in-memory bridge");
        vertx.deployVerticle(httpBridge, context.succeeding(id -> context.completeNow()));
    }
    // else we create external bridge from the OS invoked by `.jar`

    client = WebClient.create(vertx, new WebClientOptions()
        .setDefaultHost(Urls.BRIDGE_HOST)
        .setDefaultPort(Urls.BRIDGE_PORT)
    );
}
 
Example #27
Source File: ConsumerGeneratedNameTest.java    From strimzi-kafka-bridge with Apache License 2.0 6 votes vote down vote up
@BeforeAll
static void beforeAll(VertxTestContext context) {
    KAFKA_CLUSTER.start();
    vertx = Vertx.vertx();

    LOGGER.info("Environment variable EXTERNAL_BRIDGE:" + BRIDGE_EXTERNAL_ENV);

    if ("FALSE".equals(BRIDGE_EXTERNAL_ENV)) {
        bridgeConfig = BridgeConfig.fromMap(config);
        httpBridge = new HttpBridge(bridgeConfig, new MetricsReporter(jmxCollectorRegistry, meterRegistry));
        httpBridge.setHealthChecker(new HealthChecker());

        LOGGER.info("Deploying in-memory bridge");
        vertx.deployVerticle(httpBridge, context.succeeding(id -> context.completeNow()));
    }
    // else we create external bridge from the OS invoked by `.jar`

    client = WebClient.create(vertx, new WebClientOptions()
        .setDefaultHost(Urls.BRIDGE_HOST)
        .setDefaultPort(Urls.BRIDGE_PORT)
    );
}
 
Example #28
Source File: HttpAdapterClient.java    From enmasse with Apache License 2.0 6 votes vote down vote up
@Override
protected WebClient createClient() {
    var options = new WebClientOptions()
            .setSsl(true)
            .setTrustAll(true)
            .setVerifyHost(false);

    if (this.tlsVersions != null && !this.tlsVersions.isEmpty()) {
        // remove all current versions
        options.getEnabledSecureTransportProtocols().forEach(options::removeEnabledSecureTransportProtocol);
        // set new versions
        this.tlsVersions.forEach(options::addEnabledSecureTransportProtocol);
    }

    if (this.keyStoreBuffer != null) {
        options.setPfxKeyCertOptions(
                new PfxOptions()
                        .setValue(this.keyStoreBuffer)
                        .setPassword(KeyStoreCreator.KEY_PASSWORD));
    }

    return WebClient.create(vertx, options);
}
 
Example #29
Source File: MyResource.java    From redpipe with Apache License 2.0 6 votes vote down vote up
@Path("8")
@GET
public Single<String> hello8(@Context io.vertx.reactivex.core.Vertx rxVertx){
	System.err.println("Creating client");
	WebClientOptions options = new WebClientOptions();
	options.setSsl(true);
	options.setTrustAll(true);
	options.setVerifyHost(false);
	WebClient client = WebClient.create(rxVertx, options);
	Single<HttpResponse<io.vertx.reactivex.core.buffer.Buffer>> responseHandler = client.get(443,
			"www.google.com", 
			"/robots.txt").rxSend();

	System.err.println("Created client");
	return responseHandler.map(body -> {
		System.err.println("Got body");
		return body.body().toString();
	}).doAfterTerminate(() -> client.close());
}
 
Example #30
Source File: WebClientsConfiguration.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private WebClient createWebClient(Vertx vertx, URL url) {

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

        WebClientOptions options = new WebClientOptions()
                .setDefaultPort(port)
                .setDefaultHost(url.getHost())
                .setKeepAlive(true)
                .setMaxPoolSize(10)
                .setTcpKeepAlive(true)
                .setConnectTimeout(httpClientTimeout)
                .setSsl(url.getProtocol().equals(HTTPS_SCHEME));

        if (this.isProxyConfigured) {
            ProxyOptions proxyOptions = new ProxyOptions();
            proxyOptions.setType(ProxyType.valueOf(httpClientProxyType));
            if (HTTPS_SCHEME.equals(url.getProtocol())) {
                proxyOptions.setHost(httpClientProxyHttpsHost);
                proxyOptions.setPort(httpClientProxyHttpsPort);
                proxyOptions.setUsername(httpClientProxyHttpsUsername);
                proxyOptions.setPassword(httpClientProxyHttpsPassword);
            } else {
                proxyOptions.setHost(httpClientProxyHttpHost);
                proxyOptions.setPort(httpClientProxyHttpPort);
                proxyOptions.setUsername(httpClientProxyHttpUsername);
                proxyOptions.setPassword(httpClientProxyHttpPassword);
            }
            options.setProxyOptions(proxyOptions);
        }

        return WebClient.create(vertx, options);
    }