Search in sources :

Example 96 with BiConsumer

use of java.util.function.BiConsumer in project vert.x by eclipse.

the class Http1xTest method testHttpClientResponseThrowsExceptionInHandler.

private void testHttpClientResponseThrowsExceptionInHandler(String chunk, BiConsumer<HttpClientResponse, RuntimeException> handler) throws Exception {
    server.requestHandler(req -> {
        HttpServerResponse resp = req.response();
        if (chunk != null) {
            resp.end(chunk);
        } else {
            resp.end();
        }
    });
    startServer(testAddress);
    int num = 50;
    waitFor(num);
    RuntimeException failure = new RuntimeException();
    for (int i = 0; i < num; i++) {
        client.request(requestOptions).onComplete(onSuccess(req -> {
            req.send(onSuccess(resp -> {
                ContextInternal ctx = (ContextInternal) vertx.getOrCreateContext();
                ctx.exceptionHandler(err -> {
                    if (err == failure) {
                        complete();
                    }
                });
                handler.accept(resp, failure);
            }));
        }));
    }
    await();
}
Also used : HttpServerImpl(io.vertx.core.http.impl.HttpServerImpl) IntStream(java.util.stream.IntStream) java.util(java.util) io.vertx.core(io.vertx.core) ContextInternal(io.vertx.core.impl.ContextInternal) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Http1xOrH2CHandler(io.vertx.core.http.impl.Http1xOrH2CHandler) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) SimpleServer(io.vertx.test.verticles.SimpleServer) TestUtils(io.vertx.test.core.TestUtils) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) WriteStream(io.vertx.core.streams.WriteStream) BiConsumer(java.util.function.BiConsumer) RecordParser(io.vertx.core.parsetools.RecordParser) JsonObject(io.vertx.core.json.JsonObject) Assume(org.junit.Assume) CheckingSender(io.vertx.test.core.CheckingSender) VertxInternal(io.vertx.core.impl.VertxInternal) Http1xUpgradeToH2CHandler(io.vertx.core.http.impl.Http1xUpgradeToH2CHandler) ConcurrentHashSet(io.vertx.core.impl.ConcurrentHashSet) java.util.concurrent(java.util.concurrent) TooLongFrameException(io.netty.handler.codec.TooLongFrameException) Test(org.junit.Test) Http1xServerConnection(io.vertx.core.http.impl.Http1xServerConnection) EventLoop(io.netty.channel.EventLoop) Future(io.vertx.core.Future) io.vertx.core.net(io.vertx.core.net) Collectors(java.util.stream.Collectors) File(java.io.File) LongConsumer(java.util.function.LongConsumer) Channel(io.netty.channel.Channel) Consumer(java.util.function.Consumer) EventLoopContext(io.vertx.core.impl.EventLoopContext) JsonArray(io.vertx.core.json.JsonArray) Repeat(io.vertx.test.core.Repeat) Stream(java.util.stream.Stream) Buffer(io.vertx.core.buffer.Buffer) HttpUtils(io.vertx.core.http.impl.HttpUtils) Cert(io.vertx.test.tls.Cert) ChannelHandler(io.netty.channel.ChannelHandler) PUT(io.vertx.core.http.HttpMethod.PUT) ContextInternal(io.vertx.core.impl.ContextInternal)

Example 97 with BiConsumer

use of java.util.function.BiConsumer in project vert.x by eclipse.

the class DatagramTest method testMulticastJoinLeave.

