Search in sources :

Example 66 with Promise

use of io.vertx.core.Promise in project vertx-examples by vert-x3.

the class Server method start.

@Override
public void start() throws Exception {
    // The rcp service
    PingPongServiceGrpc.PingPongServiceVertxImplBase service = new PingPongServiceGrpc.PingPongServiceVertxImplBase() {

        @Override
        public void unaryCall(Messages.SimpleRequest request, Promise<Messages.SimpleResponse> future) {
            future.complete(Messages.SimpleResponse.newBuilder().setUsername("Paulo").build());
        }
    };
    // Create the server
    VertxServer rpcServer = VertxServerBuilder.forPort(vertx, 8080).addService(service).build();
    // start the server
    rpcServer.start(ar -> {
        if (ar.failed()) {
            ar.cause().printStackTrace();
        }
    });
}
Also used : Promise(io.vertx.core.Promise) Messages(io.vertx.example.grpc.Messages) VertxServer(io.vertx.grpc.VertxServer) PingPongServiceGrpc(io.vertx.example.grpc.PingPongServiceGrpc)

Example 67 with Promise

use of io.vertx.core.Promise in project vertx-examples by vert-x3.

the class Server method start.

@Override
public void start() throws Exception {
    URL featureFile = Util.getDefaultFeaturesFile();
    features = Util.parseFeatures(featureFile);
    VertxServer server = VertxServerBuilder.forAddress(vertx, "localhost", 8080).addService(new RouteGuideGrpc.RouteGuideVertxImplBase() {

        @Override
        public void getFeature(Point request, Promise<Feature> response) {
            response.complete(checkFeature(request));
        }

        @Override
        public void listFeatures(Rectangle request, GrpcWriteStream<Feature> response) {
            int left = Math.min(request.getLo().getLongitude(), request.getHi().getLongitude());
            int right = Math.max(request.getLo().getLongitude(), request.getHi().getLongitude());
            int top = Math.max(request.getLo().getLatitude(), request.getHi().getLatitude());
            int bottom = Math.min(request.getLo().getLatitude(), request.getHi().getLatitude());
            for (Feature feature : features) {
                if (!Util.exists(feature)) {
                    continue;
                }
                int lat = feature.getLocation().getLatitude();
                int lon = feature.getLocation().getLongitude();
                if (lon >= left && lon <= right && lat >= bottom && lat <= top) {
                    response.write(feature);
                }
            }
            response.end();
        }

        @Override
        public void recordRoute(GrpcReadStream<Point> request, Future<RouteSummary> response) {
            request.exceptionHandler(err -> {
                System.out.println("recordRoute cancelled");
            });
            RouteRecorder recorder = new RouteRecorder();
            request.handler(recorder::append);
            request.endHandler(v -> {
                response.complete(recorder.build());
            });
        }

        @Override
        public void routeChat(GrpcBidiExchange<RouteNote, RouteNote> exchange) {
            exchange.handler(note -> {
                List<RouteNote> notes = getOrCreateNotes(note.getLocation());
                // Respond with all previous notes at this location.
                for (RouteNote prevNote : notes.toArray(new RouteNote[0])) {
                    exchange.write(prevNote);
                }
                // Now add the new note to the list
                notes.add(note);
            });
            exchange.exceptionHandler(err -> {
                System.out.println("routeChat cancelled");
            });
            exchange.endHandler(v -> exchange.end());
        }
    }).build();
    server.start(ar -> {
        if (ar.succeeded()) {
            System.out.println("gRPC service started");
        } else {
            System.out.println("Could not start server " + ar.cause().getMessage());
        }
    });
}
Also used : GrpcBidiExchange(io.vertx.grpc.GrpcBidiExchange) VertxServer(io.vertx.grpc.VertxServer) Rectangle(io.grpc.examples.routeguide.Rectangle) Point(io.grpc.examples.routeguide.Point) Feature(io.grpc.examples.routeguide.Feature) URL(java.net.URL) Point(io.grpc.examples.routeguide.Point) Promise(io.vertx.core.Promise) GrpcReadStream(io.vertx.grpc.GrpcReadStream) RouteNote(io.grpc.examples.routeguide.RouteNote) Future(io.vertx.core.Future) GrpcWriteStream(io.vertx.grpc.GrpcWriteStream)

Example 68 with Promise

