Search in sources :

Example 76 with AsyncResult

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

the class NamespaceRepositoryVertxImpl method search.

@Override
public Observable<Page<NamespaceInfo>> search(NamespaceSearchCriteria criteria) {
    String ownerAddress = toDto(criteria.getOwnerAddress());
    NamespaceRegistrationTypeEnum registrationType = criteria.getRegistrationType() == null ? null : NamespaceRegistrationTypeEnum.fromValue(criteria.getRegistrationType().getValue());
    String level0 = criteria.getLevel0();
    AliasTypeEnum aliasType = criteria.getAliasType() == null ? null : AliasTypeEnum.fromValue(criteria.getAliasType().getValue());
    Integer pageSize = criteria.getPageSize();
    Integer pageNumber = criteria.getPageNumber();
    String offset = criteria.getOffset();
    Order order = toDto(criteria.getOrder());
    Consumer<Handler<AsyncResult<NamespacePage>>> callback = handler -> getClient().searchNamespaces(ownerAddress, registrationType, level0, aliasType, pageSize, pageNumber, offset, order, handler);
    return exceptionHandling(call(callback).map(page -> this.toPage(page.getPagination(), page.getData().stream().map(this::toNamespaceInfo).collect(Collectors.toList()))));
}
Also used : Order(io.nem.symbol.sdk.openapi.vertx.model.Order) AliasTypeEnum(io.nem.symbol.sdk.openapi.vertx.model.AliasTypeEnum) NamespaceInfo(io.nem.symbol.sdk.model.namespace.NamespaceInfo) NamespaceDTO(io.nem.symbol.sdk.openapi.vertx.model.NamespaceDTO) Addresses(io.nem.symbol.sdk.openapi.vertx.model.Addresses) NamespaceRepository(io.nem.symbol.sdk.api.NamespaceRepository) NamespaceRoutesApi(io.nem.symbol.sdk.openapi.vertx.api.NamespaceRoutesApi) ArrayList(java.util.ArrayList) Order(io.nem.symbol.sdk.openapi.vertx.model.Order) MapperUtils.toNamespaceId(io.nem.symbol.core.utils.MapperUtils.toNamespaceId) NamespaceSearchCriteria(io.nem.symbol.sdk.api.NamespaceSearchCriteria) ObjectUtils(org.apache.commons.lang3.ObjectUtils) MerkleStateInfo(io.nem.symbol.sdk.model.blockchain.MerkleStateInfo) MosaicAlias(io.nem.symbol.sdk.model.namespace.MosaicAlias) Observable(io.reactivex.Observable) AsyncResult(io.vertx.core.AsyncResult) NamespaceId(io.nem.symbol.sdk.model.namespace.NamespaceId) MosaicNamesDTO(io.nem.symbol.sdk.openapi.vertx.model.MosaicNamesDTO) MapperUtils(io.nem.symbol.core.utils.MapperUtils) Alias(io.nem.symbol.sdk.model.namespace.Alias) ApiClient(io.nem.symbol.sdk.openapi.vertx.invoker.ApiClient) MosaicsNamesDTO(io.nem.symbol.sdk.openapi.vertx.model.MosaicsNamesDTO) NamespaceName(io.nem.symbol.sdk.model.namespace.NamespaceName) NamespacePage(io.nem.symbol.sdk.openapi.vertx.model.NamespacePage) MosaicNames(io.nem.symbol.sdk.model.mosaic.MosaicNames) NamespaceNameDTO(io.nem.symbol.sdk.openapi.vertx.model.NamespaceNameDTO) MosaicId(io.nem.symbol.sdk.model.mosaic.MosaicId) NamespaceRegistrationTypeEnum(io.nem.symbol.sdk.openapi.vertx.model.NamespaceRegistrationTypeEnum) EmptyAlias(io.nem.symbol.sdk.model.namespace.EmptyAlias) Collectors(java.util.stream.Collectors) NamespaceRoutesApiImpl(io.nem.symbol.sdk.openapi.vertx.api.NamespaceRoutesApiImpl) MosaicIds(io.nem.symbol.sdk.openapi.vertx.model.MosaicIds) NamespaceIds(io.nem.symbol.sdk.openapi.vertx.model.NamespaceIds) AccountNames(io.nem.symbol.sdk.model.account.AccountNames) NamespaceRegistrationType(io.nem.symbol.sdk.model.namespace.NamespaceRegistrationType) Consumer(java.util.function.Consumer) NamespaceInfoDTO(io.nem.symbol.sdk.openapi.vertx.model.NamespaceInfoDTO) List(java.util.List) AccountNamesDTO(io.nem.symbol.sdk.openapi.vertx.model.AccountNamesDTO) AliasType(io.nem.symbol.sdk.model.namespace.AliasType) AccountsNamesDTO(io.nem.symbol.sdk.openapi.vertx.model.AccountsNamesDTO) Optional(java.util.Optional) Address(io.nem.symbol.sdk.model.account.Address) Handler(io.vertx.core.Handler) Page(io.nem.symbol.sdk.api.Page) AddressAlias(io.nem.symbol.sdk.model.namespace.AddressAlias) AliasTypeEnum(io.nem.symbol.sdk.openapi.vertx.model.AliasTypeEnum) NamespacePage(io.nem.symbol.sdk.openapi.vertx.model.NamespacePage) Handler(io.vertx.core.Handler) NamespaceRegistrationTypeEnum(io.nem.symbol.sdk.openapi.vertx.model.NamespaceRegistrationTypeEnum)

