Search in sources :

Example 6 with RouterBuilder

use of io.vertx.ext.web.openapi.RouterBuilder in project vertx-web by vert-x3.

the class OpenAPI3Examples method constructRouterBuilderFromUrlWithAuthenticationHeader.

public void constructRouterBuilderFromUrlWithAuthenticationHeader(Vertx vertx) {
    OpenAPILoaderOptions loaderOptions = new OpenAPILoaderOptions().putAuthHeader("Authorization", "Bearer xx.yy.zz");
    RouterBuilder.create(vertx, "https://raw.githubusercontent" + ".com/OAI/OpenAPI-Specification/master/examples/v3.0/petstore.yaml", loaderOptions).onSuccess(routerBuilder -> {
    // Spec loaded with success
    }).onFailure(err -> {
    // Something went wrong during router builder initialization
    });
}
Also used : OpenIDConnectAuth(io.vertx.ext.auth.oauth2.providers.OpenIDConnectAuth) ValidationHandler(io.vertx.ext.web.validation.ValidationHandler) RequestParameters(io.vertx.ext.web.validation.RequestParameters) HttpServer(io.vertx.core.http.HttpServer) Vertx(io.vertx.core.Vertx) OAuth2Options(io.vertx.ext.auth.oauth2.OAuth2Options) Router(io.vertx.ext.web.Router) BadRequestException(io.vertx.ext.web.validation.BadRequestException) AuthenticationProvider(io.vertx.ext.auth.authentication.AuthenticationProvider) JWTAuthOptions(io.vertx.ext.auth.jwt.JWTAuthOptions) Future(io.vertx.core.Future) OpenAPILoaderOptions(io.vertx.ext.web.openapi.OpenAPILoaderOptions) PubSecKeyOptions(io.vertx.ext.auth.PubSecKeyOptions) io.vertx.ext.web.handler(io.vertx.ext.web.handler) RouterBuilderOptions(io.vertx.ext.web.openapi.RouterBuilderOptions) Source(io.vertx.docgen.Source) HttpServerOptions(io.vertx.core.http.HttpServerOptions) JsonObject(io.vertx.core.json.JsonObject) RequestParameter(io.vertx.ext.web.validation.RequestParameter) RouterBuilder(io.vertx.ext.web.openapi.RouterBuilder) JWTAuth(io.vertx.ext.auth.jwt.JWTAuth) OpenAPILoaderOptions(io.vertx.ext.web.openapi.OpenAPILoaderOptions)

Example 7 with RouterBuilder

use of io.vertx.ext.web.openapi.RouterBuilder in project web3signer by ConsenSys.

the class Runner method run.