use of io.vertx.core.Promise in project raml-module-builder by folio-org.

the class PostgresClientIT method selectReturnOneRow.

@Test
public void selectReturnOneRow(TestContext context) {
    List<String> columns = new LinkedList<>();
    columns.add("field");
    RowDesc rowDesc = new RowDesc(columns);
    List<Row> rows = new LinkedList<>();
    Row row = new RowImpl(rowDesc);
    row.addString("value");
    rows.add(row);
    RowSet rowSet = new LocalRowSet(1).withColumns(columns).withRows(rows);
    Promise<RowSet<Row>> promise = Promise.promise();
    promise.complete(rowSet);
    PostgresClient.selectReturn(promise.future(), context.asyncAssertSuccess(res -> context.assertEquals("value", res.getString(0))));
}
Also used : CoreMatchers.is(org.hamcrest.CoreMatchers.is) TestContext(io.vertx.ext.unit.TestContext) RowStream(io.vertx.sqlclient.RowStream) Arrays(java.util.Arrays) PgNotification(io.vertx.pgclient.PgNotification) TransactionRollbackException(io.vertx.sqlclient.TransactionRollbackException) VertxUtils(org.folio.rest.tools.utils.VertxUtils) Tuple(io.vertx.sqlclient.Tuple) UpdateSection(org.folio.rest.persist.Criteria.UpdateSection) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) RowIterator(io.vertx.sqlclient.RowIterator) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SqlResult(io.vertx.sqlclient.SqlResult) After(org.junit.After) JsonObject(io.vertx.core.json.JsonObject) Offset(org.folio.rest.persist.Criteria.Offset) Collector(java.util.stream.Collector) Transaction(io.vertx.sqlclient.Transaction) AfterClass(org.junit.AfterClass) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) RowImpl(io.vertx.pgclient.impl.RowImpl) Set(java.util.Set) UUID(java.util.UUID) FieldException(org.folio.cql2pgjson.exception.FieldException) Future(io.vertx.core.Future) StandardCharsets(java.nio.charset.StandardCharsets) UncheckedIOException(java.io.UncheckedIOException) IOUtils(org.apache.commons.io.IOUtils) CQL2PgJSON(org.folio.cql2pgjson.CQL2PgJSON) Base64(java.util.Base64) List(java.util.List) Stream(java.util.stream.Stream) Criterion(org.folio.rest.persist.Criteria.Criterion) Results(org.folio.rest.persist.interfaces.Results) Facet(org.folio.rest.jaxrs.model.Facet) RowDesc(io.vertx.sqlclient.impl.RowDesc) Async(io.vertx.ext.unit.Async) CQLWrapper(org.folio.rest.persist.cql.CQLWrapper) BeforeClass(org.junit.BeforeClass) FacetField(org.folio.rest.persist.facets.FacetField) PostgresTesterContainer(org.folio.postgres.testing.PostgresTesterContainer) Criteria(org.folio.rest.persist.Criteria.Criteria) CoreMatchers.not(org.hamcrest.CoreMatchers.not) RunWith(org.junit.runner.RunWith) Timeout(io.vertx.ext.unit.junit.Timeout) ResultInfo(org.folio.rest.jaxrs.model.ResultInfo) Function(java.util.function.Function) TotaledResults(org.folio.rest.persist.PostgresClient.TotaledResults) ArrayList(java.util.ArrayList) PreparedStatement(io.vertx.sqlclient.PreparedStatement) HashSet(java.util.HashSet) CompositeFuture(io.vertx.core.CompositeFuture) Poline(org.folio.rest.persist.helpers.Poline) PrepareOptions(io.vertx.sqlclient.PrepareOptions) SqlConnection(io.vertx.sqlclient.SqlConnection) Limit(org.folio.rest.persist.Criteria.Limit) QueryHelper(org.folio.rest.persist.PostgresClient.QueryHelper) RowSet(io.vertx.sqlclient.RowSet) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) AsyncResult(io.vertx.core.AsyncResult) LinkedList(java.util.LinkedList) DatabaseMetadata(io.vertx.sqlclient.spi.DatabaseMetadata) CoreMatchers.nullValue(org.hamcrest.CoreMatchers.nullValue) Before(org.junit.Before) Files(java.nio.file.Files) Query(io.vertx.sqlclient.Query) Promise(io.vertx.core.Promise) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Vertx(io.vertx.core.Vertx) PgPool(io.vertx.pgclient.PgPool) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) Test(org.junit.Test) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) PreparedQuery(io.vertx.sqlclient.PreparedQuery) JsonArray(io.vertx.core.json.JsonArray) PgConnection(io.vertx.pgclient.PgConnection) Rule(org.junit.Rule) Paths(java.nio.file.Paths) Row(io.vertx.sqlclient.Row) LocalRowSet(org.folio.rest.persist.helpers.LocalRowSet) Handler(io.vertx.core.Handler) SimplePojo(org.folio.rest.persist.helpers.SimplePojo) Collections(java.util.Collections) InputStream(java.io.InputStream) RowImpl(io.vertx.pgclient.impl.RowImpl) LocalRowSet(org.folio.rest.persist.helpers.LocalRowSet) RowSet(io.vertx.sqlclient.RowSet) LocalRowSet(org.folio.rest.persist.helpers.LocalRowSet) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) Row(io.vertx.sqlclient.Row) RowDesc(io.vertx.sqlclient.impl.RowDesc) LinkedList(java.util.LinkedList) Test(org.junit.Test)

