Java Code Examples for io.vertx.core.Vertx#createHttpClient()

The following examples show how to use io.vertx.core.Vertx#createHttpClient() . 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: ClientCaOrWhitelistTest.java    From cava with Apache License 2.0 6 votes vote down vote up
@BeforeEach
void setupClient(@TempDirectory Path tempDir, @VertxInstance Vertx vertx) throws Exception {
  knownServersFile = tempDir.resolve("knownclients.txt");
  Files.write(
      knownServersFile,
      Arrays.asList("#First line", "localhost:" + fooServer.actualPort() + " " + fooFingerprint));

  HttpClientOptions options = new HttpClientOptions();
  options
      .setSsl(true)
      .setTrustOptions(VertxTrustOptions.whitelistServers(knownServersFile))
      .setConnectTimeout(1500)
      .setReuseAddress(true)
      .setReusePort(true);
  client = vertx.createHttpClient(options);
}
 
Example 2
Source File: KueRestApiTest.java    From vertx-kue with Apache License 2.0 6 votes vote down vote up
@Test
public void testApiGetJob(TestContext context) throws Exception {
  Vertx vertx = Vertx.vertx();
  HttpClient client = vertx.createHttpClient();
  Async async = context.async();
  kue.createJob(TYPE, new JsonObject().put("data", TYPE + ":data"))
    .save()
    .setHandler(jr -> {
      if (jr.succeeded()) {
        long id = jr.result().getId();
        client.getNow(PORT, HOST, "/job/" + id, response -> response.bodyHandler(body -> {
          context.assertEquals(new Job(new JsonObject(body.toString())).getId(), id);
          client.close();
          async.complete();
        }));
      } else {
        context.fail(jr.cause());
      }
    });
}
 
Example 3
Source File: ClientCaOrTofuTest.java    From incubator-tuweni with Apache License 2.0 6 votes vote down vote up
@BeforeEach
void setupClient(@TempDirectory Path tempDir, @VertxInstance Vertx vertx) throws Exception {
  knownServersFile = tempDir.resolve("known-hosts.txt");
  Files
      .write(
          knownServersFile,
          Arrays.asList("#First line", "localhost:" + foobarServer.actualPort() + " " + DUMMY_FINGERPRINT));

  HttpClientOptions options = new HttpClientOptions();
  options
      .setSsl(true)
      .setTrustOptions(VertxTrustOptions.trustServerOnFirstUse(knownServersFile))
      .setConnectTimeout(1500)
      .setReuseAddress(true)
      .setReusePort(true);
  client = vertx.createHttpClient(options);
}
 
Example 4
Source File: RouterFactory.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new OpenAPI3RouterFactory
 *
 * @param vertx
 * @param url location of your spec. It can be an absolute path, a local path or remote url (with HTTP/HTTPS protocol)
 * @param options options for specification loading
 * @param handler  When specification is loaded, this handler will be called with AsyncResult<OpenAPI3RouterFactory>
 */
static void create(Vertx vertx,
                   String url,
                   OpenAPILoaderOptions options,
                   Handler<AsyncResult<RouterFactory>> handler) {
  OpenAPIHolderImpl loader = new OpenAPIHolderImpl(vertx.createHttpClient(), vertx.fileSystem(), options);
  loader.loadOpenAPI(url).onComplete(ar -> {
    if (ar.failed()) {
      if (ar.cause() instanceof ValidationException) {
        handler.handle(Future.failedFuture(RouterFactoryException.createInvalidSpecException(ar.cause())));
      } else {
        handler.handle(Future.failedFuture(RouterFactoryException.createInvalidFileSpec(url, ar.cause())));
      }
    } else {
      RouterFactory factory;
      try {
        factory = new OpenAPI3RouterFactoryImpl(vertx, loader, options);
      } catch (Exception e) {
        handler.handle(Future.failedFuture(RouterFactoryException.createRouterFactoryInstantiationError(e, url)));
        return;
      }
      handler.handle(Future.succeededFuture(factory));
    }
  });
}
 