@Override
public void run() {
    if (config.getLogLevel() != null) {
        System.out.println("Setting logging level to " + config.getLogLevel().name());
        Configurator.setRootLevel(config.getLogLevel());
    }
    final MetricsEndpoint metricsEndpoint = new MetricsEndpoint(config.isMetricsEnabled(), config.getMetricsPort(), config.getMetricsNetworkInterface(), config.getMetricCategories(), config.getMetricsHostAllowList());
    final MetricsSystem metricsSystem = metricsEndpoint.getMetricsSystem();
    final Vertx vertx = Vertx.vertx(createVertxOptions(metricsSystem));
    final LogErrorHandler errorHandler = new LogErrorHandler();
    final ArtifactSignerProvider artifactSignerProvider = createArtifactSignerProvider(vertx, metricsSystem);
    try {
        metricsEndpoint.start(vertx);
        try {
            // wait for signers to get loaded ...
            artifactSignerProvider.load().get();
        } catch (final InterruptedException | ExecutionException e) {
            LOG.error("Error loading signers", e);
        }
        incSignerLoadCount(metricsSystem, artifactSignerProvider.availableIdentifiers().size());
        final OpenApiSpecsExtractor openApiSpecsExtractor = new OpenApiSpecsExtractor.OpenApiSpecsExtractorBuilder().withConvertRelativeRefToAbsoluteRef(true).withForceDeleteOnJvmExit(true).build();
        final Path openApiSpec = openApiSpecsExtractor.getSpecFilePathAtDestination(getOpenApiSpecResource()).orElseThrow(() -> new RuntimeException("Unable to load OpenApi spec " + getOpenApiSpecResource()));
        // vertx needs a scheme present (file://) to determine this is an absolute path
        final URI openApiSpecUri = openApiSpec.toUri();
        final RouterBuilder routerBuilder = getRouterBuilder(vertx, openApiSpecUri.toString());
        // register access log handler first
        if (config.isAccessLogsEnabled()) {
            routerBuilder.rootHandler(LoggerHandler.create(LoggerFormat.DEFAULT));
        }
        routerBuilder.rootHandler(CorsHandler.create(buildCorsRegexFromConfig()).allowedHeader("*").allowedMethod(HttpMethod.GET).allowedMethod(HttpMethod.POST).allowedMethod(HttpMethod.DELETE).allowedMethod(HttpMethod.OPTIONS));
        registerUpcheckRoute(routerBuilder, errorHandler);
        registerHttpHostAllowListHandler(routerBuilder);
        final Context context = new Context(routerBuilder, metricsSystem, errorHandler, vertx, artifactSignerProvider);
        final Router router = populateRouter(context);
        if (config.isSwaggerUIEnabled()) {
            new SwaggerUIRoute(router).register();
        }
        final HttpServer httpServer = createServerAndWait(vertx, router);
        final String tlsStatus = config.getTlsOptions().isPresent() ? "enabled" : "disabled";
        LOG.info("Web3Signer has started with TLS {}, and ready to handle signing requests on {}:{}", tlsStatus, config.getHttpListenHost(), httpServer.actualPort());
        persistPortInformation(httpServer.actualPort(), metricsEndpoint.getPort());
    } catch (final InitializationException e) {
        throw e;
    } catch (final Throwable e) {
        if (artifactSignerProvider != null) {
            artifactSignerProvider.close();
        }
        vertx.close();
        metricsEndpoint.stop();
        LOG.error("Failed to initialise application", e);
    }
}
Also used : Path(java.nio.file.Path) OpenApiSpecsExtractor(tech.pegasys.web3signer.core.util.OpenApiSpecsExtractor) Router(io.vertx.ext.web.Router) Vertx(io.vertx.core.Vertx) URI(java.net.URI) LogErrorHandler(tech.pegasys.web3signer.core.service.http.handlers.LogErrorHandler) MetricsEndpoint(tech.pegasys.web3signer.core.metrics.MetricsEndpoint) HttpServer(io.vertx.core.http.HttpServer) MetricsSystem(org.hyperledger.besu.plugin.services.MetricsSystem) SwaggerUIRoute(tech.pegasys.web3signer.core.service.http.SwaggerUIRoute) ExecutionException(java.util.concurrent.ExecutionException) RouterBuilder(io.vertx.ext.web.openapi.RouterBuilder) ArtifactSignerProvider(tech.pegasys.web3signer.signing.ArtifactSignerProvider)

Example 8 with RouterBuilder

use of io.vertx.ext.web.openapi.RouterBuilder in project integ-examples by fvaleri.

the class ApiVerticle method start.

@Override
public void start(Promise<Void> startPromise) throws Exception {
    LOG.info("Starting the server");
    // contract-first APIs development (OpenAPI 3)
    RouterBuilder.create(this.vertx, "petstore.yaml").onSuccess(routerBuilder -> {
        // maps the OpenAPI endpoint definitions to the service implementation we create
        // HTTP request validation is handled automatically
        addGetPetsHandler(routerBuilder);
        addPostPetHandler(routerBuilder);
        addGetPetHandler(routerBuilder);
        Router router = routerBuilder.createRouter();
        addErrorHandler(router, 404, "Not Found");
        addErrorHandler(router, 400, "Invalid Request");
        // generate the certificate for HTTPS
        SelfSignedCertificate cert = SelfSignedCertificate.create();
        // start the HTTP/2 server with the OpenAPI router
        this.server = vertx.createHttpServer(new HttpServerOptions().setSsl(true).setUseAlpn(true).setKeyCertOptions(cert.keyCertOptions()).setPort(PORT));
        LOG.info("Server listening on port {}", PORT);
        server.requestHandler(router).listen();
        startPromise.complete();
    }).onFailure(startPromise::fail);
}
Also used : Arrays(java.util.Arrays) Logger(org.slf4j.Logger) RequestParameters(io.vertx.ext.web.validation.RequestParameters) Promise(io.vertx.core.Promise) HttpServer(io.vertx.core.http.HttpServer) LoggerFactory(org.slf4j.LoggerFactory) HttpHeaders(io.vertx.core.http.HttpHeaders) Router(io.vertx.ext.web.Router) SelfSignedCertificate(io.vertx.core.net.SelfSignedCertificate) ArrayList(java.util.ArrayList) JsonArray(io.vertx.core.json.JsonArray) List(java.util.List) AbstractVerticle(io.vertx.core.AbstractVerticle) Optional(java.util.Optional) HttpServerOptions(io.vertx.core.http.HttpServerOptions) JsonObject(io.vertx.core.json.JsonObject) RouterBuilder(io.vertx.ext.web.openapi.RouterBuilder) SelfSignedCertificate(io.vertx.core.net.SelfSignedCertificate) HttpServerOptions(io.vertx.core.http.HttpServerOptions) Router(io.vertx.ext.web.Router)