Example 69 with Promise

use of io.vertx.core.Promise in project raml-module-builder by folio-org.

the class RestVerticle method start.

@Override
public void start(Promise<Void> startPromise) throws Exception {
    readInGitProps();
    // process cmd line arguments
    cmdProcessing(processArgs());
    deploymentId = UUID.randomUUID().toString();
    log.info("metrics enabled: {}", vertx.isMetricsEnabled());
    packageOfImplementations = config().getString("packageOfImplementations", DomainModelConsts.PACKAGE_OF_IMPLEMENTATIONS);
    // Create a router object.
    Router router = Router.router(vertx);
    // single handler for all url calls other then documentation
    // which is handled separately
    // router.routeWithRegex("^(?!.*apidocs).*$").handler(rc -> route(mappedURLs, urlPaths, regex2Pattern, rc));
    // routes requests on “/assets/*” to resources stored in the “assets”
    // directory.
    router.route("/assets/*").handler(StaticHandler.create("assets"));
    // In the following example all requests to paths starting with
    // /apidocs/ will get served from the directory resources/apidocs:
    // example:
    // http://localhost:8181/apidocs/index.html?raml=raml/_patrons.raml
    router.route("/apidocs/*").handler(StaticHandler.create("apidocs"));
    RestRouting.populateRoutes(router, packageOfImplementations).compose(x -> runHook()).compose(x -> {
        HttpServer server = vertx.createHttpServer(httpServerOptions);
        String portS = System.getProperty(HTTP_PORT_SETTING);
        int port;
        if (portS != null) {
            port = Integer.parseInt(portS);
            config().put(HTTP_PORT_SETTING, port);
        } else {
            // we are here if port was not passed via cmd line
            port = config().getInteger(HTTP_PORT_SETTING, 8081);
        }
        log.info("Listening port {}", port);
        return server.requestHandler(router).listen(port);
    }).<Void>compose(ret -> {
        try {
            // startup periodic impl if exists
            runPeriodicHook();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Future.failedFuture(e);
        }
        // check if mock mode requested and set sys param so that http client factory
        // can config itself accordingly
        String mockMode = config().getString(HttpClientMock2.MOCK_MODE);
        if (mockMode != null) {
            System.setProperty(HttpClientMock2.MOCK_MODE, mockMode);
            HttpClientFactory.setMockEnabled(true);
        }
        runPostDeployHook(res2 -> {
            if (!res2.succeeded()) {
                log.error(res2.cause().getMessage(), res2.cause());
            }
        });
        return Future.succeededFuture();
    }).onFailure(cause -> log.error(cause.getMessage(), cause)).onComplete(startPromise);
}
Also used : XOkapiHeaders(org.folio.okapi.common.XOkapiHeaders) HttpServer(io.vertx.core.http.HttpServer) Router(io.vertx.ext.web.Router) HashMap(java.util.HashMap) Context(io.vertx.core.Context) ArrayList(java.util.ArrayList) LogUtil(org.folio.rest.tools.utils.LogUtil) Map(java.util.Map) AsyncResult(io.vertx.core.AsyncResult) Method(java.lang.reflect.Method) Properties(java.util.Properties) StaticHandler(io.vertx.ext.web.handler.StaticHandler) Promise(io.vertx.core.Promise) Vertx(io.vertx.core.Vertx) IOException(java.io.IOException) UUID(java.util.UUID) Future(io.vertx.core.Future) PostgresClient(org.folio.rest.persist.PostgresClient) HttpClientFactory(org.folio.rest.tools.client.HttpClientFactory) HttpClientMock2(org.folio.rest.tools.client.test.HttpClientMock2) List(java.util.List) InterfaceToImpl(org.folio.rest.tools.utils.InterfaceToImpl) Logger(org.apache.logging.log4j.Logger) AbstractVerticle(io.vertx.core.AbstractVerticle) HttpServerOptions(io.vertx.core.http.HttpServerOptions) DomainModelConsts(org.folio.rest.resource.DomainModelConsts) Handler(io.vertx.core.Handler) LogManager(org.apache.logging.log4j.LogManager) InputStream(java.io.InputStream) HttpServer(io.vertx.core.http.HttpServer) Router(io.vertx.ext.web.Router) IOException(java.io.IOException)

