Search in sources :

Example 26 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 27 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 28 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)

Example 29 with Handler

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

the class RecordParserTest method testMixed.

@Test
public /*
  Test mixture of fixed and delimited
   */
void testMixed() {
    final int lines = 8;
    final List<Object> types = new ArrayList<Object>();
    class MyHandler implements Handler<Buffer> {

        RecordParser parser = RecordParser.newFixed(10, this);

        int pos;

        public void handle(Buffer buff) {
            if (pos < lines) {
                Object type = types.get(pos);
                if (type instanceof byte[]) {
                    byte[] bytes = (byte[]) type;
                    parser.delimitedMode(Buffer.buffer(bytes));
                } else {
                    int length = (Integer) type;
                    parser.fixedSizeMode(length);
                }
            }
        }
    }
    MyHandler out = new MyHandler();
    Buffer[] expected = new Buffer[lines];
    Buffer input = Buffer.buffer(100);
    expected[0] = TestUtils.randomBuffer(10);
    input.appendBuffer(expected[0]);
    types.add(expected[0].length());
    expected[1] = TestUtils.randomBuffer(100);
    input.appendBuffer(expected[1]);
    types.add(expected[1].length());
    byte[] delim = new byte[] { 23, -120, 100, 3 };
    expected[2] = TestUtils.randomBuffer(50, true, delim[0]);
    input.appendBuffer(expected[2]);
    types.add(delim);
    input.appendBuffer(Buffer.buffer(delim));
    expected[3] = TestUtils.randomBuffer(1000);
    input.appendBuffer(expected[3]);
    types.add(expected[3].length());
    expected[4] = TestUtils.randomBuffer(230, true, delim[0]);
    input.appendBuffer(expected[4]);
    types.add(delim);
    input.appendBuffer(Buffer.buffer(delim));
    delim = new byte[] { 17 };
    expected[5] = TestUtils.randomBuffer(341, true, delim[0]);
    input.appendBuffer(expected[5]);
    types.add(delim);
    input.appendBuffer(Buffer.buffer(delim));
    delim = new byte[] { 54, -32, 0 };
    expected[6] = TestUtils.randomBuffer(1234, true, delim[0]);
    input.appendBuffer(expected[6]);
    types.add(delim);
    input.appendBuffer(Buffer.buffer(delim));
    expected[7] = TestUtils.randomBuffer(100);
    input.appendBuffer(expected[7]);
    types.add(expected[7].length());
    feedChunks(input, out.parser, new Integer[] { 50, 10, 3 });
}
Also used : Buffer(io.vertx.core.buffer.Buffer) ArrayList(java.util.ArrayList) RecordParser(io.vertx.core.parsetools.RecordParser) Handler(io.vertx.core.Handler) Test(org.junit.Test)

Example 30 with Handler

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

the class TimerTest method periodic.

private void periodic(long delay) throws Exception {
    final int numFires = 10;
    final AtomicLong id = new AtomicLong(-1);
    id.set(vertx.setPeriodic(delay, new Handler<Long>() {

        int count;

        public void handle(Long timerID) {
            assertEquals(id.get(), timerID.longValue());
            count++;
            if (count == numFires) {
                vertx.cancelTimer(timerID);
                setEndTimer();
            }
            if (count > numFires) {
                fail("Fired too many times");
            }
        }
    }));
    await();
}
Also used : AtomicLong(java.util.concurrent.atomic.AtomicLong) AtomicLong(java.util.concurrent.atomic.AtomicLong) Handler(io.vertx.core.Handler)

Aggregations

Handler (io.vertx.core.Handler)47 Buffer (io.vertx.core.buffer.Buffer)32 AsyncResult (io.vertx.core.AsyncResult)31 Future (io.vertx.core.Future)31 Test (org.junit.Test)28 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)26 NetSocket (io.vertx.core.net.NetSocket)24 ArrayList (java.util.ArrayList)23 Context (io.vertx.core.Context)22 List (java.util.List)22 Map (java.util.Map)22 Vertx (io.vertx.core.Vertx)21 File (java.io.File)21 Collections (java.util.Collections)21 MultiMap (io.vertx.core.MultiMap)20 HttpMethod (io.vertx.core.http.HttpMethod)20 VertxInternal (io.vertx.core.impl.VertxInternal)20 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)20 Function (java.util.function.Function)20 HttpClient (io.vertx.core.http.HttpClient)19