use of io.vertx.core.AsyncResult in project vert.x by eclipse.
the class Http2ServerTest method testPushPromise.
private void testPushPromise(Http2Headers requestHeaders, BiConsumer<HttpServerResponse, Handler<AsyncResult<HttpServerResponse>>> pusher, Consumer<Http2Headers> headerChecker) throws Exception {
Context ctx = vertx.getOrCreateContext();
server.requestHandler(req -> {
Handler<AsyncResult<HttpServerResponse>> handler = ar -> {
assertSame(ctx, Vertx.currentContext());
assertTrue(ar.succeeded());
HttpServerResponse response = ar.result();
response.end("the_content");
assertIllegalStateException(() -> response.push(HttpMethod.GET, "/wibble2", resp -> {
}));
};
pusher.accept(req.response(), handler);
});
startServer(ctx);
TestClient client = new TestClient();
ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
int id = request.nextStreamId();
Http2ConnectionEncoder encoder = request.encoder;
encoder.writeHeaders(request.context, id, requestHeaders, 0, true, request.context.newPromise());
Map<Integer, Http2Headers> pushed = new HashMap<>();
request.decoder.frameListener(new Http2FrameAdapter() {
@Override
public void onPushPromiseRead(ChannelHandlerContext ctx, int streamId, int promisedStreamId, Http2Headers headers, int padding) throws Http2Exception {
pushed.put(promisedStreamId, headers);
}
@Override
public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream) throws Http2Exception {
int delta = super.onDataRead(ctx, streamId, data, padding, endOfStream);
String content = data.toString(StandardCharsets.UTF_8);
vertx.runOnContext(v -> {
assertEquals(Collections.singleton(streamId), pushed.keySet());
assertEquals("the_content", content);
Http2Headers pushedHeaders = pushed.get(streamId);
headerChecker.accept(pushedHeaders);
testComplete();
});
return delta;
}
});
});
fut.sync();
await();
}
use of io.vertx.core.AsyncResult in project vert.x by eclipse.
the class VertxImpl method close.
@Override
public synchronized void close(Handler<AsyncResult<Void>> completionHandler) {
if (closed || eventBus == null) {
// Just call the handler directly since pools shutdown
if (completionHandler != null) {
completionHandler.handle(Future.succeededFuture());
}
return;
}
closed = true;
closeHooks.run(ar -> {
deploymentManager.undeployAll(ar1 -> {
if (haManager() != null) {
haManager().stop();
}
addressResolver.close(ar2 -> {
eventBus.close(ar3 -> {
closeClusterManager(ar4 -> {
Set<HttpServer> httpServers = new HashSet<>(sharedHttpServers.values());
Set<NetServerBase> netServers = new HashSet<>(sharedNetServers.values());
sharedHttpServers.clear();
sharedNetServers.clear();
int serverCount = httpServers.size() + netServers.size();
AtomicInteger serverCloseCount = new AtomicInteger();
Handler<AsyncResult<Void>> serverCloseHandler = res -> {
if (res.failed()) {
log.error("Failure in shutting down server", res.cause());
}
if (serverCloseCount.incrementAndGet() == serverCount) {
deleteCacheDirAndShutdown(completionHandler);
}
};
for (HttpServer server : httpServers) {
server.close(serverCloseHandler);
}
for (NetServerBase server : netServers) {
server.close(serverCloseHandler);
}
if (serverCount == 0) {
deleteCacheDirAndShutdown(completionHandler);
}
});
});
});
});
});
}
use of io.vertx.core.AsyncResult in project vert.x by eclipse.
the class NetServerBase method listen.
public synchronized void listen(Handler<? super C> handler, int port, String host, Handler<AsyncResult<Void>> listenHandler) {
if (handler == null) {
throw new IllegalStateException("Set connect handler first");
}
if (listening) {
throw new IllegalStateException("Listen already called");
}
listening = true;
listenContext = vertx.getOrCreateContext();
registeredHandler = handler;
synchronized (vertx.sharedNetServers()) {
// Will be updated on bind for a wildcard port
this.actualPort = port;
id = new ServerID(port, host);
NetServerBase shared = vertx.sharedNetServers().get(id);
if (shared == null || port == 0) {
// Wildcard port will imply a new actual server each time
serverChannelGroup = new DefaultChannelGroup("vertx-acceptor-channels", GlobalEventExecutor.INSTANCE);
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(availableWorkers);
bootstrap.channel(NioServerSocketChannel.class);
sslHelper.validate(vertx);
bootstrap.childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) throws Exception {
if (isPaused()) {
ch.close();
return;
}
ChannelPipeline pipeline = ch.pipeline();
NetServerBase.this.initChannel(ch.pipeline());
pipeline.addLast("handler", new ServerHandler(ch));
}
});
applyConnectionOptions(bootstrap);
handlerManager.addHandler(handler, listenContext);
try {
bindFuture = AsyncResolveConnectHelper.doBind(vertx, port, host, bootstrap);
bindFuture.addListener(res -> {
if (res.succeeded()) {
Channel ch = res.result();
log.trace("Net server listening on " + host + ":" + ch.localAddress());
NetServerBase.this.actualPort = ((InetSocketAddress) ch.localAddress()).getPort();
NetServerBase.this.id = new ServerID(NetServerBase.this.actualPort, id.host);
serverChannelGroup.add(ch);
vertx.sharedNetServers().put(id, NetServerBase.this);
metrics = vertx.metricsSPI().createMetrics(new SocketAddressImpl(id.port, id.host), options);
} else {
vertx.sharedNetServers().remove(id);
}
});
} catch (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;
}
if (port != 0) {
vertx.sharedNetServers().put(id, this);
}
actualServer = this;
} else {
// Server already exists with that host/port - we will use that
actualServer = shared;
this.actualPort = shared.actualPort();
metrics = vertx.metricsSPI().createMetrics(new SocketAddressImpl(id.port, id.host), options);
actualServer.handlerManager.addHandler(handler, listenContext);
}
// just add it to the future so it gets notified once the bind is complete
actualServer.bindFuture.addListener(res -> {
if (listenHandler != null) {
AsyncResult<Void> ares;
if (res.succeeded()) {
ares = Future.succeededFuture();
} else {
listening = false;
ares = Future.failedFuture(res.cause());
}
listenContext.runOnContext(v -> listenHandler.handle(ares));
} else if (res.failed()) {
log.error("Failed to listen", res.cause());
listening = false;
}
});
}
return;
}
use of io.vertx.core.AsyncResult in project vert.x by eclipse.
the class NetSocketImpl method sendFile.
@Override
public NetSocket sendFile(String filename, long offset, long length, final Handler<AsyncResult<Void>> resultHandler) {
File f = vertx.resolveFile(filename);
if (f.isDirectory()) {
throw new IllegalArgumentException("filename must point to a file and not to a directory");
}
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(f, "r");
ChannelFuture future = super.sendFile(raf, Math.min(offset, f.length()), Math.min(length, f.length() - offset));
if (resultHandler != null) {
future.addListener(fut -> {
final AsyncResult<Void> res;
if (future.isSuccess()) {
res = Future.succeededFuture();
} else {
res = Future.failedFuture(future.cause());
}
vertx.runOnContext(v -> resultHandler.handle(res));
});
}
} catch (IOException e) {
try {
if (raf != null) {
raf.close();
}
} catch (IOException ignore) {
}
if (resultHandler != null) {
vertx.runOnContext(v -> resultHandler.handle(Future.failedFuture(e)));
} else {
log.error("Failed to send file", e);
}
}
return this;
}
use of io.vertx.core.AsyncResult in project vert.x by eclipse.
the class Http2ServerConnection method sendPush.
synchronized void sendPush(int streamId, String host, HttpMethod method, MultiMap headers, String path, Handler<AsyncResult<HttpServerResponse>> completionHandler) {
Http2Headers headers_ = new DefaultHttp2Headers();
if (method == HttpMethod.OTHER) {
throw new IllegalArgumentException("Cannot push HttpMethod.OTHER");
} else {
headers_.method(method.name());
}
headers_.path(path);
headers_.scheme(isSsl() ? "https" : "http");
if (host != null) {
headers_.authority(host);
}
if (headers != null) {
headers.forEach(header -> headers_.add(header.getKey(), header.getValue()));
}
handler.writePushPromise(streamId, headers_, new Handler<AsyncResult<Integer>>() {
@Override
public void handle(AsyncResult<Integer> ar) {
if (ar.succeeded()) {
synchronized (Http2ServerConnection.this) {
int promisedStreamId = ar.result();
String contentEncoding = HttpUtils.determineContentEncoding(headers_);
Http2Stream promisedStream = handler.connection().stream(promisedStreamId);
boolean writable = handler.encoder().flowController().isWritable(promisedStream);
Push push = new Push(promisedStream, contentEncoding, method, path, writable, completionHandler);
streams.put(promisedStreamId, push);
if (maxConcurrentStreams == null || concurrentStreams < maxConcurrentStreams) {
concurrentStreams++;
context.executeFromIO(push::complete);
} else {
pendingPushes.add(push);
}
}
} else {
context.executeFromIO(() -> {
completionHandler.handle(Future.failedFuture(ar.cause()));
});
}
}
});
}
Aggregations