Java Code Examples for io.vertx.core.http.HttpClientRequest#handler()

The following examples show how to use io.vertx.core.http.HttpClientRequest#handler() . 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: FormParameterExtractorTest.java    From vertx-swagger with Apache License 2.0 6 votes vote down vote up
@Test()
public void testOkFormDataSimpleRequired(TestContext context) {
    Async async = context.async();
    HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/simple/required");
    req.handler(response -> {
        response.bodyHandler(body -> {
            context.assertEquals(response.statusCode(), 200);
            context.assertEquals("toto", body.toString());
            async.complete();
        });
    });

    // Construct form
    StringBuffer payload = new StringBuffer().append("formDataRequired=").append(esc.escape("toto"));
    req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
    req.end(payload.toString());
}
 
Example 2
Source File: TranslatorExampleTest.java    From weld-vertx with Apache License 2.0 6 votes vote down vote up
@Test(timeout = DEFAULT_TIMEOUT)
public void testTranslator(TestContext context) throws InterruptedException {
    Async async = context.async();
    HttpClient client = vertx.createHttpClient();
    HttpClientRequest request = client.request(HttpMethod.POST, 8080, "localhost", "/translate");
    request.putHeader("Content-type", "application/x-www-form-urlencoded");
    request.handler((response) -> {
        if (response.statusCode() == 200) {
            response.bodyHandler((buffer) -> {
                context.assertEquals("[{\"word\":\"Hello\",\"translations\":[\"ahoj\",\"dobry den\"]},{\"word\":\"world\",\"translations\":[\"svet\"]}]",
                        buffer.toString());
                client.close();
                async.complete();
            });
        }
    });
    request.end("sentence=Hello world");
}
 
Example 3
Source File: FormParameterExtractorTest.java    From vertx-swagger with Apache License 2.0 6 votes vote down vote up
@Test()
public void testOkFormDataArray(TestContext context) throws UnsupportedEncodingException {
    Async async = context.async();
    HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/array");
    req.handler(response -> {
        response.bodyHandler(body -> {
            context.assertEquals(response.statusCode(), 200);
            context.assertEquals("[\"1\",\"2\",\"3\"]", body.toString());
            async.complete();
        });
    });

    // Construct form
    StringBuffer payload = new StringBuffer().append("array_formdata=").append(esc.escape("1,2,3"));
    req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
    req.end(payload.toString());
}
 
Example 4
Source File: FormParameterExtractorTest.java    From vertx-swagger with Apache License 2.0 6 votes vote down vote up
@Test()
public void testOkQueryArrayMulti(TestContext context) throws UnsupportedEncodingException {
    Async async = context.async();
    HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/array/multi?array_formdata=1&array_formdata=2&array_formdata=3");
    req.handler(response -> {
        response.bodyHandler(body -> {
            context.assertEquals(response.statusCode(), 200);
            context.assertEquals("[\"1\",\"2\",\"3\"]", body.toString());
            async.complete();
        });
    });

    // Construct form
    StringBuffer payload = new StringBuffer().append("array_formdata=").append(esc.escape("1")).append("&array_formdata=").append(esc.escape("2")).append("&array_formdata=")
            .append(esc.escape("3"));
    req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
    req.end(payload.toString());
}
 
Example 5
Source File: FormParameterExtractorTest.java    From vertx-swagger with Apache License 2.0 6 votes vote down vote up
@Test()
public void testOkFormDataArrayTsv(TestContext context) {
    Async async = context.async();
    HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/array/tsv");
    req.handler(response -> {
        response.bodyHandler(body -> {
            context.assertEquals(response.statusCode(), 200);
            context.assertEquals("[\"1\",\"2\",\"3\"]", body.toString());
            async.complete();
        });
    });

    // Construct form
    StringBuffer payload = new StringBuffer().append("array_formdata=").append(esc.escape("1\t2\t3"));
    req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
    req.end(payload.toString());
}
 
Example 6
Source File: FormParameterExtractorTest.java    From vertx-swagger with Apache License 2.0 6 votes vote down vote up
@Test()
public void testOkFormDataArraySsv(TestContext context) {
    Async async = context.async();
    HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/array/ssv");
    req.handler(response -> {
        response.bodyHandler(body -> {
            context.assertEquals(response.statusCode(), 200);
            context.assertEquals("[\"1\",\"2\",\"3\"]", body.toString());
            async.complete();
        });
    });

    // Construct form
    StringBuffer payload = new StringBuffer().append("array_formdata=").append(esc.escape("1 2 3"));
    req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
    req.end(payload.toString());
}
 
