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)
SignatureReturnsDescription
static builder(HttpRouter, int port)Builder
Builder.ssl(Path keyPath, Path certPath)BuilderTLS with PEM files
Builder.sslSelfSigned()BuilderTLS with a self-signed certificate generated at start time
Builder.webSocketService(WebSocketService)BuilderAttach a WebSocket dispatcher
Builder.options(HttpServerOptions)BuilderOverride the default Vert.x options
Builder.start()Future<HttpServer>Bind the listener
Lifecycle
SignatureReturnsDescription
stop()Future<HttpServer>Close the listener
state()Statestopping | stopped | starting | started
is(State)boolean
updateCertificate(Path key, Path cert)Future<Boolean>Hot-swap TLS material without restart
logOptions()voidDump effective Vert.x options to the log
static defaultOptions(HttpCertificate)HttpServerOptionsHTTP/2 with ALPN fallback
Accessors
SignatureReturnsDescription
port()intBound port
certificate()HttpCertificateActive TLS strategy
httpSessionStore()HttpSessionStore
webSocketService()WebSocketService

HttpRouter

HttpRouter class

Maps requests to WebService and WebResource endpoints.

Builder
SignatureReturnsDescription
static builder()Builder
contextPath(String)BuilderGlobal URL prefix applied to all routes
session(HttpSessionStore)BuilderInstall a session handler
contentType(String ext, String mime)BuilderMap a file extension to a MIME type for static serving
contentTypes(Map<String,String>)BuilderBulk-register extension → MIME mappings
webResource(WebApp, String url, Handler...)BuilderMount static resources from a jar or folder
webResource(WebApp, String url, HttpHeader, Handler...)BuilderSame with default response headers
webService(HttpMethod, String path, Handler...)BuilderRegister a service endpoint inline
webService(WebService)BuilderRegister a pre-built WebService
webServices(List<WebService>)BuilderBulk-register services
onRequest(Handler<HttpRequestEvent>)BuilderPre-dispatch hook; handler can abort() the exchange
onResponse(Handler<HttpResponseEvent>)BuilderPre-send hook; handler can mutate or replace the body
build()HttpRouter
Accessors & utilities
SignatureReturnsDescription
getContextPath()String
getHttpSessionStore()HttpSessionStore
getContentTypes()Map<String,String>
getWebServices()List<WebService>
hasResource(WebApp, String path)booleanWhether a bundled asset exists at path
loadResource(WebApp, String path)byte[]Read a bundled asset directly
static formatPath(String | Path)StringNormalise a path (ensure leading slash, forward slashes)
static cleanPath(String | Path)StringStrip leading slash and normalise separators

WebService / WebResource / WebApp

WebService class

One endpoint: HTTP method + path + handler chain. Path must begin with /.

SignatureReturnsDescription
WebService(HttpMethod, String path, Handler<HttpRouting>...)Constructor; path validated to start with /
getMethod()HttpMethod
getPath()String
getHandlers()List<Handler>
getType()TypeWebService 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.

SignatureReturnsDescription
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
SignatureReturnsDescription
static folder(String path)WebAppResources from a filesystem folder
static jar(String classpathBase)WebAppResources from a jar at the given classpath base
static of(Type, String path)WebApp
static of(Type, String path, String contextPath)WebAppWith an explicit URL context path
static builder(Type, String path)Builder
Accessors
SignatureReturnsDescription
type()Typefolder or jar
path()StringFilesystem path or classpath base
contextPath()StringURL prefix under which resources are served

HttpRouting / HttpRequest / HttpResponse

HttpRouting class (extends HttpRoutingContext)

Context handed to every service handler.

SignatureReturnsDescription
request()HttpRequestInbound request
response()HttpResponseOutbound response
nextHandler()voidPass control to the next handler in the chain

HttpRoutingContext class

Base context visible to both onRequest and onResponse hooks.

Session
SignatureReturnsDescription
session()HttpSessionCurrent session, or null if no session handler is configured
sessionStore()HttpSessionStore
Control flow
SignatureReturnsDescription
redirect(String path)voidSend a 302 redirect
fail(int status)voidShort-circuit with the given status code
fail(Throwable)voidShort-circuit with 500 and the given cause
fail(int, Throwable)voidShort-circuit with status + cause
failed()booleantrue if fail() has been called
Context data & resources
SignatureReturnsDescription
contextPath()StringRouter's global context path
contextPath(WebApp)StringEffective URL prefix for the given WebApp
hasResource(WebApp, String)booleanWhether the asset exists in the bundle
loadResource(WebApp, String)byte[]Read a bundled asset
putData(key, value)voidStore arbitrary data for downstream handlers
getData(key)Object
getData(key, default)Object
removeData(key)void
data()MapAll stored data

HttpRequest class

Read-only view of the inbound server request.

