Search in sources :

Example 66 with AsyncResult

use of io.vertx.core.AsyncResult 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 67 with AsyncResult

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

the class Http2ServerResponse method sendFile.

@Override
public HttpServerResponse sendFile(String filename, long offset, long length, Handler<AsyncResult<Void>> resultHandler) {
    synchronized (conn) {
        checkValid();
    }
    Handler<AsyncResult<Void>> h;
    if (resultHandler != null) {
        Context resultCtx = stream.vertx.getOrCreateContext();
        h = ar -> {
            resultCtx.runOnContext((v) -> {
                resultHandler.handle(ar);
            });
        };
    } else {
        h = ar -> {
        };
    }
    HttpUtils.resolveFile(stream.vertx, filename, offset, length, ar -> {
        if (ar.succeeded()) {
            AsyncFile file = ar.result();
            long contentLength = Math.min(length, file.getReadLength());
            if (headers.get(HttpHeaderNames.CONTENT_LENGTH) == null) {
                putHeader(HttpHeaderNames.CONTENT_LENGTH, String.valueOf(contentLength));
            }
            if (headers.get(HttpHeaderNames.CONTENT_TYPE) == null) {
                String contentType = MimeMapping.getMimeTypeForFilename(filename);
                if (contentType != null) {
                    putHeader(HttpHeaderNames.CONTENT_TYPE, contentType);
                }
            }
            checkSendHeaders(false);
            file.pipeTo(this, ar1 -> file.close(ar2 -> {
                Throwable failure = ar1.failed() ? ar1.cause() : ar2.failed() ? ar2.cause() : null;
                if (failure == null)
                    h.handle(ar1);
                else
                    h.handle(Future.failedFuture(failure));
            }));
        } else {
            h.handle(ar.mapEmpty());
        }
    });
    return this;
}
Also used : Context(io.vertx.core.Context) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) AsyncFile(io.vertx.core.file.AsyncFile) MultiMap(io.vertx.core.MultiMap) ConnectionBase(io.vertx.core.net.impl.ConnectionBase) Context(io.vertx.core.Context) Unpooled(io.netty.buffer.Unpooled) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Http2HeadersAdaptor(io.vertx.core.http.impl.headers.Http2HeadersAdaptor) ByteBuf(io.netty.buffer.ByteBuf) HttpStatusClass(io.netty.handler.codec.http.HttpStatusClass) ReadStream(io.vertx.core.streams.ReadStream) AsyncResult(io.vertx.core.AsyncResult) StreamResetException(io.vertx.core.http.StreamResetException) SET_COOKIE(io.vertx.core.http.HttpHeaders.SET_COOKIE) StreamPriority(io.vertx.core.http.StreamPriority) HttpResponse(io.vertx.core.spi.observability.HttpResponse) Promise(io.vertx.core.Promise) HttpHeaders(io.vertx.core.http.HttpHeaders) Set(java.util.Set) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) Future(io.vertx.core.Future) Nullable(io.vertx.codegen.annotations.Nullable) Buffer(io.vertx.core.buffer.Buffer) Http2Headers(io.netty.handler.codec.http2.Http2Headers) HttpMethod(io.vertx.core.http.HttpMethod) HttpServerResponse(io.vertx.core.http.HttpServerResponse) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Handler(io.vertx.core.Handler) Cookie(io.vertx.core.http.Cookie) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) NetSocket(io.vertx.core.net.NetSocket) AsyncFile(io.vertx.core.file.AsyncFile) AsyncResult(io.vertx.core.AsyncResult)

Example 68 with AsyncResult

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

the class ConnectionManagerTest method testCloseManager.