private void testMulticastJoinLeave(String bindAddress, DatagramSocketOptions options1, DatagramSocketOptions options2, BiConsumer<String, Handler<AsyncResult<Void>>> join, BiConsumer<String, Handler<AsyncResult<Void>>> leave) {
    if (USE_NATIVE_TRANSPORT) {
        return;
    }
    Buffer buffer = Buffer.buffer("HELLO");
    String groupAddress = "230.0.0.1";
    AtomicBoolean received = new AtomicBoolean();
    peer1 = vertx.createDatagramSocket(options1);
    peer2 = vertx.createDatagramSocket(options2);
    peer1.handler(packet -> {
        assertEquals(buffer, packet.data());
        received.set(true);
    });
    peer1.listen(1234, bindAddress, onSuccess(v1 -> {
        join.accept(groupAddress, onSuccess(v2 -> {
            peer2.send(buffer, 1234, groupAddress, onSuccess(ar3 -> {
                // leave group in 1 second so give it enough time to really receive the packet first
                vertx.setTimer(1000, id -> {
                    leave.accept(groupAddress, onSuccess(ar4 -> {
                        AtomicBoolean receivedAfter = new AtomicBoolean();
                        peer1.handler(packet -> {
                            // Should not receive any more event as it left the group
                            receivedAfter.set(true);
                        });
                        peer2.send(buffer, 1234, groupAddress, onSuccess(v5 -> {
                            // schedule a timer which will check in 1 second if we received a message after the group
                            // was left before
                            vertx.setTimer(1000, id2 -> {
                                assertFalse(receivedAfter.get());
                                assertTrue(received.get());
                                testComplete();
                            });
                        }));
                    }));
                });
            }));
        }));
    }));
    await();
}
Also used : Buffer(io.vertx.core.buffer.Buffer) NetworkOptions(io.vertx.core.net.NetworkOptions) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Random(java.util.Random) Context(io.vertx.core.Context) VertxTestBase(io.vertx.test.core.VertxTestBase) Utils(io.vertx.core.impl.Utils) InetAddress(java.net.InetAddress) ByteBuf(io.netty.buffer.ByteBuf) TestUtils(io.vertx.test.core.TestUtils) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) WriteStream(io.vertx.core.streams.WriteStream) BiConsumer(java.util.function.BiConsumer) JsonObject(io.vertx.core.json.JsonObject) Assume(org.junit.Assume) AsyncResult(io.vertx.core.AsyncResult) TestLoggerFactory(io.vertx.test.netty.TestLoggerFactory) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) NetworkInterface(java.net.NetworkInterface) Test(org.junit.Test) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) Buffer(io.vertx.core.buffer.Buffer) DeploymentOptions(io.vertx.core.DeploymentOptions) AbstractVerticle(io.vertx.core.AbstractVerticle) Handler(io.vertx.core.Handler) UnpooledHeapByteBuf(io.netty.buffer.UnpooledHeapByteBuf) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean)

Example 98 with BiConsumer

use of java.util.function.BiConsumer in project vert.x by eclipse.

the class MetricsContextTest method testMessageHandler.