Example 5
Source File: ClientCaOrWhitelistTest.java    From incubator-tuweni with Apache License 2.0 6 votes vote down vote up
@BeforeEach
void setupClient(@TempDirectory Path tempDir, @VertxInstance Vertx vertx) throws Exception {
  knownServersFile = tempDir.resolve("knownclients.txt");
  Files
      .write(
          knownServersFile,
          Arrays.asList("#First line", "localhost:" + fooServer.actualPort() + " " + fooFingerprint));

  HttpClientOptions options = new HttpClientOptions();
  options
      .setSsl(true)
      .setTrustOptions(VertxTrustOptions.whitelistServers(knownServersFile))
      .setConnectTimeout(1500)
      .setReuseAddress(true)
      .setReusePort(true);
  client = vertx.createHttpClient(options);
}
 
Example 6
Source File: BasicHttpClientTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void requestShouldFailIfHttpRequestTimedOut(TestContext context) {
    // given
    final Vertx vertx = Vertx.vertx();
    final BasicHttpClient httpClient = new BasicHttpClient(vertx, vertx.createHttpClient());
    final int serverPort = 7777;

    startServer(serverPort, 2000L, 0L);

    // when
    final Async async = context.async();
    final Future<?> future = httpClient.get("http://localhost:" + serverPort, 1000L);
    future.setHandler(ar -> async.complete());
    async.await();

    // then
    assertThat(future.failed()).isTrue();
    assertThat(future.cause())
            .isInstanceOf(TimeoutException.class)
            .hasMessageStartingWith("Timeout period of 1000ms has been exceeded");
}
 
Example 7
Source File: Examples.java    From vertx-junit5 with Apache License 2.0 5 votes vote down vote up
@Test
public void usingVerify(Vertx vertx, VertxTestContext testContext) {
  HttpClient client = vertx.createHttpClient();

  client.get(8080, "localhost", "/")
    .compose(HttpClientResponse::body)
    .onComplete(testContext.succeeding(buffer -> testContext.verify(() -> {
      assertThat(buffer.toString()).isEqualTo("Plop");
      testContext.completeNow();
    })));
}
 
Example 8
Source File: NetworkUtilTest.java    From AlipayWechatPlatform with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void HttpClientTest() {
    Vertx vertx = Vertx.vertx();
    System.out.println("===================Test start===================");
    HttpClient client = vertx.createHttpClient();
    client.get(8080, "localhost", "/api/prod/dfsad", response -> {
        System.out.println("Received response with status code " + response.statusCode());
    }).end();
}
 
Example 9
Source File: OpenAPIHolderTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void schemaNormalizationTestOnlyReferenceToMyself(Vertx vertx, VertxTestContext testContext) {
  OpenAPIHolderImpl loader = new OpenAPIHolderImpl(vertx.createHttpClient(), vertx.fileSystem(), new OpenAPILoaderOptions());

  testContext.assertComplete(
    startSchemaServer(vertx, "./src/test/resources/specs/schemas", Collections.emptyList(), 8081)
      .compose(v -> loader.loadOpenAPI("specs/schemas_test_spec.yaml"))
  ).onComplete(l -> {
    testContext.verify(() -> {
      JsonPointer schemaPointer = JsonPointer.fromURI(URI.create("specs/schemas_test_spec.yaml#")).append(Arrays.asList(
        "paths", "/test8", "post", "requestBody", "content", "application/json", "schema"
      ));
      JsonObject resolved = (JsonObject) schemaPointer.query(loader.getOpenAPI(), new JsonPointerIteratorWithLoader(loader));

      Map<JsonPointer, JsonObject> additionalSchemasToRegister = new HashMap<>();
      Map.Entry<JsonPointer, JsonObject> normalizedEntry = loader.normalizeSchema(resolved, schemaPointer, additionalSchemasToRegister);
      JsonObject normalized = normalizedEntry.getValue();

      assertThat(additionalSchemasToRegister).hasSize(0);

      assertThatJson(normalized)
        .extracting(JsonPointer.create().append("properties").append("parent").append("$ref"))
        .asString()
        .isEqualTo("#");

      assertThatJson(normalized)
        .extracting(JsonPointer.create().append("properties").append("children").append("items").append("$ref"))
        .asString()
        .isEqualTo("#");

      testContext.completeNow();
    });
  });
}
 