Example 9 with RouterBuilder

use of io.vertx.ext.web.openapi.RouterBuilder in project integ-examples by fvaleri.

the class ApiVerticle method addGetPetHandler.

private void addGetPetHandler(RouterBuilder routerBuilder) {
    final String operationId = "showPetById";
    routerBuilder.operation(operationId).handler(routingContext -> {
        LOG.debug("Processing {} request from {}", operationId, routingContext.request().remoteAddress());
        RequestParameters params = routingContext.get("parsedParameters");
        Integer id = params.pathParameter("petId").getInteger();
        Optional<JsonObject> pet = getAllPets().stream().filter(p -> p.getInteger("id").equals(id)).findFirst();
        if (pet.isPresent()) {
            routingContext.response().setStatusCode(200).putHeader(HttpHeaders.CONTENT_TYPE, "application/json").end(pet.get().encode());
        } else {
            routingContext.fail(404, new Exception("Pet not found"));
        }
    });
}
Also used : Arrays(java.util.Arrays) Logger(org.slf4j.Logger) RequestParameters(io.vertx.ext.web.validation.RequestParameters) Promise(io.vertx.core.Promise) HttpServer(io.vertx.core.http.HttpServer) LoggerFactory(org.slf4j.LoggerFactory) HttpHeaders(io.vertx.core.http.HttpHeaders) Router(io.vertx.ext.web.Router) SelfSignedCertificate(io.vertx.core.net.SelfSignedCertificate) ArrayList(java.util.ArrayList) JsonArray(io.vertx.core.json.JsonArray) List(java.util.List) AbstractVerticle(io.vertx.core.AbstractVerticle) Optional(java.util.Optional) HttpServerOptions(io.vertx.core.http.HttpServerOptions) JsonObject(io.vertx.core.json.JsonObject) RouterBuilder(io.vertx.ext.web.openapi.RouterBuilder) JsonObject(io.vertx.core.json.JsonObject) RequestParameters(io.vertx.ext.web.validation.RequestParameters)

Aggregations

RouterBuilder (io.vertx.ext.web.openapi.RouterBuilder)9 Router (io.vertx.ext.web.Router)6 JsonObject (io.vertx.core.json.JsonObject)5 HttpServer (io.vertx.core.http.HttpServer)4 RequestParameters (io.vertx.ext.web.validation.RequestParameters)4 AbstractVerticle (io.vertx.core.AbstractVerticle)3 Future (io.vertx.core.Future)3 Promise (io.vertx.core.Promise)3 Vertx (io.vertx.core.Vertx)3 HttpServerOptions (io.vertx.core.http.HttpServerOptions)3 JsonArray (io.vertx.core.json.JsonArray)3 ArrayList (java.util.ArrayList)3 Arrays (java.util.Arrays)3 List (java.util.List)3 HttpHeaders (io.vertx.core.http.HttpHeaders)2 SelfSignedCertificate (io.vertx.core.net.SelfSignedCertificate)2 ValidationHandler (io.vertx.ext.web.validation.ValidationHandler)2 Path (java.nio.file.Path)2 Optional (java.util.Optional)2 Logger (org.slf4j.Logger)2