smallmind-web is the parent POM for the project’s HTTP-side concerns. It does
not ship as a single artifact. Instead it is a curated set of seven sibling
modules that can be pulled in independently, each focused on one seam of the
web stack:
-
web-grizzly— an embedded Grizzly 2.4 HTTP/HTTPS/HTTP2/WebSocket server, wired through Spring, that hosts servlets, JAX-RS resources, JAX-WS SOAP endpoints, and static resources in one or more named contexts. -
web-jetty— an embedded Jetty 12 (EE10) server, assembled the same way by Spring, for deployments that prefer Jetty’s connector model and HTTP/1.1 semantics. -
web-jersey— the Jersey 3 (JAX-RS) companion library: JSON provider, exception mapper, CORS filter, pagination filter, multipart feature, an AspectJ-driven parameter-injection layer, and a dynamic JSON-over-HTTP client proxy generator. -
web-http— a pooled, asynchronous, blocking-friendly HTTP client built on Apache HttpComponents 5. -
web-json-query— a JSON/JAXB-serialisable query-expression language with translators for JPA Criteria, QueryDSL, and MongoDB/Throng. -
web-json-scaffold— the JSON codec, fault model, polymorphic Jackson module, reflection helpers, and paging primitives that the rest of theweb-*modules build on. -
web-json-doppelganger— an annotation processor that generates direction- and purpose-aware view classes from domain entities. Because the module is a separate compile-time tool with its own conceptual model, it has its own reference: see Doppelganger for a cross reference, and DOPPELGANGER.adoc for the full document. -
schema-validation-maven-plugin(directory:web/schema) — a Maven plugin that fails the build when a shipped XSD or XML instance file is malformed. Despite living underweb/schema, it has no relationship to JSON-schema generation.
Plenty of frameworks answer "how do I bring up an HTTP server?" but they tend
to couple the server, the resource layer, the serialisation layer, and the
wire-format conventions together. smallmind-web is organised around the
opposite principle: each module has a single job and a deliberate dependency
arrow.
-
Pick your container.
web-grizzlyandweb-jettysolve the same problem — host servlets, JAX-RS, JAX-WS, and WebSockets — with different engines. They have near-identical Spring configuration surface (SSLInfo,WebApplicationOption,FilterInstaller,ServletInstaller,ListenerInstaller,WebServiceInstaller,@ServicePath). Swapping containers is a dependency swap plus a bean-id rename. -
Pick your resource style.
web-jerseydecorates a JerseyResourceConfigwith the project’s opinions (JSON, CORS, exception mapping, paging, entity parameter injection). The container modules accept anyResourceConfig, so the Jersey extensions are optional even when the container is not. -
Pick your data layer.
web-json-querydescribes predicates, sorts, and paging in a way that survives JSON round-trips and translates to multiple backends — JPA, QueryDSL, or MongoDB — on the server side. -
Generate your API views.
web-json-doppelgangereliminates the hand-written DTOs that usually live between a domain entity and its JSON representation, and makes the "create vs. update vs. admin vs. public" projection distinction first-class instead of a convention.
A lean service typically pulls in web-grizzly (or web-jetty) + web-jersey
+ web-json-scaffold, and declares one or two WebApplicationOption beans.
Richer services add web-json-query and web-json-doppelganger.
-
It does not bundle security. There is no built-in authentication, RBAC, or principal model; authentication is expected to be driven by standard servlet filters, Spring Security, or a JAX-RS
ContainerRequestFilterthat the application contributes. -
It does not prescribe a persistence layer.
web-json-queryintegrates with JPA, QueryDSL, and MongoDB/Throng, but none of those dependencies are required to use the module — each is an optional dependency that activates one of its translator classes. -
It does not abstract over containers. The two container modules share a vocabulary but not an SPI; choose one or the other per deployment.
- First time through
-
Read web-grizzly (or web-jetty), then web-jersey, then web-json-scaffold. That is the minimum to stand up a JSON REST service.
- Adding a query endpoint
-
Read web-json-query, then pick one of the JPA/QueryDSL/Throng integration sub-sections.
- Building a client to another JSON service
-
Read the Client Proxies subsection of web-jersey (
JsonTarget,JsonEntityResourceProxyFactory). Considerweb-httpif you need a raw Apache HttpComponents pool. - Tokens and identity
-
Read web-jwt.
- Schema validation as a build step
- Generated DTOs
-
Read DOPPELGANGER.adoc.
| Module | Artifact | Module name | Use when you need… |
|---|---|---|---|
web-grizzly |
|
|
An embedded Grizzly server with HTTP/2, WebSockets (Tyrus), JAX-WS, and per-context servlet deployment driven by Spring. |
web-jetty |
|
|
An embedded Jetty 12 server with the same capability set as Grizzly but different HTTP and thread-pool semantics. |
web-jersey |
|
|
JAX-RS providers, filters, exception mapping, paging, entity-parameter injection, and dynamic JSON proxies on top of Jersey 3. |
web-http |
|
|
A shared, pooled, async-but-callable Apache HttpComponents 5 client. |
web-json-query |
|
|
A portable, JSON-round-trippable query language with JPA/QueryDSL/Throng translators. |
web-json-scaffold |
|
|
|
web-json-doppelganger |
|
|
Compile-time generation of directional, purpose-aware view classes. See DOPPELGANGER.adoc. |
web-jwt |
|
|
JWS (compact-serialised JWT) encoding, decoding, and signature verification over jose4j. |
schema-validation-maven-plugin |
|
Automatic module name: |
A build goal that validates XSD files and XML instance documents and fails the build on errors. |
Dependency examples in this document use ${project.version} for SmallMind
artifacts. Substitute the SmallMind version you build against.
Every module is a plain Maven artifact under org.smallmind:
<dependency>
<groupId>org.smallmind</groupId>
<artifactId>web-grizzly</artifactId>
<version>${project.version}</version>
</dependency>The container modules (web-grizzly, web-jetty) transitively pull in
web-jersey, which pulls in web-json-scaffold. Declare only what you
actually use. Optional integrations in web-json-query (JPA API, QueryDSL,
mongodb-throng) are expressed as compile dependencies of that POM; if you do
not use a backend, exclude the optional translator class from your classpath
by keeping its runtime dependency out — the class is loaded lazily only when
its utility is called.
web-grizzly brings up one embedded Grizzly HttpServer and, per named
context path, registers everything that should live inside it: servlets,
filters, listeners, a Jersey JAX-RS entry point, JAX-WS SOAP endpoints, a
Tyrus WebSocket container, and one or more static-resource handlers. The
Spring container is the system of record: you declare a
GrizzlyInitializingBean with some configuration and let Spring’s
ContextRefreshedEvent drive the startup.
GrizzlyInitializingBean-
The root bean. Implements
InitializingBean,DisposableBean,ApplicationContextAware, andApplicationListener<ContextRefreshedEvent>.afterPropertiesSet()validates the configuredWebApplicationOption[];onApplicationEvent(…)constructs and starts the server when the Spring context finishes refreshing;destroy()stops the server and its WebSocket containers. OptionalsuppressConnectionClosedExceptiondiscards"Connection is closed"IOException`s thrown through the per-application filters, and optional `perApplicationScope(set, or adopted from the scope bound on the thread delivering theContextRefreshedEvent) binds a scope on every request that passes through the servlet filter chain (not the WebSocket upgrade) and every JAX-WS call (see Per-application data on request threads). WebApplicationOption-
A value object describing one context path. Holds a
ClassLoaderResourceOption,DocumentRootOption,JaxRSOption,SpringSupportOption, andWebSocketOption, pluscontextPath(default/context) andsoapPath(default/soap). SSLInfo-
Aggregates the HTTPS listener configuration: port (default 443),
keySecureStore,trustSecureStore,requireClientAuth, andproxyMode(trusts upstreamSSL_CLIENT_*andX-Forwarded-Forheaders). @ServicePath-
Class-level annotation declaring a SOAP endpoint and the context it should live in. Detected automatically by
GrizzlyPostProcessor. GrizzlyPostProcessor-
A Spring
BeanPostProcessorthat, for eachFilterInstaller,ServletInstaller,ListenerInstaller,WebServiceInstaller,WebSocketExtensionInstaller, or@ServicePath-annotated bean, routes it to theGrizzlyWebAppStatebucket for its declared context path. GrizzlyWebAppState/GrizzlyWebAppStateLocator-
Per-context accumulator.
GrizzlyInitializingBeanimplements the locator interface soGrizzlyPostProcessorcan reach the state for a givencontextPath. PerApplicationScopeHttpHandler-
Grizzly
HttpHandlerthat runs a delegate handler’sserviceinside aPerApplicationScopeand forwardsstart/destroy. The bean wraps each JAX-WS handler in one when it resolves a scope, whether set onperApplicationScopeor adopted from the refresh thread (see Per-application data on request threads); it is public so any otherHttpHandlerregistered by hand can be wrapped the same way. ClientAuthProxyFilter-
A Grizzly network filter that either repopulates
SSL_CLIENT_S_DN,SSL_CLIENT_I_DN,SSL_CLIENT_VERIFY, andX-Forwarded-Forfrom the peer TLS certificate, or (whenSSLInfo.proxyMode=true) trusts the upstream proxy’s versions of those headers. GrizzlyRequestContextListener-
A
ServletRequestListenerthat binds Spring’sRequestContextHolderandLocaleContextHolderfor each request. Registered only when the context setsSpringSupportOption.
All installers subclass the GrizzlyInstaller abstract base, which carries
the target contextPath. The concrete subclasses and their getInstallerType
return values are:
| Installer | Type | Role |
|---|---|---|
|
|
Servlet class or instance, URL pattern, init parameters, load-on-startup, async flag. |
|
|
Filter class or instance, URL pattern, init parameters, async flag. |
|
|
Servlet context/request/session listener class or instance, context init parameters. |
|
(not in enum) |
JAX-WS endpoint — |
|
|
A Tyrus |
Each installer is a plain Spring bean. GrizzlyPostProcessor picks them up by
type.
<bean id="grizzlyServer"
class="org.smallmind.web.grizzly.GrizzlyInitializingBean">
<property name="host" value="0.0.0.0"/>
<property name="port" value="8080"/>
<property name="sslInfo" ref="sslInfo"/> <!--(1)-->
<property name="resourceConfig"> <!--(2)-->
<bean class="org.smallmind.web.jersey.spring.JerseyPostProcessor"/>
</property>
<property name="webApplicationOptions">
<list>
<bean class="org.smallmind.web.grizzly.option.WebApplicationOption">
<property name="contextPath" value="/"/>
<property name="jaxRSOption"> <!--(3)-->
<bean class="org.smallmind.web.grizzly.option.JaxRSOption">
<property name="restPath" value="/rest"/>
</bean>
</property>
<property name="springSupportOption">
<bean class="org.smallmind.web.grizzly.option.SpringSupportOption"/>
</property>
</bean>
</list>
</property>
</bean>
<bean id="grizzlyPostProcessor"
class="org.smallmind.web.grizzly.GrizzlyPostProcessor"/>
<bean class="org.smallmind.web.grizzly.installer.FilterInstaller">
<property name="contextPath" value="/"/>
<property name="urlPattern" value="/*"/>
<property name="filterClass" value="com.example.AuthFilter"/>
</bean>-
Optional. Omit to serve HTTP only.
allowInsecure=trueis the default on the initializing bean. -
The Jersey
ResourceConfig.JerseyPostProcessorscans the Spring context for@Pathbeans andResourceConfigExtensionbeans. -
Declaring
JaxRSOptioncauses the Jersey servlet to be bound atcontextPath + restPath + "/*".
When JaxRSOption is declared and a PerApplicationContext is attached
to the thread running the Spring refresh (PerApplicationContext.isBound()
is true there), the bean also maps a filter named
per-application-context on restPath + "/*" for REQUEST and ASYNC
dispatches, with async support enabled. That filter is an
org.smallmind.nutsnbolts.context.web.PerApplicationContextFilter
constructed with that bound context, so each REST request thread carries
the map the refresh registered into. Without a context on the refresh
thread no context filter is registered. Both beans build and start the
server from the ContextRefreshedEvent, on the refresh thread, so in a
context-bound deployment the container’s worker threads inherit the
refresh thread’s map as they are created; the REST-path filter guarantees
the binding for requests served by threads that did not inherit it. If the
Spring ApplicationEventMulticaster runs listeners on a task executor,
the bean evaluates these bindings — and resolves the scope below — on
that executor’s thread rather than the one that called refresh().
The bean resolves its perApplicationScope property exactly once,
through PerApplicationScope.resolve, when it receives the
ContextRefreshedEvent, on the thread delivering it, and keeps the
result for everything it registers:
-
A scope set on the property is used. It must be the scope bound on that thread, if any scope is bound there: a different scope bound there fails
onApplicationEventwithorg.smallmind.nutsnbolts.scope.ScopeException("The supplied PerApplicationScope is not the scope bound on the current thread…"). When no scope is bound there the property is accepted as given, which is the context-only host: its request threads bind the given scope, and the bridging lookups fall back to the inherited context. -
An unset property adopts the scope bound on that thread, if any (the Tanuki wrapper’s
AbstractWrapperListenerwithspark.per.application.scopeon and thePerApplicationScopeContextLoaderListenerfamily both bind one around the refresh), and the bean proceeds exactly as if that scope had been set. Whether aPerApplicationContextis also attached to the thread makes no difference to the adoption. -
An unset property on a thread with no scope bound resolves to no scope: no scope filter is registered and no JAX-WS handler is wrapped, so request threads run with no scope, carrying only the
PerApplicationContextthey inherit or the context filter binds on the REST path.
With a resolved scope, independently of the context filter, the bean:
-
maps a filter named
per-application-scope, anorg.smallmind.nutsnbolts.scope.web.PerApplicationScopeFilter, on/*of everyWebApplicationOptioncontext forREQUESTandASYNCdispatches, with async support enabled. Every servlet in the context — the JAX-RS servlet and eachServletInstallerservlet — and everyAsyncContext.dispatch(…)leg runs with thatPerApplicationScopebound for the extent of the filter chain. The WebSocket handshake is not bound: Grizzly’s Tyrus upgrade bypasses the servlet filter chain, and on Jetty the upgrade filter runs ahead of this one; -
wraps each
WebServiceInstallerhandler in aPerApplicationScopeHttpHandler, so JAX-WS calls, which Grizzly serves outside the servlet filter chain, are bound for the extent of the handler’sservicecall.
<bean id="grizzlyServer"
class="org.smallmind.web.grizzly.GrizzlyInitializingBean">
<property name="perApplicationScope"
ref="org.smallmind.spark.perApplicationScope"/> <!--(1)-->
...
</bean>-
Optional. When the refresh runs inside a scope the property can be omitted and the bean adopts that scope. When it is set and a scope is bound around the Spring refresh, it must be that instance. Declaring
PerApplicationScopeitself as a bean creates a second instance the refresh was never bound around, which the bean rejects; a bean declared withfactory-method="getBound"is the enclosing instance, and arefto it is accepted (see holding the scope as a bean). Under the Tanuki wrapper withspark.per.application.scopeon,SpringContextWrapperListenerregisters the listener’s scope under this name during the refresh, through a post-processor it adds beforehand (see the per-application scope); with the property off no bean is registered under this name, so thisreffails the refresh with aBeanCreationExceptioncaused by Spring’sNoSuchBeanDefinitionException, and the property should be left unset. Elsewhere, register the test- or bootstrap-owned instance as a singleton under the same name beforerefresh(), asTESTBENCH.adocshows. The bean enforces this only when a scope is bound on the refresh thread: a different scope there failsonApplicationEventwithScopeException, while a refresh with no scope bound accepts the property and the bridge falls back to the context.
When the refresh thread carried both bindings (as under Tanuki with
spark.per.application.scope on), both filters run on every JAX-RS
request, so such a request thread carries both bindings. The bridging
Manager classes follow the rules in
Per-application
registries: a registration lands in every registry bound on the refresh
thread, a lookup reads the scope first and falls back to the context, and
a thread whose only binding is empty resolves nothing, reported per
accessor: null from the find methods and the getter-style managers,
UnpluggedInstrumentation from Claxon’s Instrument.with,
ORMInitializationException from SessionManager.getSession and
DataSourceManager.getDataSource, and the adapter default from
PolymorphicAttributeManager. Wiring the same
scope instance here is what makes the two consistent. Data written
directly through PerApplicationContext or PerApplicationScope is
still visible only through the flavor it was written to.
In a context-only deployment (no perApplicationScope set and no scope
bound on the refresh thread) the context filter covers restPath + "/*"
for REQUEST and ASYNC dispatches and nothing else. Installer
servlets, other paths, and JAX-WS handlers see only whatever
PerApplicationContext map their serving thread inherited when it was
created, if any; on a thread that inherited none, Claxon’s
Instrument.with returns UnpluggedInstrumentation, its registry
getters return null, and every other library lookup throws
MissingPerApplicationContextException. In a
scope-only deployment no context filter is registered. A deployment with
neither binding registers no per-application filter at all; its
refresh-time registrations (ClaxonRegistryFactoryBean, ORMDao,
ProxySession, the pooled data sources) would already have failed the
refresh with MissingPerApplicationContextException, and lookups on its
request threads behave as on an unbound thread: unplugged instrumentation
and null registries for Claxon, MissingPerApplicationContextException
for the rest.
On both containers the chain runs the scope filter, then the context
filter, then the FilterInstaller filters, so installer filters mapped
under the REST path see both bindings. The context filter is mapped only
there, so installer filters on other paths see the scope alone, plus
whatever context their worker thread inherited from the refresh. Neither
filter maps the ERROR dispatcher, so error pages run with the scope
unbound.
suppressConnectionClosedException applies to both filters.
JettyInitializingBean exposes the same property with the same behavior
and registers the context filter under the same condition (its JAX-WS
contexts receive a PerApplicationScopeHttpFilter instead of a handler
wrapper). See scope — ScopedValue-bound
scopes for the scope contract.
|
Note
|
The context filter does not create a |
The binding ends where the filter chain or the handler call ends. Work
that leaves it is not bound and must hold the PerApplicationScope
instance and run its body through run / call:
-
AsyncContext.start(Runnable)andReadListener/WriteListenercallbacks (as opposed toAsyncContext.dispatch, which re-enters the chain as anASYNCdispatch and is bound); -
the WebSocket handshake, which both containers upgrade outside the scope filter, and the endpoint callbacks (
@OnOpen,@OnMessage, …), which run on the container’s WebSocket threads; -
a JAX-WS
AsyncProviderthat completes on a thread of its own, or (on Jetty) an endpoint given its ownExecutor; -
any pool or thread the application starts (see
wrapThreadFactory).
SSLInfo expects SecureStore values for the keystore and optional
truststore. The initializing bean converts these into a Grizzly
SSLEngineConfigurator and attaches an HTTP/2 add-on and a
ClientAuthProxyFilter to the secure listener:
SSLInfo sslInfo = new SSLInfo();
sslInfo.setPort(8443);
sslInfo.setKeySecureStore(keyStore);
sslInfo.setTrustSecureStore(trustStore);
sslInfo.setRequireClientAuth(true);
sslInfo.setProxyMode(false);When proxyMode=true, the filter does not enforce its own certificate
extraction — it assumes an upstream proxy has already populated the
SSL_CLIENT_* headers and leaves them in place.
WebSocketOption is a marker that causes the server to build a
TyrusGrizzlyServerContainer per context and (optionally, when
includeWsadlSupport=true) mount a WsadlHttpHandler that serves a WSADL
descriptor.
Endpoints are not discovered from the Spring context. The container is
published as the standard jakarta.websocket.server.ServerContainer
servlet-context attribute, and the application registers its endpoints
there, typically from a ServletContextListener installed with a
ListenerInstaller for the same context path:
public class EndpointRegistrar implements ServletContextListener {
@Override
public void contextInitialized (ServletContextEvent servletContextEvent) {
ServerContainer serverContainer = (ServerContainer)servletContextEvent.getServletContext().getAttribute(ServerContainer.class.getName());
try {
serverContainer.addEndpoint(EchoEndpoint.class);
} catch (DeploymentException deploymentException) {
throw new RuntimeException(deploymentException);
}
}
}<bean class="org.smallmind.web.grizzly.installer.ListenerInstaller">
<property name="contextPath" value="/app"/>
<property name="listenerClass" value="com.example.ws.EndpointRegistrar"/>
</bean>addEndpoint accepts an annotated (@ServerEndpoint) class or a
ServerEndpointConfig. Endpoint paths are relative to the context path, so
@ServerEndpoint("/echo") above answers at ws://host:port/app/echo.
A WebSocketExtensionInstaller for that context adds its extensions to an
endpoint registered as a ServerEndpointConfig whose endpoint class and
path match the installer’s; annotated classes registered directly receive
no installer extensions.
Annotate a JAX-WS service class with @ServicePath(value = "/echo",
contextPath = "/") and the GrizzlyPostProcessor will wrap it in a
WebServiceInstaller. The endpoint is published at
contextPath + soapPath + servicePath (default /soap/echo), and its WSDL
at the same URL with ?wsdl.
The SOAP runtime is Metro’s com.sun.xml.ws:jaxws-rt, the artifact Grizzly’s
JAX-WS add-on compiles against. web-grizzly excludes the OSGi repackagings
(org.glassfish.metro:webservices-osgi and com.sun.xml.bind:jaxb-osgi)
that grizzly-http-server-jaxws would otherwise bring, because they cannot
run on a module path. jaxws-rt is plain JAX-WS: the WS-* extensions
(WS-Security, WS-ReliableMessaging, WS-Policy) that the full Metro bundle
carried are not included, so an application that needs them adds Metro’s
WSIT artifacts itself.
The jar ships an explicit module descriptor for org.smallmind.web.grizzly
that exports all four of its packages and opens org.smallmind.web.grizzly
unconditionally, so classpath:org/smallmind/web/grizzly/grizzly.xml stays
loadable from other modules. On the classpath the descriptor is ignored. See
Module Path And Classpath for the
repository-wide rules.
-
It re-exports (
requires transitive) the Servlet, WebSocket, Grizzly, Tyrus, and Jersey server modules whose types appear in its public signatures, plusorg.smallmind.nutsnbolts. The Spring modules (spring.beans,spring.context,spring.web) are automatic and not re-exported; a module that calls the Spring callbacks onGrizzlyInitializingBeanorGrizzlyPostProcessorrequires them itself. -
It requires
org.glassfish.grizzly.npn.GrizzlyInitializingBeanalways registers Grizzly’s HTTP/2 add-on, which needs that module, andgrizzly-http2only declares itrequires static; naming it here brings it into the module graph. (web-grizzlyalso depends ongrizzly-npn-apifor the same reason on the classpath.) -
grizzly-http-server-jaxwshas no module name of its own, so its module name,grizzly.http.server.jaxws, is derived from the jar’s file name. -
An installer configured with a class (
servletClass,filterClass, orlistenerClass) is instantiated byorg.smallmind.web.grizzly, so the application exports that class’s package toorg.smallmind.web.grizzly. Without it startup fails withGrizzlyInitializationException: IllegalAccessException: class org.smallmind.web.grizzly.installer.ListenerInstaller … cannot access class …. Installers configured with an instance need no export.
A module-path application hosting REST resources follows the web-jersey "Module path" rules. One that publishes SOAP endpoints also:
-
Exports each
@ServicePathservice package unconditionally (and opens it tospring.coreandspring.beansif Spring instantiates the bean). Metro invokes service methods through a class in the unnamed module, so a qualifiedexportsoropensis not enough; without the unconditionalexportsthe call returns a SOAP fault reading… cannot access class … because module … does not export … to unnamed module. -
Passes
--add-reads com.sun.xml.ws=grizzly.http.server.jaxwstojava. Metro inspects Grizzly’sJaxwsConnectionthrough method handles, which need that read edge, and only the command line can add it for an automatic module. Without it every request to the endpoint, including?wsdl, fails with HTTP 500 andIllegalAccessException: module com.sun.xml.ws does not read module grizzly.http.server.jaxws.
SOAP endpoints and Jersey resources can share one Grizzly server on a module
path; launch it with the --add-modules from the web-jersey rules plus
the --add-reads above.
One that registers WebSocket endpoints exports each endpoint package to
Tyrus (exports com.example.ws to org.glassfish.tyrus.core;), which
instantiates the endpoint class reflectively. Without it the handshake
succeeds but no message reaches the endpoint, its @OnError method is not
called, and the only trace is a JUL FINE record from
org.glassfish.tyrus.core reading Component provider for class … not
found. WebSockets need no command-line flags beyond those the rest of the
application needs.
web-jetty solves the same problem as web-grizzly with Eclipse Jetty 12
(EE10 variant). A single JettyInitializingBean builds a
ContextHandlerCollection, one ServletContextHandler per
WebApplicationOption, attaches filters/servlets/listeners through the
installer pattern, hooks up Jersey, publishes JAX-WS services via
JettyHttpServer, and configures Jakarta WebSocket via
JakartaWebSocketServletContainerInitializer.
Both modules are production-ready; the choice is driven by runtime requirements.
-
Choose Grizzly if you want HTTP/2 out of the box and a Tyrus-based WebSocket stack, and you are comfortable with Grizzly’s filter-chain model.
-
Choose Jetty if you want Jetty’s thread-pool model, familiar handler chain, or integration with tooling that expects a Jetty server (Jetty runner, Jetty plugins, Jetty-specific instrumentation).
Both accept the same installer POJOs with different package names.
JettyInitializingBean-
Spring lifecycle bean. Validates
WebApplicationOption[]inafterPropertiesSet(), builds the server inonApplicationEvent(…), stops it indestroy(). Configurable surface:host,port,allowInsecure,sslInfo,resourceConfig,webApplicationOptions,initialWorkerPoolSize,maximumWorkerPoolSize,maxHttpHeaderSize,suppressConnectionClosedException,perApplicationScope(see Per-application data on request threads), anddebug(dumps SOAP traffic). WebApplicationOption(org.smallmind.web.jetty.option)-
Mirrors the Grizzly version. Holds
ClassLoaderResourceOption,DocumentRootOption,JaxRSOption,SpringSupportOption, andWebSocketOption, pluscontextPathandsoapPath. WebSocketOption-
maxSessionIdleTimeoutin ms, default five minutes. SSLInfo+SSLStore-
Jetty’s
SSLStorereferences a resource (classpath:keystore.p12,file:/etc/ssl/…) and a password.SSLStore.getBytes()reads the raw bytes whichJettyInitializingBeanwraps inByteArrayResource(an in-memoryorg.eclipse.jetty.util.resource.Resourceimplementation) and hands toSslContextFactory.Server. JettyPostProcessor+JettyWebAppState+JettyWebAppStateLocator-
Same split-by-context-path pattern as the Grizzly version.
@ServicePath(value, context)-
Marks a SOAP service bean;
JettyPostProcessorroutes it to the correct context. JettyRequestContextListener-
Binds Spring’s request context and locale for each request when
SpringSupportOptionis set. PerApplicationScopeHttpFilter-
com.sun.net.httpserver.Filterthat runs the rest of anHttpContextchain inside aPerApplicationScope. The bean adds one to each JAX-WSHttpContextwhen it resolves a scope, whether set onperApplicationScopeor adopted from the refresh thread (see Per-application data on request threads). ByteArrayResource-
Minimal Jetty
Resourcebacked by a byte array; used for in-memory keystore/truststore bytes.
| Installer | Type | Role |
|---|---|---|
|
|
Same payload as Grizzly’s version. |
|
|
Includes |
|
|
Servlet event listener plus optional context init parameters. |
|
(not in enum) |
|
<bean id="jettyServer"
class="org.smallmind.web.jetty.JettyInitializingBean">
<property name="port" value="8080"/>
<property name="allowInsecure" value="true"/>
<property name="sslInfo"> <!--(1)-->
<bean class="org.smallmind.web.jetty.SSLInfo">
<property name="port" value="8443"/>
<property name="keySSLStore">
<bean class="org.smallmind.web.jetty.SSLStore">
<property name="resource" value="classpath:server.p12"/>
<property name="password" value="changeit"/>
</bean>
</property>
</bean>
</property>
<property name="resourceConfig">
<bean class="org.smallmind.web.jersey.spring.JerseyPostProcessor"/>
</property>
<property name="webApplicationOptions">
<list>
<bean class="org.smallmind.web.jetty.option.WebApplicationOption">
<property name="contextPath" value="/"/>
<property name="jaxRSOption">
<bean class="org.smallmind.web.jetty.option.JaxRSOption">
<property name="restPath" value="/rest"/>
</bean>
</property>
</bean>
</list>
</property>
</bean>
<bean class="org.smallmind.web.jetty.JettyPostProcessor"/>-
Omit to serve HTTP only.
The optional perApplicationScope property is resolved once, through
PerApplicationScope.resolve, on the thread delivering the
ContextRefreshedEvent, exactly as described for Grizzly in
Per-application data on request threads:
a set scope is used (a different scope bound on that thread fails
onApplicationEvent with ScopeException), an unset property adopts the
scope bound there, and an unset property on an unbound thread registers no
scope filter. The resolved scope maps the scope-binding filter on /* of
every servlet context for REQUEST and ASYNC dispatches and adds a
PerApplicationScopeHttpFilter to each JAX-WS HttpContext so SOAP calls,
which Jetty serves through JettyHttpServer outside the servlet filter
chain, are bound for the extent of the exchange.
The Jetty module currently creates each ServletContextHandler with
NO_SESSIONS. Request-scoped state is expected to come from Spring’s
RequestContextHolder via SpringSupportOption, not from HTTP sessions.
The jar ships an explicit module descriptor for org.smallmind.web.jetty
that exports all three of its packages; it needs no opens, because Jersey
never reflects into it and Spring reaches JettyInitializingBean through
public setters. It re-exports (requires transitive) jakarta.servlet,
jdk.httpserver (whose Filter type PerApplicationScopeHttpFilter
extends), org.eclipse.jetty.util, org.glassfish.jersey.core.server, and
org.smallmind.nutsnbolts, and requires the Jetty, Jersey servlet-container,
WebSocket, and JAX-WS modules it uses, and the automatic spring.beans,
spring.context, and spring.web. Because the descriptor
names Jetty’s explicit modules, requiring org.smallmind.web.jetty brings
them into the module graph. A module that implements or calls the Spring
callbacks on JettyInitializingBean or JettyPostProcessor requires
spring.beans and spring.context itself.
An installer configured with a class (servletClass, filterClass, or
listenerClass) is instantiated by org.smallmind.web.jetty, so the
application exports that class’s package to org.smallmind.web.jetty;
installers configured with an instance need no export.
A module-path application hosting web-jersey resources on web-jetty
follows the web-jersey "Module path" rules.
web-jersey is the Jersey 3 layer’s batteries-included assembly. The core
building blocks are:
-
JerseyPostProcessor— aResourceConfigthat is also a SpringBeanPostProcessor. It self-registers@Path-annotated Spring beans, then applies everyResourceConfigExtensionbean in the context. -
ResourceConfigExtension(abstract) — the SPI that every optional feature uses to plug itself in. -
A set of concrete extensions that register JSON serialisation, exception mapping, CORS, multipart, paging, entity-parameter injection, and JAXB parameter conversion.
org.smallmind.web.jersey.spring-
JerseyPostProcessor,ResourceConfigExtension,PrioritizedResourceConfigExtension,ExposedApplicationContext(static hook so Jersey code can reach the Spring context),ExposedWebContextLoaderListener(SpringContextLoaderListenerthat establishes aPerApplicationContextand registers the refreshed context withExposedApplicationContext), andExposedPerApplicationScopeContextLoaderListener(its scope flavor: refreshes inside aPerApplicationScope, publishes that scope under the servlet-context attribute keyed byPerApplicationScope.class.getName(), whichPerApplicationScopeFilterreads, then registers the context the same way. The scope is the one handed to its constructor, else the one already published in the servlet context, else the one bound on the thread initializing the servlet context, else a new instance; a handed scope that differs from a published one, or a handed or published scope that differs from the one bound on the initializing thread, failscontextInitializedwithScopeException; see scope — ScopedValue-bound scopes). org.smallmind.web.jersey.json-
JsonProvider(aMessageBodyReader+MessageBodyWriterforapplication/jsonat@Priority(1), delegating toJsonCodecfromweb-json-scaffold),ThrowableExceptionMapper(catch-all mapper that tries a list ofConcreteExceptionMapperdelegates then falls back to a JSONFaultwith HTTP 500),XmlAdapterParamConverterProvider(makes JAXB adapters work for path and query parameters), and aFaultTranslatingClientResponseFilterfor the client side. Each has a sibling…Extensionclass that registers it. org.smallmind.web.jersey.cors-
CorsFilter— a@PreMatchingcontainer request/response filter that handles OPTIONS preflight and stamps CORS headers on every response. TheCorsExtensionSpring bean wires it with configured allowed/exposed header lists. org.smallmind.web.jersey.multipart-
MultiPartFile(filename, content type, stream,readAllBytes()),MultiPartFileIterator,MultiPartFileException,MultiPartContentType,MultiPartFeatureExtension(registers Jersey’s multipart feature). org.smallmind.web.jersey.page-
@PageRangename-binding annotation +PageRangeResponseFilter. The filter recognisesorg.smallmind.web.json.scaffold.util.Pagereturn values and setsContent-Rangeplus HTTP 200/206/416 appropriately. org.smallmind.web.jersey.aop-
The
@ResourceMethod/@EntityParam/@Validatedaspect layer. See Entity parameter injection below. org.smallmind.web.jersey.proxy-
JsonTarget(fluent blocking JSON client),JsonTargetFactory,JsonEntityResourceProxyFactory(generates a dynamic proxy that turns interface calls into JSON-over-HTTP),JsonHeaderInjector. org.smallmind.web.jersey.ssl-
ClientUtility.clientBuilder()returns a JerseyClientBuilderwith a permissive, all-acceptingSSLContextand hostname verifier — intended for development and test scenarios.
JsonProvider is @Priority(1) so it wins over any default providers.
Serialisation and deserialisation go through JsonCodec, which uses
Jackson’s Jakarta XML-Bind annotation introspector and the scaffold module’s
PolymorphicModule. A resource method can return any JAXB-annotated POJO or
web-json-doppelganger-generated view and it round-trips as JSON without
further configuration.
ThrowableExceptionMapper is the project’s conventional catch-all. It takes
a varargs of ConcreteExceptionMapper delegates and:
-
returns
WebApplicationExceptionresponses unchanged, -
tries each delegate (first match wins),
-
otherwise emits a JSON-serialised
Faultwith HTTP 500.
Register it through ThrowableExceptionExtension or by adding a
ThrowableExceptionMapper(…) instance to your ResourceConfig.
<bean class="org.smallmind.web.jersey.cors.spring.CorsExtension">
<constructor-arg value="Content-Type, Authorization, X-Request-Id"/>
<constructor-arg value="Location, X-Trace-Id"/>
</bean>CorsFilter sets Access-Control-Allow-Origin, Access-Control-Allow-Headers,
Access-Control-Expose-Headers, Access-Control-Allow-Methods, and
Access-Control-Allow-Credentials, and short-circuits OPTIONS preflight
requests with a 200 response carrying the appropriate headers.
Annotate a resource method with @PageRange and return
org.smallmind.web.json.scaffold.util.Page<T>:
@GET
@Path("/users")
@PageRange
public Page<UserOut> listUsers(@QueryParam("firstResult") long firstResult,
@QueryParam("maxResults") int maxResults) {
return userService.list(firstResult, maxResults);
}PageRangeResponseFilter inspects the returned Page and stamps a
Content-Range: items firstResult-last/totalResults header, converts the
body to the raw values array, and picks status 206 when the response covers a
proper subrange, 200 when it is complete, and 416 when the requested range
is out of bounds.
@ResourceMethod (with optional validate=true) and @EntityParam let a
JAX-RS method declare its parameters individually while still accepting a
single JSON object as the request body:
@POST
@Path("/users")
@ResourceMethod(value = UserCreate.class, validate = true)
public UserOut create(@EntityParam("username") String username,
@EntityParam("password") String password) {
...
}The ResourceMethodFilter JAX-RS request filter deserialises the body into a
JsonEntity, stashes it in a thread-local, and
EntityParamResolver.EntityParamValueParamProvider extracts each named
parameter from the entity when Jersey builds the argument array. When
validate=true, ResourceMethodAspect (AspectJ) runs Jakarta Bean Validation
on parameters and return value, throwing EntityValidationException on a
failed constraint.
@Validated applies the same parameter/return-value validation without
requiring @ResourceMethod.
JsonTarget is a small fluent builder over Apache HttpComponents, pinned to a
single host. The optional context path passed to manufacture(…) becomes a
prefix that path(…) prepends to each request path:
JsonTarget target = JsonTargetFactory.manufacture(
HttpProtocol.HTTPS, "api.example.com", 443, "/app");
// requests https://api.example.com:443/app/v1/users/42
UserOut user = target.path("/v1/users/42").get(UserOut.class);JsonEntityResourceProxyFactory.generateProxy(…) creates a java.lang.reflect.Proxy
for a service interface. Each method call is encoded as a JSON Envelope
(named Argument[]) and POSTed to a URL derived from
{context}/{versionPrefix}/{serviceVersion}/{serviceName}/{methodName}, where
{context} is the prefix configured on the target (empty when none is set). Header
injectors (JsonHeaderInjector) can add per-request headers such as
authorization tokens. The Spring factory beans
JsonEntityResourceProxyFactoryBean and JsonTargetFactoryBean make the
same proxies declarable in XML. Each generated proxy is also registered by
interface through JsonEntityResourceProxyManager, whose getProxy(Class)
returns the proxy or null. It bridges JsonEntityResourceProxyScopeManager
(a PerApplicationScope registry) and JsonEntityResourceProxyContextManager
(the PerApplicationContext registry with the same API): register writes
to every registry bound on the calling thread, and getProxy reads the
scope flavor first, falling back to the context flavor when the scope
holds nothing and a context is attached. generateProxy always registers,
so generating a proxy — directly or through the factory beans — on a
thread with neither bound fails with MissingPerApplicationContextException.
<dependency>
<groupId>org.smallmind</groupId>
<artifactId>web-jersey</artifactId>
<version>${project.version}</version>
</dependency><bean class="org.smallmind.web.jersey.spring.JerseyPostProcessor"/>
<bean class="org.smallmind.web.jersey.json.JsonProviderExtension"/>
<bean class="org.smallmind.web.jersey.json.ThrowableExceptionExtension"/>
<bean class="org.smallmind.web.jersey.json.XmlAdapterParamExtension"/>
<bean class="org.smallmind.web.jersey.aop.EntityParamExtension"/>
<bean class="org.smallmind.web.jersey.multipart.MultiPartFeatureExtension"/>
<bean class="org.smallmind.web.jersey.page.PageRangeResponseExtension"/>
<bean class="org.smallmind.web.jersey.cors.spring.CorsExtension">
<constructor-arg value="Content-Type"/>
<constructor-arg value=""/>
</bean>Each extension is independent — leave any of them out and the feature is simply absent.
web-jersey ships no Jersey injection manager, and neither do web-jetty or
web-grizzly. Every deployment adds one at runtime, normally jersey-hk2;
without it Jersey fails at startup with IllegalStateException:
InjectionManagerFactory not found.
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>${jersey.version}</version>
<scope>runtime</scope>
</dependency>The POM’s jersey-spring6 dependency is optional and runtime-scoped (it also
brings jersey-hk2); no web-jersey class references it.
The jar ships an explicit module descriptor for org.smallmind.web.jersey that
exports all ten of its packages. On the classpath the descriptor is ignored. See
Module Path And Classpath for the repository-wide rules.
-
It re-exports (
requires transitive)jakarta.annotation,jakarta.servlet,jakarta.validation,jakarta.ws.rs,jakarta.xml.bind,org.glassfish.jersey.core.server,org.glassfish.jersey.ext.bean.validation,org.glassfish.jersey.media.multipart,org.smallmind.nutsnbolts,org.smallmind.scribe.pen, andorg.smallmind.web.json.scaffold, whose types appear in its public signatures. It also requiresjakarta.inject,org.glassfish.jersey.core.common,org.hibernate.validator,org.smallmind.web.http, and the automatic modulesspring.beans,spring.context,spring.web,org.apache.httpcomponents.client5.httpclient5, andorg.apache.httpcomponents.core5.httpcore5. Automatic modules are never re-exported: a module that uses the Spring factory beans,JerseyPostProcessor, orExposedApplicationContextalso requiresspring.beans(andspring.context), and a module that calls theJsonTargetorJsonBodymethods takingHttpHostorContentTypealso requiresorg.apache.httpcomponents.core5.httpcore5. -
org.aspectj.runtimeisrequires static.ResourceMethodAspectandValidatedAspectadvise nothing insideweb-jersey; advice lands in the classes of an application that weaves them, and that application suppliesorg.aspectj:aspectjrtand, on a module path, requiresorg.aspectj.runtimeitself. -
It opens
org.smallmind.web.jersey.aopandorg.smallmind.web.jersey.pagetoorg.glassfish.hk2.locator,org.glassfish.hk2.utilities, andorg.glassfish.jersey.core.server, because HK2 injects non-public members ofEntityAwareContextResolver,EntityParamResolver,ResourceMethodFilter, andPageRangeResponseFilter.org.smallmind.web.jersey.aopis also opened tojakarta.xml.bindandtools.jackson.databindforEnvelope. The three Spring packages (spring,proxy.spring,cors.spring) are opened tospring.coreandspring.beans. Compiling the module reports[module] module not foundfor the two HK2 modules, which are not on its compile path; theopensclauses are written anyway and take effect at run time. -
EntityParamResolverandEntityAwareContextResolveruse two packages that Jersey does not export (org.glassfish.jersey.innate.injectandorg.glassfish.jersey.server.validation.internal). The build passes--add-exportsfor both, and a module-path application that registersEntityParamExtensionpasses the same two flags tojava:--add-exports org.glassfish.jersey.core.common/org.glassfish.jersey.innate.inject=org.smallmind.web.jersey --add-exports org.glassfish.jersey.ext.bean.validation/org.glassfish.jersey.server.validation.internal=org.smallmind.web.jersey -
jersey-spring6is classpath-only. On a module path it brings HK2’sclass-model, whoseasm-commonsrequiresorg.objectweb.asm.tree, which nothing supplies.
A module-path application that hosts web-jersey resources also does the following:
-
Open each JAX-RS resource package to HK2 and Jersey:
opens com.example.app.rest to org.glassfish.hk2.locator, org.glassfish.hk2.utilities, org.glassfish.jersey.core.server;
Without it, the first injection into a non-public member fails with
InaccessibleObjectExceptionnamingorg.glassfish.hk2.utilities. -
Open each package whose types
JsonProviderreads or writes totools.jackson.databind(see web-json-scaffold). -
Add
jersey-hk2as above and excludeorg.glassfish.hk2.external:aopalliance-repackagedfrom it. That jar andspring-aopboth containorg.aopalliance.aopandorg.aopalliance.intercept, which a module path refuses; HK2 runs on `spring-aop’s copy. -
Resolve the explicit modules that only automatic modules need, by requiring them or with
--add-modules:org.apache.commons.logging(for Spring), andjakarta.elandorg.glassfish.expressly(for Hibernate Validator). A missing one shows up asNoClassDefFoundErrorfor a class whose jar is on the module path, for exampleorg/apache/commons/logging/LogFactory.
For the container itself, both web-grizzly and web-jetty work on a module
path; see their "Module path" sections (web-grizzly, web-jetty).
web-http is a tiny companion library exposing a shared, asynchronous,
pooled Apache HttpComponents 5 client with a blocking-friendly API. The whole
module is four classes under org.smallmind.web.http.apache.
HttpClient-
Singleton holder of a
CloseableHttpAsyncClientwith aPoolingAsyncClientConnectionManagersized at 300 connections per route and 300 total,IOReactorConfigwith a 5-second socket timeout,HttpVersionPolicy.FORCE_HTTP_1, and a permissiveSSLContextthat trusts any certificate. The client is built in a static initializer; construction failure surfaces as aStaticInitializationError. The public surface is a single static method:HttpClient.execute(SimpleHttpRequest request, HttpCallback<SimpleHttpResponse> callback, int timeoutSeconds);
HttpCallback<V>-
Abstract
FutureCallbacksubclass that uses aCountDownLatchso a caller canawait(timeout, TimeUnit)for the callback (not just the future) to finish. Subclasses provideonCompleted,onFailed, andonCancelled. SimpleCallback-
Concrete default callback that stashes the response or exception in
AtomicReference`s. After `execute(…)returns, callgetResponse()to retrieve the response or rethrow the captured exception. HttpRequestCancelledException-
Thrown by
SimpleCallback.onCancelled()so callers can distinguish a cancellation from a timeout or network error.
SimpleHttpRequest request = SimpleHttpRequest.create(
"GET", URI.create("https://example.com/health"));
SimpleCallback callback = new SimpleCallback();
HttpClient.execute(request, callback, 10);
SimpleHttpResponse response = callback.getResponse();JsonTarget (in web-jersey) is a JAX-RS-style builder that understands
JSON serialisation. web-http is the raw transport — use it when you need to
talk to a non-JSON service, when you want direct control over the request,
or when you need the shared connection pool from multiple modules.
The pool size, socket timeout, and permissive TLS trust are hard-coded. If
you need different defaults, fork HttpClient; the module is deliberately
small.
The jar ships an explicit module descriptor for org.smallmind.web.http that exports
org.smallmind.web.http.apache and re-exports org.smallmind.nutsnbolts
(requires transitive). It requires the HttpComponents automatic modules
org.apache.httpcomponents.client5.httpclient5,
org.apache.httpcomponents.core5.httpcore5, and
org.apache.httpcomponents.core5.httpcore5.h2. Automatic modules are never re-exported,
and HttpClient.execute, HttpCallback, and SimpleCallback expose SimpleHttpRequest,
SimpleHttpResponse, and FutureCallback, so a module that calls them also requires
org.apache.httpcomponents.client5.httpclient5 and
org.apache.httpcomponents.core5.httpcore5. The README module table shows which of the
other web modules are explicit and which are still automatic. See Module Path And Classpath for the
repository-wide rules.
web-json-scaffold is the JSON/XML foundation the rest of the web-*
modules link against. It owns the configured ObjectMapper, the project’s
transportable Fault model, a polymorphic Jackson module, Page<T>, a
bean-reflection helper, and a small versioning SPI.
JsonCodec(inorg.smallmind.web.json.scaffold.util)-
Singleton facade over the project
ObjectMapper, retrieved withJsonCodec.instance(). The mapper is configured withJakartaXmlBindAnnotationModule(respects@XmlElement,@XmlRootElement,@XmlJavaTypeAdapter),PolymorphicModule, andMapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME.JsonCodec.redefine(ObjectMapper)swaps in a differently configured mapper as the shared instance, andJsonCodec.standardMapperBuilder()returns a fresh, pre-configured builder as a starting point. Primary methods (invoked on the instance):-
readAsJsonNode(byte[]|String|InputStream) -
read(source, Class<T>)— bindbyte[], aString, anInputStream, aJsonParser, or aJsonNodeto a POJO. -
writeAsBytes(Object)/writeAsString(Object)/writeAsPrettyPrintedString(Object) -
convert(Object, Class<T>)— round-trip re-bind via Jackson.
-
JsonCodecInitializingBean(inorg.smallmind.web.json.scaffold.util.spring)-
Spring
InitializingBeanthat extends the sharedJsonCodecwith extra Jackson modules. Set itsadditionalModulesproperty; on context startup it rebuilds the codec fromstandardMapperBuilder()with those modules added and installs it throughJsonCodec.redefine(…). Fault+FaultElement+Informed-
Faultis the transportable shape of a server-side exception. Built from aThrowable, it captures the throwable type, message,FaultElement[]stack frames, and a nested causeFault.Informed.getInformation()exposes anObjectNodefor free-form context. This is the typeThrowableExceptionMapperproduces on unhandled exceptions. PolymorphicModule+@XmlPolymorphicSubClasses-
A Jackson module that reads a class-level annotation listing the known subtypes and wires a discriminator-based deserializer. Paired with
PolymorphicXmlAdapter/AttributedPolymorphicXmlAdapterfor the JAXB side. Page<T>-
The project’s paging primitive. Holds
values,firstResult,maxResults,resultSize,totalResults. Methods:iterator(),mutate(Class<U>, Mutation<T,U>)to transform elements,jsonConvert(Class<T>)to re-bind via Jackson, and a staticPage.empty(componentClass). BeanReflector-
Walks dotted paths with array subscripts (
a.b[0].c) togetorsetnested bean properties. UsesComponentParser+PathComponentinternally. JsonNodeUtility(inorg.smallmind.web.json.scaffold.util)-
Order-independent structural comparison for Jackson
JsonNodetrees.equalsIgnoresOrder(node1, node2)matches objects by key, arrays as multisets (element order ignored), and numbers bydoublevalue, so2and2.0compare equal.hashCodeIgnoresOrder(node)is the companion hash that upholds theequals/hashCodecontract under that relation — equal nodes always share a hash — so nodes can be keyed in aHashMap/HashSet. Version/Versioned<V>-
A two-interface SPI for DTOs that declare a schema version via an enum — the interfaces are opt-in and carry no behaviour other than the type marker.
NativeObject,NativeLanguage,NativeObjectException-
Represent throwables raised in a non-Java context (for example, a database procedure) so the original diagnostic is preserved in the JSON payload.
FaultWrappingException, ResourceInvocationException,
ObjectInstantiationException, FormatteJacksonException::
Exception types used across the codebase to tag specific failure
categories.
User user = JsonCodec.instance().read(requestBytes, User.class);
byte[] payload = JsonCodec.instance().writeAsBytes(new Page<>(users, 0, 20, 135L));
String city = BeanReflector.get(order, "billingAddress.city");
BeanReflector.set(order, "items[2].quantity", 5);The jar ships an explicit module descriptor for org.smallmind.web.json.scaffold that
exports all six of its packages. On the classpath the descriptor is ignored. See
Module Path And Classpath for the repository-wide rules.
-
It re-exports (
requires transitive)tools.jackson.databind,tools.jackson.core,jakarta.xml.bind,com.fasterxml.jackson.annotation, andorg.smallmind.nutsnbolts, whose types appear in its public signatures, so a module that requiresorg.smallmind.web.json.scaffoldreads them without naming them. It also requirestools.jackson.module.jakarta.xmlbind(resolved with it, soJsonCodec’s JAXB annotation support works without `--add-modules),org.objectweb.asm(resolved with it, for the polymorphic adapters),org.smallmind.scribe.pen, andspring.beans. -
It opens
org.smallmind.web.json.scaffold.faultandorg.smallmind.web.json.scaffold.utiltojakarta.xml.bindandtools.jackson.databind, andorg.smallmind.web.json.scaffold.util.springtospring.coreandspring.beans. -
Open every package whose types
JsonCodecreads or writes totools.jackson.databind:opens com.example.app.model to tools.jackson.databind;
An unqualified
exportsalso works when Jackson touches only public members. Without either, the first call fails withDatabindException: access to public member failed: … from class tools.jackson.databind…. -
Open every package that holds subclasses handled by
PolymorphicXmlAdapterorAttributedPolymorphicXmlAdaptertoorg.smallmind.nutsnboltsandorg.smallmind.web.json.scaffoldas well. The adapters define a proxy subclass in that package and module at run time, and create instances of the real subclass:opens com.example.app.model to tools.jackson.databind, org.smallmind.nutsnbolts, org.smallmind.web.json.scaffold;
Without the
org.smallmind.nutsnboltsopen, the first marshal or unmarshal fails withByteCodeManipulationException: The module(…) of the proxy class(…) must open the package(…) to the module(org.smallmind.nutsnbolts). Without theorg.smallmind.web.json.scaffoldopen (or an unqualifiedexports), unmarshalling fails with aJAXBProcessingExceptioncaused byIllegalAccessException: … does not export … to module org.smallmind.web.json.scaffold.
web-json-query defines a compact predicate/sort/pagination vocabulary that
serialises to JSON and XML. The same query object, after deserialisation on
the server, can be translated into a JPA Predicate, a QueryDSL Predicate,
or a MongoDB criterion document. The module lives under
org.smallmind.web.json.query.
Where-
Root container. Holds a single
WhereConjunction(getRootConjunction()) and exposesgetTargetSet()to walk all referenced field names. WhereCriterion(abstract) →WhereConjunction|WhereField-
Polymorphic tree.
WhereConjunction(abstract) →AndWhereConjunction|OrWhereConjunction-
Logical group of criteria. Holds
List<WhereCriterion>;size(),isEmpty(),addCriterion(…).
WhereField(name, operator, operand) or
WhereField(entity, name, operator, operand)::
Leaf comparison. entity names the alias for scope-qualified references.
WhereOperator-
LT,LE,EQ,NE,GE,GT,EXISTS,LIKE,UNLIKE,IN. Includes anisTrue(op1, op2)method used for in-memory evaluation, and anisTrue(op1, op2, caseInsensitive)overload that comparesStringandCharacteroperand values without regard to case.LIKEaccepts leading and/or trailing*wildcards. WhereOperand<I>(abstract)-
Typed right-hand side of a comparison. Concrete subclasses cover every primitive-like type (
String,Integer,Long,Double,Float,Byte,Short,Boolean,Character,Date(LocalDateTime),Enum,Array,Null). Discriminated on the wire viaWhereOperandPolymorphicXmlAdapter.get(caseInsensitive)returns the underlying value, lower-cased when the operand carries aStringorCharacter(including inside anArray) and the flag is set;getCaseInsensitiveComparator()returns aComparator<WhereOperand<?>>that orders operands the same way, ignoring case. Sort+SortField+SortDirection(ASC,DESC)-
Ordered list of field sorts, same naming model as
WhereField.SortDirectionand its companionSortDirectionEnumXmlAdapterlive inorg.smallmind.nutsnbolts.jsonso the enum and its lowercase JAXB marshaling can be shared across query and persistence layers. WhereVisitor,WhereUtility.walk(visitor, where)-
Visitor infrastructure for tree traversal.
EntityInterrogator-
Applies a
Where/Sortpair against an in-memoryListof entities, rather than translating it to a backend query.page(entityList, where, sort, first, max, predicate, caseInsensitive)reflectively reads each field named by the query (viaBeanReflector), filters, sorts and pages the results, and returns aPage. ThecaseInsensitiveflag makes string-valued filtering and sorting ignore case, consistently for both scalar and array-typed fields.
WhereValidator + WherePermit implementations (AllowedWherePermit,
RequiredWherePermit, ExcludedWherePermit, DependentWherePermit,
TargetWherePermit)::
Validate a Where against a field whitelist/blacklist — the server can
reject queries that reference unsupported or sensitive fields.
Each translator is in its own sub-package so the backend dependency stays optional.
| Sub-package | Translator |
|---|---|
|
|
|
|
|
|
The WhereFieldTransformer supplied by the caller resolves an
(entityName, fieldName) pair to the backend-specific path. For JPA that is
a Path<?> into a Root; for QueryDSL, an Expression; for Throng, a field
key.
Where where = Where.instance(
new AndWhereConjunction(
new WhereField("age", WhereOperator.GE, new IntegerWhereOperand(18)),
new WhereField("status", WhereOperator.EQ, new StringWhereOperand("active"))
)
);
Sort sort = Sort.instance(
SortField.instance("createdAt", SortDirection.DESC));On the server, apply it to a JPA query:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Customer> cq = cb.createQuery(Customer.class);
Root<Customer> root = cq.from(Customer.class);
Product<Root<?>, Predicate> p = JPAQueryUtility.apply(
cb, where,
(entity, field) -> root.get(field),
true);
cq.where(p.getProduct());
cq.orderBy(JPAQueryUtility.applySort(cb, sort,
(entity, field) -> root.get(field)));Hint, HintType, EnumHint, ComponentType, ComponentHint,
and their polymorphic XML adapters let a server publish type metadata (for
example, "this field is an enum; here are its choices") alongside a schema so
a client form generator can render the right widget.
The jar ships an explicit module descriptor for org.smallmind.web.json.query
that exports all five of its packages (including org.smallmind.web.json,
which holds NonTerminalWildcardException) and opens
org.smallmind.web.json.query to jakarta.xml.bind and
tools.jackson.databind for its JAXB-annotated query types, and to
org.smallmind.nutsnbolts for its polymorphic adapters. On the classpath
the descriptor is ignored. See Module Path And Classpath
for the repository-wide rules.
-
It re-exports (
requires transitive)org.smallmind.web.json.scaffold,org.smallmind.persistence,org.smallmind.nutsnbolts,jakarta.persistence,jakarta.validation,jakarta.xml.bind, andtools.jackson.databind, and requirestools.jackson.core. -
The backend translators depend on optional modules, which are
requires static: a module that usesQueryDslQueryUtilityrequirescom.querydsl.core, and one that usesThrongQueryUtilityrequiresorg.smallmind.mongodb.throng.JPAQueryUtilityneeds onlyjakarta.persistence, which is re-exported.
web-jwt is a thin, typed wrapper over
jose4j focused on the JWS case:
sign compact-serialised JWTs, decode and verify them, and (when needed)
unwrap nested JWE/JWS structures.
JWTCodec-
Static encode/decode façade.
-
encode(Object claims, JWTKeyMaster key)→String -
encode(Object claims, JWTKeyMaster key, String keyId)→String -
decode(String token, JWTKeyMaster key, Class<T> claimsClass)→T -
decipher(String token, Class<T> claimsClass)→T(no signature check — for inspection and tests only).
-
JWTKeyMaster-
Pair of
(JWTEncryptionAlgorithm, java.security.Key). JWTEncryptionAlgorithm-
Enum of supported signing algorithms. Values:
HS256(HMAC-SHA-256),RS256(RSA with SHA-256),EDDSA(Edwards-curve EdDSA).getCode()returns the JWA identifier;sign(Key, String)andverify(Key, String[], boolean)delegate to the signing algorithm implementations insmallmind-nutsnbolts. The expectedKeytype depends on the algorithm: an HMAC secret key forHS256, an RSA private/public key forRS256, and an Edwards-curve private/public key forEDDSA. SymmetricJWTKeyMaster(String secret)-
Builds an HMAC-SHA-256 key from a UTF-8 secret. HS256 requires at least a 256-bit key, so a secret of 32 bytes or more is used directly while a shorter secret is SHA-256 hashed up to a 256-bit key.
AsymmetricJWTKeyMaster(Key key)throwsUnknownAlgorithmException-
Inspects
key.getAlgorithm()and mapsRSAtoRS256and any Edwards-curve key (reported asEdDSAorEd25519, depending on the provider) toEDDSA; throwsUnknownAlgorithmExceptionfor anything else. JWTToken-
Optional interface; if your claims class implements it,
getSub()andgetExp()become part of the contract.
JWTConsumer (in org.smallmind.web.jwt.jose4j) is the configurable reader:
JWTConsumer consumer = new JWTConsumer()
.setRequireSignature(true)
.setRequireEncryption(false)
.setRequireIntegrity(false);
MyClaims claims = consumer.process(token, verificationKey, MyClaims.class);It unwraps nested JOSE layers (cty: "jwt" content-types), verifies and/or
decrypts each, and finally deserialises the plaintext JSON to the claim type
via JsonCodec. Policy violations surface as InvalidJWTException; signature
failures as InvalidJWTSignatureException.
-
Expiration is not checked automatically. If your
JWTToken.getExp()should enforce expiry, do the comparison yourself. -
There is no JWK machinery. Keys come in as
java.security.Keyinstances — whatever the caller has loaded from a keystore, PEM, or config. -
JWTCodec.encodealways produces a JWS (signed token). JWE is supported on the read side by jose4j whenJWTConsumeris used directly.
The jar ships an explicit module descriptor for org.smallmind.web.jwt that exports
org.smallmind.web.jwt and org.smallmind.web.jwt.jose4j and re-exports
org.smallmind.nutsnbolts (requires transitive). It requires
org.smallmind.web.json.scaffold and the jose4j automatic module org.jose4j.
Automatic modules are never re-exported, and JWTConsumer.processContext exposes
jose4j’s JsonWebStructure, so a module that calls it also requires org.jose4j.
Claims are written and read through JsonCodec, so open each claims package to
tools.jackson.databind (see web-json-scaffold). See
Module Path And Classpath for the repository-wide rules.
The module in web/schema ships a Maven plugin — schema-validation-maven-plugin
— that validates XML Schema Definition (XSD) files and XML instance documents
at build time. It has no runtime artifact and is unrelated to JSON Schema or
to the rest of the web-* stack; it lives here because XSDs are frequently
shipped alongside REST resources and the same projects tend to use them.
XMLValidationMojo(@Mojo(name = "validate-xml", defaultPhase = VALIDATE))-
Validates every configured XSD against the W3C XML Schema meta-schema, then validates every declared XML instance against its owning XSD. A single SAX
ValidationErrorHandlerrethrows fatal errors, errors, and warnings so the build fails on the first diagnostic. XSD-
Configuration POJO.
pathpoints to an XSD in the project resources;implsis the list of XML files to validate against it.
<plugin>
<groupId>org.smallmind</groupId>
<artifactId>schema-validation-maven-plugin</artifactId>
<version>${project.version}</version>
<executions>
<execution>
<goals>
<goal>validate-xml</goal>
</goals>
<configuration>
<w3c>xsd/XMLSchema.xsd</w3c> <!--(1)-->
<schemas>
<schema>
<path>xsd/orders.xsd</path>
<impls>
<impl>samples/orders-valid.xml</impl>
<impl>samples/orders-partial.xml</impl>
</impls>
</schema>
</schemas>
</configuration>
</execution>
</executions>
</plugin>-
Path to a W3C XML Schema meta-schema file in the project’s resource directories.
The web-json-doppelganger module is a compile-time annotation processor for
generating directional, purpose-aware view classes from an annotated domain
entity. Because it has its own conceptual vocabulary (purposes, idioms,
visibilities, pledges, polymorphic adapters, real vs. virtual properties)
and its own usage model (the processor runs at javac time and writes
sources into target/generated-sources/annotations), its reference is a
separate document:
A typical service that builds its API contract with Doppelganger depends on
web-json-doppelganger at compile time and on web-json-scaffold and
web-jersey at runtime. The generated views are plain Jackson/JAXB POJOs
and need no other runtime plumbing.
- Jersey doesn’t see my
@Pathbeans -
Make sure a
JerseyPostProcessorbean exists in the same Spring context and that the container’sresourceConfigproperty refers to it. The post-processor both collects@Pathbeans and appliesResourceConfigExtensionbeans; without it, Jersey starts with an emptyResourceConfig. - CORS preflight still fails
-
Confirm
CorsExtensionis registered and that the filter’s allowed headers include the headers your client actually sends (typicallyContent-Type,Authorization).@PreMatchingensures the filter runs before resource method matching. @PageRangereturns the wrong status code-
PageRangeResponseFilterpicks 206 when the response covers a proper subrange, 200 when it is complete, and 416 when the requested range is out of bounds. Check that thePageyou return has the correctfirstResult,resultSize, andtotalResultsvalues. IllegalAccessException: module com.sun.xml.ws does not read module grizzly.http.server.jaxws-
A module-path application publishing SOAP endpoints on
web-grizzlylacks--add-reads com.sun.xml.ws=grizzly.http.server.jaxws. See web-grizzly, "Module path". - A WebSocket connects on a module path but the endpoint never answers
-
The endpoint package is not exported to
org.glassfish.tyrus.core. See web-grizzly, "Module path". IllegalStateException: InjectionManagerFactory not found.-
No Jersey injection manager is present. Add
jersey-hk2(see web-jersey, "Installation"). IllegalAccessError: superclass access check failed: … cannot access class org.glassfish.jersey.innate.inject.InternalBinder-
A module-path application registered
EntityParamExtensionwithout the two--add-exportsflags listed under web-jersey, "Module path". Add both to thejavacommand line. InaccessibleObjectExceptionnamingorg.glassfish.hk2.utilities-
On a module path, a JAX-RS resource package is not opened to HK2. Add
opens <package> to org.glassfish.hk2.locator, org.glassfish.hk2.utilities, org.glassfish.jersey.core.server;to the application’s descriptor. - Grizzly or Jetty starts but nothing answers on the port
-
Both initializing beans defer actual startup to
ContextRefreshedEvent. If the Spring context is not refreshed (for example, in an embedded test that uses a plainBeanFactory), the server is never built. UseClassPathXmlApplicationContextor an equivalent full application context. AsymmetricJWTKeyMasterrejects my key-
Only
RSAand Edwards-curve (EdDSA/Ed25519) keys are recognised. Other key types raiseUnknownAlgorithmException. Convert or wrap the key appropriately before constructing the key master. - JPA query from
web-json-querythrows on non-terminal wildcards -
Pass
allowNonTerminalWildcards=truetoJPAQueryUtility.apply(…)if your schema permitsfoopatterns. The default is restrictive to avoid accidental full-scan queries. HttpClient.executehangs past the timeout-
The socket timeout is 5 seconds (fixed), but
execute(…)waits for both the future and the callback. If a custom subclass ofHttpCallbackblocks insideonCompleted,awaitwill not return until it finishes. Keep callback implementations cheap.
| Module | Field | Default |
|---|---|---|
web-grizzly / web-jetty |
|
|
web-grizzly / web-jetty |
|
|
web-grizzly / web-jetty |
|
|
web-grizzly / web-jetty |
|
|
web-grizzly / web-jetty |
|
|
web-grizzly |
|
|
web-jetty |
|
|
web-grizzly / web-jetty |
|
|
web-grizzly / web-jetty |
|
|
web-jetty |
|
|
web-http |
|
|
web-http |
|
|
web-http |
socket timeout |
|
web-http |
TLS trust |
permissive (accept all) |
web-jersey |
|
|
-
DOPPELGANGER.adoc — the
web-json-doppelgangerreference. -
CLAXON.adoc — the in-process metrics framework; its
EmitterResourceJAX-RS endpoint is typically registered in the same JerseyResourceConfig. -
PERSISTENCE.adoc — the data access layer
web-json-querymost often targets.