Search in sources :

Example 1 with OpenApiPlugin

use of io.javalin.plugin.openapi.OpenApiPlugin in project cwms-radar-api by USACE.

the class ApiServlet method init.

@Override
public void init() throws ServletException {
    String context = this.getServletContext().getContextPath();
    PolicyFactory sanitizer = new HtmlPolicyBuilder().disallowElements("<script>").toFactory();
    ObjectMapper om = new ObjectMapper();
    JavalinValidation.register(UnitSystem.class, UnitSystem::systemFor);
    om.setPropertyNamingStrategy(PropertyNamingStrategies.KEBAB_CASE);
    // Needed in Java 8 to properly format java.time classes
    om.registerModule(new JavaTimeModule());
    AccessManager accessManager = buildAccessManager();
    javalin = Javalin.createStandalone(config -> {
        config.defaultContentType = "application/json";
        config.contextPath = context;
        config.registerPlugin(new OpenApiPlugin(getOpenApiOptions()));
        config.enableDevLogging();
        config.requestLogger((ctx, ms) -> logger.finest(ctx.toString()));
        config.accessManager(accessManager);
    }).attribute("PolicyFactory", sanitizer).attribute("ObjectMapper", om).before(ctx -> {
        ctx.attribute("sanitizer", sanitizer);
        ctx.header("X-Content-Type-Options", "nosniff");
        ctx.header("X-Frame-Options", "SAMEORIGIN");
        ctx.header("X-XSS-Protection", "1; mode=block");
    }).exception(FormattingException.class, (fe, ctx) -> {
        final RadarError re = new RadarError("Formatting error");
        if (fe.getCause() instanceof IOException) {
            ctx.status(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } else {
            ctx.status(HttpServletResponse.SC_NOT_IMPLEMENTED);
        }
        logger.log(Level.SEVERE, fe, () -> re + "for request: " + ctx.fullUrl());
        ctx.json(re);
    }).exception(UnsupportedOperationException.class, (e, ctx) -> {
        final RadarError re = RadarError.notImplemented();
        logger.log(Level.WARNING, e, () -> re + "for request: " + ctx.fullUrl());
        ctx.status(HttpServletResponse.SC_NOT_IMPLEMENTED).json(re);
    }).exception(BadRequestResponse.class, (e, ctx) -> {
        RadarError re = new RadarError("Bad Request", e.getDetails());
        logger.log(Level.INFO, re.toString(), e);
        ctx.status(e.getStatus()).json(re);
    }).exception(IllegalArgumentException.class, (e, ctx) -> {
        RadarError re = new RadarError("Bad Request");
        logger.log(Level.INFO, re.toString(), e);
        ctx.status(HttpServletResponse.SC_BAD_REQUEST).json(re);
    }).exception(NotFoundException.class, (e, ctx) -> {
        RadarError re = new RadarError("Not Found.");
        logger.log(Level.INFO, re.toString(), e);
        ctx.status(HttpServletResponse.SC_NOT_FOUND).json(re);
    }).exception(FieldException.class, (e, ctx) -> {
        RadarError re = new RadarError(e.getMessage(), e.getDetails(), true);
        ctx.status(HttpServletResponse.SC_BAD_REQUEST).json(re);
    }).exception(JsonFieldsException.class, (e, ctx) -> {
        RadarError re = new RadarError(e.getMessage(), e.getDetails(), true);
        ctx.status(HttpServletResponse.SC_BAD_REQUEST).json(re);
    }).exception(Exception.class, (e, ctx) -> {
        RadarError errResponse = new RadarError("System Error");
        logger.log(Level.WARNING, String.format("error on request[%s]: %s", errResponse.getIncidentIdentifier(), ctx.req.getRequestURI()), e);
        ctx.status(500);
        ctx.contentType(ContentType.APPLICATION_JSON.toString());
        ctx.json(errResponse);
    }).routes(this::configureRoutes).javalinServlet();
}
Also used : AccessManager(io.javalin.core.security.AccessManager) CwmsAccessManager(cwms.radar.security.CwmsAccessManager) PoolController(cwms.radar.api.PoolController) Arrays(java.util.Arrays) Connection(java.sql.Connection) UnitSystem(cwms.radar.api.enums.UnitSystem) AccessManager(io.javalin.core.security.AccessManager) ServletException(javax.servlet.ServletException) CwmsAccessManager(cwms.radar.security.CwmsAccessManager) Javalin(io.javalin.Javalin) RatingController(cwms.radar.api.RatingController) LocationController(cwms.radar.api.LocationController) ApiBuilder.prefixPath(io.javalin.apibuilder.ApiBuilder.prefixPath) NotFoundException(cwms.radar.api.NotFoundException) RouteRole(io.javalin.core.security.RouteRole) ApiBuilder.crud(io.javalin.apibuilder.ApiBuilder.crud) JavaTimeModule(com.fasterxml.jackson.datatype.jsr310.JavaTimeModule) BadRequestResponse(io.javalin.http.BadRequestResponse) Map(java.util.Map) PrintWriter(java.io.PrintWriter) RequiredFieldException(cwms.radar.api.errors.RequiredFieldException) OpenApiPlugin(io.javalin.plugin.openapi.OpenApiPlugin) ServletConfig(javax.servlet.ServletConfig) HttpServlet(javax.servlet.http.HttpServlet) ClobController(cwms.radar.api.ClobController) CrudHandlerKt(io.javalin.apibuilder.CrudHandlerKt) Resource(javax.annotation.Resource) JavalinServlet(io.javalin.http.JavalinServlet) ContentType(org.apache.http.entity.ContentType) TimeSeriesCategoryController(cwms.radar.api.TimeSeriesCategoryController) CrudFunction(io.javalin.apibuilder.CrudFunction) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) Handler(io.javalin.http.Handler) LocationCategoryController(cwms.radar.api.LocationCategoryController) FieldException(cwms.radar.api.errors.FieldException) FormattingException(cwms.radar.formatters.FormattingException) TimeZoneController(cwms.radar.api.TimeZoneController) Role(cwms.radar.security.Role) PolicyFactory(org.owasp.html.PolicyFactory) BlobController(cwms.radar.api.BlobController) Formats(cwms.radar.formatters.Formats) ApiBuilder.get(io.javalin.apibuilder.ApiBuilder.get) NotNull(org.jetbrains.annotations.NotNull) TimeSeriesController(cwms.radar.api.TimeSeriesController) ExclusiveFieldsException(cwms.radar.api.errors.ExclusiveFieldsException) ApiBuilder.staticInstance(io.javalin.apibuilder.ApiBuilder.staticInstance) MismatchedInputException(com.fasterxml.jackson.databind.exc.MismatchedInputException) CrudHandler(io.javalin.apibuilder.CrudHandler) JavalinValidation(io.javalin.core.validation.JavalinValidation) HtmlPolicyBuilder(org.owasp.html.HtmlPolicyBuilder) OpenApiOptions(io.javalin.plugin.openapi.OpenApiOptions) Level(java.util.logging.Level) PropertyNamingStrategies(com.fasterxml.jackson.databind.PropertyNamingStrategies) LevelsController(cwms.radar.api.LevelsController) UnitsController(cwms.radar.api.UnitsController) Meter(com.codahale.metrics.Meter) SQLException(java.sql.SQLException) HttpServletRequest(javax.servlet.http.HttpServletRequest) TimeSeriesGroupController(cwms.radar.api.TimeSeriesGroupController) DataSource(javax.sql.DataSource) ParametersController(cwms.radar.api.ParametersController) BasinController(cwms.radar.api.BasinController) CatalogController(cwms.radar.api.CatalogController) MetricRegistry(com.codahale.metrics.MetricRegistry) OfficeController(cwms.radar.api.OfficeController) HttpServletResponse(javax.servlet.http.HttpServletResponse) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Info(io.swagger.v3.oas.models.info.Info) IOException(java.io.IOException) RadarError(cwms.radar.api.errors.RadarError) LocationGroupController(cwms.radar.api.LocationGroupController) WebServlet(javax.servlet.annotation.WebServlet) MetricsServlet(com.codahale.metrics.servlets.MetricsServlet) JsonFieldsException(cwms.radar.api.errors.JsonFieldsException) PolicyFactory(org.owasp.html.PolicyFactory) JavaTimeModule(com.fasterxml.jackson.datatype.jsr310.JavaTimeModule) UnitSystem(cwms.radar.api.enums.UnitSystem) IOException(java.io.IOException) OpenApiPlugin(io.javalin.plugin.openapi.OpenApiPlugin) ServletException(javax.servlet.ServletException) NotFoundException(cwms.radar.api.NotFoundException) RequiredFieldException(cwms.radar.api.errors.RequiredFieldException) FieldException(cwms.radar.api.errors.FieldException) FormattingException(cwms.radar.formatters.FormattingException) ExclusiveFieldsException(cwms.radar.api.errors.ExclusiveFieldsException) MismatchedInputException(com.fasterxml.jackson.databind.exc.MismatchedInputException) SQLException(java.sql.SQLException) IOException(java.io.IOException) JsonFieldsException(cwms.radar.api.errors.JsonFieldsException) HtmlPolicyBuilder(org.owasp.html.HtmlPolicyBuilder) RadarError(cwms.radar.api.errors.RadarError) RequiredFieldException(cwms.radar.api.errors.RequiredFieldException) FieldException(cwms.radar.api.errors.FieldException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 2 with OpenApiPlugin

use of io.javalin.plugin.openapi.OpenApiPlugin in project javalin by tipsy.

the class ExampleController method main.

public static void main(String[] args) {
    ObjectMapper objectMapper = new ObjectMapper().setSerializationInclusion(JsonInclude.Include.NON_NULL);
    OpenApiOptions openApiOptions = new OpenApiOptions(new Info().version("1.0").description("My Application")).activateAnnotationScanningFor("io.javalin.examples").path("/swagger-docs").swagger(new SwaggerOptions("/swagger").title("My Swagger Documentation")).reDoc(new ReDocOptions("/redoc", new RedocOptionsObject.Builder().setHideDownloadButton(true).setTheme(new RedocOptionsTheme.Builder().setSpacingUnit(10).setTypographyOptimizeSpeed(true).build()).build()).title("My ReDoc Documentation"));
    Javalin app = Javalin.create(config -> {
        config.registerPlugin(new OpenApiPlugin(openApiOptions));
        config.jsonMapper(new JavalinJackson(objectMapper));
    }).start(7070);
    app.post("/users", ExampleController::create);
}
Also used : Javalin(io.javalin.Javalin) HttpMethod(io.javalin.plugin.openapi.annotations.HttpMethod) OpenApiPlugin(io.javalin.plugin.openapi.OpenApiPlugin) ReDocOptions(io.javalin.plugin.openapi.ui.ReDocOptions) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) RedocOptionsObject(io.javalin.plugin.openapi.ui.RedocOptionsObject) Info(io.swagger.v3.oas.models.info.Info) OpenApiContent(io.javalin.plugin.openapi.annotations.OpenApiContent) Javalin(io.javalin.Javalin) OpenApiOptions(io.javalin.plugin.openapi.OpenApiOptions) JavalinJackson(io.javalin.plugin.json.JavalinJackson) RedocOptionsTheme(io.javalin.plugin.openapi.ui.RedocOptionsTheme) OpenApiParam(io.javalin.plugin.openapi.annotations.OpenApiParam) Context(io.javalin.http.Context) OpenApiResponse(io.javalin.plugin.openapi.annotations.OpenApiResponse) JsonInclude(com.fasterxml.jackson.annotation.JsonInclude) SwaggerOptions(io.javalin.plugin.openapi.ui.SwaggerOptions) OpenApi(io.javalin.plugin.openapi.annotations.OpenApi) OpenApiOptions(io.javalin.plugin.openapi.OpenApiOptions) SwaggerOptions(io.javalin.plugin.openapi.ui.SwaggerOptions) JavalinJackson(io.javalin.plugin.json.JavalinJackson) ReDocOptions(io.javalin.plugin.openapi.ui.ReDocOptions) Info(io.swagger.v3.oas.models.info.Info) OpenApiPlugin(io.javalin.plugin.openapi.OpenApiPlugin) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 3 with OpenApiPlugin

