use of io.javalin.Javalin in project micrometer by micrometer-metrics.
the class MicrometerPlugin method main.
public static void main(String[] args) {
PrometheusMeterRegistry meterRegistry = new PrometheusMeterRegistry(PrometheusConfig.DEFAULT);
// add any tags here that will apply to all metrics streaming from this app
// (e.g. EC2 region, stack, instance id, server group)
meterRegistry.config().commonTags("app", "javalin-sample");
new JvmGcMetrics().bindTo(meterRegistry);
new JvmHeapPressureMetrics().bindTo(meterRegistry);
new JvmMemoryMetrics().bindTo(meterRegistry);
new ProcessorMetrics().bindTo(meterRegistry);
new FileDescriptorMetrics().bindTo(meterRegistry);
Javalin app = Javalin.create(config -> config.registerPlugin(new MicrometerPlugin(meterRegistry))).start(8080);
// must manually delegate to Micrometer exception handler for excepton tags to be
// correct
app.exception(IllegalArgumentException.class, (e, ctx) -> {
MicrometerPlugin.EXCEPTION_HANDLER.handle(e, ctx);
e.printStackTrace();
});
app.get("/", ctx -> ctx.result("Hello World"));
app.get("/hello/:name", ctx -> ctx.result("Hello: " + ctx.pathParam("name")));
app.get("/boom", ctx -> {
throw new IllegalArgumentException("boom");
});
app.routes(() -> {
path("hi", () -> {
get(":name", ctx -> ctx.result("Hello: " + ctx.pathParam("name")));
});
});
app.after("/hello/*", ctx -> {
System.out.println("hello");
});
app.get("/prometheus", ctx -> ctx.contentType(TextFormat.CONTENT_TYPE_004).result(meterRegistry.scrape()));
}
use of io.javalin.Javalin 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;
}
use of io.javalin.Javalin in project emfcloud-modelserver by eclipse-emfcloud.
the class ModelServerRoutingV2Test method setUp.
//
// Test framework
//
@Before
public void setUp() throws Exception {
Javalin javalin = mock(Javalin.class);
when(javalin.routes(ArgumentMatchers.any())).thenCallRealMethod();
when(javalin.get(ArgumentMatchers.anyString(), ArgumentMatchers.any())).then(invocation -> {
setHandler("GET", invocation.getArgument(0), invocation.getArgument(1));
return javalin;
});
when(context.result(ArgumentMatchers.anyString())).then(invocation -> {
resultString = invocation.getArgument(0);
return context;
});
when(context.status(ArgumentMatchers.anyInt())).then(invocation -> {
resultStatus = invocation.getArgument(0);
return context;
});
when(serverConfiguration.getWorkspaceRootURI()).thenReturn(WORKSPACE_URI);
when(uriConverter.resolveModelURI(context, "modeluri")).then(invocation -> {
return Optional.ofNullable(context.queryParam(invocation.getArgument(1))).map(uriString -> URI.createURI(uriString, true)).flatMap(uri -> new DefaultModelURIConverter.APIV2Resolver(serverConfiguration).apply(uri));
});
when(uriConverter.resolveModelURI(context)).thenCallRealMethod();
routing = new ModelServerRoutingV2(javalin, resourceManager, modelController, schemaController, serverController, sessionController, transactionController);
routing.setModelURIConverter(uriConverter);
routing.bindRoutes();
}
use of io.javalin.Javalin in project okaeri-platform by OkaeriPoland.
the class OkaeriWebApplication method plan.
@Override
public void plan(@NonNull ExecutionPlan plan) {
plan.add(PRE_SETUP, new InjectorSetupTask());
plan.add(PRE_SETUP, (ExecutionTask<OkaeriWebApplication>) platform -> {
platform.registerInjectable("dataFolder", platform.getDataFolder());
platform.registerInjectable("jarFile", platform.getFile());
platform.registerInjectable("logger", platform.getLogger());
platform.registerInjectable("app", platform);
platform.registerInjectable("javalin", platform.getJavalin());
platform.registerInjectable("jetty", Objects.requireNonNull(platform.getJavalin().jettyServer()));
platform.registerInjectable("placeholders", Placeholders.create(true));
platform.registerInjectable("defaultConfigurerProvider", (ConfigurerProvider) YamlSnakeYamlConfigurer::new);
platform.registerInjectable("defaultConfigurerSerdes", new Class[] { SerdesCommons.class, SerdesWeb.class });
platform.registerInjectable("defaultPlaceholdersFactory", new SimplePlaceholdersFactory());
platform.registerInjectable("i18nLocaleProvider", new SystemLocaleProvider());
});
plan.add(SETUP, new CommandsSetupTask(new OkaeriCommands()));
plan.add(SETUP, new CreatorSetupTask(ApplicationComponentCreator.class, WebCreatorRegistry.class));
plan.add(POST_SETUP, new BeanManifestCreateTask());
plan.add(POST_SETUP, new BeanManifestExecuteTask());
plan.add(POST_SETUP, new JavalinSetupTask());
plan.add(POST_SETUP, new PlatformBannerStartupTask());
plan.add(STARTUP, new JavalinStartTask());
plan.add(SHUTDOWN, new JavalinShutdownTask());
plan.add(SHUTDOWN, new PersistenceShutdownTask());
}
use of io.javalin.Javalin in project solinia3-core by mixxit.
the class Solinia3CorePlugin method startHttpListener.
private void startHttpListener() {
// Get the current class loader.
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
// Temporarily set this thread's class loader to the plugin's class loader.
// Replace JavalinTestPlugin.class with your own plugin's class.
Thread.currentThread().setContextClassLoader(Solinia3CorePlugin.class.getClassLoader());
// Instantiate the web server (which will now load using the plugin's class
// loader).
Javalin app = Javalin.create(config -> {
config.defaultContentType = "text/plain";
}).start(4567);
System.out.println("Listening on port 4567");
app.before(ctx -> log.info(ctx.req.getPathInfo()));
app.routes(() -> {
// Routes for v1 of the API
path(API_V1, () -> {
// Communication
post("discord", ServerApi::discordPost);
get("metrics", ServerApi::metricsGet);
});
});
// Default fallthrough. Just give them a 404.
app.get("*", ctx -> {
throw new NotFoundResponse();
});
// Put the original class loader back where it was.
Thread.currentThread().setContextClassLoader(classLoader);
}
Aggregations