Example 77 with AsyncResult

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

the class RestrictionAccountRepositoryVertxImpl method search.

@Override
public Observable<Page<AccountRestrictions>> search(AccountRestrictionSearchCriteria criteria) {
    String address = toDto(criteria.getAddress());
    Integer pageSize = criteria.getPageSize();
    Integer pageNumber = criteria.getPageNumber();
    String offset = criteria.getOffset();
    Order order = toDto(criteria.getOrder());
    Consumer<Handler<AsyncResult<AccountRestrictionsPage>>> handlerConsumer = (h) -> getClient().searchAccountRestrictions(address, pageSize, pageNumber, offset, order, h);
    return this.call(handlerConsumer, this::toPage);
}
Also used : Order(io.nem.symbol.sdk.openapi.vertx.model.Order) AccountRestrictionsPage(io.nem.symbol.sdk.openapi.vertx.model.AccountRestrictionsPage) RestrictionAccountRepository(io.nem.symbol.sdk.api.RestrictionAccountRepository) MapperUtils(io.nem.symbol.core.utils.MapperUtils) ApiClient(io.nem.symbol.sdk.openapi.vertx.invoker.ApiClient) RestrictionAccountRoutesApi(io.nem.symbol.sdk.openapi.vertx.api.RestrictionAccountRoutesApi) AccountRestrictionFlags(io.nem.symbol.sdk.model.transaction.AccountRestrictionFlags) AccountRestrictionDTO(io.nem.symbol.sdk.openapi.vertx.model.AccountRestrictionDTO) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) Consumer(java.util.function.Consumer) AccountRestrictionSearchCriteria(io.nem.symbol.sdk.api.AccountRestrictionSearchCriteria) AccountRestrictionsPage(io.nem.symbol.sdk.openapi.vertx.model.AccountRestrictionsPage) Order(io.nem.symbol.sdk.openapi.vertx.model.Order) AccountRestrictions(io.nem.symbol.sdk.model.account.AccountRestrictions) ObjectUtils(org.apache.commons.lang3.ObjectUtils) AccountRestriction(io.nem.symbol.sdk.model.account.AccountRestriction) MerkleStateInfo(io.nem.symbol.sdk.model.blockchain.MerkleStateInfo) Observable(io.reactivex.Observable) AccountRestrictionsInfoDTO(io.nem.symbol.sdk.openapi.vertx.model.AccountRestrictionsInfoDTO) AsyncResult(io.vertx.core.AsyncResult) Address(io.nem.symbol.sdk.model.account.Address) RestrictionAccountRoutesApiImpl(io.nem.symbol.sdk.openapi.vertx.api.RestrictionAccountRoutesApiImpl) Handler(io.vertx.core.Handler) Page(io.nem.symbol.sdk.api.Page) Handler(io.vertx.core.Handler)

Example 78 with AsyncResult

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

the class AbstractVertxRespositoryTest method mockErrorCodeRawResponse.

/**
 * Mocks the api client telling that the next time there is remote call, an error should be
 * returned.
 *
 * @param statusCode the status code of the response (404 for example)
 * @param errorResponse the raw response, it may or may not be a json string.
 */