General
SignatureReturnsDescription
version()HttpVersionHTTP/1.1 or HTTP/2
method()HttpMethod
ssl()booleantrue for HTTPS
host()String
path()StringRequest path without query string
Headers, parameters & cookies
SignatureReturnsDescription
hasHeader()booleantrue if any header is present
hasHeader(name)boolean
headerNames()Set<String>
header(name)StringFirst value, or null
parameters()HttpParameterAll query parameters as a multimap
parameters(name)List<String>
firstParameter(name)StringFirst value, or null
hasParameter()booleantrue if any parameter is present
parameterNames()Set<String>
cookies()Set<HttpCookie>
cookie(name)HttpCookieFirst match, or null
hasCookie()booleantrue if any cookie is present
hasCookie(name)boolean
Body
SignatureReturnsDescription
bodyAsJsonObject()JsonObject
bodyAsJsonArray()JsonArray
bodyAsText()String
bodyAsByteArray()byte[]
<C> body(Class<C>)CDeserialise 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
SignatureReturnsDescription
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()booleantrue once the response has been written
Inherited from AbstractHttpResponse
SignatureReturnsDescription
statusCode(int)voidSet the response status code
statusCode()intCurrent 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)
SignatureReturnsDescription
abort()voidShort-circuit the exchange; router replies with 444
aborted()booleantrue once abort() has been called
HttpResponseEvent (extends AbstractHttpResponse)
SignatureReturnsDescription
body()ObjectCurrent body value (JsonObject, String, byte[], …)
bodyType()Class<?>Runtime type of the body
hasBody()boolean
updateBody(JsonObject | JsonArray | String | byte[])voidReplace the body before it is written
updateJsonBody(Object [, Class view])voidSerialise via Jackson, optionally with a view
clearBody()voidRemove the body
abort()voidPrevent the response from being sent

Sessions

HttpSessionStore class

In-memory store wrapping Vert.x' LocalSessionStore.

Constructor & configuration
SignatureReturnsDescription
HttpSessionStore(String cookieName, Duration timeout)
cookieName()StringName of the session cookie
timeout()DurationSession idle timeout
onSession(Handler<HttpSession>)voidInvoked once per newly-created session
Operations
SignatureReturnsDescription
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()voidRemove all sessions

HttpSession final class

Thin façade over a Vert.x Web session.

Identity
SignatureReturnsDescription
id()StringCurrent session id
oldId()StringPrevious id, set after regeneration
regenerateId()voidIssue a new id (guards against fixation)
isRegenerated()boolean
Data
SignatureReturnsDescription
put(key, value)void
putIfAbsent(key, value)void
computeIfAbsent(key, fn)void
<T> get(key)T
<T> remove(key)T
data()MapAll session data
isEmpty()boolean
Lifecycle
SignatureReturnsDescription
timeout()DurationSession idle timeout
destroy()voidInvalidate the session
isDestroyed()boolean

WebSockets

WebSocketService class

Registry of server-side WebSocket endpoints for an HttpServer.

SignatureReturnsDescription
add(WebSocket)WebSocketRegister and start listening on the given endpoint
remove(String path)CompositeFutureClose 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
SignatureReturnsDescription
WebSocket(String path)Accept all connections
WebSocket(String path, Function<WebSocketParameter, Boolean> accept)Accept only when accept returns true
Handlers
SignatureReturnsDescription
onOpen(Handler<OpenEvent>)voidFires when a client connects; event carries WebSocketServer
onClose(Handler<CloseEvent>)voidFires when a client disconnects; event carries code() and reason()
onTextMessage(Handler<TextMessageEvent>)voidFires on each incoming text frame
onBinaryMessage(Handler<BinaryMessageEvent>)voidFires on each incoming binary frame
clear(On...)voidDrop handlers of the given kinds (open, close, textMessage, binaryMessage)
Broadcast & lifecycle
SignatureReturnsDescription
send(String)CompositeFutureBroadcast a text frame to all connected clients
send(byte[])CompositeFutureBroadcast a binary frame
isOpened()booleantrue when at least one client is connected
close() · close(short) · close(short, String)voidClose all connections with optional close code and reason

WebSocketServer · WebSocketParameter classes

ClassKey APIDescription
WebSocketServerisOpened() · host() · path() · close(...)Per-client handle injected into OpenEvent
WebSocketParameterentries() · 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.

SignatureReturnsDescription
JsonReader.readValue(String json, Class<O>)ODeserialise JSON
JsonReader.builder().view(Class).build()JsonReaderReader with a Jackson view
JsonWriter.writeValue(Object [, Class view])StringSerialise to a JSON string
JsonWriter.writeValueAsJsonObject(Object [, view])JsonObject
JsonWriter.writeValueAsJsonArray(Object [, view])JsonArray
JsonWriter.builder().pretty(boolean).view(Class).build()JsonWriter
Mapper.jsonMapper()ObjectMapperProcess-wide Jackson mapper
Mapper.jsonMapper(ObjectMapper)voidReplace the process-wide mapper

HttpServerException runtime exception

Raised for invalid paths, missing resources and unrecoverable I/O. Extends YojaAppException.

Module README (full prose + recipes): yoja-http-server/README.md.