use of io.vertx.core.Future in project vert.x by eclipse.
the class HttpClientRequestImpl method handleNextRequest.
private void handleNextRequest(HttpClientResponse resp, HttpClientRequestImpl next, long timeoutMs) {
next.handler(respHandler);
next.exceptionHandler(exceptionHandler());
exceptionHandler(null);
next.endHandler(endHandler);
next.pushHandler = pushHandler;
next.followRedirects = followRedirects - 1;
next.written = written;
if (next.hostHeader == null) {
next.hostHeader = hostHeader;
}
if (headers != null && next.headers == null) {
next.headers().addAll(headers);
}
ByteBuf body;
switch(next.method) {
case GET:
body = null;
break;
case OTHER:
next.rawMethod = rawMethod;
body = null;
break;
default:
if (cachedChunks != null) {
body = cachedChunks;
} else {
body = null;
}
break;
}
cachedChunks = null;
Future<Void> fut = Future.future();
fut.setHandler(ar -> {
if (ar.succeeded()) {
if (timeoutMs > 0) {
next.setTimeout(timeoutMs);
}
next.write(body, true);
} else {
next.handleException(ar.cause());
}
});
if (exceptionOccurred != null) {
fut.fail(exceptionOccurred);
} else if (completed) {
fut.complete();
} else {
exceptionHandler(err -> {
if (!fut.isComplete()) {
fut.fail(err);
}
});
completionHandler = v -> {
if (!fut.isComplete()) {
fut.complete();
}
};
}
}
use of io.vertx.core.Future 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.Future in project hono by eclipse.
the class StandaloneEventApiTest method prepareHonoServer.
/**
* Sets up Hono Messaging service.
*
* @param ctx The test context.
*/
@BeforeClass
public static void prepareHonoServer(final TestContext ctx) {
vertx = Vertx.vertx();
downstreamAdapter = new MessageDiscardingDownstreamAdapter(vertx);
final HonoMessagingConfigProperties configProperties = new HonoMessagingConfigProperties();
configProperties.setInsecurePort(0);
final EventEndpoint eventEndpoint = new EventEndpoint(vertx);
eventEndpoint.setMetrics(mock(MessagingMetrics.class));
eventEndpoint.setEventAdapter(downstreamAdapter);
eventEndpoint.setRegistrationAssertionValidator(assertionHelper);
eventEndpoint.setConfiguration(configProperties);
server = new HonoMessaging();
server.setSaslAuthenticatorFactory(new HonoSaslAuthenticatorFactory(TestSupport.createAuthenticationService(createUser())));
server.setConfig(configProperties);
server.addEndpoint(eventEndpoint);
Future<String> serverTracker = Future.future();
vertx.deployVerticle(server, serverTracker.completer());
serverTracker.compose(s -> {
final ClientConfigProperties clientProps = new ClientConfigProperties();
clientProps.setName("test");
clientProps.setHost(server.getInsecurePortBindAddress());
clientProps.setPort(server.getInsecurePort());
clientProps.setUsername(USER);
clientProps.setPassword(PWD);
client = new HonoClientImpl(vertx, clientProps);
return client.connect(new ProtonClientOptions());
}).setHandler(ctx.asyncAssertSuccess());
}
use of io.vertx.core.Future in project hono by eclipse.
the class StandaloneEventApiTest method testMalformedMessageGetsRejected.
/**
* Verifies that malformed messages are not forwarded downstream.
*
* @param ctx The vert.x test context.
*/
@Test
public void testMalformedMessageGetsRejected(final TestContext ctx) {
final Message msg = ProtonHelper.message("malformed");
msg.setMessageId("malformed-message");
final Future<MessageSender> senderTracker = getSender(Constants.DEFAULT_TENANT);
senderTracker.compose(sender -> {
return sender.send(msg);
}).setHandler(ctx.asyncAssertFailure(t -> {
ctx.assertTrue(ClientErrorException.class.isInstance(t));
ctx.assertTrue(senderTracker.result().isOpen());
}));
}
use of io.vertx.core.Future in project hono by eclipse.
the class CrudHttpClient method update.
/**
* Updates a resource using HTTP PUT.
*
* @param uri The resource to update.
* @param body The content to update the resource with.
* @param contentType The content type to set in the request.
* @param successPredicate A predicate on the returned HTTP status code for determining success.
* @return A future that will succeed if the predicate evaluates to {@code true}.
*/
public Future<Void> update(final String uri, final Buffer body, final String contentType, final Predicate<Integer> successPredicate) {
final Future<Void> result = Future.future();
final HttpClientRequest req = vertx.createHttpClient().put(port, host, uri).handler(response -> {
if (successPredicate.test(response.statusCode())) {
result.complete();
} else {
result.fail(new ServiceInvocationException(response.statusCode()));
}
}).exceptionHandler(result::fail);
if (contentType != null) {
req.putHeader(HttpHeaders.CONTENT_TYPE, contentType);
}
if (body == null) {
req.end();
} else {
req.end(body);
}
return result;
}
Aggregations