Example 7
Source File: FormParameterExtractorTest.java    From vertx-swagger with Apache License 2.0 6 votes vote down vote up
@Test()
public void testOkFormDataArrayCsv(TestContext context) {
    Async async = context.async();
    HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/array/csv");
    req.handler(response -> {
        response.bodyHandler(body -> {
            context.assertEquals(response.statusCode(), 200);
            context.assertEquals("[\"1\",\"2\",\"3\"]", body.toString());
            async.complete();
        });
    });

    // Construct form
    StringBuffer payload = new StringBuffer().append("array_formdata=").append(esc.escape("1,2,3"));
    req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
    req.end(payload.toString());
}
 
Example 8
Source File: FormParameterExtractorTest.java    From vertx-swagger with Apache License 2.0 6 votes vote down vote up
@Test()
public void testOkFormDataArrayPipes(TestContext context) {
    Async async = context.async();
    HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/array/pipes");
    req.handler(response -> {
        response.bodyHandler(body -> {
            context.assertEquals(response.statusCode(), 200);
            context.assertEquals("[\"1\",\"2\",\"3\"]", body.toString());
            async.complete();
        });
    });

    // Construct form
    StringBuffer payload = new StringBuffer().append("array_formdata=").append(esc.escape("1|2|3"));
    req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
    req.end(payload.toString());
}
 
Example 9
Source File: FormParameterExtractorTest.java    From vertx-swagger with Apache License 2.0 6 votes vote down vote up
@Test()
public void testOkFormDataSimpleNotRequiredWithParam(TestContext context) {
    Async async = context.async();
    HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/simple/not/required");
    req.handler(response -> {
        response.bodyHandler(body -> {
            context.assertEquals(response.statusCode(), 200);
            context.assertEquals("toto", body.toString());
            async.complete();
        });
    });

    // Construct form
    StringBuffer payload = new StringBuffer().append("formDataNotRequired=").append(esc.escape("toto"));
    req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
    req.end(payload.toString());
}
 
Example 10
Source File: FormParameterExtractorTest.java    From vertx-swagger with Apache License 2.0 6 votes vote down vote up
@Test()
public void testOkFormDataSimpleRequiredAllowEmpty(TestContext context) {
    Async async = context.async();
    HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/simple/required/allowempty");
    req.handler(response -> {
        response.bodyHandler(body -> {
            context.assertEquals(response.statusCode(), 200);
            context.assertEquals("", body.toString());
            async.complete();
        });
    });
    // Construct form
    StringBuffer payload = new StringBuffer().append("formDataRequired=");
    req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
    req.end(payload.toString());
}
 
Example 11
Source File: FormParameterExtractorTest.java    From vertx-swagger with Apache License 2.0 5 votes vote down vote up
@Test()
public void testOkFormDataSimpleNotRequiredWithoutParam(TestContext context) {
    Async async = context.async();
    HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/simple/not/required");
    req.handler(response -> {
        response.bodyHandler(body -> {
            context.assertEquals(response.statusCode(), 200);
            context.assertEquals("", body.toString());
            async.complete();
        });
    });
    req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
    req.end();
}
 
Example 12
Source File: FormParameterExtractorTest.java    From vertx-swagger with Apache License 2.0 5 votes vote down vote up
@Test()
public void testKoFormDataSimpleRequired(TestContext context) {
    Async async = context.async();
    HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/simple/required");
    req.handler(response -> {
        response.bodyHandler(body -> {
            context.assertEquals(response.statusCode(), 400);
            async.complete();
        });
    });
    req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
    req.end();
}
 
Example 13
Source File: FormParameterExtractorTest.java    From vertx-swagger with Apache License 2.0 5 votes vote down vote up
@Test()
public void testKoFormDataSimpleRequiredWithEmptyValue(TestContext context) {
    Async async = context.async();
    HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/simple/required");
    req.handler(response -> {
        response.bodyHandler(body -> {
            context.assertEquals(response.statusCode(), 400);
            async.complete();
        });
    });
    // Construct form
    StringBuffer payload = new StringBuffer().append("formDataRequired=");
    req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
    req.end(payload.toString());
}
 