protected void mockErrorCodeRawResponse(int statusCode, String errorResponse) {
    String reasonPhrase = HttpStatus.valueOf(statusCode).getReasonPhrase();
    VertxHttpHeaders headers = new VertxHttpHeaders();
    ApiException exception = new ApiException(reasonPhrase, statusCode, headers, errorResponse);
    Mockito.doAnswer((Answer<Void>) invocationOnMock -> {
        Handler<AsyncResult<Object>> resultHandler = (Handler<AsyncResult<Object>>) invocationOnMock.getArguments()[invocationOnMock.getArguments().length - 1];
        resultHandler.handle(Future.failedFuture(exception));
        return null;
    }).when(apiClientMock).invokeAPI(Mockito.anyString(), Mockito.anyString(), Mockito.anyList(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any());
}
Also used : NamespaceId(io.nem.symbol.sdk.model.namespace.NamespaceId) BeforeEach(org.junit.jupiter.api.BeforeEach) ApiClient(io.nem.symbol.sdk.openapi.vertx.invoker.ApiClient) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Mosaic(io.nem.symbol.sdk.model.mosaic.Mosaic) HashMap(java.util.HashMap) Future(io.vertx.core.Future) HttpStatus(io.nem.symbol.core.utils.HttpStatus) Mockito(org.mockito.Mockito) Answer(org.mockito.stubbing.Answer) ArgumentCaptor(org.mockito.ArgumentCaptor) VertxHttpHeaders(io.vertx.core.http.impl.headers.VertxHttpHeaders) JsonHelper(io.nem.symbol.sdk.model.transaction.JsonHelper) Map(java.util.Map) Pair(io.nem.symbol.sdk.openapi.vertx.invoker.Pair) Observable(io.reactivex.Observable) BigInteger(java.math.BigInteger) AsyncResult(io.vertx.core.AsyncResult) Address(io.nem.symbol.sdk.model.account.Address) NetworkType(io.nem.symbol.sdk.model.network.NetworkType) ApiException(io.nem.symbol.sdk.openapi.vertx.invoker.ApiException) Handler(io.vertx.core.Handler) Handler(io.vertx.core.Handler) AsyncResult(io.vertx.core.AsyncResult) VertxHttpHeaders(io.vertx.core.http.impl.headers.VertxHttpHeaders) ApiException(io.nem.symbol.sdk.openapi.vertx.invoker.ApiException)

Example 79 with AsyncResult

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

the class Http2ServerTest method testPushPromise.

private void testPushPromise(Http2Headers requestHeaders, BiConsumer<HttpServerResponse, Handler<AsyncResult<HttpServerResponse>>> pusher, Consumer<Http2Headers> headerChecker) throws Exception {
    Context ctx = vertx.getOrCreateContext();
    server.requestHandler(req -> {
        Handler<AsyncResult<HttpServerResponse>> handler = ar -> {
            assertSame(ctx, Vertx.currentContext());
            assertTrue(ar.succeeded());
            HttpServerResponse response = ar.result();
            response.end("the_content");
            assertIllegalStateException(() -> response.push(HttpMethod.GET, "/wibble2", resp -> {
            }));
        };
        pusher.accept(req.response(), handler);
    });
    startServer(ctx);
    TestClient client = new TestClient();
    ChannelFuture fut = client.connect(DEFAULT_HTTPS_PORT, DEFAULT_HTTPS_HOST, request -> {
        int id = request.nextStreamId();
        Http2ConnectionEncoder encoder = request.encoder;
        encoder.writeHeaders(request.context, id, requestHeaders, 0, true, request.context.newPromise());
        Map<Integer, Http2Headers> pushed = new HashMap<>();
        request.decoder.frameListener(new Http2FrameAdapter() {

            @Override
            public void onPushPromiseRead(ChannelHandlerContext ctx, int streamId, int promisedStreamId, Http2Headers headers, int padding) throws Http2Exception {
                pushed.put(promisedStreamId, headers);
            }

            @Override
            public int onDataRead(ChannelHandlerContext ctx, int streamId, ByteBuf data, int padding, boolean endOfStream) throws Http2Exception {
                int delta = super.onDataRead(ctx, streamId, data, padding, endOfStream);
                String content = data.toString(StandardCharsets.UTF_8);
                vertx.runOnContext(v -> {
                    assertEquals(Collections.singleton(streamId), pushed.keySet());
                    assertEquals("the_content", content);
                    Http2Headers pushedHeaders = pushed.get(streamId);
                    headerChecker.accept(pushedHeaders);
                    testComplete();
                });
                return delta;
            }
        });
    });
    fut.sync();
    await();
}
Also used : Context(io.vertx.core.Context) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) Arrays(java.util.Arrays) GZIPInputStream(java.util.zip.GZIPInputStream) HttpServer(io.vertx.core.http.HttpServer) MultiMap(io.vertx.core.MultiMap) Http2ConnectionEncoder(io.netty.handler.codec.http2.Http2ConnectionEncoder) DefaultHttp2Connection(io.netty.handler.codec.http2.DefaultHttp2Connection) Context(io.vertx.core.Context) Unpooled(io.netty.buffer.Unpooled) Http2ConnectionDecoder(io.netty.handler.codec.http2.Http2ConnectionDecoder) ByteArrayInputStream(java.io.ByteArrayInputStream) HttpVersion(io.vertx.core.http.HttpVersion) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Http2Exception(io.netty.handler.codec.http2.Http2Exception) Map(java.util.Map) ApplicationProtocolNegotiationHandler(io.netty.handler.ssl.ApplicationProtocolNegotiationHandler) ReadStream(io.vertx.core.streams.ReadStream) AbstractHttp2ConnectionHandlerBuilder(io.netty.handler.codec.http2.AbstractHttp2ConnectionHandlerBuilder) Http2FrameAdapter(io.netty.handler.codec.http2.Http2FrameAdapter) StreamResetException(io.vertx.core.http.StreamResetException) ChannelDuplexHandler(io.netty.channel.ChannelDuplexHandler) ChannelInitializer(io.netty.channel.ChannelInitializer) Http2Flags(io.netty.handler.codec.http2.Http2Flags) Set(java.util.Set) ChannelPipeline(io.netty.channel.ChannelPipeline) Http2ConnectionHandler(io.netty.handler.codec.http2.Http2ConnectionHandler) Future(io.vertx.core.Future) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) NioEventLoopGroup(io.netty.channel.nio.NioEventLoopGroup) StandardCharsets(java.nio.charset.StandardCharsets) Base64(java.util.Base64) List(java.util.List) Buffer(io.vertx.core.buffer.Buffer) SslHandler(io.netty.handler.ssl.SslHandler) Http2Headers(io.netty.handler.codec.http2.Http2Headers) HttpServerResponse(io.vertx.core.http.HttpServerResponse) Http2Error(io.netty.handler.codec.http2.Http2Error) HttpClient(io.vertx.core.http.HttpClient) NetSocket(io.vertx.core.net.NetSocket) Trust(io.vertx.test.core.tls.Trust) NioSocketChannel(io.netty.channel.socket.nio.NioSocketChannel) HttpServerRequest(io.vertx.core.http.HttpServerRequest) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Http2EventAdapter(io.netty.handler.codec.http2.Http2EventAdapter) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) Function(java.util.function.Function) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) HttpClientRequest(io.vertx.core.http.HttpClientRequest) ByteBuf(io.netty.buffer.ByteBuf) WriteStream(io.vertx.core.streams.WriteStream) Http2Stream(io.netty.handler.codec.http2.Http2Stream) BiConsumer(java.util.function.BiConsumer) AsyncResult(io.vertx.core.AsyncResult) HttpClientOptions(io.vertx.core.http.HttpClientOptions) HttpConnection(io.vertx.core.http.HttpConnection) EventLoopGroup(io.netty.channel.EventLoopGroup) VertxInternal(io.vertx.core.impl.VertxInternal) ClosedChannelException(java.nio.channels.ClosedChannelException) Vertx(io.vertx.core.Vertx) FileOutputStream(java.io.FileOutputStream) ApplicationProtocolNames(io.netty.handler.ssl.ApplicationProtocolNames) Test(org.junit.Test) IOException(java.io.IOException) SSLHelper(io.vertx.core.net.impl.SSLHelper) File(java.io.File) ChannelFuture(io.netty.channel.ChannelFuture) Channel(io.netty.channel.Channel) Http2Settings(io.netty.handler.codec.http2.Http2Settings) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Bootstrap(io.netty.bootstrap.Bootstrap) AtomicLong(java.util.concurrent.atomic.AtomicLong) Http2Connection(io.netty.handler.codec.http2.Http2Connection) HttpMethod(io.vertx.core.http.HttpMethod) HttpUtils(io.vertx.core.http.impl.HttpUtils) HttpServerOptions(io.vertx.core.http.HttpServerOptions) HttpHeaderNames(io.netty.handler.codec.http.HttpHeaderNames) Handler(io.vertx.core.Handler) Collections(java.util.Collections) TestUtils.assertIllegalStateException(io.vertx.test.core.TestUtils.assertIllegalStateException) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) ChannelFuture(io.netty.channel.ChannelFuture) Http2Exception(io.netty.handler.codec.http2.Http2Exception) Http2FrameAdapter(io.netty.handler.codec.http2.Http2FrameAdapter) HashMap(java.util.HashMap) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Http2Headers(io.netty.handler.codec.http2.Http2Headers) DefaultHttp2Headers(io.netty.handler.codec.http2.DefaultHttp2Headers) HttpServerResponse(io.vertx.core.http.HttpServerResponse) Http2ConnectionEncoder(io.netty.handler.codec.http2.Http2ConnectionEncoder) AsyncResult(io.vertx.core.AsyncResult)

