@Path("3") @GET public void hello3(@Suspended final AsyncResponse asyncResponse, // Inject the Vertx instance @Context Vertx vertx){ System.err.println("Creating client"); HttpClientOptions options = new HttpClientOptions(); options.setSsl(true); options.setTrustAll(true); options.setVerifyHost(false); HttpClient client = vertx.createHttpClient(options); client.getNow(443, "www.google.com", "/robots.txt", resp -> { System.err.println("Got response"); resp.bodyHandler(body -> { System.err.println("Got body"); asyncResponse.resume(Response.ok(body.toString()).build()); }); }); System.err.println("Created client"); }
@Test public void createClientPool(@Mocked Vertx vertx, @Mocked Context context, @Mocked HttpClient httpClient) { new Expectations(VertxImpl.class) { { VertxImpl.context(); result = context; context.owner(); result = vertx; vertx.createHttpClient(httpClientOptions); result = httpClient; } }; HttpClientWithContext pool = factory.createClientPool(); Assert.assertSame(context, pool.context()); Assert.assertSame(httpClient, pool.getHttpClient()); }
HttpClientRequest createRequest(HttpClient client, Invocation invocation, IpPort ipPort, String path, AsyncResponse asyncResp) { URIEndpointObject endpoint = (URIEndpointObject) invocation.getEndpoint().getAddress(); RequestOptions requestOptions = new RequestOptions(); requestOptions.setHost(ipPort.getHostOrIp()) .setPort(ipPort.getPort()) .setSsl(endpoint.isSslEnabled()) .setURI(path); HttpMethod method = getMethod(invocation); LOGGER.debug("Sending request by rest, method={}, qualifiedName={}, path={}, endpoint={}.", method, invocation.getMicroserviceQualifiedName(), path, invocation.getEndpoint().getEndpoint()); HttpClientRequest request = client.request(method, requestOptions, response -> { handleResponse(invocation, response, asyncResp); }); return request; }
@Test public void testDoMethodNullPointerException(@Mocked HttpClient httpClient) throws Exception { Context context = new MockUp<Context>() { @Mock public void runOnContext(Handler<Void> action) { action.handle(null); } }.getMockInstance(); HttpClientWithContext httpClientWithContext = new HttpClientWithContext(httpClient, context); Invocation invocation = mock(Invocation.class); AsyncResponse asyncResp = mock(AsyncResponse.class); try { this.doMethod(httpClientWithContext, invocation, asyncResp); fail("Expect to throw NullPointerException, but got none"); } catch (NullPointerException e) { } }
@Test public void testCreateRequest() { HttpClient client = mock(HttpClient.class); Invocation invocation = mock(Invocation.class); OperationMeta operationMeta = mock(OperationMeta.class); Endpoint endpoint = mock(Endpoint.class); URIEndpointObject address = mock(URIEndpointObject.class); when(invocation.getEndpoint()).thenReturn(endpoint); when(endpoint.getAddress()).thenReturn(address); when(address.isSslEnabled()).thenReturn(false); when(invocation.getOperationMeta()).thenReturn(operationMeta); RestOperationMeta swaggerRestOperation = mock(RestOperationMeta.class); when(operationMeta.getExtData(RestConst.SWAGGER_REST_OPERATION)).thenReturn(swaggerRestOperation); IpPort ipPort = mock(IpPort.class); when(ipPort.getPort()).thenReturn(10); when(ipPort.getHostOrIp()).thenReturn("ever"); AsyncResponse asyncResp = mock(AsyncResponse.class); List<HttpMethod> methods = new ArrayList<>( Arrays.asList(HttpMethod.GET, HttpMethod.PUT, HttpMethod.POST, HttpMethod.DELETE, HttpMethod.PATCH)); for (HttpMethod method : methods) { when(swaggerRestOperation.getHttpMethod()).thenReturn(method.toString()); HttpClientRequest obj = VertxHttpMethod.INSTANCE.createRequest(client, invocation, ipPort, "good", asyncResp); Assert.assertNull(obj); } }
public VertxClientEngine(final HttpClient httpClient) { try { this.httpClient = httpClient; sslContext = SSLContext.getDefault(); hostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier(); } catch (final NoSuchAlgorithmException e) { throw new ExceptionInInitializerError(e); } }
@Test public void testEngineWithInjectedClientPost() { final HttpClient httpClient = Vertx.vertx().createHttpClient(httpClientOptions); final Client client = new ResteasyClientBuilder().httpEngine(new VertxClientEngine(httpClient)) .register(GsonMessageBodyHandler.class).build(); final Form xform = new Form(); xform.param("userName", "ca1\\\\meowmix"); xform.param("password", "mingnamulan"); xform.param("state", "authenticate"); xform.param("style", "xml"); xform.param("xsl", "none"); final JsonObject arsString = client.target("https://httpbin.org/post").request() .post(Entity.form(xform), JsonObject.class); assertEquals("xml", arsString.getAsJsonObject("form").get("style").getAsString()); }
private Future<Double> getValueForCompany(HttpClient 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(root + "/?name=" + encode(company), response -> { response.exceptionHandler(future::fail); if (response.statusCode() == 200) { response.bodyHandler(buffer -> { double v = numberOfShares * buffer.toJsonObject().getDouble("bid"); future.complete(v); }); } else { future.complete(0.0); } }) .exceptionHandler(future::fail) .end(); return future; }
@Test public void testConfigurationOptions(TestContext testContext) throws Exception { final HttpClientOptions options = new HttpClientOptions().setTryUseCompression(false); final HttpClient httpClient = runTestOnContext.vertx().createHttpClient(options); final Async asyncOp = testContext.async(); // issue a request on the custom server bind address and port, testing for compression httpClient.get(SERVER_PORT, SERVER_BIND_ADDRESS, "/hystrix-dashboard/") .setChunked(false) .putHeader(HttpHeaders.ACCEPT_ENCODING, HttpHeaders.DEFLATE_GZIP) .handler(resp -> { testContext.assertEquals(200, resp.statusCode(), "Should have fetched the index page with status 200"); testContext.assertEquals("gzip", resp.getHeader(HttpHeaders.CONTENT_ENCODING)); }) .exceptionHandler(testContext::fail) .endHandler(event -> asyncOp.complete()) .end(); }
public void example2(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 HttpClient client = reference.getAs(HttpClient.class); // You need to path the complete path client.getNow("/api/persons", response -> { // ... // Dont' forget to release the service reference.release(); }); } }); }
public void example3(ServiceDiscovery discovery) { HttpEndpoint.getClient(discovery, new JsonObject().put("name", "some-http-service"), ar -> { if (ar.succeeded()) { HttpClient client = ar.result(); // You need to path the complete path client.getNow("/api/persons", response -> { // ... // Dont' forget to release the service ServiceDiscovery.releaseServiceObject(discovery, client); }); } }); }
@Test public void testPublicationAndConsumptionWithConfiguration(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(); HttpEndpoint.getClient(discovery, new JsonObject().put("name", "hello-service"), new JsonObject().put ("keepAlive", false), found -> { context.assertTrue(found.succeeded()); context.assertTrue(found.result() != null); HttpClient client = found.result(); client.getNow("/foo", response -> { context.assertEquals(response.statusCode(), 200); context.assertEquals(response.getHeader("connection"), "close"); response.bodyHandler(body -> { context.assertEquals(body.toString(), "hello"); ServiceDiscovery.releaseServiceObject(discovery, client); discovery.unpublish(published.getRegistration(), v -> async.complete()); }); }); }); }); }
public void handshake(HttpClient hc, FileSystem fs) { HttpClientRequest request = hc.put(AgentConstant.SERVER_PORT, AgentConstant.SERVER_ADDR, "", resp -> { System.out.println("Response: Hand Shake Status Code - " + resp.statusCode()); System.out.println("Response: Hand Shake Status Message - " + resp.statusMessage()); if (resp.statusCode() == AgentConstant.RES_SUCCESS) { System.out.println("Response: Hand Shake Status - SUCCESSFUL!"); //check if it is file/folder processing if(Files.isDirectory(Paths.get(AgentConstant.FILE_NAME))) { streamFilesDir(hc, fs); } else streamFile(hc, fs); } else System.out.println("Response: Hand Shake Status - FAILED!"); }); request.headers().add("DF_PROTOCOL","REGISTER"); request.headers().add("DF_MODE", AgentConstant.TRANS_MODE); request.headers().add("DF_TYPE", "META"); request.headers().add("DF_TOPIC", AgentConstant.META_TOPIC); request.headers().add("DF_FILENAME", AgentConstant.FILE_NAME); request.headers().add("DF_FILTER", AgentConstant.FILTER_TYPE); request.headers().add("DF_DATA_TRANS", AgentConstant.DATA_TRANS); request.end(setMetaData(AgentConstant.FILE_NAME)); }
private Future<JsonObject> getInventory(ProductTuple product, HttpClient client) { Future<Integer> future = Future.future(); client.get("/" + product.getProductId(), response -> { if (response.statusCode() == 200) { response.bodyHandler(buffer -> { try { int inventory = Integer.valueOf(buffer.toString()); future.complete(inventory); } catch (NumberFormatException ex) { future.fail(ex); } }); } else { future.fail("not_found:" + product.getProductId()); } }) .exceptionHandler(future::fail) .end(); return future.map(inv -> new JsonObject() .put("id", product.getProductId()) .put("inventory", inv) .put("amount", product.getAmount())); }
@Test public void test404Response() throws Exception { HttpClientOptions options = new HttpClientOptions(); options.setDefaultHost("localhost"); options.setDefaultPort(port()); HttpClient client = Mesh.vertx().createHttpClient(options); CompletableFuture<String> future = new CompletableFuture<>(); HttpClientRequest request = client.request(HttpMethod.POST, "/api/v1/test", rh -> { rh.bodyHandler(bh -> { future.complete(bh.toString()); }); }); request.end(); String response = future.get(1, TimeUnit.SECONDS); assertTrue("The response string should not contain any html specific characters but it was {" + response + "} ", response.indexOf("<") != 0); }
@Test public void testPaymentRoutes() throws InterruptedException { HttpClient client = vertx.createHttpClient(new HttpClientOptions().setDefaultPort(8080)); client.get("/payments").handler(r -> r.bodyHandler(b -> SYNCHRONIZER.add(b.toString()))).end(); String response = poll().toString(); JsonArray array = new JsonArray(response); assertEquals(2, array.size()); JsonObject fooPayment = array.getJsonObject(0); assertEquals("foo", fooPayment.getString("id")); assertEquals("1", fooPayment.getString("amount")); client.get("/payments/bar").handler(r -> r.bodyHandler(b -> SYNCHRONIZER.add(b.toString()))).end(); response = poll().toString(); JsonObject barPayment = new JsonObject(response); assertEquals("bar", barPayment.getString("id")); assertEquals("100", barPayment.getString("amount")); }
@Test public void testNestedRoutes() throws InterruptedException { HttpClient client = vertx.createHttpClient(new HttpClientOptions().setDefaultPort(8080)); client.get("/payments").handler(r -> r.bodyHandler(b -> SYNCHRONIZER.add(b.toString()))).end(); String response = poll().toString(); JsonArray array = new JsonArray(response); assertEquals(2, array.size()); JsonObject fooPayment = array.getJsonObject(0); assertEquals("foo", fooPayment.getString("id")); assertEquals("1", fooPayment.getString("amount")); client.get("/payments/bar").handler(r -> r.bodyHandler(b -> SYNCHRONIZER.add(b.toString()))).end(); response = poll().toString(); JsonObject barPayment = new JsonObject(response); assertEquals("bar", barPayment.getString("id")); assertEquals("100", barPayment.getString("amount")); // Test ignored routes client.get("/payments/inner").handler(r -> SYNCHRONIZER.add("" + r.statusCode())).end(); assertEquals("404", poll()); client.get("/payments/string").handler(r -> SYNCHRONIZER.add("" + r.statusCode())).end(); assertEquals("404", poll()); }
@Test public void testAdminConfigRendering() throws InterruptedException, ExecutionException, TimeoutException { HttpClient client = createHttpClient(); CompletableFuture<String> future = new CompletableFuture<>(); HttpClientRequest request = client.request(GET, "/mesh-ui/mesh-ui-config.js", rh -> { rh.bodyHandler(bh -> { if (rh.statusCode() == 200) { future.complete(bh.toString()); } else { future.completeExceptionally(new Exception("Status code wrong {" + rh.statusCode() + "}")); } }); }); request.end(); String response = future.get(10, TimeUnit.SECONDS); // String expectedUrl = "localhost:" + port; // assertTrue("The meshConfig.js file did not contain the expected url {" + expectedUrl + "} Response {" + response + "}", // response.contains(expectedUrl)); // System.out.println(response); assertTrue("The response string should not contain any html specific characters but it was {" + response + "} ", response.indexOf("<") != 0); }
private void testVerifyQueryParticularCluster(Function<ClusterSpec, String> f) { HttpClient client = vertx.createHttpClient(); ClusterSpec clusterQueried = this.createMultiNodeCluster(client, "3,3"); ClusterSpec clusterUnused = this.createMultiNodeCluster(client, "3,3"); String query = "Select * FROM TABLE2_" + clusterQueried.getName(); RequestPrime prime = createSimplePrimedQuery(query); HttpTestResponse response = this.primeSimpleRequest(client, prime, "/prime" + "/" + f.apply(clusterQueried)); Iterator<NodeSpec> nodeIteratorQueried = clusterQueried.getNodes().iterator(); Iterator<NodeSpec> nodeIteratorUnused = clusterUnused.getNodes().iterator(); while (nodeIteratorQueried.hasNext()) { NodeSpec node = nodeIteratorQueried.next(); String contactPoint = HttpTestUtil.getContactPointStringByNodeID(node); ResultSet set = HttpTestUtil.makeNativeQuery(query, contactPoint); List<Row> results = set.all(); assertThat(1).isEqualTo(results.size()); } while (nodeIteratorUnused.hasNext()) { String contactPointUnused = HttpTestUtil.getContactPointStringByNodeID(nodeIteratorUnused.next()); ResultSet setUnused = HttpTestUtil.makeNativeQuery(query, contactPointUnused); List<Row> resultsUnused = setUnused.all(); assertThat(0).isEqualTo(resultsUnused.size()); } }
private void testVerifyQueryParticularDatacenter( Function<ClusterSpec, String> fc, Function<DataCenterSpec, String> fd) { HttpClient client = vertx.createHttpClient(); ClusterSpec clusterQueried = this.createMultiNodeCluster(client, "3,3"); ClusterSpec clusterUnused = this.createMultiNodeCluster(client, "3,3"); String query = "Select * FROM TABLE2_" + clusterQueried.getName(); RequestPrime prime = createSimplePrimedQuery(query); List<DataCenterSpec> datacenters = (List<DataCenterSpec>) clusterQueried.getDataCenters(); DataCenterSpec datacenterQueried = datacenters.get(0); this.primeSimpleRequest(client, prime, fc.apply(clusterQueried), fd.apply(datacenterQueried)); Iterator<NodeSpec> nodeIteratorQueried = clusterQueried.getNodes().iterator(); Iterator<NodeSpec> nodeIteratorUnused = clusterUnused.getNodes().iterator(); while (nodeIteratorQueried.hasNext()) { NodeSpec node = nodeIteratorQueried.next(); String contactPoint = HttpTestUtil.getContactPointStringByNodeID(node); ResultSet set = HttpTestUtil.makeNativeQuery(query, contactPoint); List<Row> results = set.all(); if (node.getDataCenter().equals(datacenterQueried)) { assertThat(1).isEqualTo(results.size()); } else { assertThat(0).isEqualTo(results.size()); } } while (nodeIteratorUnused.hasNext()) { String contactPointUnused = HttpTestUtil.getContactPointStringByNodeID(nodeIteratorUnused.next()); ResultSet setUnused = HttpTestUtil.makeNativeQuery(query, contactPointUnused); List<Row> resultsUnused = setUnused.all(); assertThat(0).isEqualTo(resultsUnused.size()); } }
private HttpTestResponse primeSimpleRequest(HttpClient client, RequestPrime query, String path) { CompletableFuture<HttpTestResponse> future = new CompletableFuture<>(); try { String jsonPrime = om.writerWithDefaultPrettyPrinter().writeValueAsString(query); client .request( HttpMethod.POST, portNum, "127.0.0.1", path, response -> { response.bodyHandler( totalBuffer -> { String body = totalBuffer.toString(); HttpTestResponse testResponse = new HttpTestResponse(response, body); future.complete(testResponse); }); }) .putHeader("content-length", Integer.toString(jsonPrime.length())) .write(jsonPrime) .end(); HttpTestResponse responseToValidate = future.get(); assertThat(responseToValidate.response.statusCode()).isEqualTo(201); return responseToValidate; } catch (Exception e) { logger.error("Exception", e); fail("Exception encountered"); } return null; }
private HttpTestResponse clearQueries(HttpClient client, Scope scope) { CompletableFuture<HttpTestResponse> future = new CompletableFuture<>(); try { client .request( HttpMethod.DELETE, portNum, "127.0.0.1", "/prime/" + scope.toString(), response -> { response.bodyHandler( totalBuffer -> { String body = totalBuffer.toString(); HttpTestResponse testResponse = new HttpTestResponse(response, body); future.complete(testResponse); }); }) .end(); HttpTestResponse responseToValidate = future.get(); assertThat(responseToValidate.response.statusCode()).isEqualTo(202); return responseToValidate; } catch (Exception e) { logger.error("Exception", e); fail("Exception encountered"); } return null; }
private ClusterSpec createSingleNodeCluster(HttpClient client) { CompletableFuture<HttpTestResponse> future = new CompletableFuture<>(); client .request( HttpMethod.POST, portNum, "127.0.0.1", "/cluster/?data_centers=1", response -> { response.bodyHandler( totalBuffer -> { String body = totalBuffer.toString(); HttpTestResponse testResponse = new HttpTestResponse(response, body); future.complete(testResponse); }); }) .end(); try { HttpTestResponse responseToValidate = future.get(); ObjectMapper om = ObjectMapperHolder.getMapper(); // create cluster object from json return code assertThat(responseToValidate.response.statusCode()).isEqualTo(201); ClusterSpec cluster = om.readValue(responseToValidate.body, ClusterSpec.class); return cluster; } catch (Exception e) { fail("Exception encountered"); return null; } }
private ClusterSpec createMultiNodeCluster(HttpClient client, String datacenters) { CompletableFuture<HttpTestResponse> future = new CompletableFuture<>(); client .request( HttpMethod.POST, portNum, "127.0.0.1", "/cluster/?data_centers=" + datacenters, response -> { response.bodyHandler( totalBuffer -> { String body = totalBuffer.toString(); HttpTestResponse testResponse = new HttpTestResponse(response, body); future.complete(testResponse); }); }) .end(); try { HttpTestResponse responseToValidate = future.get(); ObjectMapper om = ObjectMapperHolder.getMapper(); // create cluster object from json return code assertThat(responseToValidate.response.statusCode()).isEqualTo(201); ClusterSpec cluster = om.readValue(responseToValidate.body, ClusterSpec.class); return cluster; } catch (Exception e) { fail(e.getMessage()); return null; } }
@Override public HttpClientWithContext createClientPool() { Context context = Vertx.currentContext(); HttpClient httpClient = context.owner().createHttpClient(httpClientOptions); return new HttpClientWithContext(httpClient, context); }
@Test public void testDoMethod(@Mocked HttpClient httpClient, @Injectable URIEndpointObject address) throws Exception { Context context = new MockUp<Context>() { @Mock public void runOnContext(Handler<Void> action) { action.handle(null); } }.getMockInstance(); HttpClientWithContext httpClientWithContext = new HttpClientWithContext(httpClient, context); Invocation invocation = mock(Invocation.class); AsyncResponse asyncResp = mock(AsyncResponse.class); OperationMeta operationMeta = mock(OperationMeta.class); RestOperationMeta swaggerRestOperation = mock(RestOperationMeta.class); Endpoint endpoint = mock(Endpoint.class); when(invocation.getOperationMeta()).thenReturn(operationMeta); URLPathBuilder urlPathBuilder = mock(URLPathBuilder.class); when(swaggerRestOperation.getPathBuilder()).thenReturn(urlPathBuilder); operationMeta.getExtData(RestConst.SWAGGER_REST_OPERATION); when(operationMeta.getExtData(RestConst.SWAGGER_REST_OPERATION)).thenReturn(swaggerRestOperation); when(invocation.getEndpoint()).thenReturn(endpoint); when(endpoint.getAddress()).thenReturn(address); when(request.exceptionHandler(Mockito.any())).then(answer -> null); this.doMethod(httpClientWithContext, invocation, asyncResp); Assert.assertTrue(true); }
@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(); }
@Path("4") @GET public void hello4(@Suspended final AsyncResponse asyncResponse, // Inject the Vertx instance @Context Vertx vertx){ System.err.println("Creating client"); HttpClientOptions options = new HttpClientOptions(); options.setSsl(true); options.setTrustAll(true); options.setVerifyHost(false); HttpClient client = vertx.createHttpClient(options); ObservableHandler<HttpClientResponse> responseHandler = RxHelper.observableHandler(); client.getNow(443, "www.google.com", "/robots.txt", responseHandler.toHandler()); ObservableHandler<Buffer> bodyHandler = RxHelper.observableHandler(); responseHandler.subscribe(resp -> { System.err.println("Got response"); resp.bodyHandler(bodyHandler.toHandler()); }); bodyHandler.subscribe(body -> { System.err.println("Got body"); asyncResponse.resume(Response.ok(body.toString()).build()); }); System.err.println("Created client"); }
@Path("5") @GET public void hello5(@Suspended final AsyncResponse asyncResponse, // Inject the Vertx instance @Context Vertx vertx){ io.vertx.rxjava.core.Vertx rxVertx = io.vertx.rxjava.core.Vertx.newInstance(vertx); System.err.println("Creating client"); HttpClientOptions options = new HttpClientOptions(); options.setSsl(true); options.setTrustAll(true); options.setVerifyHost(false); io.vertx.rxjava.core.http.HttpClient client = rxVertx.createHttpClient(options); // DOES NOT WORK: https://github.com/vert-x3/vertx-rx/issues/13 Observable<io.vertx.rxjava.core.http.HttpClientResponse> responseHandler = client.get(443, "www.google.com", "/robots.txt").toObservable(); responseHandler.map(resp -> { System.err.println("Got response"); return resp.toObservable(); }) .subscribe(body -> { System.err.println("Got body"); asyncResponse.resume(Response.ok(body.toString()).build()); }); System.err.println("Created client"); }
@Test public void testEngineWithInjectedClient() { final HttpClient httpClient = Vertx.vertx().createHttpClient(httpClientOptions); final Client client = new ResteasyClientBuilder().httpEngine(new VertxClientEngine(httpClient)).build(); final Response response = client.target("http://localhost:8900/api/sing").request().get(); assertEquals(200, response.getStatus()); assertTrue(response.readEntity(String.class).startsWith("Hello")); }
@Test public void testEngineWithInjectedClientPost2() { final ResteasyDeployment deployment = new ResteasyDeployment(); deployment.start(); final ResteasyProviderFactory providerFactory = deployment.getProviderFactory(); final HttpClient httpClient = Vertx.vertx().createHttpClient(httpClientOptions); final Client client = new ResteasyClientBuilder() .providerFactory(providerFactory) .httpEngine(new VertxClientEngine(httpClient)) .register(GsonMessageBodyHandler.class) .build(); final Form xform = new Form(); xform.param("userName", "ca1\\\\meowmix"); xform.param("password", "mingnamulan"); xform.param("state", "authenticate"); xform.param("style", "xml"); xform.param("xsl", "none"); final Response response = client.target("https://httpbin.org/post").request(MediaType.APPLICATION_JSON) .post(Entity.form(xform), Response.class); assertFalse(response.getStringHeaders().isEmpty()); System.out.println(response.getStringHeaders()); assertFalse(response.getHeaders().isEmpty()); assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getMediaType()); assertTrue(response.hasEntity()); final JsonObject arsString = response.readEntity(JsonObject.class); assertEquals("xml", arsString.getAsJsonObject("form").get("style").getAsString()); }
@Override public ConfigStore create(Vertx vertx, JsonObject configuration) { String host = configuration.getString("host"); int port = configuration.getInteger("port", 80); String path = configuration.getString("path", "/"); String username = configuration.getString("username", ""); String password = configuration.getString("password", ""); HttpClient client = vertx.createHttpClient(new HttpClientOptions() .setSsl(configuration.getBoolean("ssl", false)) .setDefaultHost(host) .setDefaultPort(port) .setTrustAll(true)); return new HttpBasicAuthConfigStore(client, path, username, password); }
private void getServiceRef(JsonObject filter, Handler<AsyncResult<ServiceReference>> handler) { discovery.getRecord(filter, ar -> { if (ar.succeeded() && ar.result() != null) { ServiceReference ref = discovery.<HttpClient>getReference(ar.result()); handler.handle(Future.succeededFuture(ref)); } else { handler.handle(Future.failedFuture(ar.cause())); } }); }
@Test(timeout = 3000L) public void testAdd(TestContext context) throws Exception { HttpClient client = vertx.createHttpClient(); Async async = context.async(); Todo todo = new Todo(164, "Test case...", false, 22, "/164"); client.post(port, "localhost", "/todos", response -> { context.assertEquals(201, response.statusCode()); client.close(); async.complete(); }).putHeader("content-type", "application/json").end(Json.encodePrettily(todo)); }
@Test(timeout = 3000L) public void testGet(TestContext context) throws Exception { HttpClient client = vertx.createHttpClient(); Async async = context.async(); client.getNow(port, "localhost", "/todos/164", response -> response.bodyHandler(body -> { context.assertEquals(getTodoFromJson(body.toString()), todoEx); client.close(); async.complete(); })); }
@Test(timeout = 3000L) public void testUpdateAndDelete(TestContext context) throws Exception { HttpClient client = vertx.createHttpClient(); Async async = context.async(); Todo todo = new Todo(164, "Test case...Update!", false, 26, "/164h"); client.request(HttpMethod.PATCH, port, "localhost", "/todos/164", response -> response.bodyHandler(body -> { context.assertEquals(getTodoFromJson(body.toString()), todoUp); client.request(HttpMethod.DELETE, port, "localhost", "/todos/164", rsp -> { context.assertEquals(204, rsp.statusCode()); async.complete(); }).end(); })).putHeader("content-type", "application/json").end(Json.encodePrettily(todo)); }
@Test public void testStockTradesAudited(TestContext context) { Async async = context.async(); HttpClientOptions options = new HttpClientOptions().setDefaultHost(config.getString("http.host")); options.setDefaultPort(config.getInt("http.port")); HttpClient client = vertx.createHttpClient(options); client.get("/", response -> { context.assertEquals(response.statusCode(), 200); response.bodyHandler(buffer -> { JsonArray body = buffer.toJsonArray(); context.assertTrue(body.size() >= 3); async.complete(); }); }).end(); }
@Override public void evaluate(Handler<AsyncResult<Double>> resultHandler) { discovery.getRecord(new JsonObject().put("name", "quotes"), ar -> { if (ar.failed()) { resultHandler.handle(Future.failedFuture(ar.cause())); } else { ServiceReference reference = discovery.getReference(ar.result()); root = reference.record().getLocation().getString("root"); HttpClient httpClient = reference.get(); computeEvaluation(httpClient, resultHandler); } }); }
private void computeEvaluation(HttpClient httpClient, Handler<AsyncResult<Double>> resultHandler) { // We need to call the service for each company we own shares List<Future> results = portfolio.getShares().entrySet().stream() .map(entry -> getValueForCompany(httpClient, entry.getKey(), entry.getValue())) .collect(Collectors.toList()); // We need to return only when we have all results, for this we create a composite future. The set handler // is called when all the futures has been assigned. CompositeFuture.all(results).setHandler( ar -> { double sum = results.stream().mapToDouble(fut -> (double) fut.result()).sum(); resultHandler.handle(Future.succeededFuture(sum)); }); }
public void example5(ServiceDiscovery discovery, Record record1, Record record2) { ServiceReference reference1 = discovery.getReference(record1); ServiceReference reference2 = discovery.getReference(record2); // Then, gets the service object, the returned type depends on the service type: // For http endpoint: HttpClient client = reference1.getAs(HttpClient.class); // For message source MessageConsumer consumer = reference2.getAs(MessageConsumer.class); // When done with the service reference1.release(); reference2.release(); }