Example 14
Source File: FormParameterExtractorTest.java    From vertx-swagger with Apache License 2.0 5 votes vote down vote up
@Test()
public void testOkFormDataSimpleFile(TestContext context) {
    Async async = context.async();
    HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/simple/file");
    req.handler(response -> {
        response.bodyHandler(body -> {
            context.assertEquals(response.statusCode(), 200);
            context.assertEquals("{\"test\":\"This is a test file.\"}", body.toString());
            async.complete();
        });
    });
    // Construct multipart data
    req.putHeader(HttpHeaders.CONTENT_TYPE, "multipart/form-data; boundary=MyBoundary");
    Buffer buffer = Buffer.factory.buffer();
    FileSystem vertxFileSystem = vertx.fileSystem();
    vertxFileSystem.readFile(TEST_FILENAME, readFile -> {
        if (readFile.succeeded()) {
            buffer.appendString("\r\n");
            buffer.appendString("--MyBoundary\r\n");
            buffer.appendString("Content-Disposition: form-data; name=\"formDataRequired\"; filename=\"" + TEST_FILENAME + "\"\r\n");
            buffer.appendString("Content-Type: text/plain\r\n");
            buffer.appendString("\r\n");
            buffer.appendString(readFile.result().toString(Charset.forName("utf-8")));
            buffer.appendString("\r\n");
            buffer.appendString("--MyBoundary--");
            req.end(buffer);
        } else {
            context.fail(readFile.cause());
        }
    });
}
 
Example 15
Source File: FormParameterExtractorTest.java    From vertx-swagger with Apache License 2.0 5 votes vote down vote up
@Test()
public void testKoFormDataSimpleFileWithoutFile(TestContext context) {
    Async async = context.async();
    HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/formdata/simple/file");
    req.handler(response -> {
        response.bodyHandler(body -> {
            context.assertEquals(response.statusCode(), 400);
            async.complete();
        });
    });
    // Construct multipart data
    req.putHeader(HttpHeaders.CONTENT_TYPE, "multipart/form-data; boundary=MyBoundary");
    req.end();
}
 
Example 16
Source File: VertxHttpClient.java    From feign-vertx with Apache License 2.0 4 votes vote down vote up
/**
 * Executes HTTP request and returns {@link Future} with response.
 *
 * @param request  request
 * @return future of HTTP response
 */
public Future<Response> execute(final Request request) {
  checkNotNull(request, "Argument request must be not null");

  final HttpClientRequest httpClientRequest;

  try {
    httpClientRequest = makeHttpClientRequest(request);
  } catch (final MalformedURLException unexpectedException) {
    return Future.failedFuture(unexpectedException);
  }

  final Future<Response> responseFuture = Future.future();

  httpClientRequest.exceptionHandler(responseFuture::fail);
  httpClientRequest.handler(response -> {
    final Map<String, Collection<String>> responseHeaders = StreamSupport
        .stream(response.headers().spliterator(), false)
        .collect(Collectors.groupingBy(
            Map.Entry::getKey,
            Collectors.mapping(
                Map.Entry::getValue,
                Collectors.toCollection(ArrayList::new))));

    response.exceptionHandler(responseFuture::fail);
    response.bodyHandler(body -> {
      final Response feignResponse = Response.create(
          response.statusCode(),
          response.statusMessage(),
          responseHeaders,
          body.getBytes());
      responseFuture.complete(feignResponse);
    });
  });

  /* Write body if exists */
  if (request.body() != null) {
    httpClientRequest.write(Buffer.buffer(request.body()));
  }

  httpClientRequest.end();

  return responseFuture;
}
 
Example 17
Source File: ProxyVerticle.java    From quarantyne with Apache License 2.0 4 votes vote down vote up
private void proxiedRequestHandler(HttpServerRequest frontReq, @Nullable Buffer frontReqBody) {
  HttpServerResponse frontRep = frontReq.response();

  CaseInsensitiveStringKV frontReqHeaders =
      new CaseInsensitiveStringKV(frontReq.headers().entries());

  // inject quarantyne headers, if any
  HttpRequest qReq = new HttpRequest(
      HttpRequestMethod.valueOf(frontReq.method().toString().toUpperCase()),
      frontReqHeaders,
      RemoteIpAddressesParser.parse(frontReqHeaders, frontReq.remoteAddress().host()),
      frontReq.path()
  );
  @Nullable final HttpRequestBody qBody =
      getBody(qReq.getMethod(), frontReqBody, frontReq.getHeader(HttpHeaders.CONTENT_TYPE));

  Set<Label> quarantyneLabels = quarantyneClassifier.classify(qReq, qBody);

  if (configSupplier.get().isBlocked(quarantyneLabels)) {
    log.info("blocking request {} because we are blocking {}", qReq.getFingerprint(), quarantyneLabels);
    bouncer.bounce(frontRep);
  } else {
    HttpClientRequest backReq = httpClient.request(
        frontReq.method(),
        frontReq.uri()
    );
    backReq.headers().setAll(frontReq.headers());
    backReq.headers().set(HttpHeaders.HOST, configArgs.getEgress().getHost());
    backReq.headers().addAll(quarantyneCheck(quarantyneLabels));
    // --------------------------------
    backReq.handler(backRep -> {
      Buffer body = Buffer.buffer();
      backRep.handler(body::appendBuffer);
      backRep.endHandler(h -> {
        // callback quarantyne with data to record, if needed
        quarantyneClassifier.record(new HttpResponse(backRep.statusCode()), qReq, qBody);
        // --------------------------------
        frontRep.setStatusCode(backRep.statusCode());
        frontRep.headers().setAll(backRep.headers());
        frontRep.end(body);
      });
    });
    backReq.exceptionHandler(ex -> {
      log.error("error while querying downstream service", ex);
      frontRep.setStatusCode(500);
      frontRep.end("Internal Server Error. This request cannot be satisfied.");
    });
    if (frontReqBody != null) {
      backReq.end(frontReqBody);
    } else {
      backReq.end();
    }
  }
}
 
