- Overview
- Quick Navigation
- At A Glance
- Reading Paths
- Installation
- Conceptual Model
- Package Reference
- command — GNU-style CLI parsing
- context — thread-bound context stacks
- scope — ScopedValue-bound scopes
- resource — uniform addressable content
- property — placeholder expansion
- io — streams, buffers, and path helpers
- csv — event-driven CSV parsing
- xml, json — XML utilities and JAXB adapters
- zip — unified ZIP/JAR handling
- freemarker — template source adapters
- email — Jakarta Mail wrapper
- http, net, ntp — network utilities
- security, ssl — cryptography and TLS
- time — date and time conversions
- retry — retry with back-off
- validation — Jakarta Bean Validation additions
- lang, reflection, apt — classloaders and metaprogramming
- layout — platform-neutral layout engine
- spring — Spring integration
- util — collections and comparators
- inject —
@Servicemarker and lazy fields - servlet, soap — servlet and SOAP helpers
- namespace.shiro — Shiro LDAP realms
- Behavioral Reference
- Limitations and Known Issues
- Dependency Notes
The smallmind-nutsnbolts module is the foundational utility jar that every
other module in the SmallMind repository builds on. It is a single artifact,
smallmind-nutsnbolts, that collects twenty-nine small, focused subpackages
of general-purpose Java infrastructure: command-line parsing, thread-bound
context stacks and ScopedValue-bound scopes, CSV and XML processing,
cryptography, layout calculation,
classloader control, property expansion, a resource abstraction, time
conversions, bag and bloom-filter collections, retry, e-mail, NTP, SSL,
servlet and SOAP helpers, and more.
None of these subpackages is a framework in its own right. Each fills a gap
in either the JDK or the Jakarta/Spring surface, and each is designed to be
usable in isolation, without pulling in the others. The package is named
"Nuts’n’Bolts" because that is what it is — small, durable, reusable parts
that other modules bolt together. Most other SmallMind jars depend on
nutsnbolts at compile time; very few things in this repository build
without it.
It’s generally useful to accumulate a common set of utility classes:
a GNU-style command-line parser, a thread-local stack of "current caller"
information, converters between Date / Calendar / ZonedDateTime, a
Base64 codec that pre-dates java.util.Base64, a classloader that can
exclude or gate specific paths, a property placeholder resolver with
encryption, a tiny retry wrapper, a bag, a bloom filter, JAXB adapters for
the java.time types that JAXB still does not marshal out of the box, a
helper that computes SHA-256 without fifteen lines of
NoSuchAlgorithmException handling, a classpath-aware FreeMarker loader,
and roughly another two dozen pieces in that vein.
smallmind-nutsnbolts is that set, written once, maintained in one place,
and reused across every other SmallMind artifact. It exists so that:
-
An application can depend on a single jar to get all of the common building blocks, instead of pulling in fragments of Apache Commons, Guava, Spring, and Bouncy Castle solely to assemble a working baseline.
-
Every Jakarta, Spring, Bouncy Castle, FreeMarker, and Commons-Net dependency is declared optional, so a consumer that does not use, for example, the e-mail or NTP subpackage does not pay for the corresponding jakarta.mail or commons-net transitive closure.
-
Other SmallMind modules —
smallmind-batch,smallmind-bayeux,smallmind-liquibase,smallmind-file,smallmind-kafka, the wholewebstack — have a shared vocabulary for resources, contexts, properties, and I/O primitives.
-
Not a competitor to Apache Commons, Guava, or Spring’s utility surfaces. Where those libraries provide what is needed, nutsnbolts does not reimplement them. The subpackages here exist because the repository needed a specific semantics that none of those libraries provide out of the box, or because the repository needed to avoid the transitive footprint.
-
Not a dependency-injection framework. The
injectsubpackage is a single marker annotation plus an AspectJ-driven lazy-field helper, not a container. -
Not a web or HTTP framework. The
httpsubpackage wrapsHttpURLConnectionfor simple request/response cases; full HTTP clients live elsewhere. -
Not a cryptography library. The
securitysubpackage is a convenience surface over JCE and Bouncy Castle; callers who need specific algorithm modes or hardware-backed keys should go to those providers directly.
| If you need … | Reach for … | Entry points |
|---|---|---|
Parse a GNU-style command line ( |
|
|
A per-thread stack of "current caller" objects that inherits into child threads |
|
|
Bind an ambient "current caller" object for the exact extent of an operation, with nothing to pop and nothing to leak |
|
|
Uniform access to content behind |
|
|
Resolve |
|
|
An in-memory |
|
|
Event-driven CSV parsing with quoting and header skipping |
|
|
Marshal |
|
|
Compress, walk, or extract ZIP and JAR archives with one API |
|
|
Load FreeMarker templates from classpath, filesystem, or a |
|
|
Send mail over SMTP/SMTPS with optional FreeMarker interpolation and attachments |
|
|
Hash, sign, encrypt, or generate keys without JCE boilerplate |
|
|
Install keystores, trust managers, and (for tests) permissive TLS |
|
|
Convert |
|
|
Run an operation with N retries and optional exponential back-off |
|
|
Add |
|
The annotation types and their matching `ConstraintValidator`s |
Gate which classes a child classloader may resolve |
|
|
Measure, constrain, and position nested boxes in a GUI-agnostic way |
|
|
Common collections the JDK does not ship (bag, bloom filter, LRU map) |
|
|
Use Spring with SmallMind |
|
|
Authenticate a Shiro subject against an LDAP or Active Directory directory |
|
|
| If you are … | Read, in this order |
|---|---|
… wiring a new service and want to know which subpackages are worth adopting before you read any API |
Installation → Conceptual Model → At A Glance → pick two or three rows of the table and jump into the matching sections. |
… already using this jar and need one specific API |
At A Glance → the matching section under Package Reference. |
… a library author considering adding a dependency on nutsnbolts |
Overview → Installation → the Optional dependency matrix subsection — most of the Jakarta/Spring/FreeMarker/Bouncy Castle couplings are optional, and you probably want to keep them that way. |
… adopting cryptography, TLS, or e-mail features for the first time |
security, ssl — cryptography and TLS → email — Jakarta Mail wrapper — these are the subpackages whose optional dependencies and runtime providers matter most. |
… debugging a classloader, bytecode, or annotation-processing problem |
lang, reflection, apt — classloaders and metaprogramming — these utilities are niche but very useful once you know they exist. |
Add the artifact to your Maven build. All third-party couplings are marked
optional in the nutsnbolts POM, so the transitive surface is minimal:
<dependency>
<groupId>org.smallmind</groupId>
<artifactId>smallmind-nutsnbolts</artifactId>
<version>${project.version}</version>
</dependency>Module name (for requires): org.smallmind.nutsnbolts
The following dependencies are declared <optional>true</optional> in the
nutsnbolts POM. A consumer that uses a specific subpackage must add the
corresponding runtime dependency to its own build; a consumer that does not
use it does not pay for the transitive closure.
| Subpackage | Required when you use … | Declare in your build |
|---|---|---|
|
|
|
|
Any |
|
|
The |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
spring XML configuration under |
importing the shipped JMX, Realm, or RMI Spring snippets |
|
|
Important
|
The default |
The jar ships an explicit module descriptor for org.smallmind.nutsnbolts. On the
classpath the descriptor is ignored. The repository-wide rules are in
Module Path And Classpath; this section lists what is specific
to this module.
Required modules. The descriptor requires java.management and, re-exported,
java.compiler, java.naming, java.rmi, and java.xml. These are JDK modules and resolve
without any action on your part.
Optional modules. Every dependency in the matrix above is requires static, and none of
them is re-exported. On the module path, a module you use must be resolved by your own
requires or by --add-modules; its jar being present is not enough. Explicit modules are
the ones that catch people out, because nothing else pulls them into the graph.
| Artifact | Module name | Kind |
|---|---|---|
|
|
explicit |
|
|
explicit |
|
|
explicit |
|
|
explicit |
|
|
explicit |
|
|
explicit |
|
|
explicit |
|
|
explicit |
|
|
explicit |
|
|
explicit |
|
|
explicit |
|
|
explicit |
|
|
explicit |
|
|
automatic |
|
|
automatic |
|
|
automatic |
|
|
automatic |
|
|
automatic |
|
|
automatic |
|
|
automatic |
|
|
automatic |
|
|
automatic |
Public signatures in email, freemarker, json, context.web, namespace.shiro.realm,
inject, scope.web, security, soap, validation, and the spring packages expose types from these
modules. Require the module in your own descriptor when you use the package that exposes
it. They are deliberately not re-exported: javac treats a requires static transitive
dependency as mandatory when compiling every module that reads org.smallmind.nutsnbolts, so
re-exporting them would force all seven of the affected APIs onto every consumer’s compile
path. shiro-spring is not named by the descriptor because no class in this jar
references it; the shipped realm.xml needs it, and as an automatic module it is resolved
along with Spring.
Packages this module opens.
-
org.smallmind.nutsnbolts.examples, unconditionally. It contains no classes; it carries the shipped Spring XML, property, YAML, and XSD resources, and the open keepsclasspath:org/smallmind/nutsnbolts/examples/…resolvable from other modules. -
org.smallmind.nutsnbolts.jsontojakarta.xml.bind. -
spring,spring.jmx,spring.property,spring.remote,spring.web,security.spring,namespace.shiro.realm.spring, andresource(all underorg.smallmind.nutsnbolts) tospring.coreandspring.beans.
Packages you open to this module. Every ProxyGenerator.createProxy overload takes a
defineInProxiedModule flag that chooses where the proxy class is defined. Each setting
has its own cache of generated classes, with one class per proxied class and
AnnotationFilter. The cache does not keep a proxied class or its class loader reachable,
so classes loaded by a discarded class loader or ModuleLayer can still be unloaded. When
org.smallmind.nutsnbolts is itself the module in a discarded loader or layer, proxying a
longer-lived type, such as a JDK interface, does not keep it loaded either, with one exception:
a false proxy of a class whose loader is neither an ancestor nor a descendant of this
module’s loader keeps this module’s loader reachable for as long as that class.
true-
The proxy class is defined in the class loader, package, and module of the class it proxies. This is the setting the
web-json-scaffoldpolymorphic adapters use. When the proxied class is in a named module, that module must open the class’s package toorg.smallmind.nutsnbolts. The package does not need to be exported, and the module does not need to readorg.smallmind.nutsnbolts. For every type the proxied methods return or declare as thrown, outside the proxied class’s own package, the module must also read the module of that type, and that type’s package must be exported to it. This matters when the proxied class inherits methods from another module that does notrequires transitivethe modules its signatures use. JDK types cannot be proxied this way, because the JDK does not open its packages. false-
The proxy class is defined in the unnamed module of a separate class loader whose parent is the proxied class’s loader, in a package of its own under
org.smallmind.nutsnbolts.reflection.proxy. Each proxy class gets a loader of its own, which is released along with the proxy class. This setting can proxy JDK interfaces, such asjava.util.function.Supplier. When the proxied class is in a named module, that module must export (or open) unconditionally the class’s package and the packages of every type its proxied methods return or declare as thrown. A qualifiedexports … tooropens … tois not enough, because a qualified directive cannot name the unnamed module.
In both settings, every type in the proxied method signatures, parameter types included, must be loadable through the proxied class’s own class loader. This matters only with class loaders that do not delegate to one another, where a superclass or interface from another loader can mention a type the proxied class’s loader cannot see.
Proxy generation needs only the org.objectweb.asm module; ClassInspector also needs
org.objectweb.asm.util. The methods of types in the proxied hierarchy are read from the class
files their loaders provide as resources, so a hidden class, or a class defined from bytes that
its loader does not also provide as a resource, cannot be proxied. JDK types, meaning those
defined by the bootstrap or platform class loader, are read through reflection instead, so a
JDK newer than the ASM release can still be proxied. That choice decides which annotations a
proxy carries; see lang, reflection, apt.
With true:
module com.example.app {
requires org.smallmind.nutsnbolts;
requires org.objectweb.asm;
opens com.example.app.model to org.smallmind.nutsnbolts;
}Otherwise createProxy(…, true) throws ByteCodeManipulationException with The module(…) of
the proxy class(…) must open the package(…) to the module(org.smallmind.nutsnbolts). When
org.smallmind.nutsnbolts is on the classpath, the last module is named unnamed, and only an
unconditional opens satisfies it.
createProxy checks the proxied class and the types in its method signatures before it
defines the proxy class, and throws ByteCodeManipulationException naming the first problem:
-
The proxy class(…) must not be hidden -
The module(…) must export the package(…) of the proxy class(…) unconditionally(false) -
Unable to locate the byte code of class(…), because its class loader does not provide it as a resource -
Unable to load the type(…) in the signature of method(…) through the class loader of the proxy class(…) -
The type(…) returned or thrown by method(…) of the proxy class(…) must be 'public'(false, ortruefor a type outside the proxied class’s package) -
The module(…) of the proxy class(…) must read the module(…) of the type(…) returned or thrown by method(…)(true) -
The module(…) must export the package(…) to the module(…) of the proxy class(…), whose method(…) returns or throws the type(…)(true) -
The module(…) must export the package(…) unconditionally, because method(…) of the proxy class(…) returns or throws the type(…)(false)
Lookups you pass. FieldUtility.getFieldAccessor and getFieldAccessors, and every
Overlay.overlay method, take a MethodHandles.Lookup. They reach fields, getters, setters,
and OverlayNullifierValidator constructors with the access of that lookup’s module, never
with the access of org.smallmind.nutsnbolts. Pass MethodHandles.lookup(), called in the
module whose access should apply. A lookup without full privilege access, such as
MethodHandles.publicLookup(), fails with IllegalArgumentException: The lookup(…) must have
full privilege access, as returned by MethodHandles.lookup().
-
A class in the lookup’s own module needs no directive.
-
A field without a public getter, or without a public setter, is read or written directly. The package declaring it, including a superclass’s package, must be opened to the lookup’s module.
-
A public getter or setter needs its declaring package exported or opened to the lookup’s module.
-
When the lookup’s module does not read the module of a class it reaches, the read edge is added for it, through the lookup. A framework module therefore does not have to
requiresthe modules whose classes it is handed. -
A
finalfield without a setter can be read but not written:FieldAccessor.setthrowsIllegalAccessException: The field(…) of class(…) is 'final' and has no setter. -
A custom
OverlayNullifierValidatoris constructed through its no-argument constructor, which must be accessible to the lookup’s module.
A refused access fails with IllegalAccessException, for example module com.example.app does
not open com.example.app.model to module com.example.framework. Overlay wraps it in an
OverlayException. Opening a package to org.smallmind.nutsnbolts gives these classes no
access, and does not let any other caller reach the package through them.
The accessors for a class are created on the first request from a module and cached for every
later request from that module, including the requests overlay makes. A request from another
module gets accessors created with its own access, or a refusal; it never receives accessors
created for a different module. A failed request is not cached. getFieldAccessors returns a
new array each time, holding the shared, immutable accessors. A FieldAccessor carries the
access of the lookup it was created with, so hand it only to code that should have that access.
The cache does not keep a class or its class loader reachable, so classes in a discarded class
loader or ModuleLayer can still be unloaded. A class from a longer-lived loader, one that is an
ancestor of the lookup’s loader, does not keep the lookup’s module or org.smallmind.nutsnbolts
loaded either. The exception is a class whose loader is neither an ancestor nor a descendant of
the lookup’s loader: that class keeps the lookup’s module, and org.smallmind.nutsnbolts, reachable
for as long as it lives.
To build an accessor from handles you create yourself, pass the field and its getter and setter
handles to the FieldAccessor constructor. Each handle must come straight from a lookup’s
unreflect, unreflectGetter, unreflectSetter, findVirtual, findGetter, or findSetter
method, without asType, bindTo, or other adaptation. A getter handle must read the field or
invoke an instance method that takes no arguments and returns a value. A setter handle must
write the field or invoke an instance method whose one parameter accepts the field’s type,
allowing for boxing. Pass null as the setter for an accessor that cannot write. Any other handle
fails at construction with IllegalArgumentException naming the field and the member the handle
reaches. Failures in getter and setter methods arrive wrapped in InvocationTargetException;
failures of direct field access do not.
FieldAccessor[] fieldAccessors = FieldUtility.getFieldAccessors(MethodHandles.lookup(), Settings.class);
settings.overlay(MethodHandles.lookup(), overrides);Packages you open. Some classes act with the access of org.smallmind.nutsnbolts itself:
-
@LazyField(throughLazyFieldAspect) reads and writes the named field with this module’s access. Open the package declaring the field toorg.smallmind.nutsnbolts, unless the field has a public getter and a public setter. -
BeanUtility,AOPUtility,Getter,Setter, andOffloadingInvocationHandlerinvoke public methods reflectively. The package of the class that declares the method must be exported to this module, or opened to it. When the runtime class of the target is not accessible, as with JDK and library implementation classes,BeanUtilityinvokes the same method as declared by an accessible superclass or interface.
module com.example.app {
requires org.smallmind.nutsnbolts;
opens com.example.app.lazy to org.smallmind.nutsnbolts;
}AnnotationLiteral calls setAccessible on the members of the annotation type it
implements; that type’s package must be exported, or opened to org.smallmind.nutsnbolts.
A small number of cross-cutting concepts show up throughout the package. Understanding them first makes every subpackage easier to read.
- Resource
-
A uniform, read-only abstraction for addressable content. Every
Resourcehas an identifier inscheme:pathform (classpath:config.xml,file:/etc/app.conf,jar:…), and implementations in other SmallMind modules typically consume this interface rather than rawFileorURL. See resource — uniform addressable content. - Context stack
-
A per-type, per-thread stack of objects implementing the
Contextmarker. Pushing a context associates a value with the thread and with every child thread spawned later (the context map is inheritable). Pop balances push. This is how request identity, caller identity, and transaction metadata are propagated through SmallMind services without polluting method signatures. See context — thread-bound context stacks. - Scope
-
The
ScopedValue-backed counterpart to the context stack. AScopeis bound, keyed by concrete class, only for the dynamic extent of the operation passed toScopeFactory.callInScopeorrunInScope. There is no pop to forget, so a scope can not leak past its operation, and bindings are not inherited by child threads — aScopeSnapshotcarries them across a thread boundary explicitly. See scope — ScopedValue-bound scopes. - PropertyExpander
-
A configurable
${…}placeholder engine that consults a map, system properties, and environment variables in a declared order, with optional decryption of values marked as encrypted. This engine backs the SpringPropertyPlaceholderConfigurerin this package and is used stand-alone by modules such asansibleandsparkfor template interpolation. See property — placeholder expansion. - Closeable, idempotent primitives
-
I/O helpers in this package are intentionally closable and safe to close twice.
ByteArrayIOStream,CircularBufferIOStream, and the segmented buffers all treatcloseas a one-way latch, so try-with-resources usage is the norm. - Optional over required dependencies
-
Every Jakarta, Spring, FreeMarker, and Bouncy Castle dependency is optional in the POM. The subpackages that depend on them fail fast at class-load time (via
NoClassDefFoundError) when a consumer exercises a code path whose optional dependency is missing. A consumer that does not use that code path experiences nothing.
Each subpackage below names its entry points, its reason for existing, and a realistic example. The examples use actual class and method names from the repository; they are deliberately short.
Packages: org.smallmind.nutsnbolts.command (CommandLineParser,
OptionSet, CommandLineException) and
org.smallmind.nutsnbolts.command.template (Template, Option,
Argument, ArgumentType, EnumeratedArgument, NoneArgument,
SingleArgument)
Parses String[] args against a Template of options, returning an
OptionSet that callers query by option name or single-character flag.
Supports long options (--verbose), short flags (-v), arguments of
type NONE, SINGLE, MULTIPLE, LIST, and ENUMERATED, optional
child-option dependencies, and an opt-in "undeclared trailing arguments"
mode for positional tokens.
Why it exists. Rolling a CLI parser by hand is a recurring source of
bugs (unclosed quotes, missing argument validation, enumerated-value
typos). This parser is small, has no transitive dependencies, and is
configurable either programmatically via Template/Option objects or
declaratively via the shipped XSD at
src/main/resources/xsd/org/smallmind/nutsnbolts/smallmind-command-1.0.xsd.
Key types.
CommandLineParser-
Static entry point.
parseCommands(Template, String[])rejects any token that is not a declared option; the three-argument overload withallowUndeclared = truecollects unrecognised trailing tokens as remaining arguments. Template-
Declares the set of valid `Option`s. Options can nest other options as dependents; a dependent may only be used when its parent is present.
Option,Argument,ArgumentType,EnumeratedArgument-
The declarative building blocks;
ArgumentTypeis the enum ofNONE,SINGLE,MULTIPLE,LIST,ENUMERATED. OptionSet-
The parsed result.
containsOption(name),getArgument(name),getArguments(name),getRemaining()for undeclared trailing tokens. CommandLineException-
Thrown on unknown options, missing required options, or dependent options used without their parent.
Example.
Template template = new Template("myapp",
new Option("verbose", 'v', false, NoneArgument.instance()),
new Option("input", 'i', true, new SingleArgument("path")), // (1)
new Option("level", 'l', false,
new EnumeratedArgument(new String[] {"low", "medium", "high"}))
);
OptionSet options = CommandLineParser.parseCommands(template, args); // (2)
boolean verbose = options.containsOption("verbose");
String input = options.getArgument("input");
String level = options.containsOption("level") ? options.getArgument("level") : "medium";-
The third argument to
Optionis therequiredflag. The parser throwsCommandLineExceptionif a required option is absent. -
parseCommandsvalidates the entire array before returning. It never partially applies options.
Package: org.smallmind.nutsnbolts.context
Maintains a per-type, per-thread stack of objects implementing the
Context marker. The underlying map is an InheritableThreadLocal, so
a child thread inherits a snapshot (a new LinkedList copy) of the
parent’s stack for every registered context type.
Why it exists. Request identity, caller identity, and other
"ambient" values must travel with a thread without appearing in every
method signature. Java’s plain ThreadLocal handles the single-value
case but loses history; nested push/pop semantics are what most
real services actually need. The ExpectedContexts annotation lets
framework glue verify that required contexts are present at a given
method boundary.
|
Note
|
scope — ScopedValue-bound scopes solves the same problem with a JDK |
Key types.
Context-
Marker interface. Implementations must be identifiable by their concrete class; the class is used as the map key.
ContextFactory-
Static stack operations:
pushContext,popContext,getContext,removeContext,exists,sizeFor, plusimportContextTrace/exportContextTracefor serialising the current thread’s stack across an asynchronous boundary. ExpectedContexts-
Method-level annotation declaring which
Contexttypes must be active when the method runs.ContextFactory.filterContextsOn(method)validates and collects them. With thefilterContextsOn(method, filters…)overload, an expected type counts as satisfied only if it is active and assignable to one of the filter types; the single-argument form filters onContextitself, so every active type qualifies. ContextLifecycleAware-
Optional hook for contexts that need setup or teardown around their stack lifetime.
beforePushruns beforeContextFactory.pushContextadds the context to the stack; if it throws, the context is not pushed.afterPopruns afterContextFactory.popContextremoves it. Only those two methods fire the callbacks:importContextTrace,exportContextTrace,removeContext,clearContextTrace, and the copy a child thread inherits do not. ContextException-
Unchecked, thrown when
ExpectedContextsexpectations are not met. PerApplicationContext-
Holds the per-application data map shared by every thread of one application, keyed by
lang.PerApplicationDataManagerclass, in anInheritableThreadLocal. Constructing one on a thread adopts the map already attached to that thread or creates and attaches a new one;prepareThreadinstalls the instance’s map on the current thread. StaticsetPerApplicationData/getPerApplicationDataread and write the current thread’s map and throwlang.MissingPerApplicationContextExceptionwhen none is attached;setPerApplicationDataIfAbsentstores a value only when the key is empty and returns whichever value the map then holds, so registries that create their backing map on first use do so atomically; the staticisBound()reports whether a map is attached without throwing. The staticwrapExecutordecorates anExecutorso that each task runs with the map attached to the thread that submitted it, captured perexecute(which throwslang.MissingPerApplicationContextExceptionwhen the submitting thread has none); this is the context counterpart of the scope’swrapExecutor, for pools whose threads were created before any context existed.generateCarriercaptures the current map in aContextCarrierfor use on another thread, andwrapThreadFactorywraps aThreadFactoryso the threads it creates start with the current map. A map, once attached, is never detached from its thread; threads created from a bound thread inherit it, whileForkJoinPool.commonPool()workers (and so theCompletableFuture.*Asyncdefaults) inherit nothing.PerApplicationScope(scope — ScopedValue-bound scopes) is theScopedValuecounterpart; the library’s bridging*Managerregistries consult both flavors under the rules in Per-application registries. PerApplicationContextFilter(org.smallmind.nutsnbolts.context.web)-
Servlet filter that installs a shared
PerApplicationContexton every request thread it is mapped to. Construct it with the context instance, optionally withsuppressConnectionClosedException, or leave the context out: the no-arg constructor is the one a container uses for a declared filter, and the(boolean suppressConnectionClosedException)constructor serves an instance registered programmatically that still reads the attribute ininit. In either caseinitreads the context from the servlet context attribute namedPerApplicationContext.class.getName()— published byspring.web.WebContextLoaderListener— and throwslang.MissingPerApplicationContextExceptionwhen none is published. The filter never creates a context of its own.doFiltercallsprepareThreadand then the rest of the chain, discarding"Connection is closed"IOException`s when `suppressConnectionClosedExceptionistrue(defaultfalse); the chaining settersetSuppressConnectionClosedExceptionturns it on for an instance registered programmatically, since the filter reads no init-params. The map stays attached to the thread after the chain returns. Pair it with the context-flavor listener; see servlet container wiring in scope — ScopedValue-bound scopes. Requiresjakarta.servlet.
Example.
public record CallerContext(String userId, String tenantId) implements Context {}
try {
ContextFactory.pushContext(new CallerContext("u-42", "t-7")); // (1)
processRequest();
} finally {
ContextFactory.popContext(CallerContext.class); // (2)
}
// Deep in the call stack — no parameter plumbing:
CallerContext caller = ContextFactory.getContext(CallerContext.class);-
Push into this thread’s stack for the concrete
CallerContextkey. -
Always pop in a
finally. Failing to pop is the single most common bug; the context survives the method and pollutes subsequent work on the same thread.
Package: org.smallmind.nutsnbolts.scope
Binds objects implementing the Scope marker, keyed by concrete class,
for the dynamic extent of an operation. The binding is a JDK
ScopedValue (final since JDK 25), so a scope exists only while the
operation passed to ScopeFactory.callInScope or runInScope is
executing and is unbound automatically when that operation returns or
throws. Entering a scope of a class that is already bound shadows the
outer binding until the inner operation completes, then restores it.
Why it exists. ContextFactory (context — thread-bound context stacks) solves the same
"ambient value" problem with an inheritable thread-local stack, which
carries two costs: a forgotten popContext leaves the value on a
pooled thread indefinitely, and every virtual thread copies the
inheritable map at creation. ScopeFactory removes both by making the
bound extent structural. The trade is that there is no push/pop
surface — the caller wraps the work in a lambda — and bindings are
not inherited by threads the operation starts; cross-thread
propagation is explicit via ScopeSnapshot.
Per-application registries. PerApplicationScope (below) and
context.PerApplicationContext (context — thread-bound context stacks) each hold a
per-application data map keyed by lang.PerApplicationDataManager
class. The scope binds its map only inside run / call and no thread
inherits it; the context attaches its map to the thread for good, and
threads created from a bound thread inherit it (ForkJoinPool.commonPool()
workers do not). The library’s bridging managers — OrmDaoManager,
SessionManager, DataSourceManager, PoolManager,
ClaxonRegistryManager (behind claxon’s Instrument),
SpringPropertyAccessorManager, JsonEntityResourceProxyManager, and
PolymorphicAttributeManager — keep one registry per flavor and follow
three rules:
-
registerwrites to every registry bound on the thread that calls it: the scope flavor when a scope is bound, the context flavor when a context is attached. Under Spring that is the thread running the refresh, so what the refresh thread carries decides where every registration lands. -
Lookups read the scope flavor first and fall back to the context flavor when the scope holds nothing and a context is attached.
-
A thread whose bound registry is empty — a scope no refresh ran in, or a context created after the refresh — resolves nothing, and each accessor reports that in its own way: the
find*methods and theOrmDaoManager,JsonEntityResourceProxyManager,PoolManager, andSpringPropertyAccessorManagergetters returnnull;SessionManager.getSessionandDataSourceManager.getDataSourcethrowORMInitializationException;PolymorphicAttributeManager.getPolymorphicAttributeNamereturns the adapter default; andClaxonRegistryManagermakesInstrument.withreturn anUnpluggedInstrumentationso metrics silently no-op. Those are the results of an empty bound registry. A thread with neither binding throwsMissingPerApplicationContextExceptionfrom every accessor exceptInstrument.with, which returnsUnpluggedInstrumentationthere as well (its underlyingClaxonRegistryManager.getRegistry()returnsnull).
Key types.
Scope-
Marker interface (
Serializable). The concrete class is the binding key. ScopeFactory-
Static entry points.
callInScope/callInScopesreturn the operation’s result and propagate its checked exception type unchanged;runInScope/runInScopestake aRunnable.getScopereturns the innermost binding for a class, ornull.filterScopesOncollects bound scopes assignable to the given filter types and validates anyExpectedScopeson the method.snapshotcaptures the current bindings for another thread;wrapExecutordecorates anExecutorso that each task it receives runs under the bindings of the thread that submitted it;wrapThreadFactorydecorates aThreadFactoryso that every thread it creates runs under the bindings in effect when the factory was wrapped. Passing anullscope, or an array containing one, throwsScopeException; anullor empty array runs the operation with no additional binding. ScopeSnapshot-
Immutable capture of the bindings on the calling thread, returned by
ScopeFactory.snapshot().run/callrebind exactly those scopes for the extent of the operation on whichever thread invokes them. Reusable any number of times; fires no lifecycle callbacks. ScopeLifecycleAware-
Optional hook for scopes that need setup or teardown.
beforeEnterruns on the entering thread before the scope is bound;afterExitruns after the operation completes, normally or by throwing. With several scopes,beforeEnterruns in array order andafterExitin reverse order; abeforeEnterthat throws, or anullelement found later in the array, still triggersafterExitfor the scopes already entered. ExpectedScopes-
Method-level annotation naming the
Scopetypes that must be bound when the method runs.ScopeFactory.filterScopesOn(method, filters…)validates and collects them. An expected type counts as satisfied only if it is bound and assignable to one of the filter types passed in the same call; an expected type outside the filters fails the check even when it is bound. ScopeException-
Unchecked, thrown for an unsatisfied
ExpectedScopesdeclaration or an attempt to bind anullscope. Also thrown byPerApplicationScope.resolvewhen the scope handed to it differs from the scope bound on the calling thread — and so, at construction or startup, by every consumer that accepts aPerApplicationScope(PerApplicationScopeFilter,PerApplicationScopeContextLoaderListener,GrizzlyInitializingBean/JettyInitializingBean, and the pools, transports, and servers of the other modules) when it was given a scope other than the one bound on the thread constructing or starting it — and by the one-argumentPerApplicationScopeContextLoaderListenerwhen a different scope is already published in the servlet context. PerApplicationScope-
The
ScopedValuecounterpart tocontext.PerApplicationContext. Each instance owns a mutable, thread-safe map keyed bylang.PerApplicationDataManagerclass; the instance methodsrun/callbind that map for the extent of an operation, and the staticsetPerApplicationData/getPerApplicationDataread and write whichever map is bound (setPerApplicationDataIfAbsentstores only into an empty key and returns the value then held, the atomic form for registries created on first use). The staticisBound()reports whether any map is bound on the calling thread without throwing, and the instance methodisBoundOnCurrentThread()reports whether the map bound there is this instance’s. Only the binding is scoped — the map is shared, so data stored in onerunis visible in every later or concurrentrunof the same instance and through every carrier taken from it. Constructing an instance binds nothing. The instance methodsboundThreadFactory/boundExecutordecorate aThreadFactoryorExecutorso that every thread created, or task executed, runs inside this scope; they capture nothing and need no binding on the calling thread, which is what separates them from the staticwrapThreadFactory/wrapExecutor. The staticgetBound()returns the instance bound on the calling thread, ornull. The staticresolve(handed)is the rule every consumer that accepts aPerApplicationScope— through a constructor parameter, a fluent setter, or a Spring property — applies exactly once, on the thread that constructs or starts it, storing the result for everything it later binds: a handed scope is returned when nothing is bound on that thread or the bound scope is that same instance; a handed scope that differs from the bound one throwsScopeException;nullreturns the bound scope, ornullwhen nothing is bound, in which case the consumer runs its threads and callbacks with no scope, carrying only whateverPerApplicationContextthey inherit. Because the call is made once, what the constructing or starting thread carries at that moment decides the outcome: a consumer created on a bound thread with no scope handed to it adopts the bound scope even when its threads start later from unbound ones, and a consumer created on an unbound thread — a lazy-init bean first touched from a plain thread, a task executor thread, a background bootstrap — resolvesnullunless a scope is handed to it. A Spring assembly refreshed inside a scope can hold the bound instance as a bean throughfactory-method="getBound"; see holding the scope as a bean. PerApplicationScope.ApplicationCarrier-
Returned by the static
generateCarrier()on a bound thread;run/callrebind the same map on any other thread, any number of times. The staticwrapThreadFactorydecorates aThreadFactoryso every thread it creates runs its whole body inside the carrier. Both throwMissingPerApplicationScopeExceptionwhen called on an unbound thread, so a missing binding fails at wiring time rather than on the first lookup. The staticwrapExecutordecorates anExecutorso each task runs inside a carrier taken from the submitting thread at submission; it throws the same exception fromexecutewhen the submitting thread is unbound. MissingPerApplicationScopeException-
Unchecked, thrown by the static accessors,
generateCarrier,wrapThreadFactory, and theexecuteof awrapExecutorexecutor when no per-application scope is bound. PerApplicationScopeFilter(org.smallmind.nutsnbolts.scope.web)-
Servlet filter that binds a
PerApplicationScopefor the extent ofchain.doFilteron every request it is mapped to. Construct it with the scope instance, optionally withsuppressConnectionClosedException, or use the no-arg constructor for container-declared filters.initsettles the scope throughPerApplicationScope.resolve, in order: the scope given to the constructor, else the servlet context attribute namedPerApplicationScope.class.getName(), else the scope bound on the thread runninginit. It throwsMissingPerApplicationScopeExceptiononly when all three are absent, andScopeExceptionwhen the constructor-supplied or published scope differs from the scope bound on the initializing thread. The filter never creates a scope of its own. The binding ends when the chain returns or throws;AsyncContext.starttasks and work handed to other threads are not bound, while anAsyncContext.dispatchleg is bound again when the filter is mapped for theASYNCdispatcher. WhensuppressConnectionClosedExceptionistrue(defaultfalse), anIOExceptionfrom the chain whose message is exactly"Connection is closed"is discarded instead of rethrown. The chaining settersetSuppressConnectionClosedExceptionturns it on for an instance registered programmatically throughaddFilter(name, instance); the filter reads no init-params, so a container-declared filter cannot enable it. Requiresjakarta.servlet. PerApplicationScopeContextLoaderListener(org.smallmind.nutsnbolts.spring.web)-
Spring
ContextLoaderListenerthat runs the web application context’s refresh and shutdown inside aPerApplicationScopeand publishes that scope under the servlet context attribute the filter reads.contextInitializedsettles the scope in order: the one given to the one-argument constructor, else the one already published in the servlet context, else the one bound on the thread initializing the servlet context (as it is when an embedded server starts from inside an enclosing scope), else a new instance. It throwsScopeExceptionwhen a scope was given to the constructor and a different scope is already published, and, throughPerApplicationScope.resolve, when the given or published scope differs from the scope bound on the initializing thread. The settled scope is published unless it is already the published one.contextDestroyedruns Spring’s shutdown inside the same scope and leaves the attribute published. Requiresspring.web.
Holding the scope as a bean. In a Spring assembly refreshed inside a
scope — under PerApplicationScopeContextLoaderListener, the Tanuki
wrapper with spark.per.application.scope on, or a test’s
scope.run(context::refresh) — declaring PerApplicationScope itself
as a bean creates a second, unbound instance, which every consumer
resolved on the refresh thread rejects with ScopeException. The
assembly holds the enclosing instance instead through the static
factory, with no registration step:
<bean id="perApplicationScope"
class="org.smallmind.nutsnbolts.scope.PerApplicationScope"
factory-method="getBound"/>Spring calls getBound() on the refreshing thread, so the bean is the
scope the refresh runs inside, reachable by name, by type, and through
ref, for code that wants the instance in hand — to build an executor
from its boundThreadFactory, say. The bean must not be lazy-init: a
bean first created from an unbound thread reads nothing. When nothing
encloses the refresh the factory returns null, which Spring keeps as a
null bean: a ref injects null, which a consumer resolves as no scope;
a lookup by type fails with NoSuchBeanDefinitionException; and a lookup
by name returns Spring’s null placeholder rather than throwing.
Servlet container wiring. In a plain servlet container the listener
establishes the binding around Spring’s refresh and the filter
re-establishes it on request threads. A listener and its filter must be
the same flavor: PerApplicationContextFilter declared with
PerApplicationScopeContextLoaderListener fails at init with
MissingPerApplicationContextException, and PerApplicationScopeFilter
declared with WebContextLoaderListener fails at init with
MissingPerApplicationScopeException unless the container initializes
it on a thread that is itself bound to a scope. In an embedded server
started from inside a scope, a no-arg listener and filter with nothing
published ahead of them both adopt that bound scope. Declare either
filter with async-supported and map it for the REQUEST and ASYNC
dispatchers: a filter in an async servlet’s chain that is not
async-supported makes startAsync throw IllegalStateException, and an
ASYNC dispatch leg may run on a thread that never served the original
request, so it needs the filter to establish the binding again.
<listener>
<listener-class>org.smallmind.nutsnbolts.spring.web.PerApplicationScopeContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>per-application-scope</filter-name>
<filter-class>org.smallmind.nutsnbolts.scope.web.PerApplicationScopeFilter</filter-class>
<async-supported>true</async-supported>
</filter>
<filter-mapping>
<filter-name>per-application-scope</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>ASYNC</dispatcher>
</filter-mapping><listener>
<listener-class>org.smallmind.nutsnbolts.spring.web.WebContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>per-application-context</filter-name>
<filter-class>org.smallmind.nutsnbolts.context.web.PerApplicationContextFilter</filter-class>
<async-supported>true</async-supported>
</filter>
<filter-mapping>
<filter-name>per-application-context</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>ASYNC</dispatcher>
</filter-mapping>suppressConnectionClosedException is not reachable from web.xml;
register the filter instance programmatically (addFilter(name,
instance)) to set it.
Example — ambient value.
public record CallerScope(String userId, String tenantId) implements Scope {}
Response response = ScopeFactory.callInScope(
new CallerScope("u-42", "t-7"), () -> processRequest()); // (1)
// Deep in the call stack — no parameter plumbing:
CallerScope caller = ScopeFactory.getScope(CallerScope.class); // (2)
// Handing work to another thread:
ScopeSnapshot snapshot = ScopeFactory.snapshot(); // (3)
executor.submit(() -> snapshot.run(() -> processInBackground()));-
The scope is bound for exactly the duration of
processRequest(). IfprocessRequestthrows a checked exception,callInScopethrows that same type; there is nothing to pop in afinally. -
Returns the innermost bound
CallerScope, ornullwhen called outside any entry. -
Bindings do not follow the task to the executor thread on their own. The snapshot rebinds them for the extent of the inner lambda.
Example — per-application scope.
PerApplicationScope applicationScope = new PerApplicationScope(); // (1)
applicationScope.run(() -> {
PerApplicationScope.setPerApplicationData(CacheManager.class, cache); // (2)
ThreadFactory workers = PerApplicationScope.wrapThreadFactory(Thread::new); // (3)
executor = Executors.newFixedThreadPool(4, workers);
});
// Bind the same scope on each servlet request:
Filter perApplicationFilter = new PerApplicationScopeFilter(applicationScope); // (4)-
The instance owns the map. Construction binds nothing to the current thread.
-
Writes into the bound map. Because the map is shared, this value is visible in every later
run/callonapplicationScopeand on every thread the wrapped factory creates. -
Must be called on a bound thread; the factory carries the binding for the whole life of each thread it creates. Pools built from an unwrapped factory see no scope binding: a direct
PerApplicationScoperead fails withMissingPerApplicationScopeException, and a lookup through one of the library’s bridging*Managerclasses falls back to whateverPerApplicationContextthe thread inherited, or fails withMissingPerApplicationContextExceptionwhen there is none (see Per-application registries). -
PerApplicationScopeFilterbinds the scope for the extent ofchain.doFilteron every request.ScopedValue.CallableOpcarries a single checked exception type, so the filter declaresX = Exceptionand rethrowsIOException,ServletException, and runtime exceptions unchanged.
Package: org.smallmind.nutsnbolts.resource
A small interface — Resource — that exposes a scheme, a path, an
identifier, and an InputStream, plus concrete implementations for
file:, classpath:, jar:, and URL-backed resources, and a
ResourceParser that constructs them from identifier strings of the
form scheme:path.
Why it exists. Configuration, templates, and data files come from
multiple places: filesystem paths, classpath JAR entries, deployment
overlays, remote URLs. Callers should not special-case each one. This
abstraction keeps Resource usage uniform throughout the rest of the
SmallMind codebase, and combined with ResourceFactory it integrates
cleanly with Spring as a FactoryBean<Resource>.
Key types.
Resource-
The interface.
getIdentifier(),getScheme(),getPath(), andgetInputStream(). The input stream may returnnullif the backing store does not locate the content (rather than throwing), and the scheme is suitable as a map key. ResourceParser,ResourceGenerator-
Parses
scheme:pathstrings intoResourceinstances. AResourceGeneratorknows which schemes it can produce; the parser maps each scheme to exactly one generator. ResourceFactory-
A Spring
FactoryBean<Resource>that reads anameproperty (a resource identifier string) and vends the parsedResourceas a singleton. FileResource,ClasspathResource,JarResource-
Concrete implementations. Instantiate directly when you know the backing store; otherwise go through the parser.
ResourceException-
Thrown when a resource cannot be opened or parsed.
Example.
ResourceParser parser = new ResourceParser(new ResourceTypeResourceGenerator());
Resource cfg = parser.parseResource("classpath:config/app.yml"); // (1)
try (InputStream in = cfg.getInputStream()) {
// ... load properties
}-
Or
file:/etc/app/app.yml, orjar:…. The rest of the code does not change.
Package: org.smallmind.nutsnbolts.property
PropertyExpander resolves ${…} (or a custom delimiter) placeholders
in a string by consulting a caller-supplied map, system properties, and
environment variables, in a declared order. It detects circular
references, tolerates nested placeholders, and supports optional
decryption of values via a pluggable Decryptor wrapped in a
PropertyClosure.
Why it exists. Externalised configuration often has placeholders. Some values are encrypted at rest; some must be resolved differently when a system property shadows a file value. A single expander with explicit resolution order, optional decryption, and strict-vs-tolerant behaviour is simpler to reason about than assembling one ad hoc per application.
Key types.
PropertyExpander-
Entry point. Construct with a
PropertyClosure, anignoreUnresolvablePropertiesflag, aSystemPropertyMode(OVERRIDEorFALLBACK), and asearchSystemEnvironmentflag. Callexpand(String)orexpand(String, Map). PropertyClosure-
Delimiter configuration (default
${/}) plus an optionalDecryptorthat is invoked when a placeholder value carries an encryption marker. PropertyExpanderException-
Unresolvable placeholder, unclosed prefix, or circular reference.
SystemPropertyMode-
Enum with
OVERRIDE(system properties take precedence over the caller map) andFALLBACK(system properties are only consulted when the caller map lacks the key).
Example.
PropertyExpander expander = new PropertyExpander(
new PropertyClosure(), // default ${...} delimiter
false, // strict: throw on unresolved
SystemPropertyMode.FALLBACK, // caller map wins
true // also consult environment
);
Map<String, Object> ctx = Map.of("service", "api", "env", "prod");
String url = expander.expand("https://${service}.${env}.example.com"); // (1)-
Placeholders are resolved left-to-right; nested placeholders such as
${prefix.${region}}are supported. Unknown keys throw becauseignoreUnresolvablePropertiesisfalse.
Package: org.smallmind.nutsnbolts.io
Segmented in-memory streams and buffers that outperform
ByteArrayOutputStream for large payloads, a circular buffer for
bounded producer/consumer queues, and path utilities for recursive
copy/configuration.
Why it exists. ByteArrayOutputStream is a single contiguous byte
array; writing a 100 MB payload means the backing array reallocates
and copies many times. The segmented ByteArrayIOBuffer grows by
appending fixed-size segments instead, avoiding quadratic
reallocation. ByteArrayIOStream additionally lets the reader and
the writer advance independently against the same buffer.
Key types.
ByteArrayIOStream-
A segmented in-memory stream with separate
ByteArrayInputStreamandByteArrayOutputStreamviews. Constructors allow choosing the segment size (default 1 024 bytes) or reusing an existingByteArrayIOBuffer.close()is a one-way latch that poisons both views. ByteArrayIOBuffer-
The underlying segmented buffer. Useful on its own when you need reference sharing between two
ByteArrayIOStreaminstances. CircularBuffer,CircularBufferIOStream-
Fixed-size ring buffer for bounded producer/consumer patterns, and the stream view over it.
CloseListener,CloseEvent,CloseableProxyFactory-
Callback mechanism to observe
close()on resources whose lifecycle is managed elsewhere.
ByteBufferInputStream, MultiOutputStream, MarkableInputStream,
ReaderInputStream::
InputStream view over a ByteBuffer’s remaining bytes, an
`OutputStream that fans every write out to a fixed array of
delegate streams, a wrapper that adds mark / reset support
to any InputStream that doesn’t natively offer it, and the
inverse of java.io.InputStreamReader — encoding a Reader’s
characters into bytes as they are consumed, via a `CharsetEncoder.
FileUtility, PathUtility, CopyTreeConfigurationBuilder,
DeleteTreeConfigurationBuilder::
Recursive tree copy, recursive delete (with optional
DirectoryNotEmptyException propagation), isDirectoryEmpty, and
builders for copy/delete configuration including per-path filters
and directory-creation attributes.
RegExTranslator, ExtensionFileFilter, WildcardFileNameFileFilter,
WildcardFileNamePathFilter, PathFilter, TimeFilter::
Glob-to-regex translation (where and ? do not cross /,
while * does), file/path filters that consume those patterns,
and a PathFilter that accepts paths whose last-modified time
satisfies a time.TimeArithmetic predicate.
Example.
try (ByteArrayIOStream pipe = new ByteArrayIOStream(8 * 1024)) {
OutputStream out = pipe.asOutputStream(); // (1)
out.write("hello".getBytes(StandardCharsets.UTF_8));
InputStream in = pipe.asInputStream(); // (2)
byte[] readBack = in.readAllBytes();
}-
The output view and the input view share the underlying segmented buffer; there is no copy.
-
The input view maintains its own read cursor and supports mark/reset.
Package: org.smallmind.nutsnbolts.csv
CSVParser reads a stream line-by-line, emits startDocument, one
handleFields(String[]) per record, and endDocument to a
CSVLineHandler. The low-level CSVReader handles quoting, embedded
delimiters, multi-line quoted fields, and "" as the escape for a
literal quote inside a quoted field. Optional flags for "skip header"
and "trim fields".
Why it exists. CSV is ubiquitous but error-prone (quoted fields containing commas, embedded newlines, escape characters). An event-driven handler model processes arbitrarily large files without materialising them in memory.
Example.
CSVParser parser = new CSVParser();
parser.setSkipHeader(true); // (1)
parser.setTrimFields(true);
parser.setLineHandler(new CSVLineHandler() {
@Override public void startDocument() {}
@Override public void handleFields(String[] fields) {
// fields[0], fields[1], ...
}
@Override public void endDocument() {}
});
parser.parse(Files.newInputStream(Paths.get("data.csv")));-
Skip the header row. Otherwise the first
handleFieldscall delivers the column titles.
Packages: org.smallmind.nutsnbolts.xml, org.smallmind.nutsnbolts.json
xml provides DOM serialisation, XML escaping, and pluggable
`ProtocolResolver`s for custom URI schemes during SAX/DOM parsing
(useful for resolving DTDs and XSDs without hitting the network).
json provides JAXB XmlAdapter`s for types that JAXB does not
marshal out of the box: `LocalDateTime, ZonedDateTime, Currency,
Timestamp, enums (via a generic adapter pattern), and the
BinaryData wrapper for encoded and encrypted byte payloads.
Encryption.AES is AES/GCM with a random IV per call; the stored
bytes are the 12-byte IV followed by the ciphertext and tag, and a
wrong key or altered payload fails decryption. The
shared SortDirection enum (ASC / DESC) and its companion
SortDirectionEnumXmlAdapter (which marshals the enum constants in
lowercase) also live here so query and persistence layers can use one
on-the-wire vocabulary.
Why they exist. Java’s XML stack is low-level: serialising a DOM
back to a string is a half-dozen lines every time, and XML External
Entity (XXE) protection requires explicit entity resolvers. Meanwhile,
JAXB’s default marshaling does not cover java.time or
java.util.Currency, so every schema ends up hand-rolling adapters.
These two subpackages hold the shared implementations.
Example — DOM to string.
String xml = XMLUtility.toString(document, true); // (1)-
Indents using three spaces per nesting level when the boolean flag is
true; the single-argument overload emits an unindented form.XMLUtility.encode(String)is the quick-escape for embedding text in XML content (it replaces&,<, and>).
Example — JAXB adapter on a field.
@XmlElement
@XmlJavaTypeAdapter(ZonedDateTimeXmlAdapter.class)
private ZonedDateTime createdAt;Package: org.smallmind.nutsnbolts.zip
CompressionType is an enum with two constants (JAR, ZIP) and
three methods each (getInputStream, getOutputStream, getEntry),
plus compress/explode/walk helpers that work against either format.
Why it exists. ZIP and JAR share a wire format but expose different
Java types (ZipOutputStream vs JarOutputStream, ZipEntry vs
JarEntry). Two enum constants with per-constant overrides give
callers one API.
Example.
CompressionType.JAR.compress(
Paths.get("build/classes"),
Paths.get("build/artifact.jar")
);
CompressionType.ZIP.walk(Paths.get("bundle.zip"), entry -> {
// inspect or read each entry
});Package: org.smallmind.nutsnbolts.freemarker
ClassPathTemplateLoader, FileSystemTemplateLoader, and
ResourceTemplateLoader plug into FreeMarker’s TemplateLoader
contract so templates can come from the classpath, a filesystem
path, or a SmallMind Resource. The matching *TemplateSource
classes wrap the underlying handle (input stream, file path, or
Resource) and are what the loader hands back to FreeMarker on each
findTemplateSource call.
Why it exists. FreeMarker ships loaders, but they assume certain deployment layouts. A classpath loader that searches with the context classloader, respects JAR entries, and caches last-modified times is a routine need.
Key constructors.
ClassPathTemplateLoader-
Three constructor shapes: no-argument (uses the context classloader and absolute resource names), single-
ClassLoader(custom classloader, absolute names), or single-Class/Class + boolean relative. Withrelative = truethe loader prefixes every requested name with the anchor class’s package path, so a template colocated with its consumer can be loaded by its short name. FileSystemTemplateLoader-
Either no-argument (template names are treated as absolute file paths, with a leading slash inserted because FreeMarker strips them as a security measure) or with a base
Paththat template names are resolved against.setBasePathswitches the root at runtime.
Package: org.smallmind.nutsnbolts.email
Postman constructs Jakarta Mail Session`s over SMTP or SMTPS, with
or without authentication, and transmits `Mail descriptors.
FreeMarker bodies are supported out of the box: passing a
non-null HashMap<String, Object> to
Postman.send(Mail, HashMap) compiles the message body as a
FreeMarker template and caches the compiled template by the
SHA-256 of the source text.
Why it exists. Jakarta Mail is a decade of verbose boilerplate
per message. Mail is a mutable value object for addressing,
subject, body (String or Reader), plaintext/HTML flag, and
attachments; Postman turns it into a MimeMessage and sends it.
Key types.
Postman-
Configured with host, port,
Authentication, and a "secure" flag that selects SMTPS (STARTTLS).send(Mail)orsend(Mail, HashMap<String, Object>)for FreeMarker interpolation. Mail-
Addressing, subject, body, attachments. Multiple constructors for common shapes; setters for everything else.
setHtml(true)emitstext/html. Authentication,AuthType-
Authentication descriptor and the enum of supported strategies. Use the shared
Authentication.NONEconstant or construct via the no-argument constructor and populatesetType(AuthType)/setData(String[]). Protocol-
SMTP/SMTPS. Used internally byPostmanto build theSession. MailDeliveryException-
Wraps any construction or transport failure.
Example.
Authentication auth = new Authentication();
auth.setType(AuthType.LOGIN);
auth.setData(new String[] {"app@example.com", "secret"});
Postman postman = new Postman(
"smtp.example.com", 587,
auth,
true // (1)
);
Mail mail = new Mail(
"app@example.com",
"alerts@example.com",
"Build ${buildId} failed on ${host}" // (2)
);
mail.setSubject("CI failure");
HashMap<String, Object> model = new HashMap<>(); // (3)
model.put("buildId", "4217");
model.put("host", "ci-3");
postman.send(mail, model);-
STARTTLS/SMTPS.
-
Body is a FreeMarker template because the interpolation map in
sendis non-null. -
Compiled template is cached by SHA-256 of the body text; repeated sends of the same template recompile only once.
Packages: org.smallmind.nutsnbolts.http,
org.smallmind.nutsnbolts.net, org.smallmind.nutsnbolts.ntp
http wraps HttpURLConnection for simple GET/PUT/POST/DELETE cases
(HttpTransmitter, HttpPipe, HttpMethod) and provides the common
codec utilities used during HTTP plumbing — Base64Codec (standard,
URL-safe, and custom-alphabet variants), URLCodec (RFC-3986
percent-encoding with optional +-for-space), HTTPCodec for
application/x-www-form-urlencoded query strings, and HTMLUtility
which converts newlines to <br> and renders Throwable stack traces
as HTML. For escaping & / < / > see XMLUtility.encode in the
xml package.
net contains InetAddressComparator, which orders IP addresses by
their byte representation rather than string-wise (lexicographic
ordering puts 10.0.0.1 before 2.0.0.1).
ntp has one class, NTPTime, that queries NTP servers and returns
the computed clock offset in milliseconds. Use it to detect local
clock skew before making time-sensitive decisions.
Example — NTP offset.
NTPTime ntp = new NTPTime(new String[] {"pool.ntp.org", "time.google.com"});
long offsetMillis = ntp.getOffset(5_000); // (1)-
Five-second timeout. Throws
IOExceptionon unreachable servers.
Packages: org.smallmind.nutsnbolts.security,
org.smallmind.nutsnbolts.ssl
security is a convenience layer over JCE with type-safe algorithm
enums. EncryptionUtility provides static methods for hashing,
symmetric and asymmetric signing/verification, symmetric encryption
and decryption, key-pair generation, and serialisation via KeyRep.
AsymmetricKeyGenerator, CertificateUtility, and the x509 /
kms subpackages handle higher-level key-management scenarios —
these require Bouncy Castle on the classpath and, in some cases,
the provider registered.
ssl provides KeyStoreUtility, TrustManagerUtility, and a set of
test-only permissive implementations — NaiveTrustManager,
NaiveHostNameVerifier, NaiveSSLSocketFactory — for cases where TLS
must be short-circuited in an isolated test environment.
Why they exist. JCE boilerplate is noisy and easy to get subtly
wrong (wrong cipher mode, missing padding, missing IV). Enum-driven
algorithm selection (HashAlgorithm.SHA_256,
SymmetricSigningAlgorithm., AsymmetricSigningAlgorithm.)
collapses the typo surface, and SHA-256 in one line instead of five
is why this utility exists.
Key types.
EncryptionUtility-
Static:
hash,sign,verify,encrypt,decrypt,generateKeyPair,serializeKey,deserializeKey, and helpers likeconvertToBlockfor PEM-style line wrapping. HashAlgorithm-
Enum of supported message digests (
MD5,SHA_1,SHA_256,SHA_512). HexCodec-
Lowercase hexadecimal encoding (with zero-padding for byte values below
0x10) and decoding (accepting both upper and lower case, rejecting odd-length and non-hex input). Used bySnowflakeIdand available standalone. SymmetricAlgorithm,AsymmetricAlgorithm-
Enums for cipher selection.
SymmetricSigningAlgorithm,AsymmetricSigningAlgorithm-
Interfaces that concrete algorithm enums implement.
HMACSigningAlgorithm,ECDSASigningAlgorithm,EdDSASigningAlgorithm,RSASigningAlgorithm-
Enum implementations providing the signing algorithm constants.
HMACSigningAlgorithm.HMAC_SHA_256is the one callers reach for most often.EdDSASigningAlgorithm.ED_DSAmaps to the JCAEdDSAsignature, which selects the Edwards curve from the supplied key. AsymmetricKeyGenerator-
Generates RSA/EC key pairs;
AsymmetricKeySpecandAsymmetricKeyTypedescribe the requested shape. CertificateUtility-
X.509 certificate helpers (requires Bouncy Castle).
SecurityProviderInitializingBean-
Spring
InitializingBeanthat registers aSecurityProviderwith the JVM during context startup. KeyStoreUtility,TrustManagerUtility-
Build
KeyStore,KeyManagerFactory, andTrustManagerFactoryinstances from configured material. NaiveTrustManager,NaiveHostNameVerifier,NaiveSSLSocketFactory-
Skip certificate and hostname validation. Test-only.
|
Important
|
|
Example — SHA-256.
byte[] digest = EncryptionUtility.hash(
HashAlgorithm.SHA_256,
payload.getBytes(StandardCharsets.UTF_8)
);Example — HMAC sign/verify.
byte[] mac = EncryptionUtility.sign(
HMACSigningAlgorithm.HMAC_SHA_256, sharedKey, message
);
boolean ok = EncryptionUtility.verify(
HMACSigningAlgorithm.HMAC_SHA_256, sharedKey, message, mac
);Package: org.smallmind.nutsnbolts.time
TimeUtility converts legacy types (Date, Calendar, epoch
milliseconds, LocalDateTime) to ZonedDateTime and parses/formats
ISO-8601 strings in all four common shapes (date-only, local, offset,
zoned) using the corresponding java.time.format.DateTimeFormatter,
auto-detecting the shape from the input.
Stint is an immutable duration value (a non-negative long paired
with a TimeUnit); StintUtility.convertToDouble converts between
units with sub-unit precision preserved when going from finer to
coarser units. TimeArithmetic pairs a reference ZonedDateTime with
a TimeOperation (BEFORE, BEFORE_OR_ON, ON_OR_AFTER, AFTER)
to test arbitrary Instant values against a single reference point —
used by io.TimeFilter for filesystem tree walks. Day and Month
are enums; CalendarUtility provides integer-driven calendar
arithmetic (days in month, day of week via Zeller’s congruence,
simplified % 4 leap-year rule).
Why it exists. Java’s Date → java.time migration is only mostly
done in real codebases. A single utility that turns any legacy value
into a ZonedDateTime — and back — cuts down the conversion boilerplate
dramatically.
Example.
ZonedDateTime now = TimeUtility.fromMilliseconds(System.currentTimeMillis());
ZonedDateTime parsed = TimeUtility.parse("2026-04-21T12:00:00Z");
String iso = TimeUtility.format(now);Package: org.smallmind.nutsnbolts.retry
Retry.execute(retryCall, retries, delay, exponential) runs the
supplied RetryCall on a fresh thread, joins it, and repeats up to
retries additional attempts with either a flat delay or delay *
attemptNumber. Returns true on success.
Why it exists. The code path is short but error-prone. Encapsulating
retry-with-back-off once avoids bespoke loops. Running each attempt
on a dedicated thread keeps a pathological blocking RetryCall from
spilling delay time onto the caller.
Example.
boolean ok = Retry.execute(
() -> { httpClient.ping("https://api.example.com/health"); }, // (1)
3, // retries
1_000L, // 1-second base delay
true // exponential: 1s, 2s, 3s between attempts
);-
RetryCallis a functional interface that may throwThrowable.
Package: org.smallmind.nutsnbolts.validation
Custom Jakarta Bean Validation constraints plus their
ConstraintValidator implementations: @Email (regex),
@NotBlank, @NotEmpty, @GreaterThan, @LowerBound. Paired with
FormattedValidationException for error messages built from a
format string and varargs.
Why it exists. The standard Jakarta Validation annotations cover
@NotNull, @Size, @Min/@Max, etc. — but a pragmatic set of
additions (email, numeric lower bound, greater-than comparisons,
blank/empty strings) is often welcome.
Example.
public record CreateUserRequest(
@Email String email,
@NotBlank String displayName,
@GreaterThan(0) int credits
) {}Packages: org.smallmind.nutsnbolts.lang,
org.smallmind.nutsnbolts.reflection,
org.smallmind.nutsnbolts.apt
lang contains classloader infrastructure, exception helpers, and
the AnnotationLiteral proxy factory for synthesising annotation
instances at runtime:
GatingClassLoader-
A
SecureClassLoaderthat delegates class resolution through a chain ofClassGate`s. Gates decide which resources a given child loader may see; a `ClasspathClassGateaccepts a list of filesystem or JAR paths. Optional grace-period logic compares last-modified timestamps to detect stale class definitions for reloadable extensions.
ClassGate, ClasspathClassGate, ClassGateTicket,
ClassStreamTicket, ClassVerifier::
Gate SPI, the classpath-based default, and a helper that verifies a
loaded class is signed with a certificate trusted by a given keystore.
ClassLoaderAwareCache-
A concurrent cache partitioned by the class that a constructor-supplied function maps each key to. The cache never keeps that class, or its class loader, reachable, so a partition is released when its class is unloaded. A value that references classes from another class loader keeps that loader reachable for as long as the key’s class is.
AllPermissionsClassLoader-
A trivial child loader that grants every permission; audit-only.
AnnotationLiteral-
Runtime factory for synthetic annotation proxies — useful for programmatic service discovery and metadata injection.
FormattedException/FormattedRuntimeException-
Checked and unchecked exception base classes whose detail messages are built via
String.format(message, args). Subclasses across the repository (such asCSVParseException,SpreadParserException,DotNotationException,MutationException) inherit this pattern so callers can writethrow new FooException("Bad id(%s)", id)instead of pre-formatting. WrappedException-
Adapts a checked exception into a
RuntimeExceptionfor propagation through functional APIs, with aconvert(Class<E>)accessor that casts the wrapped cause back to its original type. UnknownSwitchCaseException-
Convenience throw for default branches of exhaustive switches, naming the unhandled case.
StackTraceAccumulator/ArrayStackTraceAccumulator/StackTraceUtility-
Pluggable sink for stack-trace lines plus a static
obtainStackTraceAsString(Throwable)helper used byhttp.HTMLUtility.convertThrowableand elsewhere.
reflection provides field introspection (FieldAccessor,
FieldUtility, and the Overlay mixin built on them, all of which work with the access of a
MethodHandles.Lookup you pass; see Module Path), annotation filtering
(AnnotationFilter), bytecode
debugging via ASM (ClassInspector.trace, .asmify), ASM-generated
subclass and interface proxies that route every public method through an
InvocationHandler (ProxyGenerator; see Module Path for
the opens it needs), and getter matching. A proxy also routes the methods of
superinterfaces, the default methods a proxied class inherits from its interfaces,
and hashCode, equals, and toString. A null handler makes every method return
null, false, or zero. An exception thrown by the handler propagates unchanged when
it is unchecked or declared by the method, and arrives wrapped in
UndeclaredThrowableException otherwise. OffloadingInvocationHandler rethrows
whatever the target method throws.
Each proxy method carries copies of the method and parameter annotations of one declaration of
the method it proxies, less any that the AnnotationFilter passed to createProxy excludes.
That declaration is the first one found by searching the proxied class, then its superclasses,
then its interfaces, so the annotations on an overriding method replace those on the method it
overrides. Annotations on the proxied type itself are never copied.
Annotations on methods declared by JDK types, meaning types defined by the bootstrap or platform
class loader, are not copied, whatever the filter. A proxy method whose declaration comes from a
JDK type, such as get() on a proxy of java.util.function.Supplier, or a JDK superclass method
that your class inherits without overriding it, carries no annotations. To give such a method
annotations, override or redeclare it in your own class or interface and annotate the
declaration there. JDK modules that the application class loader defines, such as
jdk.compiler, do not count as JDK types here, and their annotations are copied.
apt exposes AptUtility, a small set of methods for reading
AnnotationMirror values from the compile-time annotation-processor
environment. Used by SmallMind’s own annotation processors.
Example — gated classloader for a plugin.
ClassGate gate = new ClasspathClassGate("plugins/acme-extension.jar");
GatingClassLoader loader = new GatingClassLoader(
Thread.currentThread().getContextClassLoader(),
0, // (1)
gate
);
Class<?> entry = loader.loadClass("com.acme.ExtensionEntry");
// ... reflectively invoke an extension contract-
Grace period in seconds; a negative value disables staleness checking entirely.
Package: org.smallmind.nutsnbolts.layout
A three-pass (minimum / preferred / maximum) measurement layout engine
with serial and parallel boxes, grow/shrink constraints,
alignment, justification, gaps, and bias (which axis is the "main"
one). Written without any specific GUI toolkit in mind — it operates
over the generic ParaboxElement<T> wrapper that a concrete toolkit
binds to its component type.
Why it exists. Layout code in Swing/JavaFX/web is the same math each
time: resolve minimum sizes bottom-up, spread surplus based on grow
weights, resolve alignment on the cross axis. Factoring that math
into a toolkit-agnostic engine lets SmallMind’s javafx and desktop
modules share a single implementation.
Key types.
ParaboxLayout-
The top-level layout coordinator. Constructed around a
ParaboxContaineradapter for the host GUI toolkit. ProducesSerialBoxandParallelBoxinstances viaserialBox(…)andparallelBox(…)factory methods and exposes the horizontal and vertical root boxes viasetHorizontalBox/setVerticalBox. Box<B>-
Abstract base for child boxes. Subclasses implement
doLayout,calculateMinimumMeasurement,calculatePreferredMeasurement,calculateMaximumMeasurement. SerialBox,ParallelBox-
The two concrete box types. Serial arranges children along the main axis; parallel stacks children on top of each other against a shared cross axis.
ParaboxContainer,ParaboxPlatform-
Adapters the host toolkit implements so the engine can ask it for child measurements and apply computed positions.
ParaboxElement<T>,ComponentParaboxElement,BoxParaboxElement-
Wraps a toolkit component or a nested
Boxas a child of a layout box. Concrete toolkits subclassComponentParaboxElementto adapt their widget type. Constraint-
Captures the grow and shrink weights for a child. Shared factories are
Constraint.immutable()(rigid),Constraint.expand()(grow only),Constraint.contract()(shrink only), andConstraint.stretch()(both). UseConstraint.create()for a mutable variant, ornew Constraint(grow, shrink)for explicit weights. Bias-
HORIZONTALorVERTICAL. Drives which axis each calculation runs on.
Alignment, Justification, Flow, Gap, Dimensionality,
Perimeter, LayoutTailor::
Supporting types.
Sketch.
ParaboxLayout layout = new ParaboxLayout(container); // (1)
SerialBox horizontal = layout.serialBox()
.add(labelElement, Constraint.immutable())
.add(inputElement, Constraint.stretch())
.add(buttonElement, Constraint.immutable());
SerialBox vertical = layout.serialBox()
.add(headerElement, Constraint.immutable())
.add(bodyElement, Constraint.expand());
layout.setHorizontalBox(horizontal);
layout.setVerticalBox(vertical);-
containeris aParaboxContainersupplied by the host toolkit (e.g. a Swing or JavaFX adapter).
Package: org.smallmind.nutsnbolts.spring
Spring-specific extensions built on the rest of this module.
PropertyPlaceholderConfigurer-
A
BeanFactoryPostProcessorthat runs the nutsnboltsPropertyExpanderover Spring bean definitions during context initialisation — the point of integration between this module’s placeholder engine and Spring’s bean lifecycle. PropertyConfiguration,PropertyPlaceholderStringValueResolver-
Supporting types for the above.
ResourceConverter-
A Spring
Converterthat turns aStringidentifier into a nutsnboltsResource. Enables@Value("classpath:config.xml")style injection intoResource-typed bean properties. ExtensionLoader<E>-
Loads a Spring XML context from a working directory, optionally installing a
GatingClassLoaderso the loaded extension sees a restricted classpath. Used by services that support runtime extension packs. ExtensionInstance-
Interface that an extension’s "root bean" should implement so the loader can report a coherent handle back to the host.
SpringPropertyAccessorContextManager,SpringPropertyAccessorScopeManager-
Static holders for the application’s
SpringPropertyAccessor, keyed throughlang.PerApplicationDataManager. The context flavor stores it incontext.PerApplicationContext. The scope flavor has the sameregister/getSpringPropertyAccessorAPI resolved throughPerApplicationScope(see scope) and throwsMissingPerApplicationScopeExceptionon an unbound thread. The two holders are unrelated.SpringPropertyAccessorManagerbridges them under the rules in Per-application registries:registerwrites to every registry bound on the calling thread, andgetSpringPropertyAccessorreads the scope flavor first, falling back to the context flavor when the scope holds nothing and a context is attached; a thread with neither bound fails withMissingPerApplicationContextException.PropertyPlaceholderConfigurerregisters through the bridging manager, and the dynamic initializing beans read through it. WebContextLoaderListener,PerApplicationScopeContextLoaderListener(spring.web)-
ContextLoaderListenerextensions for servlet deployments. The first attaches acontext.PerApplicationContextmap to the refresh thread before Spring’s refresh — so library registrations made during the refresh land in it — and publishes it under the servlet context attributePerApplicationContextFilterreads. When that attribute is already published, the listener attaches the published map to the refresh thread (prepareThread), so the registrations land in the map the filter serves; otherwise it constructs a context, adopting any map already attached to the thread, and publishes it.contextDestroyedattaches the published map to the destroying thread before Spring’s shutdown, so shutdown-time lookups resolve even when the container destroys on a thread other than the one that refreshed. That adoption is a deployment constraint: a container that deploys several webapps sharing one copy of thenutsnboltsclasses and initializes them on one thread lets the second webapp adopt the first’s map, and the two then share one registry. Give each webapp its own copy inWEB-INF/libto keep them apart. The second listener runs the refresh and shutdown inside aPerApplicationScopeand publishes that scope forPerApplicationScopeFilter; the scope is the one handed to its constructor, else the one already published, else the one bound on the initializing thread, else a new instance, and it throwsScopeExceptionwhen the handed or published scope differs from the bound one (see scope). A listener and its filter must be the same flavor; see servlet container wiring. The Jersey module’sExposedWebContextLoaderListenerandExposedPerApplicationScopeContextLoaderListenerextend the two with the same flavor rules and filter pairing, and additionally expose the refreshed context (see WEB.adoc). All four requirespring.webandjakarta.servlet.
Three Spring XML fragments ship alongside in
src/main/resources/spring/org/smallmind/nutsnbolts/:
jmx.xml, realm.xml, and rmi.xml. These are ready-to-import
<import resource="classpath:org/smallmind/nutsnbolts/jmx.xml"/>
snippets for common infrastructure.
Package: org.smallmind.nutsnbolts.util
A toolkit of small, general-purpose utilities. The ones a consumer is most likely to reach for:
Bag<E>/HashBag<E>-
A multiset collection with duplicate counting. Adds and removes in multiples.
BloomFilter-
Space-efficient probabilistic set (false positives possible, no false negatives).
LRUMap<K,V>-
LinkedHashMap-backed bounded cache; insertion-order eviction by default, access-order via the two-argLRUMap(true, size)constructor. AlphaNumericComparator-
Char-by-char sort where digits sort before letters and letters compare case-insensitively. Note that the comparison is per character, not per numeric run, so
"a10"sorts before"a2". SemanticVersionComparator-
Sorts dot-separated numeric version strings segment-by-segment as integers (so
"1.10.0"correctly sorts after"1.2.0"). Null and empty inputs sort first. DotNotationComparator-
Comparator for dot-separated strings (paths, domain names, log categories) that compares each segment using
AlphaNumericComparator. Thereversedconstructor flag changes segment iteration order to right-to-left, useful when the rightmost segment is the most significant key (such as the TLD of a domain name); it does not invert the sign of the comparison result. SnowflakeId,SnowflakeVariant,SnowflakeVersion-
Eighteen-byte identifiers combining a millisecond timestamp, the host MAC address (or random fallback), the JVM process id, and a per-millisecond counter. Supports hex, dotted, and compact alphanumeric encodings, with
Comparableordering by timestamp. Pair<L,R>-
Immutable two-element record.
Pair.of(a, b)is the typical constructor. Tuple<K,V>-
Ordered, duplicate-allowing collection of key/value pairs with iterator support and fail-fast concurrent-modification detection.
Counter-
Mutable
intcounter with pre- and post-variants ofincAndGet/getAndInc/decAndGet/getAndDec/addAndGet/getAndAdd/subtractAndGet/getAndSubtract. Not thread-safe — for that, useAtomicInteger. Mutation<T,R>/MutationUtility-
A
Function-like functional interface whoseapplyis allowed to throw checked exceptions.MutationUtilityruns aMutationover arrays, iterators, iterables, and collections to produce arrays, lists, sets, maps, orBag`s, wrapping any thrown exception in a `MutationException. Option<T>/Some<T>/None<T>-
Lightweight option-type helpers for codebases that prefer to model presence/absence explicitly without
java.util.Optional.Optionis aSerializableinterface with two implementations:Some, the present case, built withOption.of(value); andNone, the absent case, a singleton obtained fromOption.none()and typed to the caller’s element type. BecauseSomeaccepts anullvalue,isNone()(which of the two cases this is) andisEmpty()(whetherget()returnsnull) are distinct questions — a present option can be empty. Unrelated to the command-lineOptioninorg.smallmind.nutsnbolts.command.template, despite the shared simple name. AnsiColor-
Terminal color escape sequences.
Bytes-
Big-endian conversion between primitive
long/int/shortvalues and fixed-width byte arrays, used bySnowflakeIdand elsewhere to pack numeric identifiers. For hex encoding seeHexCodecin thesecuritypackage. SelfDestructiveMap<K,V>-
A map whose entries expire after a configurable TTL; uses
SelfDestructiveKeyunder the hood. NumberComparator-
Cross-type numeric comparator that normalises across
BigDecimal,BigInteger, floating-point, and integral primitive wrappers before comparing. ThrowsFormattedRuntimeExceptionwhen handed aNumbersubtype it does not recognise. DirectionalComparator<T>/NaturalDirectionalComparator<T>-
Abstract base that carries a sort
Direction(ASCENDING/DESCENDING), and a concrete subclass that delegates toComparable.compareTo. DotNotation-
Compiles a glob-style dotted pattern (segments joined by
., with*and?as wildcards) into aPattern, and computes a bitmask value reflecting which segments matched. Rejects malformed input such as leading or trailing dots, consecutive dots, or wildcards mid-segment viaDotNotationException. Spread/NumericSpread/AlphaSpread-
Expand comma-delimited range expressions such as
"1,3..5,9"or"a,c..e,z"into arrays.Spreaddispatches to the numeric or alphabetic variant based on the first character. Errors are surfaced asSpreadParserException. MagicHash-
XOR-shift hash mixer that reduces clustering and improves bit distribution for
inthash codes. Useful when building custom hash tables over inputs whose natural hash code clusters in the low bits. MartianBase34-
Encodes non-negative
longvalues into a 34-character custom alphabet, applying a per-Groupadditive mix constant. ThreeGroupconstants (FIRST,SECOND,THIRD) carry distinct mix values. Best used with explicit digit widths that comfortably accommodate the mix constant — auto-width selection may produce encoded strings whose decode does not round-trip cleanly. MacAddress/MacAddressException-
Reads the host MAC address from the first non-loopback network interface. Used by
SnowflakeIdto embed a machine identifier in every generated id. LocaleUtility,StringUtility,EnumUtility,ArrayUtility-
Assorted helpers.
EnumUtility.toEnumNameconverts free-form text into upper snake-case enum constant names with configurable digit-prefix handling.StringUtilitycovers display/camel-case conversion, Java-identifier validation, and ellipsis trimming.ArrayUtilityclones, concatenates, and linear-searches generic arrays.LocaleUtility.forCountryISO3Codelooks up aLocaleby its three-letter ISO country code.
Example — LRU cache.
LRUMap<String, User> cache = new LRUMap<>(1_000); // (1)
User user = cache.computeIfAbsent(userId, id -> repo.loadUser(id));-
Fixed capacity; the oldest entry by insertion order is evicted when full.
Package: org.smallmind.nutsnbolts.inject
@Service-
A marker annotation for classes that participate in custom service-discovery scans. SmallMind framework code (and applications built on top of it) uses this marker to locate components without pulling in a specific DI container.
@LazyField,LazyFieldAspect,LazyError-
An AspectJ-driven mechanism to declare a field as lazily initialised. The aspect intercepts the first read and delegates to a supplier. Useful for breaking cyclic references between beans whose initialisation order is hard to fix at container level.
|
Important
|
|
Packages: org.smallmind.nutsnbolts.servlet,
org.smallmind.nutsnbolts.soap
servlet is deliberately minimal today: FormattedServletException
is a ServletException whose constructor takes a
String.format-style pattern plus varargs, saving a line every time
you throw one.
soap ships MonitorHandler, a
jakarta.xml.ws.handler.soap.SOAPHandler that can be added to a
web-service client or endpoint to observe requests and responses for
logging or tracing. MessageDirection distinguishes inbound from
outbound messages in handler callbacks.
Package: org.smallmind.nutsnbolts.namespace.shiro.realm
(plus …realm.spring)
Apache Shiro AuthorizingRealm implementations that authenticate a
subject against a directory over JNDI. This is the realm that backs
the shipped realm.xml Spring fragment. The package depends on
shiro-spring (optional in the POM) and on the JDK’s built-in
com.sun.jndi.ldap.LdapCtxFactory; no third-party LDAP client is
required.
LdapAuthorizingRealm-
Abstract base extending Shiro’s
AuthorizingRealm. It owns the two collaborators every implementation needs — anLdapConnectionDetailsand a user search path — taking them as constructor arguments, and exposes a protectedgetLdapContextbind helper to its subclasses. The group-to-role map is set afterwards viasetGroupRoleMap. It also owns authorization: it reads the groups a subject belongs to (via the subclass hookgetDirectoryGroups) and grants each subject theRoleTypeits groups map to. A subject whose groups are absent from the map receives no roles, so an empty (unconfigured) map grants nothing. DefaultLdapRealm-
Realm for a generic LDAP directory that stores a hashed password on the user entry. It binds with the service account, looks up
uid=<principal>under the search path, reads theuserPasswordattribute, and authenticates only when that value equals{SHA}followed by the Base64-encoded SHA-256 hash of the presented credentials. A missing entry, a missing password attribute, or a mismatch yields no authentication info. For authorization,getDirectoryGroupssearches a group subtree for entries whose member attribute references the user and returns each match’s DN — so its group-to-role keys are full group DNs, like the AD realm. All collaborators are required constructor arguments:connectionDetailsandsearchPath(from the base), then the four group-schema argumentsgroupSearchPath,groupObjectClass,memberAttribute, andmemberValueTemplate(the member value to match, with{0}replaced by the principal, e.g.uid={0},ou=peoplefor full-DN members or{0}for posixmemberUid). It has no no-argument constructor. ActiveDirectoryLdapRealm-
Realm for Microsoft Active Directory. Rather than comparing a stored hash, it binds with the service account, runs a subtree search for
(&(objectClass=user)(sAMAccountName=<principal>)), and — when a matching entry exists — verifies the credentials by performing a second bind as the user principal name<principal>@<domain>. A successful bind authenticates the user; a wrong password surfaces as theNamingExceptionraised by that bind. Its constructor takesconnectionDetails,searchPath, and the UPNdomain, so it has no no-argument constructor. For authorization,getDirectoryGroupsreads the user’smemberOfgroup distinguished names, which the base class maps to roles — so the keys in the group-to-role map are full group DNs. LdapConnectionDetails-
Plain JavaBean carrying the host, port, root namespace, and service-account user name and password. The host, port, and root namespace are assembled into an
ldap://host:port/rootNamespaceprovider URL. Credentials are held in plain text for the life of the realm. RoleType-
Enum of grantable role codes (
ADMIN,USER,GUEST), with afromCode(String)reverse lookup. Shiro attaches no meaning to role strings — these are this package’s vocabulary, and a realm grants them by mapping directory groups onto them throughsetGroupRoleMap. Add constants here to model additional roles. DefaultLdapRealmFactoryBean,ActiveDirectoryLdapRealmFactoryBean(in…realm.spring)-
One Spring
FactoryBeanper realm, each honest about exactly what it builds. Every constructor argument of its realm is exposed as a settable property —connectionDetails,searchPath, and the group schema (DefaultLdapRealm) ordomain(ActiveDirectoryLdapRealm) — plus the optionalgroupRoleMap. Each builds its realm once inafterPropertiesSet(), returns it as a singleton, and reports the concrete realm class fromgetObjectType(). Prefer these to hand-wiring<constructor-arg>lists, since named properties read more clearly.
Wiring. Import the shipped fragment:
<import resource="classpath:org/smallmind/nutsnbolts/realm.xml"/>The fragment wires an ldapRealm through DefaultLdapRealmFactoryBean
(building a DefaultLdapRealm), installs it into a Shiro
DefaultSecurityManager, and registers that manager globally via
SecurityUtils.setSecurityManager. It reads these placeholders:
| Placeholder | Meaning |
|---|---|
|
Service-account bind credentials |
|
Directory host, port, and root namespace |
|
Subtree under which user entries are searched |
|
Subtree searched for group entries |
|
Group object class, member attribute, and member-value template
( |
|
Group DN granted |
|
Important
|
The shipped fragment builds a <bean id="ldapRealm" class="org.smallmind.nutsnbolts.namespace.shiro.realm.spring.ActiveDirectoryLdapRealmFactoryBean">
<property name="domain" value="${ldap.domain}"/>
<property name="searchPath" value="${ldap.auth.search_path}"/>
<property name="connectionDetails" ref="ldapConnectionDetails"/>
<property name="groupRoleMap">
<map>
<entry key="CN=Admins,OU=Groups,DC=example,DC=com" value="ADMIN"/>
<entry key="CN=Staff,OU=Groups,DC=example,DC=com" value="USER"/>
</map>
</property>
</bean>Each |
ByteArrayIOStream, CircularBufferIOStream, and their paired
input/output views treat close() as a one-way latch. Once closed:
-
asInputStream()andasOutputStream()still return the view instances, but subsequent reads and writes throwIOException. -
close()itself is idempotent; calling it more than once has no additional effect. -
Try-with-resources usage is the intended pattern.
ContextFactory is backed by InheritableThreadLocal. When a new
thread is created from a parent, childValue runs and copies each
context type’s stack into a fresh LinkedList. The child has an
independent stack thereafter; push/pop in the child does not affect
the parent.
Any context that refers to mutable state (connection handles, transactions, open resources) is still shared by reference with the parent — inheritability copies the stacks, not the objects on them.
ScopeFactory is backed by a ScopedValue. A binding is visible only
on the thread that entered it and only for the dynamic extent of the
entered operation. Threads started from inside that extent — via
new Thread, an executor, or a CompletableFuture — see no bindings.
To carry bindings across a thread boundary, call
ScopeFactory.snapshot() on the originating thread and run the
downstream work through ScopeSnapshot.run or call. The snapshot is
an immutable copy of the binding map taken at that moment; it does not
track later entries or exits on the originating thread, and it can be
reused for any number of runs on any number of threads.
ScopeFactory.wrapExecutor(executor) packages that pattern for a pool:
the returned Executor takes a snapshot inside execute, per task, and
runs the task through it on the delegate. The capture happens at
submission, not when the executor is wrapped, so a pool wrapped once at
startup still carries each request’s bindings to the task that request
submits; a task submitted from an unbound thread runs with no scopes
bound. Only Executor.execute is decorated. That is sufficient for
CompletableFuture.*Async(task, executor) and plain execute, but an
ExecutorService passed in comes back as a bare Executor.
ScopeFactory.wrapThreadFactory(threadFactory) is the other capture
moment: it takes one snapshot when the factory is wrapped and runs the
whole body of every thread the factory creates inside it. Bindings
present when newThread is later called are ignored. That makes it the
right tool for scopes that are long-lived and bound around pool
construction, and the wrong tool for request scopes, which exist only
at submission time and need wrapExecutor or a per-task snapshot().
Wrapping from an unbound thread yields threads that start with no
scopes bound. The two wrappers are independent of
PerApplicationScope.wrapThreadFactory and generateCarrier; a pool
that must carry both applies both.
As with context inheritance, the snapshot copies the map, not the
scope objects. A scope that refers to mutable state is shared by
reference with every thread that rebinds it. ScopeLifecycleAware
callbacks fire only on the original entry through ScopeFactory, never
on a snapshot rebind.
PerApplicationScope follows the same rule with
PerApplicationScope.generateCarrier(), wrapThreadFactory, and
wrapExecutor, with the same two capture moments: wrapThreadFactory
captures once when wrapped, wrapExecutor captures per task at
submission. Code that holds the scope instance rather than a binding
uses the instance’s boundThreadFactory / boundExecutor instead;
those bind that scope directly, with no capture step and no
MissingPerApplicationScopeException. The difference between the
carrier and snapshot families is what is copied: a ScopeSnapshot copies
an immutable binding map, whereas an ApplicationCarrier refers to the
scope’s one shared, mutable map, so data stored after the capture — on
any thread — is still visible through the carrier.
Every consumer that accepts a PerApplicationScope — the servlet
listener and filter below, GrizzlyInitializingBean and
JettyInitializingBean, and the pools, transports, and servers of the
other modules — settles it once, through PerApplicationScope.resolve,
on the thread that constructs or starts it, and that result is the
scope it binds from then on. A consumer created from inside a bound
scope with no scope handed to it therefore runs in that scope; one
created on an unbound thread with none handed runs with no scope,
carrying only whatever PerApplicationContext its threads inherit; and
one handed a scope other than the bound one fails with ScopeException
at that point.
In a servlet container the two bound entry points are
PerApplicationScopeContextLoaderListener, which binds the scope around
Spring’s refresh and shutdown, and PerApplicationScopeFilter, which
rebinds it for the extent of each request’s filter chain. Both are
described in scope.
Structured concurrency (StructuredTaskScope) propagates ScopedValue
bindings to forked subtasks automatically, but that API is still a
preview feature in JDK 25 and this module does not depend on it.
With SystemPropertyMode.FALLBACK (the default):
-
Caller map (
expand(expansion, expansionMap)). -
System properties (
System.getProperty). -
Environment variables (
System.getenv) ifsearchSystemEnvironmentistrue.
With SystemPropertyMode.OVERRIDE:
-
System properties.
-
Environment variables (if enabled).
-
Caller map.
Placeholders inside resolved values are expanded recursively; circular
references throw PropertyExpanderException rather than looping.
Retry.execute runs the RetryCall on a fresh thread for each
attempt. The calling thread sleeps between attempts via
Thread.sleep, not via scheduled executors, so the method is
appropriate for coarse retries, not for high-frequency polling.
Postman keeps a HashMap<SHA256Key, Template> of compiled FreeMarker
templates, keyed by SHA-256 of the raw body text. Two distinct Mail
messages with identical body text share the same compiled template.
The cache has no eviction policy; templates live for the life of the
Postman instance. For workloads that generate large numbers of
unique bodies, prefer constructing a fresh Postman per campaign and
discarding it afterwards.
Resource.getInputStream() returns null when the backing store can
be consulted but does not locate the content (the default convention
across the shipped implementations). It throws ResourceException
when the backing store itself errors (permission denied, malformed
URL, failed URL connection). Callers should handle both.
GatingClassLoader can compare a class’s last-modified timestamp
against a gracePeriodSeconds tolerance to detect stale definitions
for reloadable extensions. A negative grace period disables the check
entirely; a value of 0 keeps the check enabled with no fresh window,
so the source is consulted on every subsequent loadClass call.
Stale detection is not automatic reloading; the loader throws
StaleClassLoaderException, and it is up to the host to drop and
recreate the loader.
NaiveTrustManager, NaiveHostNameVerifier, and
NaiveSSLSocketFactory accept every certificate and every hostname.
They exist for controlled test environments (integration tests against
a self-signed fixture). Registering them as JVM-wide defaults silently
disables TLS validation for every connection in the process.
- Broad scope, narrow depth
-
This package is deliberately broad. Each subpackage solves its specific problem and stops. Where a first-class library such as Netty, OkHttp, Jackson, Guava, or Bouncy Castle covers the same territory with more depth, the expectation is that consumers will use that library directly for that surface, not attempt to extend the corresponding nutsnbolts subpackage.
- Optional dependency failure modes
-
A code path whose optional dependency is missing will fail with
NoClassDefFoundErrororClassNotFoundExceptionon first use, not at application startup. Read the Optional Dependency Matrix before wiring a new subpackage into production. Retryblocks the caller-
Retry.executeruns each attempt on a fresh thread and joins on it, but the calling thread is blocked for the full duration of all attempts plus all back-off intervals. For high-concurrency retry needs, wrap calls in your own executor. Postmantemplate cache has no evictionsslnaive trust classes are test-only-
They are shipped for convenience but must never be the default in production JVMs. See security, ssl — cryptography and TLS.
injectis not a DI container-
@Serviceis a marker.@LazyFieldrequires AspectJ weaving. Neither substitutes for Spring, CDI, or Guice. namespace.shiroauthorization must be configured-
Roles come from the group-to-
RoleTypemap set viasetGroupRoleMap; an unconfigured map grants no roles.ActiveDirectoryLdapRealmderives groups from the user’smemberOfattribute;DefaultLdapRealmderives them by searching the group subtree using the schema given as constructor arguments. Both realms take required constructor arguments and so have no no-argument constructor — assemble them throughDefaultLdapRealmFactoryBean/ActiveDirectoryLdapRealmFactoryBean(or a direct<constructor-arg>bean). See namespace.shiro — Shiro LDAP realms. layoutis toolkit-agnostic by design-
It does not know about Swing, JavaFX, SWT, or any specific GUI widget. Using it in a real application requires writing the
ParaboxElementadapter for your toolkit (thesmallmind-javafxmodule contains a JavaFX adapter as a reference). scopebindings do not cross plain thread boundaries-
Unlike
ContextFactory,ScopeFactorybindings are not inherited by child threads or executor tasks, and there is no push/pop API for binding at one call site and unbinding at another. UseScopeFactory.snapshot()withScopeSnapshot.run/callto rebind explicitly, submit throughScopeFactory.wrapExecutor(executor), or build the pool fromScopeFactory.wrapThreadFactory(threadFactory)when the bindings are fixed at pool construction. The same applies toPerApplicationScope: a thread pool you build yourself that resolves per-application data must be built fromPerApplicationScope.wrapThreadFactory, receive its tasks throughPerApplicationScope.wrapExecutor, or have them run through anApplicationCarrier; unlikecontext.PerApplicationContext, nothing is inherited. The library’s own pools, transports, and servers that accept aPerApplicationScopebind it for you, as the scope handed to them or, when none is, the scope bound on the thread that constructs or starts them; constructed or started on an unbound thread with none handed, their threads run with no scope. See Scope propagation. PerApplicationContextadoption is per thread, not per webapp-
new PerApplicationContext()adopts whatever map is already attached to the constructing thread. A container that deploys several webapps sharing one copy of thenutsnboltsclasses and initializes them on one thread lets the second webapp’sWebContextLoaderListeneradopt the first’s map, so the two share one registry. Give each webapp its own copy inWEB-INF/lib, or deploy one application per container. PerApplicationContextmaps are never detached-
prepareThreadand inheritance attach a map to a thread for the thread’s lifetime; no filter or carrier removes it. Where thenutsnboltsclasses are shared at container level, a request thread that once served webapp A carries A’s map onto B’s paths that noPerApplicationContextFilteris mapped to, and ontoERRORdispatches, which neither per-application filter maps, so lookups on such a thread resolve A’s registrations rather than failing. With a per-webapp copy B has its own thread-local: such lookups resolve B’s own map once B’s filter or inheritance has attached it to that thread, and before that they fail withMissingPerApplicationContextException(Claxon excepted, which returnsnullregistries and unplugged instrumentation). The same holds across a redeploy when thenutsnboltsclasses are shared:WebContextLoaderListenerattaches the published map to the thread that destroys the webapp, and a replacement initialized on that thread with nothing published adopts it, starting from the old registrations and overwriting them key by key as its own refresh registers. With a per-webapp copy inWEB-INF/libnothing is adopted; the attached map instead pins the destroyed webapp’s class loader for the thread’s lifetime, as every request thread that ranPerApplicationContextFilteralready does. - Both bindings in a plain servlet container
-
PerApplicationScopeContextLoaderListenerbinds only the scope, so registrations made during its refresh land only in the scope map and threads that inherit a context see nothing. To give a plain-container deployment both bindings, attach aPerApplicationContextto the deploy thread and publish it under thePerApplicationContext.class.getName()attribute beforePerApplicationScopeContextLoaderListenerruns — aServletContextListenerdeclared ahead of it that constructs aPerApplicationContextand sets the attribute — then map bothPerApplicationScopeFilterandPerApplicationContextFilter; the refresh thread then carries both, registrations land in both maps, and each filter re-establishes its flavor on request threads. The pools and transports the refresh constructs or starts adopt the bound scope whether or not a context is attached as well; the second binding changes what plain threads that inherit the context can resolve, not what those components bind. PerApplicationScopeFilterbinds only the filter chain-
The scope is bound for the extent of
chain.doFilterand nothing else. AnAsyncContext.dispatchleg is bound only when the filter is mapped for theASYNCdispatcher with async support enabled, as servlet container wiring shows and asGrizzlyInitializingBeanandJettyInitializingBeanmap it (see Per-application data on request threads);AsyncContext.start, read and write listener callbacks, and any work the request hands to another thread run unbound unless they go through anApplicationCarrier. The no-arg filter settles its scope ininitfrom the servlet context attribute published byPerApplicationScopeContextLoaderListeneror application code, else from the scope bound on the thread runninginit; with neither it fails withMissingPerApplicationScopeException, as it does not create one. - Optional modules on the module path
-
Every optional dependency is
requires staticin the module descriptor. On the module path a jar that is present but not required by anything is not resolved, and the code that uses it fails withNoClassDefFoundErrorexactly as if the jar were missing.requiresthe module or pass--add-modules. See Module Path. examplesopens a package with no classes-
The descriptor opens
org.smallmind.nutsnbolts.examplesso its resources stay loadable by path.javacreports[opens] package is empty or does not existfor that line while compiling this module; the warning is expected. At run time the package exists because the jar contains its resource files.
-
smallmind-nutsnboltssits at the bottom of the dependency graph in this repository. Nearly every other SmallMind module depends on it; it depends on nothing else in the repository. -
The POM lists all Jakarta, Spring, Shiro, FreeMarker, Commons-Net, Bouncy Castle, ASM, and SnakeYAML dependencies as
optional, and inheritsaspectjrtasoptionalfrom the parent POM. A consumer choosing a specific subpackage must add the corresponding runtime dependency to its own build. The module descriptor mirrors this: each optional dependency isrequires static(see Module Path). -
The build configures the
smallmind-license-maven-plugin(for dual AGPL/Apache licensing headers) and theaspectj-maven-plugin(becauseLazyFieldAspectis an AspectJ aspect woven at compile time for this jar). A consumer that uses@LazyFieldin its own code must configure AspectJ weaving on its side; weaving is not transitive through the dependency relationship. -
The shipped Spring XML fragments (
jmx.xml,realm.xml,rmi.xml) and the command XSD (smallmind-command-1.0.xsd) are published as classpath resources underorg/smallmind/nutsnbolts/. Consumers import them withclasspath:references.