use of io.vertx.core.Handler 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.Handler in project vert.x by eclipse.
the class Http2ServerResponseImpl method sendFile.
@Override
public HttpServerResponse sendFile(String filename, long offset, long length, Handler<AsyncResult<Void>> resultHandler) {
synchronized (conn) {
checkEnded();
Context resultCtx = resultHandler != null ? stream.vertx.getOrCreateContext() : null;
File file = stream.vertx.resolveFile(filename);
if (!file.exists()) {
if (resultHandler != null) {
resultCtx.runOnContext((v) -> resultHandler.handle(Future.failedFuture(new FileNotFoundException())));
} else {
log.error("File not found: " + filename);
}
return this;
}
RandomAccessFile raf;
try {
raf = new RandomAccessFile(file, "r");
} catch (IOException e) {
if (resultHandler != null) {
resultCtx.runOnContext((v) -> resultHandler.handle(Future.failedFuture(e)));
} else {
log.error("Failed to send file", e);
}
return this;
}
long contentLength = Math.min(length, file.length() - offset);
if (headers.get(HttpHeaderNames.CONTENT_LENGTH) == null) {
putHeader(HttpHeaderNames.CONTENT_LENGTH, String.valueOf(contentLength));
}
if (headers.get(HttpHeaderNames.CONTENT_TYPE) == null) {
String contentType = MimeMapping.getMimeTypeForFilename(filename);
if (contentType != null) {
putHeader(HttpHeaderNames.CONTENT_TYPE, contentType);
}
}
checkSendHeaders(false);
FileStreamChannel fileChannel = new FileStreamChannel(ar -> {
if (ar.succeeded()) {
bytesWritten += ar.result();
end();
}
if (resultHandler != null) {
resultCtx.runOnContext(v -> {
resultHandler.handle(Future.succeededFuture());
});
}
}, stream, offset, contentLength);
drainHandler(fileChannel.drainHandler);
ctx.channel().eventLoop().register(fileChannel);
fileChannel.pipeline().fireUserEventTriggered(raf);
}
return this;
}
use of io.vertx.core.Handler in project vert.x by eclipse.
the class EventBusInterceptorTest method testRemoveInterceptor.
@Test
public void testRemoveInterceptor() {
AtomicInteger cnt1 = new AtomicInteger();
AtomicInteger cnt2 = new AtomicInteger();
Handler<SendContext> eb1 = sc -> {
cnt1.incrementAndGet();
sc.next();
};
Handler<SendContext> eb2 = sc -> {
cnt2.incrementAndGet();
sc.next();
};
eb.addInterceptor(eb1).addInterceptor(eb2);
eb.consumer("some-address", msg -> {
if (msg.body().equals("armadillo")) {
assertEquals(1, cnt1.get());
assertEquals(1, cnt2.get());
eb.removeInterceptor(eb2);
eb.send("some-address", "aardvark");
} else if (msg.body().equals("aardvark")) {
assertEquals(2, cnt1.get());
assertEquals(1, cnt2.get());
testComplete();
} else {
fail("wrong body");
}
});
eb.send("some-address", "armadillo");
await();
}
use of io.vertx.core.Handler in project vert.x by eclipse.
the class ClusteredEventBusTestBase method testPublish.
@Override
protected <T> void testPublish(T val, Consumer<T> consumer) {
int numNodes = 3;
startNodes(numNodes);
AtomicInteger count = new AtomicInteger();
class MyHandler implements Handler<Message<T>> {
@Override
public void handle(Message<T> msg) {
if (consumer == null) {
assertFalse(msg.isSend());
assertEquals(val, msg.body());
} else {
consumer.accept(msg.body());
}
if (count.incrementAndGet() == numNodes - 1) {
testComplete();
}
}
}
AtomicInteger registerCount = new AtomicInteger(0);
class MyRegisterHandler implements Handler<AsyncResult<Void>> {
@Override
public void handle(AsyncResult<Void> ar) {
assertTrue(ar.succeeded());
if (registerCount.incrementAndGet() == 2) {
vertices[0].eventBus().publish(ADDRESS1, val);
}
}
}
MessageConsumer reg = vertices[2].eventBus().<T>consumer(ADDRESS1).handler(new MyHandler());
reg.completionHandler(new MyRegisterHandler());
reg = vertices[1].eventBus().<T>consumer(ADDRESS1).handler(new MyHandler());
reg.completionHandler(new MyRegisterHandler());
vertices[0].eventBus().publish(ADDRESS1, val);
await();
}
use of io.vertx.core.Handler in project vert.x by eclipse.
the class NetClientImpl method connect.
private void connect(int port, String host, Handler<AsyncResult<NetSocket>> connectHandler, int remainingAttempts) {
Objects.requireNonNull(host, "No null host accepted");
Objects.requireNonNull(connectHandler, "No null connectHandler accepted");
ContextImpl context = vertx.getOrCreateContext();
sslHelper.validate(vertx);
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(context.nettyEventLoop());
bootstrap.channel(NioSocketChannel.class);
applyConnectionOptions(bootstrap);
ChannelProvider channelProvider;
if (options.getProxyOptions() == null) {
channelProvider = ChannelProvider.INSTANCE;
} else {
channelProvider = ProxyChannelProvider.INSTANCE;
}
Handler<Channel> channelInitializer = ch -> {
if (sslHelper.isSSL()) {
SslHandler sslHandler = sslHelper.createSslHandler(vertx, host, port);
ch.pipeline().addLast("ssl", sslHandler);
}
ChannelPipeline pipeline = ch.pipeline();
if (logEnabled) {
pipeline.addLast("logging", new LoggingHandler());
}
if (sslHelper.isSSL()) {
pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
}
if (options.getIdleTimeout() > 0) {
pipeline.addLast("idle", new IdleStateHandler(0, 0, options.getIdleTimeout()));
}
pipeline.addLast("handler", new VertxNetHandler<NetSocketImpl>(ch, socketMap) {
@Override
protected void handleMsgReceived(Object msg) {
ByteBuf buf = (ByteBuf) msg;
conn.handleDataReceived(Buffer.buffer(buf));
}
});
};
Handler<AsyncResult<Channel>> channelHandler = res -> {
if (res.succeeded()) {
Channel ch = res.result();
if (sslHelper.isSSL()) {
SslHandler sslHandler = (SslHandler) ch.pipeline().get("ssl");
io.netty.util.concurrent.Future<Channel> fut = sslHandler.handshakeFuture();
fut.addListener(future2 -> {
if (future2.isSuccess()) {
connected(context, ch, connectHandler, host, port);
} else {
failed(context, ch, future2.cause(), connectHandler);
}
});
} else {
connected(context, ch, connectHandler, host, port);
}
} else {
if (remainingAttempts > 0 || remainingAttempts == -1) {
context.executeFromIO(() -> {
log.debug("Failed to create connection. Will retry in " + options.getReconnectInterval() + " milliseconds");
vertx.setTimer(options.getReconnectInterval(), tid -> connect(port, host, connectHandler, remainingAttempts == -1 ? remainingAttempts : remainingAttempts - 1));
});
} else {
failed(context, null, res.cause(), connectHandler);
}
}
};
channelProvider.connect(vertx, bootstrap, options.getProxyOptions(), host, port, channelInitializer, channelHandler);
}
Aggregations