use of io.javalin.plugin.openapi.OpenApiPlugin in project Jexxa by repplix.

the class OpenAPIConvention method initOpenAPI.

private void initOpenAPI() {
    if (properties.containsKey(JEXXA_REST_OPEN_API_PATH)) {
        var applicationInfo = new Info().version(properties.getProperty(JEXXA_CONTEXT_VERSION, "1.0")).description("Auto generated OpenAPI for " + properties.getProperty(JEXXA_CONTEXT_NAME, "Unknown Context")).title(properties.getProperty(JEXXA_CONTEXT_NAME, "Unknown Context"));
        openApiOptions = new OpenApiOptions(applicationInfo).path("/" + properties.getProperty(JEXXA_REST_OPEN_API_PATH));
        // Show all fields of an ValueObject
        openApiOptions.getJacksonMapper().setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
        javalinConfig.registerPlugin(new OpenApiPlugin(openApiOptions));
        javalinConfig.enableCorsForAllOrigins();
        openApiOptions.defaultDocumentation(doc -> {
            doc.json(String.valueOf(HTTP_BAD_REQUEST), BadRequestResponse.class);
            doc.json(String.valueOf(HTTP_BAD_REQUEST), BadRequestResponse.class);
        });
    }
}
Also used : OpenApiOptions(io.javalin.plugin.openapi.OpenApiOptions) Info(io.swagger.v3.oas.models.info.Info) OpenApiPlugin(io.javalin.plugin.openapi.OpenApiPlugin)

