use of io.vertx.core.AsyncResult in project vert.x by eclipse.
the class FakeStreamTest method testAsyncEndDeferred.
@Test
public void testAsyncEndDeferred() {
Promise<Void> end = Promise.promise();
AtomicInteger ended = new AtomicInteger();
AtomicReference<AsyncResult> endRes = new AtomicReference<>();
stream.setEnd(end.future());
stream.pause();
stream.emit(3);
stream.endHandler(v -> ended.incrementAndGet());
stream.end(endRes::set);
assertEquals(0, ended.get());
assertNull(endRes.get());
end.complete();
assertEquals(0, ended.get());
assertNull(endRes.get());
stream.fetch(1);
assertEquals(0, ended.get());
assertNull(endRes.get());
stream.fetch(1);
assertEquals(1, ended.get());
assertTrue(endRes.get().succeeded());
}
use of io.vertx.core.AsyncResult in project vert.x by eclipse.
the class WebSocketTest method testInvalidHandshake.
// Check client response with the ws handler
private void testInvalidHandshake(Consumer<Handler<AsyncResult<HttpClientResponse>>> requestProvider, boolean expectEvent, boolean upgradeRequest, int expectedStatus) {
client = vertx.createHttpClient(new HttpClientOptions().setMaxPoolSize(1));
if (upgradeRequest) {
server = vertx.createHttpServer().webSocketHandler(ws -> {
// Check we can get notified
// handshake fails after this method returns and does not reject the ws
assertTrue(expectEvent);
}).requestHandler(req -> {
req.response().end();
});
} else {
AtomicBoolean first = new AtomicBoolean();
server = vertx.createHttpServer().requestHandler(req -> {
if (first.compareAndSet(false, true)) {
try {
req.toWebSocket();
} catch (Exception e) {
// Expected
}
} else {
req.response().end();
}
});
}
server.listen(DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST, onSuccess(s -> {
requestProvider.accept(onSuccess(resp -> {
assertEquals(expectedStatus, resp.statusCode());
resp.endHandler(v1 -> {
// Make another request to check the connection remains usable
client.request(new RequestOptions().setPort(DEFAULT_HTTP_PORT).setHost(DEFAULT_HTTP_HOST)).onComplete(onSuccess(req2 -> {
req2.send(onSuccess(resp2 -> {
resp2.endHandler(v2 -> {
testComplete();
});
}));
}));
});
}));
}));
}
use of io.vertx.core.AsyncResult in project vert.x by eclipse.
the class WebSocketTest method testTLS.
private void testTLS(Cert<?> clientCert, Trust<?> clientTrust, Cert<?> serverCert, Trust<?> serverTrust, boolean requireClientAuth, boolean serverUsesCrl, boolean clientTrustAll, boolean clientUsesCrl, boolean shouldPass, boolean clientSsl, boolean serverSsl, boolean sni, String[] enabledCipherSuites, BiConsumer<HttpClient, Handler<AsyncResult<WebSocket>>> wsProvider) throws Exception {
HttpClientOptions options = new HttpClientOptions();
options.setSsl(clientSsl);
options.setTrustAll(clientTrustAll);
if (clientUsesCrl) {
options.addCrlPath("tls/root-ca/crl.pem");
}
options.setTrustOptions(clientTrust.get());
options.setKeyCertOptions(clientCert.get());
for (String suite : enabledCipherSuites) {
options.addEnabledCipherSuite(suite);
}
client = vertx.createHttpClient(options);
HttpServerOptions serverOptions = new HttpServerOptions();
serverOptions.setSsl(serverSsl);
serverOptions.setSni(sni);
serverOptions.setTrustOptions(serverTrust.get());
serverOptions.setKeyCertOptions(serverCert.get());
if (requireClientAuth) {
serverOptions.setClientAuth(ClientAuth.REQUIRED);
}
if (serverUsesCrl) {
serverOptions.addCrlPath("tls/root-ca/crl.pem");
}
for (String suite : enabledCipherSuites) {
serverOptions.addEnabledCipherSuite(suite);
}
server = vertx.createHttpServer(serverOptions.setPort(4043));
server.webSocketHandler(ws -> {
ws.handler(ws::write);
});
try {
server.listen(ar -> {
assertTrue(ar.succeeded());
Handler<AsyncResult<WebSocket>> handler = ar2 -> {
if (ar2.succeeded()) {
WebSocket ws = ar2.result();
if (clientSsl && sni) {
try {
Certificate clientPeerCert = ws.peerCertificates().get(0);
assertEquals("host2.com", TestUtils.cnOf(clientPeerCert));
} catch (Exception err) {
fail(err);
}
}
int size = 100;
Buffer received = Buffer.buffer();
ws.handler(data -> {
received.appendBuffer(data);
if (received.length() == size) {
ws.close();
testComplete();
}
});
Buffer buff = Buffer.buffer(TestUtils.randomByteArray(size));
ws.writeFrame(WebSocketFrame.binaryFrame(buff, true));
} else {
if (shouldPass) {
ar2.cause().printStackTrace();
fail("Should not throw exception");
} else {
testComplete();
}
}
};
wsProvider.accept(client, handler);
});
} catch (Exception e) {
e.printStackTrace();
}
await();
}
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 -> {
assertSameEventLoop(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 BareCommand method startVertx.
/**
* Starts the vert.x instance.
*
* @return the created instance of vert.x
*/
@SuppressWarnings("ThrowableResultOfMethodCallIgnored")
protected Vertx startVertx() {
JsonObject optionsJson = getJsonFromFileOrString(vertxOptions, "options");
EventBusOptions eventBusOptions;
VertxBuilder builder;
if (optionsJson == null) {
eventBusOptions = getEventBusOptions();
builder = new VertxBuilder();
} else {
eventBusOptions = getEventBusOptions(optionsJson.getJsonObject("eventBusOptions"));
builder = new VertxBuilder(optionsJson);
}
options = builder.options();
options.setEventBusOptions(eventBusOptions);
beforeStartingVertx(options);
configureFromSystemProperties.set(log);
try {
configureFromSystemProperties(options, VERTX_OPTIONS_PROP_PREFIX);
if (options.getMetricsOptions() != null) {
configureFromSystemProperties(options.getMetricsOptions(), METRICS_OPTIONS_PROP_PREFIX);
}
builder.init();
} finally {
configureFromSystemProperties.set(null);
}
Vertx instance;
if (isClustered()) {
log.info("Starting clustering...");
eventBusOptions = options.getEventBusOptions();
if (!Objects.equals(eventBusOptions.getHost(), EventBusOptions.DEFAULT_CLUSTER_HOST)) {
clusterHost = eventBusOptions.getHost();
}
if (eventBusOptions.getPort() != EventBusOptions.DEFAULT_CLUSTER_PORT) {
clusterPort = eventBusOptions.getPort();
}
if (!Objects.equals(eventBusOptions.getClusterPublicHost(), EventBusOptions.DEFAULT_CLUSTER_PUBLIC_HOST)) {
clusterPublicHost = eventBusOptions.getClusterPublicHost();
}
if (eventBusOptions.getClusterPublicPort() != EventBusOptions.DEFAULT_CLUSTER_PUBLIC_PORT) {
clusterPublicPort = eventBusOptions.getClusterPublicPort();
}
eventBusOptions.setHost(clusterHost).setPort(clusterPort).setClusterPublicHost(clusterPublicHost);
if (clusterPublicPort != -1) {
eventBusOptions.setClusterPublicPort(clusterPublicPort);
}
if (getHA()) {
options.setHAEnabled(true);
if (haGroup != null) {
options.setHAGroup(haGroup);
}
if (quorum != -1) {
options.setQuorumSize(quorum);
}
}
CountDownLatch latch = new CountDownLatch(1);
AtomicReference<AsyncResult<Vertx>> result = new AtomicReference<>();
create(builder, ar -> {
result.set(ar);
latch.countDown();
});
try {
if (!latch.await(2, TimeUnit.MINUTES)) {
log.error("Timed out in starting clustered Vert.x");
return null;
}
} catch (InterruptedException e) {
log.error("Thread interrupted in startup");
Thread.currentThread().interrupt();
return null;
}
if (result.get().failed()) {
log.error("Failed to form cluster", result.get().cause());
return null;
}
instance = result.get().result();
} else {
instance = create(builder);
}
addShutdownHook(instance, log, finalAction);
afterStartingVertx(instance);
return instance;
}
Aggregations