@Test
public void testCloseManager() throws Exception {
    EventLoopContext ctx = (EventLoopContext) vertx.getOrCreateContext();
    Connection expected = new Connection();
    boolean[] disposed = new boolean[1];
    ConnectionManager<Object, Connection> mgr = new ConnectionManager<>(new EndpointProvider<Object, Connection>() {

        @Override
        public Endpoint<Connection> create(Object key, ContextInternal ctx, Runnable dispose) {
            return new Endpoint<Connection>(dispose) {

                @Override
                public void requestConnection(ContextInternal ctx, long timeout, Handler<AsyncResult<Connection>> handler) {
                    incRefCount();
                    handler.handle(Future.succeededFuture(expected));
                }

                @Override
                protected void dispose() {
                    disposed[0] = true;
                }

                @Override
                protected void close() {
                    super.close();
                    decRefCount();
                }
            };
        }
    });
    CountDownLatch latch = new CountDownLatch(1);
    mgr.getConnection(ctx, TEST_KEY, onSuccess(conn -> {
        assertEquals(expected, conn);
        latch.countDown();
    }));
    awaitLatch(latch);
    assertFalse(disposed[0]);
    mgr.close();
    assertTrue(disposed[0]);
}
Also used : EventLoopContext(io.vertx.core.impl.EventLoopContext) CountDownLatch(java.util.concurrent.CountDownLatch) ContextInternal(io.vertx.core.impl.ContextInternal) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Test(org.junit.Test) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) Future(io.vertx.core.Future) VertxTestBase(io.vertx.test.core.VertxTestBase) AtomicReference(java.util.concurrent.atomic.AtomicReference) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) ContextInternal(io.vertx.core.impl.ContextInternal) CountDownLatch(java.util.concurrent.CountDownLatch) EventLoopContext(io.vertx.core.impl.EventLoopContext) AsyncResult(io.vertx.core.AsyncResult) Test(org.junit.Test)

Example 69 with AsyncResult

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

the class ConnectionManagerTest method testConcurrentDispose.

@Test
public void testConcurrentDispose() throws Exception {
    EventLoopContext ctx = (EventLoopContext) vertx.getOrCreateContext();
    ConcurrentLinkedQueue<AtomicBoolean> disposals = new ConcurrentLinkedQueue<>();
    ConnectionManager<Object, Connection> mgr = new ConnectionManager<>(new EndpointProvider<Object, Connection>() {

        @Override
        public Endpoint<Connection> create(Object key, ContextInternal ctx, Runnable dispose) {
            AtomicBoolean disposed = new AtomicBoolean();
            disposals.add(disposed);
            return new Endpoint<Connection>(dispose) {

                @Override
                public void requestConnection(ContextInternal ctx, long timeout, Handler<AsyncResult<Connection>> handler) {
                    if (disposed.get()) {
                        // Check we don't have reentrant demands once disposed
                        fail();
                    } else {
                        Connection conn = new Connection();
                        incRefCount();
                        handler.handle(Future.succeededFuture(conn));
                        decRefCount();
                    }
                }

                @Override
                protected void dispose() {
                    disposed.set(true);
                }
            };
        }
    });
    int num = 100000;
    int concurrency = 4;
    CountDownLatch[] latches = new CountDownLatch[concurrency];
    for (int i = 0; i < concurrency; i++) {
        CountDownLatch cc = new CountDownLatch(num);
        latches[i] = cc;
        new Thread(() -> {
            for (int j = 0; j < num; j++) {
                mgr.getConnection(ctx, TEST_KEY, onSuccess(conn -> {
                    cc.countDown();
                }));
            }
        }).start();
    }
    for (int i = 0; i < concurrency; i++) {
        awaitLatch(latches[i]);
    }
    disposals.forEach(disposed -> {
        waitUntil(disposed::get);
    });
}
Also used : ContextInternal(io.vertx.core.impl.ContextInternal) CountDownLatch(java.util.concurrent.CountDownLatch) EventLoopContext(io.vertx.core.impl.EventLoopContext) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) AsyncResult(io.vertx.core.AsyncResult) Test(org.junit.Test)

Example 70 with AsyncResult

use of io.vertx.core.AsyncResult in project nem2-sdk-java by nemtech.

the class MetadataRepositoryVertxImpl method search.