Example 4 with OpenApiPlugin

use of io.javalin.plugin.openapi.OpenApiPlugin in project cineast by vitrivr.

the class APIEndpoint method dispatchService.

/**
 * Dispatches a new Jetty {@link Javalin} (HTTP endpoint). The method takes care of all the necessary setup.
 *
 * @param secure If true, the new Service will be setup as secure with TLS enabled.
 * @return {@link Javalin}
 */
public Javalin dispatchService(boolean secure) {
    final APIConfig config = Config.sharedConfig().getApi();
    final int port = this.validateAndNormalizePort(secure, config);
    final Javalin service = Javalin.create(serviceConfig -> {
        /* Default return mime */
        serviceConfig.defaultContentType = "application/json";
        /* Prefer 405 over 404 to not expose information */
        serviceConfig.prefer405over404 = true;
        /* Configure server (TLS, thread pool, etc.) */
        serviceConfig.enableCorsForAllOrigins();
        /* Configuration of the actual server */
        serviceConfig.server(() -> {
            QueuedThreadPool threadPool = new QueuedThreadPool(config.getThreadPoolSize(), 2, 30000);
            Server server = new Server(threadPool);
            ServerConnector connector;
            if (secure) {
                /* Setup TLS if secure flag was set. */
                SslContextFactory sslContextFactory = new SslContextFactory.Server();
                sslContextFactory.setKeyStorePath(config.getKeystore());
                sslContextFactory.setKeyStorePassword(config.getKeystorePassword());
                connector = new ServerConnector(server, sslContextFactory);
            } else {
                connector = new ServerConnector(server);
            }
            if (port > 0) {
                connector.setPort(port);
            }
            server.setConnectors(new Connector[] { connector });
            return server;
        });
        /* Configure OpenAPI/Swagger doc */
        if (config.getEnableLiveDoc()) {
            this.openApi = new OpenApiPlugin(OpenApiCompatHelper.getJavalinOpenApiOptions(config));
            serviceConfig.registerPlugin(this.openApi);
            /* Enable webjars to serve Swagger-UI */
            serviceConfig.enableWebjars();
        }
        /* Serve the UI if requested statically*/
        if (config.getServeUI()) {
            LOGGER.info("UI serving is enabled");
            /* Add css, js and other static files */
            serviceConfig.addStaticFiles(config.getUiLocation(), Location.EXTERNAL);
            /* Add index.html - the ui's front page as default route. Anything reroutes to there */
            serviceConfig.addSinglePageRoot("/", config.getUiLocation() + "/index.html", Location.EXTERNAL);
        }
    });
    /* Enable WebSocket (if configured). */
    if (config.getEnableWebsocket()) {
        LOGGER.info("Starting WS API");
        this.webSocketApi = new WebsocketAPI();
        service.ws(String.format("%s/websocket", namespace()), handler -> {
            handler.onConnect(ctx -> webSocketApi.connected(ctx.session));
            handler.onClose(ctx -> webSocketApi.closed(ctx.session, ctx.status(), ctx.reason()));
            handler.onError(ctx -> webSocketApi.onWebSocketException(ctx.session, ctx.error()));
            handler.onMessage(ctx -> webSocketApi.message(ctx.session, ctx.message()));
        });
    }
    /* Setup HTTP/RESTful connection (if configured). */
    if (config.getEnableRest() || config.getEnableRestSecure()) {
        LOGGER.info("Starting REST API");
        this.restHandlers.forEach(handler -> registerRestHandler(service, handler));
        this.registerServingRoutes(service, config);
    }
    /* Register a general exception handler. TODO: Add fine grained exception handling. */
    service.exception(Exception.class, (ex, ctx) -> {
        ex.printStackTrace();
        LOGGER.error(ex);
    });
    /* Start javalin */
    try {
        if (port > 0) {
            service.start(port);
        } else {
            service.start();
        }
    } catch (Exception ex) {
        LOGGER.log(Level.FATAL, "Failed to start HTTP endpoint due to an exception. Cineast will shut down now!", ex);
        System.exit(100);
    }
    return service;
}
Also used : Javalin(io.javalin.Javalin) ServerConnector(org.eclipse.jetty.server.ServerConnector) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) Server(org.eclipse.jetty.server.Server) APIConfig(org.vitrivr.cineast.standalone.config.APIConfig) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) WebsocketAPI(org.vitrivr.cineast.api.websocket.WebsocketAPI) OpenApiPlugin(io.javalin.plugin.openapi.OpenApiPlugin)