private void testMessageHandler(BiConsumer<Vertx, Handler<Void>> runOnContext) {
    AtomicReference<Thread> scheduleThread = new AtomicReference<>();
    AtomicReference<Thread> deliveredThread = new AtomicReference<>();
    AtomicBoolean registeredCalled = new AtomicBoolean();
    AtomicBoolean unregisteredCalled = new AtomicBoolean();
    AtomicBoolean messageDelivered = new AtomicBoolean();
    VertxMetricsFactory factory = (options) -> new DummyVertxMetrics() {

        @Override
        public EventBusMetrics createEventBusMetrics() {
            return new DummyEventBusMetrics() {

                @Override
                public Void handlerRegistered(String address, String repliedAddress) {
                    registeredCalled.set(true);
                    return null;
                }

                @Override
                public void handlerUnregistered(Void handler) {
                    unregisteredCalled.set(true);
                }

                @Override
                public void scheduleMessage(Void handler, boolean local) {
                    scheduleThread.set(Thread.currentThread());
                }

                @Override
                public void messageDelivered(Void handler, boolean local) {
                    deliveredThread.set(Thread.currentThread());
                }
            };
        }
    };
    Vertx vertx = vertx(new VertxOptions().setMetricsOptions(new MetricsOptions().setEnabled(true).setFactory(factory)));
    EventBus eb = vertx.eventBus();
    Thread t = new Thread(() -> {
        eb.send("the_address", "the_msg");
    });
    runOnContext.accept(vertx, v -> {
        MessageConsumer<Object> consumer = eb.consumer("the_address");
        consumer.handler(msg -> {
            Thread consumerThread = Thread.currentThread();
            executeInVanillaThread(() -> {
                vertx.getOrCreateContext().runOnContext(v2 -> {
                    consumer.unregister(onSuccess(v3 -> {
                        assertTrue(registeredCalled.get());
                        assertSame(t, scheduleThread.get());
                        assertSame(consumerThread, deliveredThread.get());
                        assertWaitUntil(() -> unregisteredCalled.get());
                        testComplete();
                    }));
                });
            });
        }).completionHandler(onSuccess(v2 -> {
            t.start();
        }));
    });
    await();
}
Also used : io.vertx.core(io.vertx.core) DatagramSocket(io.vertx.core.datagram.DatagramSocket) HttpResponse(io.vertx.core.spi.observability.HttpResponse) VertxMetricsFactory(io.vertx.core.spi.VertxMetricsFactory) HttpRequest(io.vertx.core.spi.observability.HttpRequest) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.junit.Test) DummyVertxMetrics(io.vertx.core.metrics.impl.DummyVertxMetrics) io.vertx.core.net(io.vertx.core.net) VertxTestBase(io.vertx.test.core.VertxTestBase) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) io.vertx.core.http(io.vertx.core.http) CountDownLatch(java.util.concurrent.CountDownLatch) EventBus(io.vertx.core.eventbus.EventBus) Buffer(io.vertx.core.buffer.Buffer) MetricsOptions(io.vertx.core.metrics.MetricsOptions) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BiConsumer(java.util.function.BiConsumer) DatagramSocketOptions(io.vertx.core.datagram.DatagramSocketOptions) EventBusOptions(io.vertx.core.eventbus.EventBusOptions) MessageConsumer(io.vertx.core.eventbus.MessageConsumer) MetricsOptions(io.vertx.core.metrics.MetricsOptions) AtomicReference(java.util.concurrent.atomic.AtomicReference) DummyVertxMetrics(io.vertx.core.metrics.impl.DummyVertxMetrics) EventBus(io.vertx.core.eventbus.EventBus) VertxMetricsFactory(io.vertx.core.spi.VertxMetricsFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean)

Example 99 with BiConsumer

use of java.util.function.BiConsumer in project crate by crate.

the class InboundPipelineTests method testPipelineHandling.

