use of io.vertx.core.net.NetSocket 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.net.NetSocket in project vert.x by eclipse.
the class HttpRequestStreamTest method testReadStreamPauseResume.
@Test
public void testReadStreamPauseResume() {
String path = "/some/path";
this.server = vertx.createHttpServer(new HttpServerOptions().setAcceptBacklog(10).setPort(HttpTestBase.DEFAULT_HTTP_PORT));
ReadStream<HttpServerRequest> httpStream = server.requestStream();
AtomicBoolean paused = new AtomicBoolean();
httpStream.handler(req -> {
assertFalse(paused.get());
HttpServerResponse response = req.response();
response.setStatusCode(200).end();
response.close();
});
server.listen(listenAR -> {
assertTrue(listenAR.succeeded());
paused.set(true);
httpStream.pause();
netClient = vertx.createNetClient(new NetClientOptions().setConnectTimeout(1000));
netClient.connect(HttpTestBase.DEFAULT_HTTP_PORT, "localhost", socketAR -> {
assertTrue(socketAR.succeeded());
NetSocket socket = socketAR.result();
Buffer buffer = Buffer.buffer();
socket.handler(buffer::appendBuffer);
socket.closeHandler(v -> {
assertEquals(0, buffer.length());
paused.set(false);
httpStream.resume();
client = vertx.createHttpClient(new HttpClientOptions());
client.request(HttpMethod.GET, HttpTestBase.DEFAULT_HTTP_PORT, "localhost", path, resp -> {
assertEquals(200, resp.statusCode());
testComplete();
}).end();
});
});
});
await();
}
use of io.vertx.core.net.NetSocket in project vert.x by eclipse.
the class Http2ServerTest method testNetSocketSendFile.
private void testNetSocketSendFile(Buffer expected, String path, long offset, long length) throws Exception {
server.requestHandler(req -> {
NetSocket socket = req.netSocket();
socket.sendFile(path, offset, length, ar -> {
assertTrue(ar.succeeded());
socket.end();
});
});
startServer();
TestClient client = new TestClient();
ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
int id = request.nextStreamId();
request.decoder.frameListener(new Http2EventAdapter() {
@Override
public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) throws Http2Exception {
vertx.runOnContext(v -> {
assertEquals("200", headers.status().toString());
assertFalse(endStream);
});
}
Buffer received = Buffer.buffer();
@Override
public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream) throws Http2Exception {
received.appendBuffer(Buffer.buffer(data.copy()));
if (endOfStream) {
vertx.runOnContext(v -> {
assertEquals(received, expected);
testComplete();
});
}
return data.readableBytes() + padding;
}
});
request.encoder.writeHeaders(request.context, id, GET("/"), 0, true, request.context.newPromise());
request.context.flush();
});
fut.sync();
await();
}
use of io.vertx.core.net.NetSocket in project vert.x by eclipse.
the class Http2ServerTest method testServerCloseNetSocket.
@Test
public void testServerCloseNetSocket() throws Exception {
waitFor(2);
AtomicInteger status = new AtomicInteger();
server.requestHandler(req -> {
NetSocket socket = req.netSocket();
socket.handler(buff -> {
switch(status.getAndIncrement()) {
case 0:
assertEquals(Buffer.buffer("some-data"), buff);
socket.write(buff);
socket.close();
break;
case 1:
assertEquals(Buffer.buffer("last-data"), buff);
break;
default:
fail();
break;
}
});
socket.endHandler(v -> {
assertEquals(2, status.getAndIncrement());
});
socket.closeHandler(v -> {
assertEquals(3, status.getAndIncrement());
complete();
});
});
startServer();
TestClient client = new TestClient();
ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
int id = request.nextStreamId();
request.decoder.frameListener(new Http2EventAdapter() {
int count = 0;
@Override
public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) throws Http2Exception {
int c = count++;
vertx.runOnContext(v -> {
assertEquals(0, c);
});
request.encoder.writeData(request.context, id, Buffer.buffer("some-data").getByteBuf(), 0, false, request.context.newPromise());
request.context.flush();
}
StringBuilder received = new StringBuilder();
@Override
public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream) throws Http2Exception {
String s = data.toString(StandardCharsets.UTF_8);
received.append(s);
if (endOfStream) {
request.encoder.writeData(request.context, id, Buffer.buffer("last-data").getByteBuf(), 0, true, request.context.newPromise());
vertx.runOnContext(v -> {
assertEquals("some-data", received.toString());
complete();
});
}
return data.readableBytes() + padding;
}
});
request.encoder.writeHeaders(request.context, id, GET("/"), 0, false, request.context.newPromise());
request.context.flush();
});
fut.sync();
await();
}
use of io.vertx.core.net.NetSocket in project vert.x by eclipse.
the class Http2ServerTest method testNetSocketHandleReset.
@Test
public void testNetSocketHandleReset() throws Exception {
server.requestHandler(req -> {
NetSocket socket = req.netSocket();
AtomicInteger status = new AtomicInteger();
socket.exceptionHandler(err -> {
assertTrue(err instanceof StreamResetException);
StreamResetException ex = (StreamResetException) err;
assertEquals(0, ex.getCode());
assertEquals(0, status.getAndIncrement());
});
socket.endHandler(v -> {
fail();
});
socket.closeHandler(v -> {
assertEquals(1, status.getAndIncrement());
testComplete();
});
});
startServer();
TestClient client = new TestClient();
ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
int id = request.nextStreamId();
request.decoder.frameListener(new Http2EventAdapter() {
int count = 0;
@Override
public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int streamDependency, short weight, boolean exclusive, int padding, boolean endStream) throws Http2Exception {
int c = count++;
vertx.runOnContext(v -> {
assertEquals(0, c);
});
request.encoder.writeRstStream(ctx, streamId, 0, ctx.newPromise());
request.context.flush();
}
});
request.encoder.writeHeaders(request.context, id, GET("/"), 0, false, request.context.newPromise());
request.context.flush();
});
fut.sync();
await();
}
Aggregations