io.vertx.ext.web.client.webclient Java Examples
The following examples show how to use
io.vertx.ext.web.client.webclient.
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 |
/** * 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: AuditVerticleTest.java From vertx-microservices-workshop with Apache License 2.0 | 6 votes |
@Test public void testInsertion(TestContext tc) { Async async = tc.async(); vertx.eventBus().publish("portfolio", createBuyOperation()); WebClient.create(vertx).get(8081, "localhost", "/") .as(BodyCodec.jsonArray()) .send(tc.asyncAssertSuccess(response -> { tc.assertEquals(response.statusCode(), 200); tc.assertEquals(response.body().size(), 1); async.complete(); })); }
Example #3
Source File: WebClientExamples.java From vertx-web with Apache License 2.0 | 6 votes |
public void receiveResponseAsJsonObject(WebClient client) { client .get(8080, "myserver.mycompany.com", "/some-uri") .as(BodyCodec.jsonObject()) .send() .onSuccess(res -> { JsonObject body = res.body(); System.out.println( "Received response with status code" + res.statusCode() + " with body " + body); }) .onFailure(err -> System.out.println("Something went wrong " + err.getMessage())); }
Example #4
Source File: WebClientExamples.java From vertx-web with Apache License 2.0 | 6 votes |
public void manualSanityChecks(WebClient client) { client .get(8080, "myserver.mycompany.com", "/some-uri") .send() .onSuccess(res -> { if ( res.statusCode() == 200 && res.getHeader("content-type").equals("application/json")) { // Decode the body as a json object JsonObject body = res.bodyAsJsonObject(); System.out.println( "Received response with status code" + res.statusCode() + " with body " + body); } else { System.out.println("Something went wrong " + res.statusCode()); } }) .onFailure(err -> System.out.println("Something went wrong " + err.getMessage())); }
Example #5
Source File: WebClientExamples.java From vertx-web with Apache License 2.0 | 6 votes |
public void sendMultipartWithFileUpload(WebClient client) { MultipartForm form = MultipartForm.create() .attribute("imageDescription", "a very nice image") .binaryFileUpload( "imageFile", "image.jpg", "/path/to/image", "image/jpeg"); // Submit the form as a multipart form body client .post(8080, "myserver.mycompany.com", "/some-uri") .sendMultipartForm(form) .onSuccess(res -> { // OK }); }
Example #6
Source File: HttpKafkaConsumer.java From client-examples with Apache License 2.0 | 6 votes |
@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 #7
Source File: AbstractHealthServiceTest.java From cassandra-sidecar with Apache License 2.0 | 6 votes |
@DisplayName("Should return HTTP 503 Failure when check=False") @Test public void testHealthCheckReturns503Failure(VertxTestContext testContext) { check.setStatus(false); 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(503, response.statusCode()); testContext.completeNow(); }))); }
Example #8
Source File: PortfolioServiceImpl.java From vertx-microservices-workshop with Apache License 2.0 | 6 votes |
private Future<Double> getValueForCompany(WebClient client, String company, int numberOfShares) { // Create the future object that will get the value once the value have been retrieved Future<Double> future = Future.future(); //---- client.get("/?name=" + encode(company)) .as(BodyCodec.jsonObject()) .send(ar -> { if (ar.succeeded()) { HttpResponse<JsonObject> response = ar.result(); if (response.statusCode() == 200) { double v = numberOfShares * response.body().toJsonObject().getDouble("bid"); future.complete(v); } else { future.complete(0.0); } } else { future.fail(ar.cause()); } }); // --- return future; }
Example #9
Source File: WebClientExamples.java From vertx-web with Apache License 2.0 | 6 votes |
public void sendStream(WebClient client, FileSystem fs) { fs.open("content.txt", new OpenOptions(), fileRes -> { if (fileRes.succeeded()) { ReadStream<Buffer> fileStream = fileRes.result(); String fileLen = "1024"; // Send the file to the server using POST client .post(8080, "myserver.mycompany.com", "/some-uri") .putHeader("content-length", fileLen) .sendStream(fileStream) .onSuccess(res -> { // OK }) ; } }); }
Example #10
Source File: Http2TestCase.java From quarkus with Apache License 2.0 | 6 votes |
@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 #11
Source File: VertxTest.java From rest.vertx with Apache License 2.0 | 6 votes |
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 #12
Source File: ValidationHandlerTest.java From vertx-starter with Apache License 2.0 | 6 votes |
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 #13
Source File: ApiControllerTest.java From exonum-java-binding with Apache License 2.0 | 6 votes |
@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 #14
Source File: BridgeUtils.java From strimzi-kafka-operator with Apache License 2.0 | 6 votes |
public static JsonObject sendMessagesHttpRequest(JsonObject records, String bridgeHost, int bridgePort, String topicName, WebClient client) throws InterruptedException, ExecutionException, TimeoutException { LOGGER.info("Sending records to KafkaBridge"); CompletableFuture<JsonObject> future = new CompletableFuture<>(); client.post(bridgePort, bridgeHost, "/topics/" + topicName) .putHeader("Content-length", String.valueOf(records.toBuffer().length())) .putHeader("Content-Type", Constants.KAFKA_BRIDGE_JSON_JSON) .as(BodyCodec.jsonObject()) .sendJsonObject(records, ar -> { if (ar.succeeded()) { HttpResponse<JsonObject> response = ar.result(); if (response.statusCode() == HttpResponseStatus.OK.code()) { LOGGER.debug("Server accepted post"); future.complete(response.body()); } else { LOGGER.error("Server didn't accept post", ar.cause()); } } else { LOGGER.error("Server didn't accept post", ar.cause()); future.completeExceptionally(ar.cause()); } }); return future.get(1, TimeUnit.MINUTES); }
Example #15
Source File: HTTPEndpointExamples.java From vertx-service-discovery with Apache License 2.0 | 6 votes |
public void example2_webclient(ServiceDiscovery discovery) { // Get the record discovery.getRecord(new JsonObject().put("name", "some-http-service"), ar -> { if (ar.succeeded() && ar.result() != null) { // Retrieve the service reference ServiceReference reference = discovery.getReference(ar.result()); // Retrieve the service object WebClient client = reference.getAs(WebClient.class); // You need to path the complete path client.get("/api/persons").send( response -> { // ... // Dont' forget to release the service reference.release(); }); } }); }
Example #16
Source File: WebClientExamples.java From vertx-web with Apache License 2.0 | 6 votes |
public void receiveResponseAsJsonPOJO(WebClient client) { client .get(8080, "myserver.mycompany.com", "/some-uri") .as(BodyCodec.json(User.class)) .send() .onSuccess(res -> { User user = res.body(); System.out.println( "Received response with status code" + res.statusCode() + " with body " + user.getFirstName() + " " + user.getLastName()); }) .onFailure(err -> System.out.println("Something went wrong " + err.getMessage())); }
Example #17
Source File: WebClientExamples.java From vertx-web with Apache License 2.0 | 6 votes |
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 #18
Source File: WebClientExamples.java From vertx-web with Apache License 2.0 | 6 votes |
public void testSocketAddress(WebClient client) { // Creates the unix domain socket address to access the Docker API SocketAddress serverAddress = SocketAddress .domainSocketAddress("/var/run/docker.sock"); // We still need to specify host and port so the request // HTTP header will be localhost:8080 // otherwise it will be a malformed HTTP request // the actual value does not matter much for this example client .request( HttpMethod.GET, serverAddress, 8080, "localhost", "/images/json") .expect(ResponsePredicate.SC_ACCEPTED) .as(BodyCodec.jsonObject()) .send() .onSuccess(res -> System.out.println("Current Docker images" + res.body())) .onFailure(err -> System.out.println("Something went wrong " + err.getMessage())); }
Example #19
Source File: AbstractAdapterConfig.java From hono with Eclipse Public License 2.0 | 6 votes |
/** * 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 #20
Source File: PrometheusBasedResourceLimitChecks.java From hono with Eclipse Public License 2.0 | 6 votes |
/** * Creates new checks. * * @param webClient The client to use for querying the Prometheus server. * @param config The PrometheusBasedResourceLimitChecks configuration object. * @param cacheProvider The cache provider to use for creating caches for metrics data retrieved * from the prometheus backend or {@code null} if they should not be cached. * @param tracer The tracer instance. * @throws NullPointerException if any of the parameters except cacheProvider are {@code null}. */ public PrometheusBasedResourceLimitChecks( final WebClient webClient, final PrometheusBasedResourceLimitChecksConfig config, final CacheProvider cacheProvider, final Tracer tracer) { this.client = Objects.requireNonNull(webClient); this.config = Objects.requireNonNull(config); this.limitsCache = Optional.ofNullable(cacheProvider) .map(provider -> provider.getCache(LIMITS_CACHE_NAME)) .orElse(null); this.tracer = Objects.requireNonNull(tracer); this.url = String.format("%s://%s:%d%s", config.isTlsEnabled() ? "https" : "http", config.getHost(), config.getPort(), QUERY_URI); }
Example #21
Source File: ApiControllerTest.java From exonum-java-binding with Apache License 2.0 | 6 votes |
@BeforeEach void setup(Vertx vertx, VertxTestContext context) { httpServer = vertx.createHttpServer(); webClient = WebClient.create(vertx); Router router = Router.router(vertx); new ApiController(qaService).mountApi(router); httpServer.requestHandler(router) .listen(0, context.succeeding(result -> { // Set the actual server port. port = result.actualPort(); context.completeNow(); })); }
Example #22
Source File: PortfolioServiceImpl.java From vertx-microservices-workshop with Apache License 2.0 | 6 votes |
@Override public void evaluate(Handler<AsyncResult<Double>> resultHandler) { // ---- // First we need to discover and get a HTTP client for the `quotes` service: HttpEndpoint.getWebClient(discovery, new JsonObject().put("name", "quotes"), client -> { if (client.failed()) { // It failed... resultHandler.handle(Future.failedFuture(client.cause())); } else { // We have the client WebClient webClient = client.result(); computeEvaluation(webClient, resultHandler); } }); // --- }
Example #23
Source File: HttpEndpoint.java From vertx-service-discovery with Apache License 2.0 | 5 votes |
/** * Convenient method that looks for a HTTP endpoint and provides the configured {@linkWebClient}. The async result * is marked as failed is there are no matching services, or if the lookup fails. * * @param discovery The service discovery instance * @param filter The filter, optional * @param resultHandler The result handler */ static void getWebClient(ServiceDiscovery discovery, JsonObject filter, Handler<AsyncResult<WebClient>> resultHandler) { discovery.getRecord(filter, ar -> { if (ar.failed() || ar.result() == null) { resultHandler.handle(Future.failedFuture("No matching record")); } else { resultHandler.handle(Future.succeededFuture(discovery.<HttpClient>getReference(ar.result()).getAs(WebClient.class))); } }); }
Example #24
Source File: HonoApiClient.java From enmasse with Apache License 2.0 | 5 votes |
@Override protected WebClient createClient () { return WebClient.create(this.vertx, new WebClientOptions() .setSsl(true) .setTrustAll(true) .setVerifyHost(false)); }
Example #25
Source File: WebClientExamples.java From vertx-web with Apache License 2.0 | 5 votes |
public void receiveResponseAsWriteStream(WebClient client, WriteStream<Buffer> writeStream) { client .get(8080, "myserver.mycompany.com", "/some-uri") .as(BodyCodec.pipe(writeStream)) .send() .onSuccess(res -> System.out.println("Received response with status code" + res.statusCode())) .onFailure(err -> System.out.println("Something went wrong " + err.getMessage())); }
Example #26
Source File: HttpEndpoint.java From vertx-service-discovery with Apache License 2.0 | 5 votes |
/** * Convenient method that looks for a HTTP endpoint and provides the configured {@link WebClient}. The async result * is marked as failed is there are no matching services, or if the lookup fails. This method accepts a * configuration for the HTTP client * * @param discovery The service discovery instance * @param filter The filter, optional * @param conf the configuration of the client * @param resultHandler The result handler */ static void getWebClient(ServiceDiscovery discovery, JsonObject filter, JsonObject conf, Handler<AsyncResult<WebClient>> resultHandler) { discovery.getRecord(filter, ar -> { if (ar.failed() || ar.result() == null) { resultHandler.handle(Future.failedFuture("No matching record")); } else { resultHandler.handle(Future.succeededFuture(discovery.<HttpClient>getReferenceWithConfiguration(ar.result(), conf) .getAs(WebClient.class))); } }); }
Example #27
Source File: WebClientExamples.java From vertx-web with Apache License 2.0 | 5 votes |
public void sendBuffer(WebClient client, Buffer buffer) { // Send a buffer to the server using POST, the content-length // header will be set for you client .post(8080, "myserver.mycompany.com", "/some-uri") .sendBuffer(buffer) .onSuccess(res -> { // OK }); }
Example #28
Source File: ApiClient.java From enmasse with Apache License 2.0 | 5 votes |
/** * Get the client, create a new one if necessary. * * @return The client to use. */ protected WebClient getClient() { if (this.client == null) { this.client = createClient(); } return this.client; }
Example #29
Source File: WebClientExamples.java From vertx-web with Apache License 2.0 | 5 votes |
public void usingSpecificContentType(WebClient client) { client .get(8080, "myserver.mycompany.com", "/some-uri") .expect(ResponsePredicate.contentType("some/content-type")) .send() .onSuccess(res -> { // .... }); }
Example #30
Source File: HttpEndpointTest.java From vertx-service-discovery with Apache License 2.0 | 5 votes |
@Test public void testPublicationAndConsumptionAsWebClient(TestContext context) { Async async = context.async(); // Publish the service Record record = HttpEndpoint.createRecord("hello-service", "localhost", 8080, "/foo"); discovery.publish(record, rec -> { Record published = rec.result(); discovery.getRecord(new JsonObject().put("name", "hello-service"), found -> { context.assertTrue(found.succeeded()); context.assertTrue(found.result() != null); Record match = found.result(); ServiceReference reference = discovery.getReference(match); context.assertEquals(reference.record().getLocation().getString("endpoint"), "http://localhost:8080/foo"); context.assertFalse(reference.record().getLocation().getBoolean("ssl")); WebClient client = reference.getAs(WebClient.class); WebClient client2 = reference.cachedAs(WebClient.class); context.assertTrue(client == client2); client.get("/foo") .send(response -> { if (response.failed()) { context.fail(response.cause()); } else { HttpResponse<Buffer> resp = response.result(); context.assertEquals(resp.statusCode(), 200); context.assertEquals(resp.body().toString(), "hello"); reference.release(); discovery.unpublish(published.getRegistration(), v -> async.complete()); } }); }); }); }