public void testPipelineHandling() throws IOException {
    final List<Tuple<MessageData, Exception>> expected = new ArrayList<>();
    final List<Tuple<MessageData, Exception>> actual = new ArrayList<>();
    final List<ReleasableBytesReference> toRelease = new ArrayList<>();
    final BiConsumer<TcpChannel, InboundMessage> messageHandler = (c, m) -> {
        try {
            final Header header = m.getHeader();
            final MessageData actualData;
            final Version version = header.getVersion();
            final boolean isRequest = header.isRequest();
            final long requestId = header.getRequestId();
            final boolean isCompressed = header.isCompressed();
            if (m.isShortCircuit()) {
                actualData = new MessageData(version, requestId, isRequest, isCompressed, header.getActionName(), null);
            } else if (isRequest) {
                final TestRequest request = new TestRequest(m.openOrGetStreamInput());
                actualData = new MessageData(version, requestId, isRequest, isCompressed, header.getActionName(), request.value);
            } else {
                final TestResponse response = new TestResponse(m.openOrGetStreamInput());
                actualData = new MessageData(version, requestId, isRequest, isCompressed, null, response.value);
            }
            actual.add(new Tuple<>(actualData, m.getException()));
        } catch (IOException e) {
            throw new AssertionError(e);
        }
    };
    final StatsTracker statsTracker = new StatsTracker();
    final LongSupplier millisSupplier = () -> TimeValue.nsecToMSec(System.nanoTime());
    final InboundDecoder decoder = new InboundDecoder(Version.CURRENT, PageCacheRecycler.NON_RECYCLING_INSTANCE);
    final String breakThisAction = "break_this_action";
    final String actionName = "actionName";
    final Predicate<String> canTripBreaker = breakThisAction::equals;
    final TestCircuitBreaker circuitBreaker = new TestCircuitBreaker();
    circuitBreaker.startBreaking();
    final InboundAggregator aggregator = new InboundAggregator(() -> circuitBreaker, canTripBreaker);
    final InboundPipeline pipeline = new InboundPipeline(statsTracker, millisSupplier, decoder, aggregator, messageHandler);
    final FakeTcpChannel channel = new FakeTcpChannel();
    final int iterations = randomIntBetween(100, 500);
    long totalMessages = 0;
    long bytesReceived = 0;
    for (int i = 0; i < iterations; ++i) {
        actual.clear();
        expected.clear();
        toRelease.clear();
        try (BytesStreamOutput streamOutput = new BytesStreamOutput()) {
            while (streamOutput.size() < BYTE_THRESHOLD) {
                final Version version = randomFrom(Version.CURRENT, Version.CURRENT.minimumCompatibilityVersion());
                final String value = randomAlphaOfLength(randomIntBetween(10, 200));
                final boolean isRequest = randomBoolean();
                final boolean isCompressed = randomBoolean();
                final long requestId = totalMessages++;
                final MessageData messageData;
                Exception expectedExceptionClass = null;
                OutboundMessage message;
                if (isRequest) {
                    if (rarely()) {
                        messageData = new MessageData(version, requestId, true, isCompressed, breakThisAction, null);
                        message = new OutboundMessage.Request(new TestRequest(value), version, breakThisAction, requestId, false, isCompressed);
                        expectedExceptionClass = new CircuitBreakingException("");
                    } else {
                        messageData = new MessageData(version, requestId, true, isCompressed, actionName, value);
                        message = new OutboundMessage.Request(new TestRequest(value), version, actionName, requestId, false, isCompressed);
                    }
                } else {
                    messageData = new MessageData(version, requestId, false, isCompressed, null, value);
                    message = new OutboundMessage.Response(new TestResponse(value), version, requestId, false, isCompressed);
                }
                expected.add(new Tuple<>(messageData, expectedExceptionClass));
                final BytesReference reference = message.serialize(new BytesStreamOutput());
                Streams.copy(reference.streamInput(), streamOutput);
            }
            final BytesReference networkBytes = streamOutput.bytes();
            int currentOffset = 0;
            while (currentOffset != networkBytes.length()) {
                final int remainingBytes = networkBytes.length() - currentOffset;
                final int bytesToRead = Math.min(randomIntBetween(1, 32 * 1024), remainingBytes);
                final BytesReference slice = networkBytes.slice(currentOffset, bytesToRead);
                try (ReleasableBytesReference reference = new ReleasableBytesReference(slice, () -> {
                })) {
                    toRelease.add(reference);
                    bytesReceived += reference.length();
                    pipeline.handleBytes(channel, reference);
                    currentOffset += bytesToRead;
                }
            }
            final int messages = expected.size();
            for (int j = 0; j < messages; ++j) {
                final Tuple<MessageData, Exception> expectedTuple = expected.get(j);
                final Tuple<MessageData, Exception> actualTuple = actual.get(j);
                final MessageData expectedMessageData = expectedTuple.v1();
                final MessageData actualMessageData = actualTuple.v1();
                assertEquals(expectedMessageData.requestId, actualMessageData.requestId);
                assertEquals(expectedMessageData.isRequest, actualMessageData.isRequest);
                assertEquals(expectedMessageData.isCompressed, actualMessageData.isCompressed);
                assertEquals(expectedMessageData.actionName, actualMessageData.actionName);
                assertEquals(expectedMessageData.value, actualMessageData.value);
                if (expectedTuple.v2() != null) {
                    assertNotNull(actualTuple.v2());
                    assertThat(actualTuple.v2(), instanceOf(expectedTuple.v2().getClass()));
                }
            }
            for (ReleasableBytesReference released : toRelease) {
                assertEquals(0, released.refCount());
            }
        }
        assertEquals(bytesReceived, statsTracker.getBytesRead());
        assertEquals(totalMessages, statsTracker.getMessagesReceived());
    }
}
Also used : Tuple(io.crate.common.collections.Tuple) LongSupplier(java.util.function.LongSupplier) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) BytesStreamOutput(org.elasticsearch.common.io.stream.BytesStreamOutput) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) BytesArray(org.elasticsearch.common.bytes.BytesArray) CircuitBreaker(org.elasticsearch.common.breaker.CircuitBreaker) BiConsumer(java.util.function.BiConsumer) NoopCircuitBreaker(org.elasticsearch.common.breaker.NoopCircuitBreaker) ESTestCase(org.elasticsearch.test.ESTestCase) Streams(io.crate.common.io.Streams) Releasable(org.elasticsearch.common.lease.Releasable) Predicate(java.util.function.Predicate) PageCacheRecycler(org.elasticsearch.common.util.PageCacheRecycler) IOException(java.io.IOException) BytesReference(org.elasticsearch.common.bytes.BytesReference) TestCircuitBreaker(org.elasticsearch.common.breaker.TestCircuitBreaker) Objects(java.util.Objects) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) List(java.util.List) Version(org.elasticsearch.Version) CircuitBreakingException(org.elasticsearch.common.breaker.CircuitBreakingException) TimeValue(io.crate.common.unit.TimeValue) ReleasableBytesReference(org.elasticsearch.common.bytes.ReleasableBytesReference) ArrayList(java.util.ArrayList) BytesStreamOutput(org.elasticsearch.common.io.stream.BytesStreamOutput) Version(org.elasticsearch.Version) BytesReference(org.elasticsearch.common.bytes.BytesReference) ReleasableBytesReference(org.elasticsearch.common.bytes.ReleasableBytesReference) ReleasableBytesReference(org.elasticsearch.common.bytes.ReleasableBytesReference) TestCircuitBreaker(org.elasticsearch.common.breaker.TestCircuitBreaker) IOException(java.io.IOException) IOException(java.io.IOException) CircuitBreakingException(org.elasticsearch.common.breaker.CircuitBreakingException) CircuitBreakingException(org.elasticsearch.common.breaker.CircuitBreakingException) LongSupplier(java.util.function.LongSupplier) Tuple(io.crate.common.collections.Tuple)

