use of io.vertx.core.http.HttpClientRequest in project vert.x by eclipse.
the class HttpMetricsTest method testHttpClientLifecycle.
private void testHttpClientLifecycle(HttpVersion protocol) throws Exception {
HttpServer server = vertx.createHttpServer();
CountDownLatch requestBeginLatch = new CountDownLatch(1);
CountDownLatch requestBodyLatch = new CountDownLatch(1);
CountDownLatch requestEndLatch = new CountDownLatch(1);
CompletableFuture<Void> beginResponse = new CompletableFuture<>();
CompletableFuture<Void> endResponse = new CompletableFuture<>();
server.requestHandler(req -> {
assertEquals(protocol, req.version());
requestBeginLatch.countDown();
req.handler(buff -> {
requestBodyLatch.countDown();
});
req.endHandler(v -> {
requestEndLatch.countDown();
});
Context ctx = vertx.getOrCreateContext();
beginResponse.thenAccept(v1 -> {
ctx.runOnContext(v2 -> {
req.response().setChunked(true).write(TestUtils.randomAlphaString(1024));
});
});
endResponse.thenAccept(v1 -> {
ctx.runOnContext(v2 -> {
req.response().end();
});
});
});
CountDownLatch listenLatch = new CountDownLatch(1);
server.listen(8080, "localhost", onSuccess(s -> {
listenLatch.countDown();
}));
awaitLatch(listenLatch);
HttpClient client = vertx.createHttpClient(new HttpClientOptions().setProtocolVersion(protocol));
FakeHttpClientMetrics clientMetrics = FakeMetricsBase.getMetrics(client);
CountDownLatch responseBeginLatch = new CountDownLatch(1);
CountDownLatch responseEndLatch = new CountDownLatch(1);
HttpClientRequest req = client.post(8080, "localhost", "/somepath", resp -> {
responseBeginLatch.countDown();
resp.endHandler(v -> {
responseEndLatch.countDown();
});
}).setChunked(true);
req.sendHead();
awaitLatch(requestBeginLatch);
HttpClientMetric reqMetric = clientMetrics.getMetric(req);
assertEquals(0, reqMetric.requestEnded.get());
assertEquals(0, reqMetric.responseBegin.get());
req.write(TestUtils.randomAlphaString(1024));
awaitLatch(requestBodyLatch);
assertEquals(0, reqMetric.requestEnded.get());
assertEquals(0, reqMetric.responseBegin.get());
req.end();
awaitLatch(requestEndLatch);
assertEquals(1, reqMetric.requestEnded.get());
assertEquals(0, reqMetric.responseBegin.get());
beginResponse.complete(null);
awaitLatch(responseBeginLatch);
assertEquals(1, reqMetric.requestEnded.get());
assertEquals(1, reqMetric.responseBegin.get());
endResponse.complete(null);
awaitLatch(responseEndLatch);
assertNull(clientMetrics.getMetric(req));
assertEquals(1, reqMetric.requestEnded.get());
assertEquals(1, reqMetric.responseBegin.get());
}
use of io.vertx.core.http.HttpClientRequest in project vert.x by eclipse.
the class HttpMetricsTest method testClientConnectionClosed.
private void testClientConnectionClosed(HttpVersion protocol) throws Exception {
server.requestHandler(req -> {
req.response().setChunked(true).write(Buffer.buffer("some-data"));
});
startServer();
client = vertx.createHttpClient(new HttpClientOptions().setProtocolVersion(protocol).setIdleTimeout(2));
FakeHttpClientMetrics metrics = FakeMetricsBase.getMetrics(client);
HttpClientRequest req = client.get(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath");
req.handler(resp -> {
HttpClientMetric metric = metrics.getMetric(req);
assertNotNull(metric);
assertFalse(metric.failed.get());
resp.exceptionHandler(err -> {
assertNull(metrics.getMetric(req));
assertTrue(metric.failed.get());
testComplete();
});
});
req.end();
await();
}
use of io.vertx.core.http.HttpClientRequest in project vert.x by eclipse.
the class HttpProxy method start.
/**
* Start the server.
*
* @param vertx
* Vertx instance to use for creating the server and client
* @param finishedHandler
* will be called when the server has started
*/
@Override
public void start(Vertx vertx, Handler<Void> finishedHandler) {
HttpServerOptions options = new HttpServerOptions();
options.setHost("localhost").setPort(PORT);
server = vertx.createHttpServer(options);
server.requestHandler(request -> {
HttpMethod method = request.method();
String uri = request.uri();
if (username != null) {
String auth = request.getHeader("Proxy-Authorization");
String expected = "Basic " + Base64.getEncoder().encodeToString((username + ":" + username).getBytes());
if (auth == null || !auth.equals(expected)) {
request.response().setStatusCode(407).end("proxy authentication failed");
return;
}
}
lastRequestHeaders = MultiMap.caseInsensitiveMultiMap().addAll(request.headers());
if (error != 0) {
request.response().setStatusCode(error).end("proxy request failed");
} else if (method == HttpMethod.CONNECT) {
if (!uri.contains(":")) {
request.response().setStatusCode(403).end("invalid request");
} else {
lastUri = uri;
if (forceUri != null) {
uri = forceUri;
}
String[] split = uri.split(":");
String host = split[0];
int port;
try {
port = Integer.parseInt(split[1]);
} catch (NumberFormatException ex) {
port = 443;
}
if (port == 8080 || port < 1024 && port != 443) {
request.response().setStatusCode(403).end("access to port denied");
return;
}
NetSocket serverSocket = request.netSocket();
NetClientOptions netOptions = new NetClientOptions();
NetClient netClient = vertx.createNetClient(netOptions);
netClient.connect(port, host, result -> {
if (result.succeeded()) {
NetSocket clientSocket = result.result();
serverSocket.write("HTTP/1.0 200 Connection established\n\n");
serverSocket.closeHandler(v -> clientSocket.close());
clientSocket.closeHandler(v -> serverSocket.close());
Pump.pump(serverSocket, clientSocket).start();
Pump.pump(clientSocket, serverSocket).start();
} else {
request.response().setStatusCode(403).end("request failed");
}
});
}
} else if (method == HttpMethod.GET) {
lastUri = request.uri();
HttpClient client = vertx.createHttpClient();
HttpClientRequest clientRequest = client.getAbs(request.uri(), resp -> {
for (String name : resp.headers().names()) {
request.response().putHeader(name, resp.headers().getAll(name));
}
resp.bodyHandler(body -> {
request.response().end(body);
});
});
for (String name : request.headers().names()) {
if (!name.equals("Proxy-Authorization")) {
clientRequest.putHeader(name, request.headers().getAll(name));
}
}
clientRequest.exceptionHandler(e -> {
log.debug("exception", e);
int status;
if (e instanceof UnknownHostException) {
status = 504;
} else {
status = 400;
}
request.response().setStatusCode(status).end(e.toString() + " on client request");
});
clientRequest.end();
} else {
request.response().setStatusCode(405).end("method not supported");
}
});
server.listen(server -> {
finishedHandler.handle(null);
});
}
use of io.vertx.core.http.HttpClientRequest in project vert.x by eclipse.
the class HttpTest method testResponseDataTimeout.
@Test
public void testResponseDataTimeout() {
Buffer expected = TestUtils.randomBuffer(1000);
server.requestHandler(req -> {
req.response().setChunked(true).write(expected);
});
server.listen(onSuccess(s -> {
HttpClientRequest req = client.request(HttpMethod.GET, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, DEFAULT_TEST_URI);
Buffer received = Buffer.buffer();
req.handler(resp -> {
req.setTimeout(500);
resp.handler(received::appendBuffer);
});
AtomicInteger count = new AtomicInteger();
req.exceptionHandler(t -> {
if (count.getAndIncrement() == 0) {
assertTrue(t instanceof TimeoutException);
assertEquals(expected, received);
testComplete();
}
});
req.sendHead();
}));
await();
}
use of io.vertx.core.http.HttpClientRequest in project vert.x by eclipse.
the class HttpTest method testFormUploadFile.
private void testFormUploadFile(String contentStr, boolean streamToDisk) throws Exception {
Buffer content = Buffer.buffer(contentStr);
AtomicInteger attributeCount = new AtomicInteger();
server.requestHandler(req -> {
if (req.method() == HttpMethod.POST) {
assertEquals(req.path(), "/form");
req.response().setChunked(true);
req.setExpectMultipart(true);
assertTrue(req.isExpectMultipart());
req.setExpectMultipart(true);
assertTrue(req.isExpectMultipart());
req.uploadHandler(upload -> {
Buffer tot = Buffer.buffer();
assertEquals("file", upload.name());
assertEquals("tmp-0.txt", upload.filename());
assertEquals("image/gif", upload.contentType());
String uploadedFileName;
if (!streamToDisk) {
upload.handler(buffer -> tot.appendBuffer(buffer));
uploadedFileName = null;
} else {
uploadedFileName = new File(testDir, UUID.randomUUID().toString()).getPath();
upload.streamToFileSystem(uploadedFileName);
}
upload.endHandler(v -> {
if (streamToDisk) {
Buffer uploaded = vertx.fileSystem().readFileBlocking(uploadedFileName);
assertEquals(content, uploaded);
} else {
assertEquals(content, tot);
}
assertTrue(upload.isSizeAvailable());
assertEquals(content.length(), upload.size());
});
});
req.endHandler(v -> {
MultiMap attrs = req.formAttributes();
attributeCount.set(attrs.size());
req.response().end();
});
}
});
server.listen(onSuccess(s -> {
HttpClientRequest req = client.request(HttpMethod.POST, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/form", resp -> {
assertEquals(200, resp.statusCode());
resp.bodyHandler(body -> {
assertEquals(0, body.length());
});
assertEquals(0, attributeCount.get());
testComplete();
});
String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO";
Buffer buffer = Buffer.buffer();
String body = "--" + boundary + "\r\n" + "Content-Disposition: form-data; name=\"file\"; filename=\"tmp-0.txt\"\r\n" + "Content-Type: image/gif\r\n" + "\r\n" + contentStr + "\r\n" + "--" + boundary + "--\r\n";
buffer.appendString(body);
req.headers().set("content-length", String.valueOf(buffer.length()));
req.headers().set("content-type", "multipart/form-data; boundary=" + boundary);
req.write(buffer).end();
}));
await();
}
Aggregations