Search in sources :

Example 66 with Handler

use of io.vertx.core.Handler in project vert.x by eclipse.

the class WebsocketTest method testUpgrade.

private void testUpgrade(boolean delayed) {
    String path = "/some/path";
    server = vertx.createHttpServer(new HttpServerOptions().setPort(HttpTestBase.DEFAULT_HTTP_PORT));
    server.requestHandler(request -> {
        Runnable runner = () -> {
            ServerWebSocket ws = request.upgrade();
            ws.handler(buff -> {
                ws.write(Buffer.buffer("helloworld"));
                ws.close();
            });
        };
        if (delayed) {
            vertx.runOnContext(v -> {
                runner.run();
            });
        } else {
            runner.run();
        }
    });
    server.listen(ar -> {
        assertTrue(ar.succeeded());
        client.websocketStream(HttpTestBase.DEFAULT_HTTP_PORT, HttpTestBase.DEFAULT_HTTP_HOST, path, null).handler(ws -> {
            Buffer buff = Buffer.buffer();
            ws.handler(b -> {
                buff.appendBuffer(b);
            });
            ws.endHandler(v -> {
                assertEquals("helloworld", buff.toString());
                testComplete();
            });
            ws.write(Buffer.buffer("foo"));
        });
    });
    await();
}
Also used : Arrays(java.util.Arrays) MessageDigest(java.security.MessageDigest) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Cert(io.vertx.test.core.tls.Cert) WebSocketHandshakeException(io.netty.handler.codec.http.websocketx.WebSocketHandshakeException) Context(io.vertx.core.Context) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TestUtils(io.vertx.test.core.TestUtils) Map(java.util.Map) ReadStream(io.vertx.core.streams.ReadStream) AsyncResult(io.vertx.core.AsyncResult) ConcurrentHashSet(io.vertx.core.impl.ConcurrentHashSet) java.util.concurrent(java.util.concurrent) Vertx(io.vertx.core.Vertx) Set(java.util.Set) Test(org.junit.Test) Future(io.vertx.core.Future) io.vertx.core.http(io.vertx.core.http) Consumer(java.util.function.Consumer) Base64(java.util.Base64) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) DeploymentOptions(io.vertx.core.DeploymentOptions) NetServer(io.vertx.core.net.NetServer) AbstractVerticle(io.vertx.core.AbstractVerticle) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Handler(io.vertx.core.Handler) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Collections(java.util.Collections) NetSocket(io.vertx.core.net.NetSocket) Trust(io.vertx.test.core.tls.Trust) Buffer(io.vertx.core.buffer.Buffer)

Example 67 with Handler

use of io.vertx.core.Handler in project vert.x by eclipse.

the class VertxTest method testCloseHookFailure2.

@Test
public void testCloseHookFailure2() throws Exception {
    AtomicInteger closedCount = new AtomicInteger();
    class Hook implements Closeable {

        @Override
        public void close(Handler<AsyncResult<Void>> completionHandler) {
            if (closedCount.incrementAndGet() == 1) {
                completionHandler.handle(Future.succeededFuture());
                throw new RuntimeException();
            } else {
                completionHandler.handle(Future.succeededFuture());
            }
        }
    }
    VertxInternal vertx = (VertxInternal) Vertx.vertx();
    vertx.addCloseHook(new Hook());
    vertx.addCloseHook(new Hook());
    // Now undeploy
    vertx.close(ar -> {
        assertTrue(ar.succeeded());
        assertEquals(2, closedCount.get());
        testComplete();
    });
    await();
}
Also used : VertxInternal(io.vertx.core.impl.VertxInternal) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Closeable(io.vertx.core.Closeable) Handler(io.vertx.core.Handler) Test(org.junit.Test)

Example 68 with Handler

use of io.vertx.core.Handler in project vert.x by eclipse.

the class SocksProxy method start.

/**
   * Start the server.
   * 
   * @param vertx
   *          Vertx instance to use for creating the server and client
   * @param finishedHandler
   *          will be called when the start has started
   */