Example 10
Source File: ServerCaOrWhitelistTest.java    From cava with Apache License 2.0 5 votes vote down vote up
@BeforeAll
static void setupClients(@TempDirectory Path tempDir, @VertxInstance Vertx vertx) throws Exception {
  SelfSignedCertificate caClientCert = SelfSignedCertificate.create();
  SecurityTestUtils.configureJDKTrustStore(tempDir, caClientCert);
  caClient = vertx.createHttpClient(
      new HttpClientOptions().setTrustOptions(InsecureTrustOptions.INSTANCE).setSsl(true).setKeyCertOptions(
          caClientCert.keyCertOptions()));

  SelfSignedCertificate fooCert = SelfSignedCertificate.create("foo.com");
  fooFingerprint = certificateHexFingerprint(Paths.get(fooCert.keyCertOptions().getCertPath()));
  HttpClientOptions fooClientOptions = new HttpClientOptions();
  fooClientOptions
      .setSsl(true)
      .setKeyCertOptions(fooCert.keyCertOptions())
      .setTrustOptions(InsecureTrustOptions.INSTANCE)
      .setConnectTimeout(1500)
      .setReuseAddress(true)
      .setReusePort(true);
  fooClient = vertx.createHttpClient(fooClientOptions);

  SelfSignedCertificate barCert = SelfSignedCertificate.create("bar.com");
  HttpClientOptions barClientOptions = new HttpClientOptions();
  barClientOptions
      .setSsl(true)
      .setKeyCertOptions(barCert.keyCertOptions())
      .setTrustOptions(InsecureTrustOptions.INSTANCE)
      .setConnectTimeout(1500)
      .setReuseAddress(true)
      .setReusePort(true);
  barClient = vertx.createHttpClient(barClientOptions);
}
 
Example 11
Source File: S3Client.java    From vertx-s3-client with Apache License 2.0 5 votes vote down vote up
public S3Client(Vertx vertx, S3ClientOptions s3ClientOptions, Clock clock) {
    checkNotNull(vertx, "vertx must not be null");
    checkNotNull(isNotBlank(s3ClientOptions.getAwsRegion()), "AWS region must be set");
    checkNotNull(isNotBlank(s3ClientOptions.getAwsServiceName()), "AWS service name must be set");
    checkNotNull(clock, "Clock must not be null");
    checkNotNull(s3ClientOptions.getGlobalTimeoutMs(), "global timeout must be null");
    checkArgument(s3ClientOptions.getGlobalTimeoutMs() > 0, "global timeout must be more than zero ms");

    this.jaxbMarshaller = createJaxbMarshaller();
    this.jaxbUnmarshaller = createJaxbUnmarshaller();

    this.vertx = vertx;
    this.clock = clock;
    this.awsServiceName = s3ClientOptions.getAwsServiceName();
    this.awsRegion = s3ClientOptions.getAwsRegion();
    this.awsAccessKey = s3ClientOptions.getAwsAccessKey();
    this.awsSecretKey = s3ClientOptions.getAwsSecretKey();
    this.globalTimeout = s3ClientOptions.getGlobalTimeoutMs();
    this.signPayload = s3ClientOptions.isSignPayload();

    final String hostnameOverride = s3ClientOptions.getHostnameOverride();
    if (!Strings.isNullOrEmpty(hostnameOverride)) {
        hostname = hostnameOverride;
    } else {
        if (DEFAULT_REGION.equals(s3ClientOptions.getAwsRegion())) {
            hostname = DEFAULT_ENDPOINT;
        } else {
            hostname = MessageFormat.format(ENDPOINT_PATTERN, awsRegion);
        }
    }

    final S3ClientOptions options = new S3ClientOptions(s3ClientOptions);
    options.setDefaultHost(hostname);

    this.client = vertx.createHttpClient(options);
}
 
Example 12
Source File: ServerTofaTest.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
@BeforeAll
static void setupClients(@TempDirectory Path tempDir, @VertxInstance Vertx vertx) throws Exception {
  SelfSignedCertificate caClientCert = SelfSignedCertificate.create("example.com");
  caFingerprint = certificateHexFingerprint(Paths.get(caClientCert.keyCertOptions().getCertPath()));
  SecurityTestUtils.configureJDKTrustStore(tempDir, caClientCert);
  caClient = vertx
      .createHttpClient(
          new HttpClientOptions()
              .setTrustOptions(InsecureTrustOptions.INSTANCE)
              .setSsl(true)
              .setKeyCertOptions(caClientCert.keyCertOptions()));

  SelfSignedCertificate fooCert = SelfSignedCertificate.create("foo.com");
  fooFingerprint = certificateHexFingerprint(Paths.get(fooCert.keyCertOptions().getCertPath()));
  HttpClientOptions fooClientOptions = new HttpClientOptions();
  fooClientOptions
      .setSsl(true)
      .setKeyCertOptions(fooCert.keyCertOptions())
      .setTrustOptions(InsecureTrustOptions.INSTANCE)
      .setConnectTimeout(1500)
      .setReuseAddress(true)
      .setReusePort(true);
  fooClient = vertx.createHttpClient(fooClientOptions);

  SelfSignedCertificate foobarCert = SelfSignedCertificate.create("foobar.com");
  HttpClientOptions foobarClientOptions = new HttpClientOptions();
  foobarClientOptions
      .setSsl(true)
      .setKeyCertOptions(foobarCert.keyCertOptions())
      .setTrustOptions(InsecureTrustOptions.INSTANCE)
      .setConnectTimeout(1500)
      .setReuseAddress(true)
      .setReusePort(true);
  foobarClient = vertx.createHttpClient(foobarClientOptions);
}
 