Example 100 with BiConsumer

use of java.util.function.BiConsumer in project crate by crate.

the class InboundPipelineTests method testDecodeExceptionIsPropagated.

public void testDecodeExceptionIsPropagated() throws IOException {
    BiConsumer<TcpChannel, InboundMessage> messageHandler = (c, m) -> {
    };
    final StatsTracker statsTracker = new StatsTracker();
    final LongSupplier millisSupplier = () -> TimeValue.nsecToMSec(System.nanoTime());
    final InboundDecoder decoder = new InboundDecoder(Version.CURRENT, PageCacheRecycler.NON_RECYCLING_INSTANCE);
    final Supplier<CircuitBreaker> breaker = () -> new NoopCircuitBreaker("test");
    final InboundAggregator aggregator = new InboundAggregator(breaker, (Predicate<String>) action -> true);
    final InboundPipeline pipeline = new InboundPipeline(statsTracker, millisSupplier, decoder, aggregator, messageHandler);
    try (BytesStreamOutput streamOutput = new BytesStreamOutput()) {
        String actionName = "actionName";
        final Version invalidVersion = Version.V_3_2_0;
        final String value = randomAlphaOfLength(1000);
        final boolean isRequest = randomBoolean();
        final long requestId = randomNonNegativeLong();
        OutboundMessage message;
        if (isRequest) {
            message = new OutboundMessage.Request(new TestRequest(value), invalidVersion, actionName, requestId, false, false);
        } else {
            message = new OutboundMessage.Response(new TestResponse(value), invalidVersion, requestId, false, false);
        }
        final BytesReference reference = message.serialize(streamOutput);
        try (ReleasableBytesReference releasable = ReleasableBytesReference.wrap(reference)) {
            expectThrows(IllegalStateException.class, () -> pipeline.handleBytes(new FakeTcpChannel(), releasable));
        }
        // Pipeline cannot be reused after uncaught exception
        final IllegalStateException ise = expectThrows(IllegalStateException.class, () -> pipeline.handleBytes(new FakeTcpChannel(), ReleasableBytesReference.wrap(BytesArray.EMPTY)));
        assertEquals("Pipeline state corrupted by uncaught exception", ise.getMessage());
    }
}
Also used : Tuple(io.crate.common.collections.Tuple) LongSupplier(java.util.function.LongSupplier) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) BytesStreamOutput(org.elasticsearch.common.io.stream.BytesStreamOutput) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) BytesArray(org.elasticsearch.common.bytes.BytesArray) CircuitBreaker(org.elasticsearch.common.breaker.CircuitBreaker) BiConsumer(java.util.function.BiConsumer) NoopCircuitBreaker(org.elasticsearch.common.breaker.NoopCircuitBreaker) ESTestCase(org.elasticsearch.test.ESTestCase) Streams(io.crate.common.io.Streams) Releasable(org.elasticsearch.common.lease.Releasable) Predicate(java.util.function.Predicate) PageCacheRecycler(org.elasticsearch.common.util.PageCacheRecycler) IOException(java.io.IOException) BytesReference(org.elasticsearch.common.bytes.BytesReference) TestCircuitBreaker(org.elasticsearch.common.breaker.TestCircuitBreaker) Objects(java.util.Objects) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) List(java.util.List) Version(org.elasticsearch.Version) CircuitBreakingException(org.elasticsearch.common.breaker.CircuitBreakingException) TimeValue(io.crate.common.unit.TimeValue) ReleasableBytesReference(org.elasticsearch.common.bytes.ReleasableBytesReference) CircuitBreaker(org.elasticsearch.common.breaker.CircuitBreaker) NoopCircuitBreaker(org.elasticsearch.common.breaker.NoopCircuitBreaker) TestCircuitBreaker(org.elasticsearch.common.breaker.TestCircuitBreaker) BytesStreamOutput(org.elasticsearch.common.io.stream.BytesStreamOutput) Version(org.elasticsearch.Version) NoopCircuitBreaker(org.elasticsearch.common.breaker.NoopCircuitBreaker) BytesReference(org.elasticsearch.common.bytes.BytesReference) ReleasableBytesReference(org.elasticsearch.common.bytes.ReleasableBytesReference) ReleasableBytesReference(org.elasticsearch.common.bytes.ReleasableBytesReference) LongSupplier(java.util.function.LongSupplier)

Aggregations

BiConsumer (java.util.function.BiConsumer)255 Test (org.junit.Test)110 List (java.util.List)106 Map (java.util.Map)77 IOException (java.io.IOException)75 Consumer (java.util.function.Consumer)69 ArrayList (java.util.ArrayList)68 HashMap (java.util.HashMap)64 Collectors (java.util.stream.Collectors)53 CountDownLatch (java.util.concurrent.CountDownLatch)52 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)50 Collections (java.util.Collections)46 Set (java.util.Set)46 Collection (java.util.Collection)45 Arrays (java.util.Arrays)44 TimeUnit (java.util.concurrent.TimeUnit)43 Assert (org.junit.Assert)43 Function (java.util.function.Function)41 Optional (java.util.Optional)40 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)35