Skip to content

Latest commit

 

History

History
1784 lines (1499 loc) · 78.9 KB

WEB.adoc

File metadata and controls

1784 lines (1499 loc) · 78.9 KB

SmallMind Web

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 the web-* 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 under web/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.

  1. Pick your container. web-grizzly and web-jetty solve 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.

  2. Pick your resource style. web-jersey decorates a Jersey ResourceConfig with the project’s opinions (JSON, CORS, exception mapping, paging, entity parameter injection). The container modules accept any ResourceConfig, so the Jersey extensions are optional even when the container is not.

  3. Pick your data layer. web-json-query describes 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.

  4. Generate your API views. web-json-doppelganger eliminates 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 ContainerRequestFilter that the application contributes.

  • It does not prescribe a persistence layer. web-json-query integrates 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). Consider web-http if you need a raw Apache HttpComponents pool.

Tokens and identity

Read web-jwt.

Schema validation as a build step

Read schema-validation-maven-plugin.

Generated DTOs

Read DOPPELGANGER.adoc.

Module Artifact Module name Use when you need…

web-grizzly

org.smallmind:web-grizzly

org.smallmind.web.grizzly

An embedded Grizzly server with HTTP/2, WebSockets (Tyrus), JAX-WS, and per-context servlet deployment driven by Spring.

web-jetty

org.smallmind:web-jetty

org.smallmind.web.jetty

An embedded Jetty 12 server with the same capability set as Grizzly but different HTTP and thread-pool semantics.

web-jersey

org.smallmind:web-jersey

org.smallmind.web.jersey

JAX-RS providers, filters, exception mapping, paging, entity-parameter injection, and dynamic JSON proxies on top of Jersey 3.

web-http

org.smallmind:web-http

org.smallmind.web.http

A shared, pooled, async-but-callable Apache HttpComponents 5 client.

web-json-query

org.smallmind:web-json-query

org.smallmind.web.json.query

A portable, JSON-round-trippable query language with JPA/QueryDSL/Throng translators.

web-json-scaffold

org.smallmind:web-json-scaffold

org.smallmind.web.json.scaffold

JsonCodec, Fault, polymorphic Jackson support, Page, and bean reflection helpers. Always a compile dependency of web-jersey.

web-json-doppelganger

org.smallmind:web-json-doppelganger

org.smallmind.web.json.doppelganger

Compile-time generation of directional, purpose-aware view classes. See DOPPELGANGER.adoc.

web-jwt

org.smallmind:web-jwt

org.smallmind.web.jwt

JWS (compact-serialised JWT) encoding, decoding, and signature verification over jose4j.

schema-validation-maven-plugin

org.smallmind:schema-validation-maven-plugin

Automatic module name: org.smallmind.web.schema — Maven loads plugins through its own class realms, so this name only identifies the jar; it is not intended for a consumer’s requires.

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, and ApplicationListener<ContextRefreshedEvent>. afterPropertiesSet() validates the configured WebApplicationOption[]; onApplicationEvent(…​) constructs and starts the server when the Spring context finishes refreshing; destroy() stops the server and its WebSocket containers. Optional suppressConnectionClosedException discards "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 the ContextRefreshedEvent) 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, and WebSocketOption, plus contextPath (default /context) and soapPath (default /soap).

SSLInfo

Aggregates the HTTPS listener configuration: port (default 443), keySecureStore, trustSecureStore, requireClientAuth, and proxyMode (trusts upstream SSL_CLIENT_* and X-Forwarded-For headers).

@ServicePath

Class-level annotation declaring a SOAP endpoint and the context it should live in. Detected automatically by GrizzlyPostProcessor.

GrizzlyPostProcessor

A Spring BeanPostProcessor that, for each FilterInstaller, ServletInstaller, ListenerInstaller, WebServiceInstaller, WebSocketExtensionInstaller, or @ServicePath-annotated bean, routes it to the GrizzlyWebAppState bucket for its declared context path.

GrizzlyWebAppState / GrizzlyWebAppStateLocator

Per-context accumulator. GrizzlyInitializingBean implements the locator interface so GrizzlyPostProcessor can reach the state for a given contextPath.

PerApplicationScopeHttpHandler