Example 13
Source File: SfsSingletonServer.java    From sfs with Apache License 2.0 5 votes vote down vote up
protected HttpClient createHttpClient(Vertx v, boolean https) {
    HttpClientOptions httpClientOptions = new HttpClientOptions()
            .setConnectTimeout(remoteNodeConnectTimeout)
            .setMaxPoolSize(remoteNodeMaxPoolSize)
            .setKeepAlive(true)
            .setPipelining(false)
            .setMaxWaitQueueSize(200)
            .setReuseAddress(true)
            .setIdleTimeout(remoteNodeIdleConnectionTimeout)
            .setSsl(https);

    HttpClient client = v.createHttpClient(httpClientOptions);

    return client;
}
 
Example 14
Source File: IntegrationTest.java    From vertx-junit5 with Apache License 2.0 5 votes vote down vote up
@Test
@Timeout(10_000)
@DisplayName("Start a HTTP server, make 10 client requests, and use several checkpoints")
void start_and_request_http_server_with_checkpoints(Vertx vertx, VertxTestContext testContext) {
  Checkpoint serverStarted = testContext.checkpoint();
  Checkpoint requestsServed = testContext.checkpoint(10);
  Checkpoint responsesReceived = testContext.checkpoint(10);

  vertx.createHttpServer()
    .requestHandler(req -> {
      req.response().end("Ok");
      requestsServed.flag();
    })
    .listen(8080, ar -> {
      if (ar.failed()) {
        testContext.failNow(ar.cause());
      } else {
        serverStarted.flag();
      }
    });

  HttpClient client = vertx.createHttpClient();
  for (int i = 0; i < 10; i++) {
    client.get(8080, "localhost", "/")
      .flatMap(HttpClientResponse::body)
      .onFailure(testContext::failNow)
      .onSuccess(buffer -> {
        testContext.verify(() -> assertThat(buffer.toString()).isEqualTo("Ok"));
        responsesReceived.flag();
      });
  }
}
 
Example 15
Source File: ServerWhitelistTest.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
@BeforeAll
static void setupClients(@TempDirectory Path tempDir, @VertxInstance Vertx vertx) throws Exception {
  SelfSignedCertificate caClientCert = SelfSignedCertificate.create();
  SecurityTestUtils.configureJDKTrustStore(tempDir, caClientCert);
  caClient = vertx
      .createHttpClient(
          new HttpClientOptions()
              .setTrustOptions(InsecureTrustOptions.INSTANCE)
              .setSsl(true)
              .setKeyCertOptions(caClientCert.keyCertOptions()));

  SelfSignedCertificate fooCert = SelfSignedCertificate.create("foo.com");
  fooFingerprint = certificateHexFingerprint(Paths.get(fooCert.keyCertOptions().getCertPath()));
  HttpClientOptions fooClientOptions = new HttpClientOptions();
  fooClientOptions
      .setSsl(true)
      .setKeyCertOptions(fooCert.keyCertOptions())
      .setTrustOptions(InsecureTrustOptions.INSTANCE)
      .setConnectTimeout(1500)
      .setReuseAddress(true)
      .setReusePort(true);
  fooClient = vertx.createHttpClient(fooClientOptions);

  SelfSignedCertificate barCert = SelfSignedCertificate.create("bar.com");
  HttpClientOptions barClientOptions = new HttpClientOptions();
  barClientOptions
      .setSsl(true)
      .setKeyCertOptions(barCert.keyCertOptions())
      .setTrustOptions(InsecureTrustOptions.INSTANCE)
      .setConnectTimeout(1500)
      .setReuseAddress(true)
      .setReusePort(true);
  barClient = vertx.createHttpClient(barClientOptions);
}
 
