Search in sources :

Example 41 with Buffer

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

the class NetTest method testInVerticle.

private void testInVerticle(boolean worker) throws Exception {
    client.close();
    server.close();
    class MyVerticle extends AbstractVerticle {

        Context ctx;

        @Override
        public void start() {
            ctx = context;
            if (worker) {
                assertTrue(ctx instanceof WorkerContext);
            } else {
                assertTrue(ctx instanceof EventLoopContext);
            }
            Thread thr = Thread.currentThread();
            server = vertx.createNetServer(new NetServerOptions().setPort(1234).setHost("localhost"));
            server.connectHandler(sock -> {
                sock.handler(buff -> {
                    sock.write(buff);
                });
                assertSame(ctx, context);
                if (!worker) {
                    assertSame(thr, Thread.currentThread());
                }
            });
            server.listen(ar -> {
                assertTrue(ar.succeeded());
                assertSame(ctx, context);
                if (!worker) {
                    assertSame(thr, Thread.currentThread());
                }
                client = vertx.createNetClient(new NetClientOptions());
                client.connect(1234, "localhost", ar2 -> {
                    assertSame(ctx, context);
                    if (!worker) {
                        assertSame(thr, Thread.currentThread());
                    }
                    assertTrue(ar2.succeeded());
                    NetSocket sock = ar2.result();
                    Buffer buff = TestUtils.randomBuffer(10000);
                    sock.write(buff);
                    Buffer brec = Buffer.buffer();
                    sock.handler(rec -> {
                        assertSame(ctx, context);
                        if (!worker) {
                            assertSame(thr, Thread.currentThread());
                        }
                        brec.appendBuffer(rec);
                        if (brec.length() == buff.length()) {
                            testComplete();
                        }
                    });
                });
            });
        }
    }
    MyVerticle verticle = new MyVerticle();
    vertx.deployVerticle(verticle, new DeploymentOptions().setWorker(worker));
    await();
}
Also used : Buffer(io.vertx.core.buffer.Buffer)

Example 42 with Buffer

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

the class NetTest method testTLS.