Grizzly HttpHandler that runs a delegate handler’s service inside a PerApplicationScope and forwards start / destroy. The bean wraps each JAX-WS handler in one when it resolves a scope, whether set on perApplicationScope or adopted from the refresh thread (see Per-application data on request threads); it is public so any other HttpHandler registered 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, and X-Forwarded-For from the peer TLS certificate, or (when SSLInfo.proxyMode=true) trusts the upstream proxy’s versions of those headers.

GrizzlyRequestContextListener

A ServletRequestListener that binds Spring’s RequestContextHolder and LocaleContextHolder for each request. Registered only when the context sets SpringSupportOption.

All installers subclass the GrizzlyInstaller abstract base, which carries the target contextPath. The concrete subclasses and their getInstallerType return values are:

Installer Type Role

ServletInstaller

SERVLET

Servlet class or instance, URL pattern, init parameters, load-on-startup, async flag.

FilterInstaller

FILTER

Filter class or instance, URL pattern, init parameters, async flag.

ListenerInstaller

LISTENER

Servlet context/request/session listener class or instance, context init parameters.

WebServiceInstaller

(not in enum)

JAX-WS endpoint — path, service instance, asyncSupported.

WebSocketExtensionInstaller

WEB_SOCKET_EXTENSION

A Tyrus Extension to install on one or more endpoints.

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>
  1. Optional. Omit to serve HTTP only. allowInsecure=true is the default on the initializing bean.

  2. The Jersey ResourceConfig. JerseyPostProcessor scans the Spring context for @Path beans and ResourceConfigExtension beans.

  3. Declaring JaxRSOption causes the Jersey servlet to be bound at contextPath + 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 onApplicationEvent with org.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 AbstractWrapperListener with spark.per.application.scope on and the PerApplicationScopeContextLoaderListener family both bind one around the refresh), and the bean proceeds exactly as if that scope had been set. Whether a PerApplicationContext is 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 PerApplicationContext they 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, an org.smallmind.nutsnbolts.scope.web.PerApplicationScopeFilter, on /* of every WebApplicationOption context for REQUEST and ASYNC dispatches, with async support enabled. Every servlet in the context — the JAX-RS servlet and each ServletInstaller servlet — and every AsyncContext.dispatch(…​) leg runs with that PerApplicationScope bound 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 WebServiceInstaller handler in a PerApplicationScopeHttpHandler, so JAX-WS calls, which Grizzly serves outside the servlet filter chain, are bound for the extent of the handler’s service call.

<bean id="grizzlyServer"
      class="org.smallmind.web.grizzly.GrizzlyInitializingBean">
  <property name="perApplicationScope"
            ref="org.smallmind.spark.perApplicationScope"/>  <!--(1)-->
  ...
</bean>
  1. 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 PerApplicationScope itself as a bean creates a second instance the refresh was never bound around, which the bean rejects; a bean declared with factory-method="getBound" is the enclosing instance, and a ref to it is accepted (see holding the scope as a bean). Under the Tanuki wrapper with spark.per.application.scope on, SpringContextWrapperListener registers 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 this ref fails the refresh with a BeanCreationException caused by Spring’s NoSuchBeanDefinitionException, and the property should be left unset. Elsewhere, register the test- or bootstrap-owned instance as a singleton under the same name before refresh(), as TESTBENCH.adoc shows. The bean enforces this only when a scope is bound on the refresh thread: a different scope there fails onApplicationEvent with ScopeException, 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 PerApplicationContext of its own. A context-only deployment that relied on the filter creating one needs a context attached to the refresh thread, so the bean registers the filter with it, or — in a plain servlet container — WebContextLoaderListener (ExposedWebContextLoaderListener for Jersey), which publishes the context the container-declared filter reads.

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) and ReadListener / WriteListener callbacks (as opposed to AsyncContext.dispatch, which re-enters the chain as an ASYNC dispatch 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 AsyncProvider that completes on a thread of its own, or (on Jetty) an endpoint given its own Executor;

  • 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, plus org.smallmind.nutsnbolts. The Spring modules (spring.beans, spring.context, spring.web) are automatic and not re-exported; a module that calls the Spring callbacks on GrizzlyInitializingBean or GrizzlyPostProcessor requires them itself.

  • It requires org.glassfish.grizzly.npn. GrizzlyInitializingBean always registers Grizzly’s HTTP/2 add-on, which needs that module, and grizzly-http2 only declares it requires static; naming it here brings it into the module graph. (web-grizzly also depends on grizzly-npn-api for the same reason on the classpath.)

  • grizzly-http-server-jaxws has 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, or listenerClass) is instantiated by org.smallmind.web.grizzly, so the application exports that class’s package to org.smallmind.web.grizzly. Without it startup fails with GrizzlyInitializationException: 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 @ServicePath service package unconditionally (and opens it to spring.core and spring.beans if Spring instantiates the bean). Metro invokes service methods through a class in the unnamed module, so a qualified exports or opens is not enough; without the unconditional exports the 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.jaxws to java. Metro inspects Grizzly’s JaxwsConnection through 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 and IllegalAccessException: 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[] in afterPropertiesSet(), builds the server in onApplicationEvent(…​), stops it in destroy(). Configurable surface: host, port, allowInsecure, sslInfo, resourceConfig, webApplicationOptions, initialWorkerPoolSize, maximumWorkerPoolSize, maxHttpHeaderSize, suppressConnectionClosedException, perApplicationScope (see Per-application data on request threads), and debug (dumps SOAP traffic).

WebApplicationOption (org.smallmind.web.jetty.option)

Mirrors the Grizzly version. Holds ClassLoaderResourceOption, DocumentRootOption, JaxRSOption, SpringSupportOption, and WebSocketOption, plus contextPath and soapPath.

WebSocketOption

maxSessionIdleTimeout in ms, default five minutes.

SSLInfo + SSLStore

Jetty’s SSLStore references a resource (classpath:keystore.p12, file:/etc/ssl/…) and a password. SSLStore.getBytes() reads the raw bytes which JettyInitializingBean wraps in ByteArrayResource (an in-memory org.eclipse.jetty.util.resource.Resource implementation) and hands to SslContextFactory.Server.

JettyPostProcessor + JettyWebAppState + JettyWebAppStateLocator

Same split-by-context-path pattern as the Grizzly version.

@ServicePath(value, context)

Marks a SOAP service bean; JettyPostProcessor routes it to the correct context.

JettyRequestContextListener

Binds Spring’s request context and locale for each request when SpringSupportOption is set.

PerApplicationScopeHttpFilter

com.sun.net.httpserver.Filter that runs the rest of an HttpContext chain inside a PerApplicationScope. The bean adds one to each JAX-WS HttpContext when it resolves a scope, whether set on perApplicationScope or adopted from the refresh thread (see Per-application data on request threads).

ByteArrayResource

Minimal Jetty Resource backed by a byte array; used for in-memory keystore/truststore bytes.

Installer Type Role

ServletInstaller

SERVLET

Same payload as Grizzly’s version.

FilterInstaller

FILTER

Includes matchAfter flag.

ListenerInstaller

LISTENER

Servlet event listener plus optional context init parameters.

WebServiceInstaller

(not in enum)

(path, service) constructor; optional asyncSupported.

<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"/>
  1. 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 — a ResourceConfig that is also a Spring BeanPostProcessor. It self-registers @Path-annotated Spring beans, then applies every ResourceConfigExtension bean 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 (Spring ContextLoaderListener that establishes a PerApplicationContext and registers the refreshed context with ExposedApplicationContext), and ExposedPerApplicationScopeContextLoaderListener (its scope flavor: refreshes inside a PerApplicationScope, publishes that scope under the servlet-context attribute keyed by PerApplicationScope.class.getName(), which PerApplicationScopeFilter reads, 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, fails contextInitialized with ScopeException; see scope — ScopedValue-bound scopes).

org.smallmind.web.jersey.json

JsonProvider (a MessageBodyReader + MessageBodyWriter for application/json at @Priority(1), delegating to JsonCodec from web-json-scaffold), ThrowableExceptionMapper (catch-all mapper that tries a list of ConcreteExceptionMapper delegates then falls back to a JSON Fault with HTTP 500), XmlAdapterParamConverterProvider (makes JAXB adapters work for path and query parameters), and a FaultTranslatingClientResponseFilter for the client side. Each has a sibling …Extension class that registers it.

org.smallmind.web.jersey.cors

CorsFilter — a @PreMatching container request/response filter that handles OPTIONS preflight and stamps CORS headers on every response. The CorsExtension Spring 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

@PageRange name-binding annotation + PageRangeResponseFilter. The filter recognises org.smallmind.web.json.scaffold.util.Page return values and sets Content-Range plus HTTP 200/206/416 appropriately.

org.smallmind.web.jersey.aop

The @ResourceMethod / @EntityParam / @Validated aspect 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 Jersey ClientBuilder with a permissive, all-accepting SSLContext and 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:

  1. returns WebApplicationException responses unchanged,

  2. tries each delegate (first match wins),

  3. otherwise emits a JSON-serialised Fault with 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, and org.smallmind.web.json.scaffold, whose types appear in its public signatures. It also requires jakarta.inject, org.glassfish.jersey.core.common, org.hibernate.validator, org.smallmind.web.http, and the automatic modules spring.beans, spring.context, spring.web, org.apache.httpcomponents.client5.httpclient5, and org.apache.httpcomponents.core5.httpcore5. Automatic modules are never re-exported: a module that uses the Spring factory beans, JerseyPostProcessor, or ExposedApplicationContext also requires spring.beans (and spring.context), and a module that calls the JsonTarget or JsonBody methods taking HttpHost or ContentType also requires org.apache.httpcomponents.core5.httpcore5.

  • org.aspectj.runtime is requires static. ResourceMethodAspect and ValidatedAspect advise nothing inside web-jersey; advice lands in the classes of an application that weaves them, and that application supplies org.aspectj:aspectjrt and, on a module path, requires org.aspectj.runtime itself.

  • It opens org.smallmind.web.jersey.aop and org.smallmind.web.jersey.page to org.glassfish.hk2.locator, org.glassfish.hk2.utilities, and org.glassfish.jersey.core.server, because HK2 injects non-public members of EntityAwareContextResolver, EntityParamResolver, ResourceMethodFilter, and PageRangeResponseFilter. org.smallmind.web.jersey.aop is also opened to jakarta.xml.bind and tools.jackson.databind for Envelope. The three Spring packages (spring, proxy.spring, cors.spring) are opened to spring.core and spring.beans. Compiling the module reports [module] module not found for the two HK2 modules, which are not on its compile path; the opens clauses are written anyway and take effect at run time.

  • EntityParamResolver and EntityAwareContextResolver use two packages that Jersey does not export (org.glassfish.jersey.innate.inject and org.glassfish.jersey.server.validation.internal). The build passes --add-exports for both, and a module-path application that registers EntityParamExtension passes the same two flags to java:

    --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-spring6 is classpath-only. On a module path it brings HK2’s class-model, whose asm-commons requires org.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 InaccessibleObjectException naming org.glassfish.hk2.utilities.

  • Open each package whose types JsonProvider reads or writes to tools.jackson.databind (see web-json-scaffold).

  • Add jersey-hk2 as above and exclude org.glassfish.hk2.external:aopalliance-repackaged from it. That jar and spring-aop both contain org.aopalliance.aop and org.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), and jakarta.el and org.glassfish.expressly (for Hibernate Validator). A missing one shows up as NoClassDefFoundError for a class whose jar is on the module path, for example org/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 CloseableHttpAsyncClient with a PoolingAsyncClientConnectionManager sized at 300 connections per route and 300 total, IOReactorConfig with a 5-second socket timeout, HttpVersionPolicy.FORCE_HTTP_1, and a permissive SSLContext that trusts any certificate. The client is built in a static initializer; construction failure surfaces as a StaticInitializationError. The public surface is a single static method:

HttpClient.execute(SimpleHttpRequest request,
                   HttpCallback<SimpleHttpResponse> callback,
                   int timeoutSeconds);
HttpCallback<V>

Abstract FutureCallback subclass that uses a CountDownLatch so a caller can await(timeout, TimeUnit) for the callback (not just the future) to finish. Subclasses provide onCompleted, onFailed, and onCancelled.

SimpleCallback

Concrete default callback that stashes the response or exception in AtomicReference`s. After `execute(…​) returns, call getResponse() 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 (in org.smallmind.web.json.scaffold.util)

Singleton facade over the project ObjectMapper, retrieved with JsonCodec.instance(). The mapper is configured with JakartaXmlBindAnnotationModule (respects @XmlElement, @XmlRootElement, @XmlJavaTypeAdapter), PolymorphicModule, and MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME. JsonCodec.redefine(ObjectMapper) swaps in a differently configured mapper as the shared instance, and JsonCodec.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>) — bind byte[], a String, an InputStream, a JsonParser, or a JsonNode to a POJO.

  • writeAsBytes(Object) / writeAsString(Object) / writeAsPrettyPrintedString(Object)

  • convert(Object, Class<T>) — round-trip re-bind via Jackson.

JsonCodecInitializingBean (in org.smallmind.web.json.scaffold.util.spring)

Spring InitializingBean that extends the shared JsonCodec with extra Jackson modules. Set its additionalModules property; on context startup it rebuilds the codec from standardMapperBuilder() with those modules added and installs it through JsonCodec.redefine(…​).

Fault + FaultElement + Informed

Fault is the transportable shape of a server-side exception. Built from a Throwable, it captures the throwable type, message, FaultElement[] stack frames, and a nested cause Fault. Informed.getInformation() exposes an ObjectNode for free-form context. This is the type ThrowableExceptionMapper produces 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 / AttributedPolymorphicXmlAdapter for 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 static Page.empty(componentClass).

BeanReflector

Walks dotted paths with array subscripts (a.b[0].c) to get or set nested bean properties. Uses ComponentParser + PathComponent internally.

JsonNodeUtility (in org.smallmind.web.json.scaffold.util)

Order-independent structural comparison for Jackson JsonNode trees. equalsIgnoresOrder(node1, node2) matches objects by key, arrays as multisets (element order ignored), and numbers by double value, so 2 and 2.0 compare equal. hashCodeIgnoresOrder(node) is the companion hash that upholds the equals/hashCode contract under that relation — equal nodes always share a hash — so nodes can be keyed in a HashMap/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, and org.smallmind.nutsnbolts, whose types appear in its public signatures, so a module that requires org.smallmind.web.json.scaffold reads them without naming them. It also requires tools.jackson.module.jakarta.xmlbind (resolved with it, so JsonCodec’s JAXB annotation support works without `--add-modules), org.objectweb.asm (resolved with it, for the polymorphic adapters), org.smallmind.scribe.pen, and spring.beans.

  • It opens org.smallmind.web.json.scaffold.fault and org.smallmind.web.json.scaffold.util to jakarta.xml.bind and tools.jackson.databind, and org.smallmind.web.json.scaffold.util.spring to spring.core and spring.beans.

  • Open every package whose types JsonCodec reads or writes to tools.jackson.databind:

    opens com.example.app.model to tools.jackson.databind;

    An unqualified exports also works when Jackson touches only public members. Without either, the first call fails with DatabindException: access to public member failed: … from class tools.jackson.databind….

  • Open every package that holds subclasses handled by PolymorphicXmlAdapter or AttributedPolymorphicXmlAdapter to org.smallmind.nutsnbolts and org.smallmind.web.json.scaffold as 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.nutsnbolts open, the first marshal or unmarshal fails with ByteCodeManipulationException: The module(…) of the proxy class(…) must open the package(…) to the module(org.smallmind.nutsnbolts). Without the org.smallmind.web.json.scaffold open (or an unqualified exports), unmarshalling fails with a JAXBProcessingException caused by IllegalAccessException: … 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 exposes getTargetSet() 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 an isTrue(op1, op2) method used for in-memory evaluation, and an isTrue(op1, op2, caseInsensitive) overload that compares String and Character operand values without regard to case. LIKE accepts 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 via WhereOperandPolymorphicXmlAdapter. get(caseInsensitive) returns the underlying value, lower-cased when the operand carries a String or Character (including inside an Array) and the flag is set; getCaseInsensitiveComparator() returns a Comparator<WhereOperand<?>> that orders operands the same way, ignoring case.

Sort + SortField + SortDirection (ASC, DESC)

Ordered list of field sorts, same naming model as WhereField. SortDirection and its companion SortDirectionEnumXmlAdapter live in org.smallmind.nutsnbolts.json so 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/Sort pair against an in-memory List of 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 (via BeanReflector), filters, sorts and pages the results, and returns a Page. The caseInsensitive flag 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

…query.jpa

JPAQueryUtility.apply(CriteriaBuilder, Where, WhereFieldTransformer, allowNonTerminalWildcards) → a Product<Root<?>, Predicate> wrapping the JPA roots and a combined Predicate. applySort(CriteriaBuilder, Sort, WhereFieldTransformer) returns Order[].

…query.querydsl

QueryDslQueryUtility.apply(WhereFieldTransformer, Where) → a QueryDSL Predicate.

…query.throng

ThrongQueryUtility.apply(WhereFieldTransformer, Where) → a mongodb-throng criterion.

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, and tools.jackson.databind, and requires tools.jackson.core.

  • The backend translators depend on optional modules, which are requires static: a module that uses QueryDslQueryUtility requires com.querydsl.core, and one that uses ThrongQueryUtility requires org.smallmind.mongodb.throng. JPAQueryUtility needs only jakarta.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) and verify(Key, String[], boolean) delegate to the signing algorithm implementations in smallmind-nutsnbolts. The expected Key type depends on the algorithm: an HMAC secret key for HS256, an RSA private/public key for RS256, and an Edwards-curve private/public key for EDDSA.

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) throws UnknownAlgorithmException

Inspects key.getAlgorithm() and maps RSA to RS256 and any Edwards-curve key (reported as EdDSA or Ed25519, depending on the provider) to EDDSA; throws UnknownAlgorithmException for anything else.

JWTToken

Optional interface; if your claims class implements it, getSub() and getExp() 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.Key instances — whatever the caller has loaded from a keystore, PEM, or config.

  • JWTCodec.encode always produces a JWS (signed token). JWE is supported on the read side by jose4j when JWTConsumer is 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 ValidationErrorHandler rethrows fatal errors, errors, and warnings so the build fails on the first diagnostic.

XSD

Configuration POJO. path points to an XSD in the project resources; impls is 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>
  1. 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 @Path beans

Make sure a JerseyPostProcessor bean exists in the same Spring context and that the container’s resourceConfig property refers to it. The post-processor both collects @Path beans and applies ResourceConfigExtension beans; without it, Jersey starts with an empty ResourceConfig.

CORS preflight still fails

Confirm CorsExtension is registered and that the filter’s allowed headers include the headers your client actually sends (typically Content-Type, Authorization). @PreMatching ensures the filter runs before resource method matching.

@PageRange returns the wrong status code

PageRangeResponseFilter picks 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 the Page you return has the correct firstResult, resultSize, and totalResults values.

IllegalAccessException: module com.sun.xml.ws does not read module grizzly.http.server.jaxws

A module-path application publishing SOAP endpoints on web-grizzly lacks --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 EntityParamExtension without the two --add-exports flags listed under web-jersey, "Module path". Add both to the java command line.

InaccessibleObjectException naming org.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 plain BeanFactory), the server is never built. Use ClassPathXmlApplicationContext or an equivalent full application context.

AsymmetricJWTKeyMaster rejects my key

Only RSA and Edwards-curve (EdDSA/Ed25519) keys are recognised. Other key types raise UnknownAlgorithmException. Convert or wrap the key appropriately before constructing the key master.

JPA query from web-json-query throws on non-terminal wildcards

Pass allowNonTerminalWildcards=true to JPAQueryUtility.apply(…​) if your schema permits foo patterns. The default is restrictive to avoid accidental full-scan queries.

HttpClient.execute hangs past the timeout

The socket timeout is 5 seconds (fixed), but execute(…​) waits for both the future and the callback. If a custom subclass of HttpCallback blocks inside onCompleted, await will not return until it finishes. Keep callback implementations cheap.

Module Field Default

web-grizzly / web-jetty

WebApplicationOption.contextPath

/context

web-grizzly / web-jetty

WebApplicationOption.soapPath

/soap

web-grizzly / web-jetty

JaxRSOption.restPath

/rest

web-grizzly / web-jetty

ClassLoaderResourceOption.staticPath

/static

web-grizzly / web-jetty

DocumentRootOption.documentPath

/document

web-grizzly

WebSocketOption.includeWsadlSupport

false

web-jetty

WebSocketOption.maxSessionIdleTimeout

300000 (5 min)

web-grizzly / web-jetty

SSLInfo.port

443

web-grizzly / web-jetty

*InitializingBean.port

80

web-jetty

*InitializingBean.allowInsecure

true

web-http

HttpClient pool per-route

300

web-http

HttpClient pool total

300

web-http

socket timeout

5 s

web-http

TLS trust

permissive (accept all)

web-jersey

JsonProvider priority

1

  • DOPPELGANGER.adoc — the web-json-doppelganger reference.

  • CLAXON.adoc — the in-process metrics framework; its EmitterResource JAX-RS endpoint is typically registered in the same Jersey ResourceConfig.

  • PERSISTENCE.adoc — the data access layer web-json-query most often targets.