Java Code Examples for io.vertx.ext.web.client.WebClient#create()

The following examples show how to use io.vertx.ext.web.client.WebClient#create() . 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: WebClientExamples.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
public void simpleGetAndHead(Vertx vertx) {

    WebClient client = WebClient.create(vertx);

    // Send a GET request
    client
      .get(8080, "myserver.mycompany.com", "/some-uri")
      .send()
      .onSuccess(response -> System.out
        .println("Received response with status code" + response.statusCode()))
      .onFailure(err ->
        System.out.println("Something went wrong " + err.getMessage()));

    // Send a HEAD request
    client
      .head(8080, "myserver.mycompany.com", "/some-uri")
      .send()
      .onSuccess(response -> System.out
        .println("Received response with status code" + response.statusCode()))
      .onFailure(err ->
        System.out.println("Something went wrong " + err.getMessage()));
  }
 
Example 2
Source File: ApiControllerTest.java    From exonum-java-binding with Apache License 2.0 6 votes vote down vote up
@BeforeEach
void setup(Vertx vertx, VertxTestContext context) {
  httpServer = vertx.createHttpServer();
  webClient = WebClient.create(vertx);

  Router router = Router.router(vertx);
  ApiController controller = new ApiController(service);
  controller.mountApi(router);

  httpServer.requestHandler(router)
      .listen(0, context.succeeding(result -> {
        // Set the actual server port.
        port = result.actualPort();
        // Notify that the HTTP Server is accepting connections.
        context.completeNow();
      }));
}
 
Example 3
Source File: VertxTest.java    From rest.vertx with Apache License 2.0 6 votes vote down vote up
public static void before() {

        vertx = Vertx.vertx();
        vertxTestContext = new VertxTestContext();

        // clear all registered writers or reader and handlers
        RestRouter.getReaders().clear();
        RestRouter.getWriters().clear();
        RestRouter.getExceptionHandlers().clear();
        RestRouter.getContextProviders().clear();

        // clear
        RestRouter.validateWith((Validator) null);
        RestRouter.injectWith((InjectionProvider) null);

        client = WebClient.create(vertx);
    }
 
Example 4
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 5
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 6
Source File: AbstractHealthServiceTest.java    From cassandra-sidecar with Apache License 2.0 6 votes vote down vote up
@DisplayName("Should return HTTP 200 OK when check=True")
@Test
public void testHealthCheckReturns200OK(VertxTestContext testContext)
{
    check.setStatus(true);
    service.refreshNow();

    WebClient client = WebClient.create(vertx);

    client.get(config.getPort(), "localhost", "/api/v1/__health")
          .as(BodyCodec.string())
          .ssl(isSslEnabled())
          .send(testContext.succeeding(response -> testContext.verify(() ->
          {
              Assert.assertEquals(200, response.statusCode());
              testContext.completeNow();
          })));
}
 
Example 7
Source File: CollectorService.java    From vertx-in-action with MIT License 5 votes vote down vote up
@Override
public void start(Promise<Void> promise) {
  webClient = WebClient.create(vertx);
  vertx.createHttpServer()
    .requestHandler(this::handleRequest)
    .listen(8080)
    .onFailure(promise::fail)
    .onSuccess(ok -> {
      System.out.println("http://localhost:8080/");
      promise.complete();
    });
}
 
Example 8
Source File: Stadium.java    From demo-mesh-arena with Apache License 2.0 5 votes vote down vote up
private Stadium(Vertx vertx) {
  client = WebClient.create(vertx);
  stadiumJson = new JsonObject()
      .put("id", NAME + "-stadium")
      .put("style", "position: absolute; top: " + TX_TOP + "px; left: " + TX_LEFT + "px; width: " + TX_WIDTH + "px; height: " + TX_HEIGHT + "px; background-image: url(./football-ground.png); background-size: cover; color: black")
      .put("text", "");

  scoreJson = new JsonObject()
      .put("id", NAME + "-score")
      .put("style", "position: absolute; top: " + (TX_TOP + 5) + "px; left: " + (TX_LEFT + 5) + "px; color: black; font-weight: bold; z-index: 10;")
      .put("text", "");
}
 
Example 9
Source File: SessionTokenGrantAuthHandler.java    From VX-API-Gateway with MIT License 5 votes vote down vote up
/**
 * 当存在坏的后台服务时重试连接后台看后台连接是否可用
 * 
 * @param vertx
 */
public void retryConnServer(Vertx vertx) {
	if (!policy.isCheckWaiting()) {
		if (webClient == null) {
			webClient = WebClient.create(vertx);
		}
		policy.setCheckWaiting(true);
		vertx.setTimer(serOptions.getRetryTime(), testConn -> {
			List<VxApiServerURLInfo> service = policy.getBadService();
			if (service != null) {
				for (VxApiServerURLInfo urlinfo : service) {
					webClient.requestAbs(serOptions.getMethod(), urlinfo.getUrl()).timeout(serOptions.getTimeOut()).send(res -> {
						if (res.succeeded()) {
							int statusCode = res.result().statusCode();
							if (statusCode != 200) {
								LOG.warn(String.format("应用:%s -> API:%s重试连接后台服务URL,连接成功但得到一个%d状态码,", api.getAppName(), api.getApiName(), statusCode));
							} else {
								if (LOG.isDebugEnabled()) {
									LOG.debug(String.format("应用:%s -> API:%s重试连接后台服务URL,连接成功!", api.getAppName(), api.getApiName()));
								}
							}
							policy.reportGreatService(urlinfo.getIndex());
						}
					});
				}
			}
			policy.setCheckWaiting(false);
		});
	}
}
 