@Override
public Observable<Page<Metadata>> search(MetadataSearchCriteria criteria) {
    String sourceAddress = toDto(criteria.getSourceAddress());
    String targetAddress = toDto(criteria.getTargetAddress());
    String scopedMetadataKey = toDto(criteria.getScopedMetadataKey());
    String targetId = criteria.getTargetId();
    MetadataTypeEnum metadataType = criteria.getMetadataType() == null ? null : MetadataTypeEnum.fromValue(criteria.getMetadataType().getValue());
    String offset = criteria.getOffset();
    Integer pageSize = criteria.getPageSize();
    Integer pageNumber = criteria.getPageNumber();
    Order order = toDto(criteria.getOrder());
    Consumer<Handler<AsyncResult<MetadataPage>>> callback = handler -> getClient().searchMetadataEntries(sourceAddress, targetAddress, scopedMetadataKey, targetId, metadataType, pageSize, pageNumber, offset, order, handler);
    return exceptionHandling(call(callback).map(page -> this.toPage(page.getPagination(), page.getData().stream().map(this::toMetadata).collect(Collectors.toList()))));
}
Also used : MetadataTypeEnum(io.nem.symbol.sdk.openapi.vertx.model.MetadataTypeEnum) BigInteger(java.math.BigInteger) Order(io.nem.symbol.sdk.openapi.vertx.model.Order) MapperUtils(io.nem.symbol.core.utils.MapperUtils) ApiClient(io.nem.symbol.sdk.openapi.vertx.invoker.ApiClient) ConvertUtils(io.nem.symbol.core.utils.ConvertUtils) MetadataType(io.nem.symbol.sdk.model.metadata.MetadataType) MetadataTypeEnum(io.nem.symbol.sdk.openapi.vertx.model.MetadataTypeEnum) Collectors(java.util.stream.Collectors) MetadataRepository(io.nem.symbol.sdk.api.MetadataRepository) MetadataEntryDTO(io.nem.symbol.sdk.openapi.vertx.model.MetadataEntryDTO) MetadataInfoDTO(io.nem.symbol.sdk.openapi.vertx.model.MetadataInfoDTO) Consumer(java.util.function.Consumer) Order(io.nem.symbol.sdk.openapi.vertx.model.Order) ObjectUtils(org.apache.commons.lang3.ObjectUtils) MetadataSearchCriteria(io.nem.symbol.sdk.api.MetadataSearchCriteria) MerkleStateInfo(io.nem.symbol.sdk.model.blockchain.MerkleStateInfo) MetadataPage(io.nem.symbol.sdk.openapi.vertx.model.MetadataPage) Observable(io.reactivex.Observable) BigInteger(java.math.BigInteger) MetadataRoutesApiImpl(io.nem.symbol.sdk.openapi.vertx.api.MetadataRoutesApiImpl) AsyncResult(io.vertx.core.AsyncResult) Handler(io.vertx.core.Handler) Metadata(io.nem.symbol.sdk.model.metadata.Metadata) MetadataRoutesApi(io.nem.symbol.sdk.openapi.vertx.api.MetadataRoutesApi) Page(io.nem.symbol.sdk.api.Page) MetadataPage(io.nem.symbol.sdk.openapi.vertx.model.MetadataPage) Handler(io.vertx.core.Handler)

Aggregations

AsyncResult (io.vertx.core.AsyncResult)162 Handler (io.vertx.core.Handler)106 Test (org.junit.Test)72 JsonObject (io.vertx.core.json.JsonObject)68 CountDownLatch (java.util.concurrent.CountDownLatch)62 Future (io.vertx.core.Future)59 List (java.util.List)49 RequestParameter (io.vertx.ext.web.api.RequestParameter)48 RequestParameters (io.vertx.ext.web.api.RequestParameters)48 HashMap (java.util.HashMap)45 Map (java.util.Map)42 IOException (java.io.IOException)41 ArrayList (java.util.ArrayList)40 Vertx (io.vertx.core.Vertx)35 Collectors (java.util.stream.Collectors)35 RoutingContext (io.vertx.ext.web.RoutingContext)28 Buffer (io.vertx.core.buffer.Buffer)24 StandardCharsets (java.nio.charset.StandardCharsets)23 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)23 Consumer (java.util.function.Consumer)23