@Override
public void start(Vertx vertx, Handler<Void> finishedHandler) {
    NetServerOptions options = new NetServerOptions();
    options.setHost("localhost").setPort(PORT);
    server = vertx.createNetServer(options);
    server.connectHandler(socket -> {
        socket.handler(buffer -> {
            Buffer expectedInit = username == null ? clientInit : clientInitAuth;
            if (!buffer.equals(expectedInit)) {
                throw new IllegalStateException("expected " + toHex(expectedInit) + ", got " + toHex(buffer));
            }
            boolean useAuth = buffer.equals(clientInitAuth);
            log.debug("got request: " + toHex(buffer));
            final Handler<Buffer> handler = buffer2 -> {
                if (!buffer2.getBuffer(0, clientRequest.length()).equals(clientRequest)) {
                    throw new IllegalStateException("expected " + toHex(clientRequest) + ", got " + toHex(buffer2));
                }
                int stringLen = buffer2.getUnsignedByte(4);
                log.debug("string len " + stringLen);
                if (buffer2.length() != 7 + stringLen) {
                    throw new IllegalStateException("format error in client request, got " + toHex(buffer2));
                }
                String host = buffer2.getString(5, 5 + stringLen);
                int port = buffer2.getUnsignedShort(5 + stringLen);
                log.debug("got request: " + toHex(buffer2));
                log.debug("connect: " + host + ":" + port);
                socket.handler(null);
                lastUri = host + ":" + port;
                if (forceUri != null) {
                    host = forceUri.substring(0, forceUri.indexOf(':'));
                    port = Integer.valueOf(forceUri.substring(forceUri.indexOf(':') + 1));
                }
                log.debug("connecting to " + host + ":" + port);
                NetClient netClient = vertx.createNetClient(new NetClientOptions());
                netClient.connect(port, host, result -> {
                    if (result.succeeded()) {
                        log.debug("writing: " + toHex(connectResponse));
                        socket.write(connectResponse);
                        log.debug("connected, starting pump");
                        NetSocket clientSocket = result.result();
                        socket.closeHandler(v -> clientSocket.close());
                        clientSocket.closeHandler(v -> socket.close());
                        Pump.pump(socket, clientSocket).start();
                        Pump.pump(clientSocket, socket).start();
                    } else {
                        log.error("exception", result.cause());
                        socket.handler(null);
                        log.debug("writing: " + toHex(errorResponse));
                        socket.write(errorResponse);
                        socket.close();
                    }
                });
            };
            if (useAuth) {
                socket.handler(buffer3 -> {
                    log.debug("auth handler");
                    log.debug("got request: " + toHex(buffer3));
                    Buffer authReply = Buffer.buffer(new byte[] { 1, (byte) username.length() });
                    authReply.appendString(username);
                    authReply.appendByte((byte) username.length());
                    authReply.appendString(username);
                    if (!buffer3.equals(authReply)) {
                        log.debug("expected " + toHex(authReply) + ", got " + toHex(buffer3));
                        socket.handler(null);
                        log.debug("writing: " + toHex(authFailed));
                        socket.write(authFailed);
                        socket.close();
                    } else {
                        socket.handler(handler);
                        log.debug("writing: " + toHex(authSuccess));
                        socket.write(authSuccess);
                    }
                });
                log.debug("writing: " + toHex(serverReplyAuth));
                socket.write(serverReplyAuth);
            } else {
                socket.handler(handler);
                log.debug("writing: " + toHex(serverReply));
                socket.write(serverReply);
            }
        });
    });
    server.listen(result -> {
        log.debug("socks5 server started");
        finishedHandler.handle(null);
    });
}
Also used : Buffer(io.vertx.core.buffer.Buffer) NetServerOptions(io.vertx.core.net.NetServerOptions) Buffer(io.vertx.core.buffer.Buffer) NetServer(io.vertx.core.net.NetServer) Vertx(io.vertx.core.Vertx) Pump(io.vertx.core.streams.Pump) Handler(io.vertx.core.Handler) Logger(io.vertx.core.logging.Logger) NetClient(io.vertx.core.net.NetClient) LoggerFactory(io.vertx.core.logging.LoggerFactory) NetClientOptions(io.vertx.core.net.NetClientOptions) NetSocket(io.vertx.core.net.NetSocket) NetSocket(io.vertx.core.net.NetSocket) NetClientOptions(io.vertx.core.net.NetClientOptions) NetClient(io.vertx.core.net.NetClient) NetServerOptions(io.vertx.core.net.NetServerOptions)