Example 10
Source File: PrometheusApiClient.java    From enmasse with Apache License 2.0 5 votes vote down vote up
@Override
protected WebClient createClient() {
    return WebClient.create(vertx, new WebClientOptions()
            .setSsl(true)
            .setTrustAll(true)
            .setVerifyHost(false));
}
 
Example 11
Source File: HttpCorsTests.java    From strimzi-kafka-bridge with Apache License 2.0 5 votes vote down vote up
private void createWebClient() {
    client = WebClient.create(vertx, new WebClientOptions()
            .setDefaultHost(Urls.BRIDGE_HOST)
            .setDefaultPort(Urls.BRIDGE_PORT)
    );

}
 
Example 12
Source File: CollectorServiceCBH.java    From vertx-in-action with MIT License 5 votes vote down vote up
@Override
public void start() {
  webClient = WebClient.create(vertx);
  vertx.createHttpServer()
    .requestHandler(this::handleRequest)
    .listen(8080);
}
 
Example 13
Source File: HttpBridgeBaseST.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@BeforeAll
void deployClusterOperator(Vertx vertx) throws Exception {
    ResourceManager.setClassResources();
    installClusterOperator(getBridgeNamespace());

    // Create http client
    client = WebClient.create(vertx, new WebClientOptions()
        .setSsl(false));
}
 
Example 14
Source File: HeatApi.java    From vertx-in-action with MIT License 5 votes vote down vote up
@Override
public void start(Promise<Void> startPromise) {
  Map<String, String> env = System.getenv();
  int httpPort = Integer.parseInt(env.getOrDefault("HTTP_PORT", "8080"));
  String gatewayHost = env.getOrDefault("GATEWAY_HOST", "sensor-gateway");
  int gatewayPort = Integer.parseInt(env.getOrDefault("GATEWAY_PORT", "8080"));
  lowLimit = Double.parseDouble(env.getOrDefault("LOW_TEMP", "10.0"));
  highLimit = Double.parseDouble(env.getOrDefault("HIGH_TEMP", "30.0"));

  logger.info("Correct temperatures range: [{}, {}]", lowLimit, highLimit);

  webClient = WebClient.create(vertx, new WebClientOptions()
    .setDefaultHost(gatewayHost)
    .setDefaultPort(gatewayPort));

  Router router = Router.router(vertx);
  router.get("/all").handler(this::fetchAllData);
  router.get("/warnings").handler(this::sensorsOverLimits);
  router.get("/health/ready").handler(this::readinessCheck);
  router.get("/health/live").handler(this::livenessCheck);

  vertx.createHttpServer()
    .requestHandler(router)
    .listen(httpPort, ar -> {
      if (ar.succeeded()) {
        logger.info("HTTP server listening on port {}", httpPort);
        startPromise.complete();
      } else {
        startPromise.fail(ar.cause());
      }
    });
}
 
Example 15
Source File: ApiClient.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Build the WebClient used to make HTTP requests.
 *
 * @param vertx Vertx
 * @return WebClient
 */
protected WebClient buildWebClient(Vertx vertx, JsonObject config) {

    if (!config.containsKey("userAgent")) {
        config.put("userAgent", "OpenAPI-Generator/1.0.0/java");
    }

    return WebClient.create(vertx, new WebClientOptions(config));
}
 
Example 16
Source File: HTTPFunctionClient.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
private void createClient() {
  final RemoteFunctionConfig remoteFunction = getConnectorConfig().remoteFunction;
  if (!(remoteFunction instanceof Http)) {
    throw new IllegalArgumentException("Invalid remoteFunctionConfig argument, must be an instance of HTTP");
  }
  Http httpRemoteFunction = (Http) remoteFunction;
  url = httpRemoteFunction.url.toString();
  webClient = WebClient.create(Service.vertx, new WebClientOptions()
      .setUserAgent(Service.XYZ_HUB_USER_AGENT)
      .setMaxPoolSize(getMaxConnections()));
}
 
Example 17
Source File: ConsulClientImpl.java    From vertx-consul-client with Apache License 2.0 5 votes vote down vote up
public ConsulClientImpl(Vertx vertx, ConsulClientOptions options) {
  Objects.requireNonNull(vertx);
  Objects.requireNonNull(options);
  webClient = WebClient.create(vertx, options);
  ctx = vertx.getOrCreateContext();
  aclToken = options.getAclToken();
  dc = options.getDc();
  timeoutMs = options.getTimeout();
}
 
Example 18
Source File: Config.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * Constructs messageMapping.
 *
 * @return Returns MessageMapping containing a webclient to perform mapper requests.
 */
@Bean
public MessageMapping<MqttContext> messageMapping() {
    final WebClient webClient = WebClient.create(vertx());
    return new HttpBasedMessageMapping(webClient, adapterProperties());
}
 
Example 19
Source File: WebClientExamples.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
public void create(Vertx vertx) {
  WebClient client = WebClient.create(vertx);
}
 
Example 20
Source File: WebClientExamples.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
public void testClientChangeMaxRedirects(Vertx vertx) {

    // Follow at most 5 redirections
    WebClient client = WebClient
      .create(vertx, new WebClientOptions().setMaxRedirects(5));
  }