use of io.vertx.core.http.HttpVersion in project vert.x by eclipse.
the class HttpServerImpl method listen.
public synchronized HttpServer listen(int port, String host, Handler<AsyncResult<HttpServer>> listenHandler) {
if (requestStream.handler() == null && wsStream.handler() == null) {
throw new IllegalStateException("Set request or websocket handler first");
}
if (listening) {
throw new IllegalStateException("Already listening");
}
listenContext = vertx.getOrCreateContext();
listening = true;
serverOrigin = (options.isSsl() ? "https" : "http") + "://" + host + ":" + port;
List<HttpVersion> applicationProtocols = options.getAlpnVersions();
if (listenContext.isWorkerContext()) {
applicationProtocols = applicationProtocols.stream().filter(v -> v != HttpVersion.HTTP_2).collect(Collectors.toList());
}
sslHelper.setApplicationProtocols(applicationProtocols);
synchronized (vertx.sharedHttpServers()) {
// Will be updated on bind for a wildcard port
this.actualPort = port;
id = new ServerID(port, host);
HttpServerImpl shared = vertx.sharedHttpServers().get(id);
if (shared == null || port == 0) {
serverChannelGroup = new DefaultChannelGroup("vertx-acceptor-channels", GlobalEventExecutor.INSTANCE);
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(vertx.getAcceptorEventLoopGroup(), availableWorkers);
bootstrap.channel(NioServerSocketChannel.class);
applyConnectionOptions(bootstrap);
sslHelper.validate(vertx);
bootstrap.childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
if (requestStream.isPaused() || wsStream.isPaused()) {
ch.close();
return;
}
ChannelPipeline pipeline = ch.pipeline();
if (sslHelper.isSSL()) {
pipeline.addLast("ssl", sslHelper.createSslHandler(vertx));
if (options.isUseAlpn()) {
pipeline.addLast("alpn", new ApplicationProtocolNegotiationHandler("http/1.1") {
@Override
protected void configurePipeline(ChannelHandlerContext ctx, String protocol) throws Exception {
if (protocol.equals("http/1.1")) {
configureHttp1(pipeline);
} else {
handleHttp2(ch);
}
}
});
} else {
configureHttp1(pipeline);
}
} else {
if (DISABLE_HC2) {
configureHttp1(pipeline);
} else {
pipeline.addLast(new Http1xOrHttp2Handler());
}
}
}
});
addHandlers(this, listenContext);
try {
bindFuture = AsyncResolveConnectHelper.doBind(vertx, port, host, bootstrap);
bindFuture.addListener(res -> {
if (res.failed()) {
vertx.sharedHttpServers().remove(id);
} else {
Channel serverChannel = res.result();
HttpServerImpl.this.actualPort = ((InetSocketAddress) serverChannel.localAddress()).getPort();
serverChannelGroup.add(serverChannel);
metrics = vertx.metricsSPI().createMetrics(this, new SocketAddressImpl(port, host), options);
}
});
} catch (final Throwable t) {
// Make sure we send the exception back through the handler (if any)
if (listenHandler != null) {
vertx.runOnContext(v -> listenHandler.handle(Future.failedFuture(t)));
} else {
// No handler - log so user can see failure
log.error(t);
}
listening = false;
return this;
}
vertx.sharedHttpServers().put(id, this);
actualServer = this;
} else {
// Server already exists with that host/port - we will use that
actualServer = shared;
this.actualPort = shared.actualPort;
addHandlers(actualServer, listenContext);
metrics = vertx.metricsSPI().createMetrics(this, new SocketAddressImpl(port, host), options);
}
actualServer.bindFuture.addListener(future -> {
if (listenHandler != null) {
final AsyncResult<HttpServer> res;
if (future.succeeded()) {
res = Future.succeededFuture(HttpServerImpl.this);
} else {
res = Future.failedFuture(future.cause());
listening = false;
}
listenContext.runOnContext((v) -> listenHandler.handle(res));
} else if (future.failed()) {
listening = false;
log.error(future.cause());
}
});
}
return this;
}
use of io.vertx.core.http.HttpVersion 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.HttpVersion in project java-chassis by ServiceComb.
the class WebsocketClientPool method createHttpClientOptions.
@Override
public HttpClientOptions createHttpClientOptions() {
HttpVersion ver = ServiceRegistryConfig.INSTANCE.getHttpVersion();
HttpClientOptions httpClientOptions = new HttpClientOptions();
httpClientOptions.setProtocolVersion(ver);
httpClientOptions.setConnectTimeout(ServiceRegistryConfig.INSTANCE.getConnectionTimeout());
// httpClientOptions.setIdleTimeout(ServiceRegistryConfig.INSTANCE.getIdleConnectionTimeout());
if (ver == HttpVersion.HTTP_2) {
LOGGER.debug("service center ws client protocol version is HTTP/2");
httpClientOptions.setHttp2ClearTextUpgrade(false);
}
if (ServiceRegistryConfig.INSTANCE.isSsl()) {
LOGGER.debug("service center ws client performs requests over TLS");
buildSecureClientOptions(httpClientOptions);
}
return httpClientOptions;
}
use of io.vertx.core.http.HttpVersion in project vert.x by eclipse.
the class SSLEngineTest method doTest.
private void doTest(SSLEngineOptions engine, boolean useAlpn, HttpVersion version, String error, String expectedSslContext, boolean expectCause) {
server.close();
HttpServerOptions options = new HttpServerOptions().setSslEngineOptions(engine).setPort(DEFAULT_HTTP_PORT).setHost(DEFAULT_HTTP_HOST).setKeyCertOptions(Cert.SERVER_PEM.get()).setSsl(true).setUseAlpn(useAlpn);
try {
server = vertx.createHttpServer(options);
} catch (VertxException e) {
e.printStackTrace();
if (error == null) {
fail(e);
} else {
assertEquals(error, e.getMessage());
if (expectCause) {
assertNotSame(e, e.getCause());
}
}
return;
}
server.requestHandler(req -> {
assertEquals(req.version(), version);
assertTrue(req.isSSL());
req.response().end();
});
server.listen(onSuccess(s -> {
HttpServerImpl impl = (HttpServerImpl) s;
SSLHelper sslHelper = impl.getSslHelper();
SslContext ctx = sslHelper.getContext((VertxInternal) vertx);
switch(expectedSslContext) {
case "jdk":
assertTrue(ctx instanceof JdkSslContext);
break;
case "openssl":
assertTrue(ctx instanceof OpenSslContext);
break;
}
client = vertx.createHttpClient(new HttpClientOptions().setSslEngineOptions(engine).setSsl(true).setUseAlpn(useAlpn).setTrustAll(true).setProtocolVersion(version));
client.getNow(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, "/somepath", resp -> {
assertEquals(200, resp.statusCode());
testComplete();
});
}));
await();
}
use of io.vertx.core.http.HttpVersion in project vert.x by eclipse.
the class ClientConnection method handleResponse.
void handleResponse(HttpResponse resp) {
if (resp.status().code() == 100) {
//If we get a 100 continue it will be followed by the real response later, so we don't remove it yet
requestForResponse = requests.peek();
} else {
requestForResponse = requests.poll();
}
if (requestForResponse == null) {
throw new IllegalStateException("No response handler");
}
io.netty.handler.codec.http.HttpVersion nettyVersion = resp.protocolVersion();
HttpVersion vertxVersion;
if (nettyVersion == io.netty.handler.codec.http.HttpVersion.HTTP_1_0) {
vertxVersion = HttpVersion.HTTP_1_0;
} else if (nettyVersion == io.netty.handler.codec.http.HttpVersion.HTTP_1_1) {
vertxVersion = HttpVersion.HTTP_1_1;
} else {
vertxVersion = null;
}
HttpClientResponseImpl nResp = new HttpClientResponseImpl(requestForResponse, vertxVersion, this, resp.status().code(), resp.status().reasonPhrase(), new HeadersAdaptor(resp.headers()));
currentResponse = nResp;
if (metrics.isEnabled()) {
metrics.responseBegin(requestForResponse.metric(), nResp);
}
if (vertxVersion != null) {
requestForResponse.handleResponse(nResp);
} else {
requestForResponse.handleException(new IllegalStateException("Unsupported HTTP version: " + nettyVersion));
}
}
Aggregations