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();
}
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();
}
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();
}
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());
}
}
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());
}
}
Aggregations