Search in sources :

Example 1 with Javalin

use of io.javalin.Javalin in project training by java-gcp-220228.

the class Driver method main.

public static void main(String[] args) {
    Javalin app = Javalin.create();
    // This will execute before every single request
    app.before((ctx) -> {
        logger.info(ctx.method() + " request received for " + ctx.path());
    });
    mapControllers(app, new HelloWorldController(), new StudentController(), new ExceptionController());
    // port 8080 by default
    app.start();
}
Also used : Javalin(io.javalin.Javalin) HelloWorldController(com.revature.controller.HelloWorldController) ExceptionController(com.revature.controller.ExceptionController) StudentController(com.revature.controller.StudentController)

Example 2 with Javalin

use of io.javalin.Javalin in project codex by apycazo.

the class OkHttpClientDemo method main.

public static void main(String[] args) {
    int port = 9090;
    String url = "http://localhost:" + port;
    Javalin server = createTestServer(port);
    OkHttpClient client = new OkHttpClient();
    sendGetRequest(client, url);
    sendPostRequest(client, url);
    server.stop();
}
Also used : Javalin(io.javalin.Javalin)

Example 3 with Javalin

use of io.javalin.Javalin in project DV_Projekt by marc-staiger.

the class Main method main.

public static void main(String[] args) {
    // --- set up web server ---//
    int port = 5000;
    Javalin app = Javalin.create(config -> config.addStaticFiles(staticFiles -> {
        // change to host files on a subpath, like '/assets'
        staticFiles.hostedPath = "/";
        // the directory where your files are located
        staticFiles.directory = "www";
        // Location.CLASSPATH (jar) or Location.EXTERNAL (file system)
        staticFiles.location = Location.EXTERNAL;
    })).start(port);
    // --- set up routes ---//
    app.get("/", ctx -> ctx.redirect("/index.html"));
    app.get("/hello", ctx -> ctx.result("Hello World"));
    app.get("/getdata", ctx -> {
        ctx.json(Map.ofEntries(Map.entry("value", "some data"), Map.entry("timestamp", new Date())));
    });
    app.post("/postdata", ctx -> {
        String body = ctx.body();
        Map data = (Map) JSON.parse(body);
        System.out.println(data.get("value"));
    });
}
Also used : Javalin(io.javalin.Javalin) JSON(org.eclipse.jetty.util.ajax.JSON) Date(java.util.Date) Map(java.util.Map) Javalin(io.javalin.Javalin) Location(io.javalin.http.staticfiles.Location) Map(java.util.Map) Date(java.util.Date)

Example 4 with Javalin

use of io.javalin.Javalin 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 5 with Javalin

use of io.javalin.Javalin in project 2203Java by adamranieri.

the class WebApp method main.

public static void main(String[] args) {
    Javalin app = applicationContext.getBean("ProductionApp", Javalin.class);
    // CREATE
    app.post("/books", context -> {
        String body = context.body();
        // JSON fields need to match what the fields are in the class
        Book book = gson.fromJson(body, Book.class);
        bookService.registerBook(book);
        // 201 is the status code for succesffully creating something
        context.status(201);
        String bookJSON = gson.toJson(book);
        context.result(bookJSON);
    });
    // //READ
    app.get("/books", context -> {
        String title = context.queryParam("title");
        if (title == null) {
            List<Book> books = bookService.libraryCatalogue();
            String bookJSON = gson.toJson(books);
            context.result(bookJSON);
        } else {
            List<Book> books = bookService.getBooksByTitle(title);
            String bookJSON = gson.toJson(books);
            context.result(bookJSON);
        }
    });
    app.get("/books/{id}", context -> {
        int id = Integer.parseInt(context.pathParam("id"));
        try {
            String bookJSON = gson.toJson(bookService.retrieveBookById(id));
            context.result(bookJSON);
        } catch (ResourceNotFound e) {
            context.status(404);
            context.result("The book id " + id + "was not found");
        }
    });
    // 
    // //UPDATE
    app.put("/books/{id}", context -> {
        int id = Integer.parseInt(context.pathParam("id"));
        String body = context.body();
        Book book = gson.fromJson(body, Book.class);
        // the id in the uri should take precedence
        book.setId(id);
        bookService.replaceBook(book);
        context.result("Book replaced");
    });
    app.patch("/books/{id}/checkout", context -> {
        try {
            int id = Integer.parseInt(context.pathParam("id"));
            bookService.checkOut(id);
            context.status(204);
        } catch (ResourceNotFound e) {
            context.status(404);
            context.result(e.getMessage());
        }
    });
    app.patch("/books/{id}/checkin", context -> {
        int id = Integer.parseInt(context.pathParam("id"));
        Book book = bookService.retrieveBookById(id);
        bookService.checkIn(book);
        context.result("Book checked in");
    });
    // 
    // //DELETE
    app.delete("/books/{id}", context -> {
        int id = Integer.parseInt(context.pathParam("id"));
        boolean result = bookService.destroyBookById(id);
        if (result) {
            context.status(204);
        } else {
            context.status(500);
        }
    });
    app.start(7000);
}
Also used : Javalin(io.javalin.Javalin) Book(dev.ranieri.entities.Book) ResourceNotFound(dev.ranieri.exceptions.ResourceNotFound)

Aggregations

Javalin (io.javalin.Javalin)47 Test (org.junit.jupiter.api.Test)9 ApiBuilder.get (io.javalin.apibuilder.ApiBuilder.get)4 Context (io.javalin.http.Context)4 Config (org.devocative.artemis.cfg.Config)4 Server (org.eclipse.jetty.server.Server)4 OpenApiPlugin (io.javalin.plugin.openapi.OpenApiPlugin)3 Info (io.swagger.v3.oas.models.info.Info)3 Map (java.util.Map)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)3 HttpServletResponse (javax.servlet.http.HttpServletResponse)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 Context (io.javalin.Context)2 Handler (io.javalin.Handler)2 ApiBuilder.path (io.javalin.apibuilder.ApiBuilder.path)2 Plugin (io.javalin.core.plugin.Plugin)2 ExceptionHandler (io.javalin.http.ExceptionHandler)2 Handler (io.javalin.http.Handler)2 HandlerEntry (io.javalin.http.HandlerEntry)2 HandlerType (io.javalin.http.HandlerType)2