Example 18
Source File: HttpProvider.java    From gravitee-management-rest-api with Apache License 2.0 4 votes vote down vote up
@Override
public CompletableFuture<Collection<DynamicProperty>> get() {
    CompletableFuture<Buffer> future = new VertxCompletableFuture<>(vertx);

    URI requestUri = URI.create(configuration.getUrl());
    boolean ssl = HTTPS_SCHEME.equalsIgnoreCase(requestUri.getScheme());

    final HttpClientOptions options = new HttpClientOptions()
            .setSsl(ssl)
            .setTrustAll(true)
            .setMaxPoolSize(1)
            .setKeepAlive(false)
            .setTcpKeepAlive(false)
            .setConnectTimeout(2000);

    final HttpClient httpClient = vertx.createHttpClient(options);

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

    try {
        HttpClientRequest request = httpClient.request(
                HttpMethod.GET,
                port,
                requestUri.getHost(),
                requestUri.toString()
        );

        request.putHeader(HttpHeaders.USER_AGENT, NodeUtils.userAgent(node));
        request.putHeader("X-Gravitee-Request-Id", RandomString.generate());

        if (configuration.getHeaders() != null) {
            configuration.getHeaders().forEach(httpHeader ->
                    request.putHeader(httpHeader.getName(), httpHeader.getValue()));
        }

        request.handler(response -> {
            if (response.statusCode() == HttpStatusCode.OK_200) {
                response.bodyHandler(buffer -> {
                    future.complete(buffer);

                    // Close client
                    httpClient.close();
                });
            } else {
                future.complete(null);
            }
        });

        request.exceptionHandler(event -> {
            try {
                future.completeExceptionally(event);

                // Close client
                httpClient.close();
            } catch (IllegalStateException ise) {
                // Do not take care about exception when closing client
            }
        });

        request.end();
    } catch (Exception ex) {
        logger.error("Unable to look for dynamic properties", ex);
        future.completeExceptionally(ex);
    }

    return future.thenApply(buffer -> {
        if (buffer == null) {
            return null;
        }
        return mapper.map(buffer.toString());
    });
}
 
Example 19
Source File: HttpProvider.java    From gravitee-management-rest-api with Apache License 2.0 4 votes vote down vote up
@Override
public CompletableFuture<Collection<DynamicProperty>> get() {
    CompletableFuture<Buffer> future = new VertxCompletableFuture<>(vertx);

    URI requestUri = URI.create(dpConfiguration.getUrl());
    boolean ssl = HTTPS_SCHEME.equalsIgnoreCase(requestUri.getScheme());

    final HttpClientOptions options = new HttpClientOptions()
            .setSsl(ssl)
            .setTrustAll(true)
            .setMaxPoolSize(1)
            .setKeepAlive(false)
            .setTcpKeepAlive(false)
            .setConnectTimeout(2000);

    final HttpClient httpClient = vertx.createHttpClient(options);

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

    try {
        HttpClientRequest request = httpClient.request(
                HttpMethod.GET,
                port,
                requestUri.getHost(),
                requestUri.toString()
        );

        request.putHeader(HttpHeaders.USER_AGENT, NodeUtils.userAgent(node));
        request.putHeader("X-Gravitee-Request-Id", RandomString.generate());

        request.handler(response -> {
            if (response.statusCode() == HttpStatusCode.OK_200) {
                response.bodyHandler(buffer -> {
                    future.complete(buffer);

                    // Close client
                    httpClient.close();
                });
            } else {
                future.complete(null);
            }
        });

        request.exceptionHandler(event -> {
            try {
                future.completeExceptionally(event);

                // Close client
                httpClient.close();
            } catch (IllegalStateException ise) {
                // Do not take care about exception when closing client
            }
        });

        request.end();
    } catch (Exception ex) {
        logger.error("Unable to look for dynamic properties", ex);
        future.completeExceptionally(ex);
    }

    return future.thenApply(buffer -> {
        if (buffer == null) {
            return null;
        }
        return mapper.map(buffer.toString());
    });
}