Example 16
Source File: OpenAPIHolderTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void loadFromFileLocalCircularRef(Vertx vertx, VertxTestContext testContext) {
  OpenAPIHolderImpl loader = new OpenAPIHolderImpl(vertx.createHttpClient(), vertx.fileSystem(), new OpenAPILoaderOptions());

  loader.loadOpenAPI("yaml/valid/local_circular_refs.yaml").onComplete(testContext.succeeding(openapi -> {
    testContext.verify(() -> {
      assertThat(loader)
          .hasCached(URI.create("yaml/valid/refs/Circular.yaml"));

      assertThat(loader)
          .extractingWithRefSolve(JsonPointer.create()
              .append("paths")
              .append("/simple")
              .append("post")
              .append("requestBody")
              .append("content")
              .append("application/json")
              .append("schema")
              .append("properties")
              .append("parent")
              .append("properties")
              .append("childs")
              .append("items")
              .append("properties")
              .append("value")
              .append("type")
          ).isEqualTo("string");
    });
    testContext.completeNow();
  }));
}
 
Example 17
Source File: OpenAPIHolderTest.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Test
public void schemaNormalizationTest(Vertx vertx, VertxTestContext testContext) {
  OpenAPIHolderImpl loader = new OpenAPIHolderImpl(vertx.createHttpClient(), vertx.fileSystem(), new OpenAPILoaderOptions());

  testContext.assertComplete(
    startSchemaServer(vertx, "./src/test/resources/specs/schemas", Collections.emptyList(), 8081)
      .compose(v -> loader.loadOpenAPI("specs/schemas_test_spec.yaml"))
  ).onComplete(l -> {
    testContext.verify(() -> {
      JsonPointer schemaPointer = JsonPointer.create().append(Arrays.asList(
        "paths", "/test10", "post", "requestBody", "content", "application/json", "schema"
      ));
      JsonObject resolved = (JsonObject) schemaPointer.query(loader.getOpenAPI(), new JsonPointerIteratorWithLoader(loader));

      assertThatJson(resolved.getString("$ref")).isEqualTo("http://localhost:8081/tree.yaml#/tree");

      Map<JsonPointer, JsonObject> additionalSchemasToRegister = new HashMap<>();
      Map.Entry<JsonPointer, JsonObject> normalizedEntry = loader.normalizeSchema(resolved, schemaPointer, additionalSchemasToRegister);
      JsonObject normalized = normalizedEntry.getValue();

      assertThat(additionalSchemasToRegister).hasSize(1);
      String treeObjectUri = additionalSchemasToRegister.keySet().iterator().next().toURI().toString();
      JsonObject treeObject = additionalSchemasToRegister.values().iterator().next();

      assertThat(normalized.getString("$ref")).isEqualTo(treeObjectUri);

      assertThatJson(treeObject)
        .extracting(JsonPointer.create().append("properties").append("childs").append("items").append("$ref"))
        .asString()
        .isEqualTo("#");

      testContext.completeNow();
    });
  });
}
 
Example 18
Source File: OAuth2API.java    From vertx-auth with Apache License 2.0 4 votes vote down vote up
public OAuth2API(Vertx vertx, OAuth2Options config) {
  this.config = config;
  this.client = vertx.createHttpClient(config.getHttpClientOptions());
}
 
Example 19
Source File: PullManager.java    From okapi with Apache License 2.0 4 votes vote down vote up
public PullManager(Vertx vertx, ModuleManager moduleManager) {
  this.httpClient = vertx.createHttpClient();
  this.moduleManager = moduleManager;
}
 
Example 20
Source File: CrudHttpClient.java    From hono with Eclipse Public License 2.0 2 votes vote down vote up
/**
 * Creates a new client for a host and port.
 *
 * @param vertx The vert.x instance to use.
 * @param options The client options to use for connecting to servers.
 * @throws NullPointerException if any of the parameters is {@code null}.
 */
public CrudHttpClient(final Vertx vertx, final HttpClientOptions options) {
    this.options = Objects.requireNonNull(options);
    this.client = vertx.createHttpClient(options);
    this.context = vertx.getOrCreateContext();
}