Example 70 with Promise

use of io.vertx.core.Promise in project chili-core by codingchili.

the class BenchmarkIT method testBenchmarkBuilders.

@Test
public void testBenchmarkBuilders(TestContext test) {
    Async async = test.async();
    List<BenchmarkGroup> groups = new ArrayList<>();
    BiConsumer<BenchmarkGroup, String> addOneOperation = (group, implementation) -> {
        group.implementation(implementation).add("sleep1x", Promise::complete).add("sleep2x", Promise::complete);
    };
    BiConsumer<String, Integer> addOneGroup = (name, iterations) -> {
        BenchmarkGroup group = new BenchmarkGroupBuilder(name, iterations);
        addOneOperation.accept(group, "fastImplementation");
        addOneOperation.accept(group, "slowImplementation");
        groups.add(group);
    };
    addOneGroup.accept("group_1", ITERATIONS);
    addOneGroup.accept("group_2", ITERATIONS);
    addOneGroup.accept("group_3", ITERATIONS);
    new BenchmarkExecutor(context).start(groups).onComplete(done -> {
        new BenchmarkHTMLReport(done.result()).saveTo("wowza.html");
        async.complete();
    });
}
Also used : TestContext(io.vertx.ext.unit.TestContext) Async(io.vertx.ext.unit.Async) BenchmarkHTMLReport(com.codingchili.core.benchmarking.reporting.BenchmarkHTMLReport) PARAM_ITERATIONS(com.codingchili.core.configuration.CoreStrings.PARAM_ITERATIONS) Promise(io.vertx.core.Promise) RunWith(org.junit.runner.RunWith) Timeout(io.vertx.ext.unit.junit.Timeout) VertxUnitRunner(io.vertx.ext.unit.junit.VertxUnitRunner) ArrayList(java.util.ArrayList) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) com.codingchili.core.context(com.codingchili.core.context) BiConsumer(java.util.function.BiConsumer) org.junit(org.junit) ArrayList(java.util.ArrayList) Promise(io.vertx.core.Promise) BenchmarkHTMLReport(com.codingchili.core.benchmarking.reporting.BenchmarkHTMLReport) Async(io.vertx.ext.unit.Async)

Aggregations

Promise (io.vertx.core.Promise)155 Future (io.vertx.core.Future)122 Handler (io.vertx.core.Handler)95 List (java.util.List)86 Vertx (io.vertx.core.Vertx)85 Buffer (io.vertx.core.buffer.Buffer)83 TimeUnit (java.util.concurrent.TimeUnit)79 HttpURLConnection (java.net.HttpURLConnection)66 Logger (org.slf4j.Logger)63 LoggerFactory (org.slf4j.LoggerFactory)63 Optional (java.util.Optional)62 AsyncResult (io.vertx.core.AsyncResult)61 Truth.assertThat (com.google.common.truth.Truth.assertThat)60 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)60 VertxTestContext (io.vertx.junit5.VertxTestContext)59 Test (org.junit.jupiter.api.Test)58 Map (java.util.Map)54 UUID (java.util.UUID)52 ArrayList (java.util.ArrayList)51 JsonObject (io.vertx.core.json.JsonObject)50