Example 5 with OpenApiPlugin

use of io.javalin.plugin.openapi.OpenApiPlugin in project Jexxa by jexxa-projects.

the class OpenAPIConvention method initOpenAPI.

private void initOpenAPI() {
    if (properties.containsKey(JEXXA_REST_OPEN_API_PATH)) {
        var applicationInfo = new Info().version(properties.getProperty(JEXXA_CONTEXT_VERSION, "1.0")).description("Auto generated OpenAPI for " + properties.getProperty(JEXXA_CONTEXT_NAME, "Unknown Context")).title(properties.getProperty(JEXXA_CONTEXT_NAME, "Unknown Context"));
        openApiOptions = new OpenApiOptions(applicationInfo).path("/" + properties.getProperty(JEXXA_REST_OPEN_API_PATH));
        // Show all fields of an ValueObject
        openApiOptions.getJacksonMapper().setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
        javalinConfig.registerPlugin(new OpenApiPlugin(openApiOptions));
        javalinConfig.enableCorsForAllOrigins();
        openApiOptions.defaultDocumentation(doc -> {
            doc.json(String.valueOf(HTTP_BAD_REQUEST), BadRequestResponse.class);
            doc.json(String.valueOf(HTTP_BAD_REQUEST), BadRequestResponse.class);
        });
    }
}
Also used : OpenApiOptions(io.javalin.plugin.openapi.OpenApiOptions) Info(io.swagger.v3.oas.models.info.Info) OpenApiPlugin(io.javalin.plugin.openapi.OpenApiPlugin)