Example 80 with AsyncResult

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

the class FutureTest method testDefaultCompleter.

@Test
public void testDefaultCompleter() {
    AsyncResult<Object> succeededAsyncResult = new AsyncResult<Object>() {

        Object result = new Object();

        public Object result() {
            return result;
        }

        public Throwable cause() {
            throw new UnsupportedOperationException();
        }

        public boolean succeeded() {
            return true;
        }

        public boolean failed() {
            throw new UnsupportedOperationException();
        }

        public <U> AsyncResult<U> map(Function<Object, U> mapper) {
            throw new UnsupportedOperationException();
        }

        public <V> AsyncResult<V> map(V value) {
            throw new UnsupportedOperationException();
        }
    };
    AsyncResult<Object> failedAsyncResult = new AsyncResult<Object>() {

        Throwable cause = new Throwable();

        public Object result() {
            throw new UnsupportedOperationException();
        }

        public Throwable cause() {
            return cause;
        }

        public boolean succeeded() {
            return false;
        }

        public boolean failed() {
            throw new UnsupportedOperationException();
        }

        public <U> AsyncResult<U> map(Function<Object, U> mapper) {
            throw new UnsupportedOperationException();
        }

        public <V> AsyncResult<V> map(V value) {
            throw new UnsupportedOperationException();
        }
    };
    class DefaultCompleterTestFuture<T> implements Future<T> {

        boolean succeeded;

        boolean failed;

        T result;

        Throwable cause;

        public boolean isComplete() {
            throw new UnsupportedOperationException();
        }

        public Future<T> setHandler(Handler<AsyncResult<T>> handler) {
            throw new UnsupportedOperationException();
        }

        public void complete(T result) {
            if (!tryComplete(result)) {
                throw new IllegalStateException();
            }
        }

        public void complete() {
            if (!tryComplete()) {
                throw new IllegalStateException();
            }
        }

        public void fail(Throwable cause) {
            if (!tryFail(cause)) {
                throw new IllegalStateException();
            }
        }

        public void fail(String failureMessage) {
            if (!tryFail(failureMessage)) {
                throw new IllegalStateException();
            }
        }

        public boolean tryComplete(T result) {
            if (succeeded || failed) {
                return false;
            }
            succeeded = true;
            this.result = result;
            return true;
        }

        public boolean tryComplete() {
            throw new UnsupportedOperationException();
        }

        public boolean tryFail(Throwable cause) {
            if (succeeded || failed) {
                return false;
            }
            failed = true;
            this.cause = cause;
            return true;
        }

        public boolean tryFail(String failureMessage) {
            throw new UnsupportedOperationException();
        }

        public T result() {
            throw new UnsupportedOperationException();
        }

        public Throwable cause() {
            throw new UnsupportedOperationException();
        }

        public boolean succeeded() {
            throw new UnsupportedOperationException();
        }

        public boolean failed() {
            throw new UnsupportedOperationException();
        }

        public void handle(AsyncResult<T> asyncResult) {
            if (asyncResult.succeeded()) {
                complete(asyncResult.result());
            } else {
                fail(asyncResult.cause());
            }
        }
    }
    DefaultCompleterTestFuture<Object> successFuture = new DefaultCompleterTestFuture<>();
    successFuture.completer().handle(succeededAsyncResult);
    assertTrue(successFuture.succeeded);
    assertEquals(succeededAsyncResult.result(), successFuture.result);
    DefaultCompleterTestFuture<Object> failureFuture = new DefaultCompleterTestFuture<>();
    failureFuture.completer().handle(failedAsyncResult);
    assertTrue(failureFuture.failed);
    assertEquals(failedAsyncResult.cause(), failureFuture.cause);
}
Also used : Handler(io.vertx.core.Handler) BiFunction(java.util.function.BiFunction) Function(java.util.function.Function) NoStackTraceThrowable(io.vertx.core.impl.NoStackTraceThrowable) Future(io.vertx.core.Future) CompositeFuture(io.vertx.core.CompositeFuture) AsyncResult(io.vertx.core.AsyncResult) Test(org.junit.Test)

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