void testTLS(boolean clientCert, boolean clientTrust, boolean serverCert, boolean serverTrust, boolean requireClientAuth, boolean clientTrustAll, boolean shouldPass, boolean startTLS, String[] enabledCipherSuites, String[] enabledSecureTransportProtocols) throws Exception {
    server.close();
    NetServerOptions options = new NetServerOptions();
    if (!startTLS) {
        options.setSsl(true);
    }
    if (serverTrust) {
        options.setTrustStoreOptions(new JksOptions().setPath("tls/server-truststore.jks").setPassword("wibble"));
    }
    if (serverCert) {
        options.setKeyStoreOptions(new JksOptions().setPath("tls/server-keystore.jks").setPassword("wibble"));
    }
    if (requireClientAuth) {
        options.setClientAuth(ClientAuth.REQUIRED);
    }
    for (String suite : enabledCipherSuites) {
        options.addEnabledCipherSuite(suite);
    }
    for (String protocol : enabledSecureTransportProtocols) {
        options.addEnabledSecureTransportProtocol(protocol);
    }
    Consumer<NetSocket> certificateChainChecker = socket -> {
        try {
            X509Certificate[] certs = socket.peerCertificateChain();
            if (clientCert) {
                assertNotNull(certs);
                assertEquals(1, certs.length);
            } else {
                assertNull(certs);
            }
        } catch (SSLPeerUnverifiedException e) {
            assertTrue(clientTrust || clientTrustAll);
        }
    };
    options.setPort(4043);
    server = vertx.createNetServer(options);
    Handler<NetSocket> serverHandler = socket -> {
        if (socket.isSsl()) {
            certificateChainChecker.accept(socket);
        }
        AtomicBoolean upgradedServer = new AtomicBoolean();
        AtomicInteger upgradedServerCount = new AtomicInteger();
        socket.handler(buff -> {
            socket.write(buff);
            if (startTLS) {
                if (upgradedServer.compareAndSet(false, true)) {
                    assertFalse(socket.isSsl());
                    socket.upgradeToSsl(v -> {
                        certificateChainChecker.accept(socket);
                        upgradedServerCount.incrementAndGet();
                        assertTrue(socket.isSsl());
                    });
                } else {
                    assertTrue(socket.isSsl());
                    assertEquals(1, upgradedServerCount.get());
                }
            } else {
                assertTrue(socket.isSsl());
            }
        });
    };
    server.connectHandler(serverHandler).listen(ar -> {
        client.close();
        NetClientOptions clientOptions = new NetClientOptions();
        if (!startTLS) {
            clientOptions.setSsl(true);
        }
        if (clientTrustAll) {
            clientOptions.setTrustAll(true);
        }
        if (clientTrust) {
            clientOptions.setTrustStoreOptions(new JksOptions().setPath("tls/client-truststore.jks").setPassword("wibble"));
        }
        if (clientCert) {
            clientOptions.setKeyStoreOptions(new JksOptions().setPath("tls/client-keystore.jks").setPassword("wibble"));
        }
        for (String suite : enabledCipherSuites) {
            clientOptions.addEnabledCipherSuite(suite);
        }
        for (String protocol : enabledSecureTransportProtocols) {
            clientOptions.addEnabledSecureTransportProtocol(protocol);
        }
        client = vertx.createNetClient(clientOptions);
        client.connect(4043, "localhost", ar2 -> {
            if (ar2.succeeded()) {
                if (!shouldPass) {
                    fail("Should not connect");
                    return;
                }
                final int numChunks = 100;
                final int chunkSize = 100;
                final List<Buffer> toSend = new ArrayList<>();
                final Buffer expected = Buffer.buffer();
                for (int i = 0; i < numChunks; i++) {
                    Buffer chunk = TestUtils.randomBuffer(chunkSize);
                    toSend.add(chunk);
                    expected.appendBuffer(chunk);
                }
                final Buffer received = Buffer.buffer();
                final NetSocket socket = ar2.result();
                final AtomicBoolean upgradedClient = new AtomicBoolean();
                socket.handler(buffer -> {
                    received.appendBuffer(buffer);
                    if (received.length() == expected.length()) {
                        assertEquals(expected, received);
                        testComplete();
                    }
                    if (startTLS && !upgradedClient.get()) {
                        upgradedClient.set(true);
                        assertFalse(socket.isSsl());
                        socket.upgradeToSsl(v -> {
                            assertTrue(socket.isSsl());
                            for (int i = 1; i < numChunks; i++) {
                                socket.write(toSend.get(i));
                            }
                        });
                    } else {
                        assertTrue(socket.isSsl());
                    }
                });
                int numToSend = startTLS ? 1 : numChunks;
                for (int i = 0; i < numToSend; i++) {
                    socket.write(toSend.get(i));
                }
            } else {
                if (shouldPass) {
                    fail("Should not fail to connect");
                } else {
                    testComplete();
                }
            }
        });
    });
    await();
}
Also used : java.util(java.util) io.vertx.core(io.vertx.core) io.vertx.core.impl(io.vertx.core.impl) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Cert(io.vertx.test.core.tls.Cert) TestUtils.assertNullPointerException(io.vertx.test.core.TestUtils.assertNullPointerException) AtomicReference(java.util.concurrent.atomic.AtomicReference) LoggerFactory(io.vertx.core.logging.LoggerFactory) InetAddress(java.net.InetAddress) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ReadStream(io.vertx.core.streams.ReadStream) OutputStreamWriter(java.io.OutputStreamWriter) JsonObject(io.vertx.core.json.JsonObject) Assume(org.junit.Assume) Logger(io.vertx.core.logging.Logger) TestLoggerFactory(io.vertx.test.netty.TestLoggerFactory) BufferedWriter(java.io.BufferedWriter) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Message(io.vertx.core.eventbus.Message) FileOutputStream(java.io.FileOutputStream) Test(org.junit.Test) X509Certificate(javax.security.cert.X509Certificate) io.vertx.core.net(io.vertx.core.net) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) JsonArray(io.vertx.core.json.JsonArray) CountDownLatch(java.util.concurrent.CountDownLatch) Rule(org.junit.Rule) Buffer(io.vertx.core.buffer.Buffer) ClientAuth(io.vertx.core.http.ClientAuth) InternalLoggerFactory(io.netty.util.internal.logging.InternalLoggerFactory) MessageConsumer(io.vertx.core.eventbus.MessageConsumer) SocketAddressImpl(io.vertx.core.net.impl.SocketAddressImpl) TemporaryFolder(org.junit.rules.TemporaryFolder) Trust(io.vertx.test.core.tls.Trust) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) TestUtils.assertIllegalArgumentException(io.vertx.test.core.TestUtils.assertIllegalArgumentException) Buffer(io.vertx.core.buffer.Buffer) SSLPeerUnverifiedException(javax.net.ssl.SSLPeerUnverifiedException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicInteger(java.util.concurrent.atomic.AtomicInteger)

Example 43 with Buffer

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

the class RecordParserTest method testFixed.

@Test
public /*
  Test parsing with fixed size records
   */
void testFixed() {
    int lines = 50;
    Buffer[] expected = new Buffer[lines];
    //We create lines of length zero to <lines> and shuffle them
    List<Buffer> lineList = generateLines(lines, false, (byte) 0);
    expected = lineList.toArray(expected);
    // The sum of 0...(lines - 1)
    int totLength = lines * (lines - 1) / 2;
    Buffer inp = Buffer.buffer(totLength);
    for (int i = 0; i < lines; i++) {
        inp.appendBuffer(expected[i]);
    }
    //We then try every combination of chunk size up to twice the input string length
    for (int i = 1; i < inp.length() * 2; i++) {
        doTestFixed(inp, new Integer[] { i }, expected);
    }
    //Then we try a sequence of random chunk sizes
    List<Integer> chunkSizes = generateChunkSizes(lines);
    //Repeat a few times
    for (int i = 0; i < 10; i++) {
        Collections.shuffle(chunkSizes);
        doTestFixed(inp, chunkSizes.toArray(new Integer[] {}), expected);
    }
}
Also used : Buffer(io.vertx.core.buffer.Buffer) Test(org.junit.Test)

Example 44 with Buffer

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

the class RecordParserTest method delimited.

/*
  We create some input dataHandler which contains <lines> lines of lengths in randm order between 0 and lines
  And then passes them into the RecordParser in chunk sizes from 0 to twice the total input buffer size
   */
private void delimited(Buffer delim) {
    int lines = 50;
    Buffer[] expected = new Buffer[lines];
    //We create lines of length zero to <lines> and shuffle them
    List<Buffer> lineList = generateLines(lines, true, delim.getByte(0));
    expected = lineList.toArray(expected);
    // The sum of 0...(lines - 1)
    int totLength = lines * (lines - 1) / 2;
    Buffer inp = Buffer.buffer(totLength + lines * delim.length());
    for (int i = 0; i < lines; i++) {
        inp.appendBuffer(expected[i]);
        inp.appendBuffer(delim);
    }
    //We then try every combination of chunk size up to twice the input string length
    for (int i = 1; i < inp.length() * 2; i++) {
        doTestDelimited(inp, delim, new Integer[] { i }, expected);
    }
    //Then we try a sequence of random chunk sizes
    List<Integer> chunkSizes = generateChunkSizes(lines);
    //Repeat a few times
    for (int i = 0; i < 10; i++) {
        Collections.shuffle(chunkSizes);
        doTestDelimited(inp, delim, chunkSizes.toArray(new Integer[] {}), expected);
    }
}
Also used : Buffer(io.vertx.core.buffer.Buffer)

Example 45 with Buffer

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

the class NetTest method testEchoString.

@Test
public void testEchoString() {
    String sent = TestUtils.randomUnicodeString(100);
    Buffer buffSent = Buffer.buffer(sent);
    testEcho(sock -> sock.write(sent), buff -> assertEquals(buffSent, buff), buffSent.length());
}
Also used : Buffer(io.vertx.core.buffer.Buffer) Test(org.junit.Test)

Aggregations

Buffer (io.vertx.core.buffer.Buffer)1053 Test (org.junit.Test)604 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)256 Future (io.vertx.core.Future)253 AtomicReference (java.util.concurrent.atomic.AtomicReference)237 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)235 Handler (io.vertx.core.Handler)230 Vertx (io.vertx.core.Vertx)185 TestUtils (io.vertx.test.core.TestUtils)177 JsonObject (io.vertx.core.json.JsonObject)172 TimeUnit (java.util.concurrent.TimeUnit)161 CountDownLatch (java.util.concurrent.CountDownLatch)153 List (java.util.List)152 Consumer (java.util.function.Consumer)149 Function (java.util.function.Function)142 ReadStream (io.vertx.core.streams.ReadStream)139 Context (io.vertx.core.Context)135 ArrayList (java.util.ArrayList)132 MultiMap (io.vertx.core.MultiMap)130 Assume (org.junit.Assume)130