Home /
Modules / yoja-http-server
yoja-http-server
Declarative router with sessions, WebSocket dispatching, static-resource
serving (from jars or folders), request/response hooks and TLS
hot-reload — built on Vert.x Web.
Installation
implementation 'com.easygoingapi:yoja-http-server:VERSION'
Quick start
import com.easygoingapi.yoja.core.YojaApp;
import com.easygoingapi.yoja.core.http.HttpMethod;
import com.easygoingapi.yoja.http.server.*;
import io.vertx.core.json.JsonObject;
public class App {
public static void main(String[] args) {
YojaApp.start();
HttpRouter router = HttpRouter.builder()
.contextPath("/api")
.contentType("html", "text/html")
.webResource(WebApp.jar("com.example.webapp"), "/*")
.webService(HttpMethod.GET, "/hello", r ->
r.response().send(new JsonObject().put("hello", "world")))
.onResponse(e -> e.putHeader("X-Powered-By", "yoja"))
.build();
HttpServer.builder(router, 8080)
.sslSelfSigned()
.start();
}
}
HttpServer
HttpServer class (Certificatable)
Vert.x lifecycle wrapper. Owns the listener and implements Certificatable for hot TLS rotation.
Factory (Builder)
| Signature | Returns | Description |
static builder(HttpRouter, int port) | Builder | |
Builder.ssl(Path keyPath, Path certPath) | Builder | TLS with PEM files |
Builder.sslSelfSigned() | Builder | TLS with a self-signed certificate generated at start time |
Builder.webSocketService(WebSocketService) | Builder | Attach a WebSocket dispatcher |
Builder.options(HttpServerOptions) | Builder | Override the default Vert.x options |
Builder.start() | Future<HttpServer> | Bind the listener |
Lifecycle
| Signature | Returns | Description |
stop() | Future<HttpServer> | Close the listener |
state() | State | stopping | stopped | starting | started |
is(State) | boolean | |
updateCertificate(Path key, Path cert) | Future<Boolean> | Hot-swap TLS material without restart |
logOptions() | void | Dump effective Vert.x options to the log |
static defaultOptions(HttpCertificate) | HttpServerOptions | HTTP/2 with ALPN fallback |
Accessors
| Signature | Returns | Description |
port() | int | Bound port |
certificate() | HttpCertificate | Active TLS strategy |
httpSessionStore() | HttpSessionStore | |
webSocketService() | WebSocketService | |
HttpRouter
HttpRouter class
Maps requests to WebService and WebResource endpoints.
Builder
| Signature | Returns | Description |
static builder() | Builder | |
contextPath(String) | Builder | Global URL prefix applied to all routes |
session(HttpSessionStore) | Builder | Install a session handler |
contentType(String ext, String mime) | Builder | Map a file extension to a MIME type for static serving |
contentTypes(Map<String,String>) | Builder | Bulk-register extension → MIME mappings |
webResource(WebApp, String url, Handler...) | Builder | Mount static resources from a jar or folder |
webResource(WebApp, String url, HttpHeader, Handler...) | Builder | Same with default response headers |
webService(HttpMethod, String path, Handler...) | Builder | Register a service endpoint inline |
webService(WebService) | Builder | Register a pre-built WebService |
webServices(List<WebService>) | Builder | Bulk-register services |
onRequest(Handler<HttpRequestEvent>) | Builder | Pre-dispatch hook; handler can abort() the exchange |
onResponse(Handler<HttpResponseEvent>) | Builder | Pre-send hook; handler can mutate or replace the body |
build() | HttpRouter | |
Accessors & utilities
| Signature | Returns | Description |
getContextPath() | String | |
getHttpSessionStore() | HttpSessionStore | |
getContentTypes() | Map<String,String> | |
getWebServices() | List<WebService> | |
hasResource(WebApp, String path) | boolean | Whether a bundled asset exists at path |
loadResource(WebApp, String path) | byte[] | Read a bundled asset directly |
static formatPath(String | Path) | String | Normalise a path (ensure leading slash, forward slashes) |
static cleanPath(String | Path) | String | Strip leading slash and normalise separators |
WebService / WebResource / WebApp
WebService class
One endpoint: HTTP method + path + handler chain. Path must begin with /.
| Signature | Returns | Description |
WebService(HttpMethod, String path, Handler<HttpRouting>...) | | Constructor; path validated to start with / |
getMethod() | HttpMethod | |
getPath() | String | |
getHandlers() | List<Handler> | |
getType() | Type | WebService or WebResource — discriminator |
WebResource class (extends WebService)
A GET endpoint serving static content from a WebApp. The route pattern includes the web app's own context path.
| Signature | Returns | Description |
WebResource(WebApp, String path, Handler...) | | |
WebResource(WebApp, String path, HttpHeader, Handler...) | | With default response headers added to every static response |
webApp() | WebApp | |
headers() | Map<String,String> | Default response headers; empty if none configured |
WebApp class
Describes a bundle of static resources: source type (folder or jar), base path, and optional URL context path.
Factory
| Signature | Returns | Description |
static folder(String path) | WebApp | Resources from a filesystem folder |
static jar(String classpathBase) | WebApp | Resources from a jar at the given classpath base |
static of(Type, String path) | WebApp | |
static of(Type, String path, String contextPath) | WebApp | With an explicit URL context path |
static builder(Type, String path) | Builder | |
Accessors
| Signature | Returns | Description |
type() | Type | folder or jar |
path() | String | Filesystem path or classpath base |
contextPath() | String | URL prefix under which resources are served |
HttpRouting / HttpRequest / HttpResponse
HttpRouting class (extends HttpRoutingContext)
Context handed to every service handler.
| Signature | Returns | Description |
request() | HttpRequest | Inbound request |
response() | HttpResponse | Outbound response |
nextHandler() | void | Pass control to the next handler in the chain |
HttpRoutingContext class
Base context visible to both onRequest and onResponse hooks.
Session
| Signature | Returns | Description |
session() | HttpSession | Current session, or null if no session handler is configured |
sessionStore() | HttpSessionStore | |
Control flow
| Signature | Returns | Description |
redirect(String path) | void | Send a 302 redirect |
fail(int status) | void | Short-circuit with the given status code |
fail(Throwable) | void | Short-circuit with 500 and the given cause |
fail(int, Throwable) | void | Short-circuit with status + cause |
failed() | boolean | true if fail() has been called |
Context data & resources
| Signature | Returns | Description |
contextPath() | String | Router's global context path |
contextPath(WebApp) | String | Effective URL prefix for the given WebApp |
hasResource(WebApp, String) | boolean | Whether the asset exists in the bundle |
loadResource(WebApp, String) | byte[] | Read a bundled asset |
putData(key, value) | void | Store arbitrary data for downstream handlers |
getData(key) | Object | |
getData(key, default) | Object | |
removeData(key) | void | |
data() | Map | All stored data |
HttpRequest class
Read-only view of the inbound server request.
General
| Signature | Returns | Description |
version() | HttpVersion | HTTP/1.1 or HTTP/2 |
method() | HttpMethod | |
ssl() | boolean | true for HTTPS |
host() | String | |
path() | String | Request path without query string |
Headers, parameters & cookies
| Signature | Returns | Description |
hasHeader() | boolean | true if any header is present |
hasHeader(name) | boolean | |
headerNames() | Set<String> | |
header(name) | String | First value, or null |
parameters() | HttpParameter | All query parameters as a multimap |
parameters(name) | List<String> | |
firstParameter(name) | String | First value, or null |
hasParameter() | boolean | true if any parameter is present |
parameterNames() | Set<String> | |
cookies() | Set<HttpCookie> | |
cookie(name) | HttpCookie | First match, or null |
hasCookie() | boolean | true if any cookie is present |
hasCookie(name) | boolean | |
Body
| Signature | Returns | Description |
bodyAsJsonObject() | JsonObject | |
bodyAsJsonArray() | JsonArray | |
bodyAsText() | String | |
bodyAsByteArray() | byte[] | |
<C> body(Class<C>) | C | Deserialise to the given type via Jackson |
isEmptyBody() | boolean | |
HttpResponse class (extends AbstractHttpResponse)
Outbound response. Every send* call triggers the onResponse hook chain before writing.
Send
| Signature | Returns | Description |
send() | Future<Void> | Empty body |
send(JsonObject) · send(JsonArray) · send(String) · send(byte[]) | Future<Void> | Auto Content-Type from body type |
sendJson(Object) | Future<Void> | Serialise via Jackson |
sendJson(Object, Class<?> view) | Future<Void> | Serialise with a Jackson view |
sent() | boolean | true once the response has been written |
Inherited from AbstractHttpResponse
| Signature | Returns | Description |
statusCode(int) | void | Set the response status code |
statusCode() | int | Current status code (default 200) |
putHeader(name, value) | void | |
addCookie(HttpCookie) | void | |
removeCookie(name) | void | |
hasHeader(name) · hasCookie(name) | boolean | |
Events / hooks
HttpRequestEvent · HttpResponseEvent classes
Events handed to onRequest and onResponse hooks. Both extend the full request/response surface.
HttpRequestEvent (extends HttpRequest)
| Signature | Returns | Description |
abort() | void | Short-circuit the exchange; router replies with 444 |
aborted() | boolean | true once abort() has been called |
HttpResponseEvent (extends AbstractHttpResponse)
| Signature | Returns | Description |
body() | Object | Current body value (JsonObject, String, byte[], …) |
bodyType() | Class<?> | Runtime type of the body |
hasBody() | boolean | |
updateBody(JsonObject | JsonArray | String | byte[]) | void | Replace the body before it is written |
updateJsonBody(Object [, Class view]) | void | Serialise via Jackson, optionally with a view |
clearBody() | void | Remove the body |
abort() | void | Prevent the response from being sent |
Sessions
HttpSessionStore class
In-memory store wrapping Vert.x' LocalSessionStore.
Constructor & configuration
| Signature | Returns | Description |
HttpSessionStore(String cookieName, Duration timeout) | | |
cookieName() | String | Name of the session cookie |
timeout() | Duration | Session idle timeout |
onSession(Handler<HttpSession>) | void | Invoked once per newly-created session |
Operations
| Signature | Returns | Description |
size() | Future<Integer> | Number of active sessions |
sessions() | Future<Set<HttpSession>> | All active sessions |
get(String id) | Future<HttpSession> | Look up by session id |
delete(String id) | Future<Void> | Invalidate and remove a session |
clear() | void | Remove all sessions |
HttpSession final class
Thin façade over a Vert.x Web session.
Identity
| Signature | Returns | Description |
id() | String | Current session id |
oldId() | String | Previous id, set after regeneration |
regenerateId() | void | Issue a new id (guards against fixation) |
isRegenerated() | boolean | |
Data
| Signature | Returns | Description |
put(key, value) | void | |
putIfAbsent(key, value) | void | |
computeIfAbsent(key, fn) | void | |
<T> get(key) | T | |
<T> remove(key) | T | |
data() | Map | All session data |
isEmpty() | boolean | |
Lifecycle
| Signature | Returns | Description |
timeout() | Duration | Session idle timeout |
destroy() | void | Invalidate the session |
isDestroyed() | boolean | |
WebSockets
WebSocketService class
Registry of server-side WebSocket endpoints for an HttpServer.
| Signature | Returns | Description |
add(WebSocket) | WebSocket | Register and start listening on the given endpoint |
remove(String path) | CompositeFuture | Close all connections and unregister the endpoint |
hasWebSocket(String path) | boolean | |
getWebSocket(String path) | WebSocket | |
getWebSocketPaths() | Set<String> | All registered paths |
getWebSocketPaths(Status) | Set<String> | Paths filtered by Status.open or Status.close |
getWebSockets(Status) | Set<WebSocket> | Endpoints filtered by status |
WebSocket class
One logical endpoint at a single path. Fans events out to all connected clients. An optional accept function can reject handshakes based on query parameters.
Constructor
| Signature | Returns | Description |
WebSocket(String path) | | Accept all connections |
WebSocket(String path, Function<WebSocketParameter, Boolean> accept) | | Accept only when accept returns true |
Handlers
| Signature | Returns | Description |
onOpen(Handler<OpenEvent>) | void | Fires when a client connects; event carries WebSocketServer |
onClose(Handler<CloseEvent>) | void | Fires when a client disconnects; event carries code() and reason() |
onTextMessage(Handler<TextMessageEvent>) | void | Fires on each incoming text frame |
onBinaryMessage(Handler<BinaryMessageEvent>) | void | Fires on each incoming binary frame |
clear(On...) | void | Drop handlers of the given kinds (open, close, textMessage, binaryMessage) |
Broadcast & lifecycle
| Signature | Returns | Description |
send(String) | CompositeFuture | Broadcast a text frame to all connected clients |
send(byte[]) | CompositeFuture | Broadcast a binary frame |
isOpened() | boolean | true when at least one client is connected |
close() · close(short) · close(short, String) | void | Close all connections with optional close code and reason |
WebSocketServer · WebSocketParameter classes
| Class | Key API | Description |
WebSocketServer | isOpened() · host() · path() · close(...) | Per-client handle injected into OpenEvent |
WebSocketParameter | entries() · values(name) · firstValue(name) · names() · hasName(name) | Parsed handshake query string, used by the accept function |
JSON helpers
json.JsonReader · json.JsonWriter · json.Mapper classes
Thin Jackson wrappers. Failures wrap as HttpServerException.
| Signature | Returns | Description |
JsonReader.readValue(String json, Class<O>) | O | Deserialise JSON |
JsonReader.builder().view(Class).build() | JsonReader | Reader with a Jackson view |
JsonWriter.writeValue(Object [, Class view]) | String | Serialise to a JSON string |
JsonWriter.writeValueAsJsonObject(Object [, view]) | JsonObject | |
JsonWriter.writeValueAsJsonArray(Object [, view]) | JsonArray | |
JsonWriter.builder().pretty(boolean).view(Class).build() | JsonWriter | |
Mapper.jsonMapper() | ObjectMapper | Process-wide Jackson mapper |
Mapper.jsonMapper(ObjectMapper) | void | Replace the process-wide mapper |
HttpServerException runtime exception
Raised for invalid paths, missing resources and unrecoverable I/O. Extends YojaAppException.