Aggregations

OpenApiPlugin (io.javalin.plugin.openapi.OpenApiPlugin)5 OpenApiOptions (io.javalin.plugin.openapi.OpenApiOptions)4 Info (io.swagger.v3.oas.models.info.Info)4 Javalin (io.javalin.Javalin)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 Meter (com.codahale.metrics.Meter)1 MetricRegistry (com.codahale.metrics.MetricRegistry)1 MetricsServlet (com.codahale.metrics.servlets.MetricsServlet)1 JsonInclude (com.fasterxml.jackson.annotation.JsonInclude)1 PropertyNamingStrategies (com.fasterxml.jackson.databind.PropertyNamingStrategies)1 MismatchedInputException (com.fasterxml.jackson.databind.exc.MismatchedInputException)1 JavaTimeModule (com.fasterxml.jackson.datatype.jsr310.JavaTimeModule)1 BasinController (cwms.radar.api.BasinController)1 BlobController (cwms.radar.api.BlobController)1 CatalogController (cwms.radar.api.CatalogController)1 ClobController (cwms.radar.api.ClobController)1 LevelsController (cwms.radar.api.LevelsController)1 LocationCategoryController (cwms.radar.api.LocationCategoryController)1 LocationController (cwms.radar.api.LocationController)1 LocationGroupController (cwms.radar.api.LocationGroupController)1