Example 69 with Handler

use of io.vertx.core.Handler in project vert.x by eclipse.

the class ProxyErrorTest method proxyTest.

private void proxyTest(int error, String username, String url, Handler<HttpClientResponse> assertResponse, boolean completeOnException) throws Exception {
    startProxy(error, username);
    final HttpClientOptions options = new HttpClientOptions().setSsl(url.startsWith("https")).setProxyOptions(new ProxyOptions().setType(ProxyType.HTTP).setHost("localhost").setPort(proxy.getPort()));
    HttpClient client = vertx.createHttpClient(options);
    client.getAbs(url, assertResponse).exceptionHandler(e -> {
        if (completeOnException) {
            testComplete();
        } else {
            fail(e);
        }
    }).end();
    await();
}
Also used : CountDownLatch(java.util.concurrent.CountDownLatch) HttpClientResponse(io.vertx.core.http.HttpClientResponse) ProxyOptions(io.vertx.core.net.ProxyOptions) ProxyType(io.vertx.core.net.ProxyType) HttpProxy(io.vertx.test.core.HttpProxy) Test(org.junit.Test) HttpClientOptions(io.vertx.core.http.HttpClientOptions) Handler(io.vertx.core.Handler) Logger(io.vertx.core.logging.Logger) VertxTestBase(io.vertx.test.core.VertxTestBase) LoggerFactory(io.vertx.core.logging.LoggerFactory) HttpClient(io.vertx.core.http.HttpClient) ProxyOptions(io.vertx.core.net.ProxyOptions) HttpClient(io.vertx.core.http.HttpClient) HttpClientOptions(io.vertx.core.http.HttpClientOptions)

Example 70 with Handler

use of io.vertx.core.Handler in project vert.x by eclipse.

the class RecordParserTest method doTestDelimited.

private void doTestDelimited(final Buffer input, Buffer delim, Integer[] chunkSizes, final Buffer... expected) {
    final Buffer[] results = new Buffer[expected.length];
    Handler<Buffer> out = new Handler<Buffer>() {

        int pos;

        public void handle(Buffer buff) {
            results[pos++] = buff;
        }
    };
    RecordParser parser = RecordParser.newDelimited(delim, out);
    feedChunks(input, parser, chunkSizes);
    checkResults(expected, results);
}
Also used : Buffer(io.vertx.core.buffer.Buffer) Handler(io.vertx.core.Handler) RecordParser(io.vertx.core.parsetools.RecordParser)

Aggregations

Handler (io.vertx.core.Handler)119 Test (org.junit.Test)78 Future (io.vertx.core.Future)67 Vertx (io.vertx.core.Vertx)59 AsyncResult (io.vertx.core.AsyncResult)57 Context (io.vertx.core.Context)52 Buffer (io.vertx.core.buffer.Buffer)48 Async (io.vertx.ext.unit.Async)41 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)39 Map (java.util.Map)38 TestContext (io.vertx.ext.unit.TestContext)37 VertxUnitRunner (io.vertx.ext.unit.junit.VertxUnitRunner)36 RunWith (org.junit.runner.RunWith)36 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)34 Collections (java.util.Collections)33 JsonObject (io.vertx.core.json.JsonObject)31 HttpURLConnection (java.net.HttpURLConnection)31 Before (org.junit.Before)31 StandardCharsets (java.nio.charset.StandardCharsets)29 TimeUnit (java.util.concurrent.TimeUnit)29