Skip to content

Latest commit

 

History

History
2815 lines (2348 loc) · 126 KB

NUTSNBOLTS.adoc

File metadata and controls

2815 lines (2348 loc) · 126 KB

SmallMind NutsNBolts

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 whole web stack — 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 inject subpackage is a single marker annotation plus an AspectJ-driven lazy-field helper, not a container.

  • Not a web or HTTP framework. The http subpackage wraps HttpURLConnection for simple request/response cases; full HTTP clients live elsewhere.

  • Not a cryptography library. The security subpackage 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 (--name value, -f, enumerated options)

org.smallmind.nutsnbolts.command

CommandLineParser.parseCommands, Template, OptionSet

A per-thread stack of "current caller" objects that inherits into child threads

org.smallmind.nutsnbolts.context

ContextFactory.pushContext, getContext, popContext

Bind an ambient "current caller" object for the exact extent of an operation, with nothing to pop and nothing to leak

org.smallmind.nutsnbolts.scope

ScopeFactory.callInScope, runInScope, getScope, snapshot, wrapExecutor, wrapThreadFactory

Uniform access to content behind file:, classpath:, jar:, or URL schemes

org.smallmind.nutsnbolts.resource

Resource, ResourceParser, ResourceFactory (Spring FactoryBean)

Resolve ${…​} placeholders against a map, system properties, and environment

org.smallmind.nutsnbolts.property

PropertyExpander, PropertyClosure

An in-memory InputStream/OutputStream pair with independent read and write cursors

org.smallmind.nutsnbolts.io

ByteArrayIOStream, CircularBufferIOStream

Event-driven CSV parsing with quoting and header skipping

org.smallmind.nutsnbolts.csv

CSVParser, CSVLineHandler

Marshal LocalDateTime, ZonedDateTime, Currency, enums with JAXB

org.smallmind.nutsnbolts.json

LocalDateTimeXmlAdapter, ZonedDateTimeXmlAdapter, EnumXmlAdapter

Compress, walk, or extract ZIP and JAR archives with one API

org.smallmind.nutsnbolts.zip

CompressionType.JAR, CompressionType.ZIP

Load FreeMarker templates from classpath, filesystem, or a Resource

org.smallmind.nutsnbolts.freemarker

ClassPathTemplateLoader, FileSystemTemplateLoader, ResourceTemplateLoader

Send mail over SMTP/SMTPS with optional FreeMarker interpolation and attachments

org.smallmind.nutsnbolts.email

Postman, Mail, Authentication, Protocol

Hash, sign, encrypt, or generate keys without JCE boilerplate

org.smallmind.nutsnbolts.security

EncryptionUtility, HashAlgorithm, AsymmetricKeyGenerator

Install keystores, trust managers, and (for tests) permissive TLS

org.smallmind.nutsnbolts.ssl

KeyStoreUtility, TrustManagerUtility, NaiveTrustManager

Convert Date, Calendar, epoch millis, and ISO-8601 to ZonedDateTime

org.smallmind.nutsnbolts.time

TimeUtility, Stint, CalendarUtility

Run an operation with N retries and optional exponential back-off

org.smallmind.nutsnbolts.retry

Retry.execute, RetryCall

Add @Email, @NotBlank, @NotEmpty, @GreaterThan, @LowerBound constraints

org.smallmind.nutsnbolts.validation

The annotation types and their matching `ConstraintValidator`s

Gate which classes a child classloader may resolve

org.smallmind.nutsnbolts.lang

GatingClassLoader, ClassGate, ClasspathClassGate

Measure, constrain, and position nested boxes in a GUI-agnostic way

org.smallmind.nutsnbolts.layout

ParaboxLayout, SerialBox, ParallelBox, Constraint

Common collections the JDK does not ship (bag, bloom filter, LRU map)

org.smallmind.nutsnbolts.util

Bag / HashBag, BloomFilter, LRUMap, AlphaNumericComparator, SemanticVersionComparator, DotNotationComparator

Use Spring with SmallMind Resource, extension loaders, and placeholder configs

org.smallmind.nutsnbolts.spring

PropertyPlaceholderConfigurer, ResourceConverter, ExtensionLoader

Authenticate a Shiro subject against an LDAP or Active Directory directory

org.smallmind.nutsnbolts.namespace.shiro.realm

DefaultLdapRealm, ActiveDirectoryLdapRealm, their …spring factory beans, realm.xml

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

email

Postman, Mail, FreeMarker interpolation of bodies

jakarta.mail:jakarta.mail-api + a Jakarta Mail runtime (e.g. org.eclipse.angus:angus-mail), jakarta.activation:jakarta.activation-api, org.freemarker:freemarker

freemarker

Any *TemplateLoader or *TemplateSource

org.freemarker:freemarker

validation

The @Email, @NotBlank, @NotEmpty, @GreaterThan, @LowerBound annotations

jakarta.validation:jakarta.validation-api + a runtime such as Hibernate Validator

servlet

FormattedServletException and any servlet helpers

jakarta.servlet:jakarta.servlet-api

soap

MonitorHandler and the jakarta.xml.soap / jakarta.xml.ws integration points

jakarta.xml.soap:jakarta.xml.soap-api, jakarta.xml.ws:jakarta.xml.ws-api

json (JAXB adapters)

*XmlAdapter classes

jakarta.xml.bind:jakarta.xml.bind-api + a JAXB runtime (e.g. org.glassfish.jaxb:jaxb-runtime)

spring, resource (ResourceFactory)

PropertyPlaceholderConfigurer, ResourceFactory, ResourceConverter, ExtensionLoader

org.springframework:spring-beans, spring-context, spring-core

security / x509

CertificateUtility, any subpackage under security/x509 or security/kms that requires a Bouncy Castle provider

org.bouncycastle:bcprov-jdk18on, org.bouncycastle:bcpkix-jdk18on (and register the provider — see security, ssl — cryptography and TLS)

namespace.shiro.realm

DefaultLdapRealm, ActiveDirectoryLdapRealm, the …spring factory beans, the shipped realm.xml

org.apache.shiro:shiro-spring (which pulls in shiro-core); the directory access itself uses the JDK’s built-in JNDI LDAP provider

reflection (proxy generation)

ProxyGenerator

org.ow2.asm:asm

reflection (bytecode trace, ASMify)

ClassInspector.trace, .asmify

org.ow2.asm:asm, org.ow2.asm:asm-util

ntp

NTPTime

commons-net:commons-net

inject, reflection.aop

@LazyField with LazyFieldAspect, AOPUtility

org.aspectj:aspectjrt (and weaving in your own build — see inject — @Service marker and lazy fields)

spring XML configuration under src/main/resources/spring/org/smallmind/nutsnbolts/

importing the shipped JMX, Realm, or RMI Spring snippets

org.springframework:spring-context (and SnakeYAML, if the consuming app loads YAML property sources: org.yaml:snakeyaml)

Important

The default PropertyExpander and the property-placeholder Spring integration are designed to tolerate missing encryption providers — encryption is only required when a placeholder is actually marked as encrypted. Similarly, JAXB adapters are declared as compile-optional so types that merely reference the adapter classes at runtime do not need a JAXB runtime on the classpath.

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

jakarta.activation:jakarta.activation-api

jakarta.activation

explicit

jakarta.mail:jakarta.mail-api

jakarta.mail

explicit

jakarta.servlet:jakarta.servlet-api

jakarta.servlet

explicit

jakarta.validation:jakarta.validation-api

jakarta.validation

explicit

jakarta.xml.bind:jakarta.xml.bind-api

jakarta.xml.bind

explicit

jakarta.xml.soap:jakarta.xml.soap-api

jakarta.xml.soap

explicit

jakarta.xml.ws:jakarta.xml.ws-api

jakarta.xml.ws

explicit

org.bouncycastle:bcpkix-jdk18on

org.bouncycastle.pkix

explicit

org.bouncycastle:bcprov-jdk18on

org.bouncycastle.provider

explicit

org.ow2.asm:asm

org.objectweb.asm

explicit

org.ow2.asm:asm-util

org.objectweb.asm.util

explicit

org.yaml:snakeyaml

org.yaml.snakeyaml

explicit

commons-net:commons-net

org.apache.commons.net

explicit

org.freemarker:freemarker

freemarker

automatic

org.apache.shiro:shiro-core

org.apache.shiro.core

automatic

org.apache.shiro:shiro-crypto-hash

org.apache.shiro.crypto.hash

automatic

org.apache.shiro:shiro-lang

org.apache.shiro.lang

automatic

org.springframework:spring-beans

spring.beans

automatic

org.springframework:spring-context

spring.context

automatic

org.springframework:spring-core

spring.core

automatic

org.springframework:spring-web

spring.web

automatic

org.aspectj:aspectjrt

org.aspectj.runtime

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 keeps classpath:org/smallmind/nutsnbolts/examples/…​ resolvable from other modules.

  • org.smallmind.nutsnbolts.json to jakarta.xml.bind.

  • spring, spring.jmx, spring.property, spring.remote, spring.web, security.spring, namespace.shiro.realm.spring, and resource (all under org.smallmind.nutsnbolts) to spring.core and spring.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-scaffold polymorphic adapters use. When the proxied class is in a named module, that module must open the class’s package to org.smallmind.nutsnbolts. The package does not need to be exported, and the module does not need to read org.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 not requires transitive the 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 as java.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 qualified exports … to or opens … to is 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, or true for 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 requires the modules whose classes it is handed.

  • A final field without a setter can be read but not written: FieldAccessor.set throws IllegalAccessException: The field(…) of class(…) is 'final' and has no setter.

  • A custom OverlayNullifierValidator is 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 (through LazyFieldAspect) reads and writes the named field with this module’s access. Open the package declaring the field to org.smallmind.nutsnbolts, unless the field has a public getter and a public setter.

  • BeanUtility, AOPUtility, Getter, Setter, and OffloadingInvocationHandler invoke 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, BeanUtility invokes 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 Resource has an identifier in scheme:path form (classpath:config.xml, file:/etc/app.conf, jar:…​), and implementations in other SmallMind modules typically consume this interface rather than raw File or URL. See resource — uniform addressable content.

Context stack

A per-type, per-thread stack of objects implementing the Context marker. 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. A Scope is bound, keyed by concrete class, only for the dynamic extent of the operation passed to ScopeFactory.callInScope or runInScope. There is no pop to forget, so a scope can not leak past its operation, and bindings are not inherited by child threads — a ScopeSnapshot carries 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 Spring PropertyPlaceholderConfigurer in this package and is used stand-alone by modules such as ansible and spark for 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 treat close as 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 with allowUndeclared = true collects 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; ArgumentType is the enum of NONE, 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";
  1. The third argument to Option is the required flag. The parser throws CommandLineException if a required option is absent.

  2. parseCommands validates 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 ScopedValue instead of an inheritable thread-local. Prefer it for new code that can wrap its work in a lambda; keep ContextFactory where push and pop must happen at different call sites or where child-thread inheritance is relied upon.

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, plus importContextTrace / exportContextTrace for serialising the current thread’s stack across an asynchronous boundary.

ExpectedContexts

Method-level annotation declaring which Context types must be active when the method runs. ContextFactory.filterContextsOn(method) validates and collects them. With the filterContextsOn(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 on Context itself, so every active type qualifies.

ContextLifecycleAware

Optional hook for contexts that need setup or teardown around their stack lifetime. beforePush runs before ContextFactory.pushContext adds the context to the stack; if it throws, the context is not pushed. afterPop runs after ContextFactory.popContext removes 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 ExpectedContexts expectations are not met.

PerApplicationContext

Holds the per-application data map shared by every thread of one application, keyed by lang.PerApplicationDataManager class, in an InheritableThreadLocal. Constructing one on a thread adopts the map already attached to that thread or creates and attaches a new one; prepareThread installs the instance’s map on the current thread. Static setPerApplicationData / getPerApplicationData read and write the current thread’s map and throw lang.MissingPerApplicationContextException when none is attached; setPerApplicationDataIfAbsent stores 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 static isBound() reports whether a map is attached without throwing. The static wrapExecutor decorates an Executor so that each task runs with the map attached to the thread that submitted it, captured per execute (which throws lang.MissingPerApplicationContextException when the submitting thread has none); this is the context counterpart of the scope’s wrapExecutor, for pools whose threads were created before any context existed. generateCarrier captures the current map in a ContextCarrier for use on another thread, and wrapThreadFactory wraps a ThreadFactory so 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, while ForkJoinPool.commonPool() workers (and so the CompletableFuture.*Async defaults) inherit nothing. PerApplicationScope (scope — ScopedValue-bound scopes) is the ScopedValue counterpart; the library’s bridging *Manager registries consult both flavors under the rules in Per-application registries.

PerApplicationContextFilter (org.smallmind.nutsnbolts.context.web)

Servlet filter that installs a shared PerApplicationContext on every request thread it is mapped to. Construct it with the context instance, optionally with suppressConnectionClosedException, 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 in init. In either case init reads the context from the servlet context attribute named PerApplicationContext.class.getName() — published by spring.web.WebContextLoaderListener — and throws lang.MissingPerApplicationContextException when none is published. The filter never creates a context of its own. doFilter calls prepareThread and then the rest of the chain, discarding "Connection is closed" IOException`s when `suppressConnectionClosedException is true (default false); the chaining setter setSuppressConnectionClosedException turns 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. Requires jakarta.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);
  1. Push into this thread’s stack for the concrete CallerContext key.

  2. 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:

  1. register writes 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.

  2. Lookups read the scope flavor first and fall back to the context flavor when the scope holds nothing and a context is attached.

  3. 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 the OrmDaoManager, JsonEntityResourceProxyManager, PoolManager, and SpringPropertyAccessorManager getters return null; SessionManager.getSession and DataSourceManager.getDataSource throw ORMInitializationException; PolymorphicAttributeManager.getPolymorphicAttributeName returns the adapter default; and ClaxonRegistryManager makes Instrument.with return an UnpluggedInstrumentation so metrics silently no-op. Those are the results of an empty bound registry. A thread with neither binding throws MissingPerApplicationContextException from every accessor except Instrument.with, which returns UnpluggedInstrumentation there as well (its underlying ClaxonRegistryManager.getRegistry() returns null).

Key types.

Scope

Marker interface (Serializable). The concrete class is the binding key.

ScopeFactory

Static entry points. callInScope / callInScopes return the operation’s result and propagate its checked exception type unchanged; runInScope / runInScopes take a Runnable. getScope returns the innermost binding for a class, or null. filterScopesOn collects bound scopes assignable to the given filter types and validates any ExpectedScopes on the method. snapshot captures the current bindings for another thread; wrapExecutor decorates an Executor so that each task it receives runs under the bindings of the thread that submitted it; wrapThreadFactory decorates a ThreadFactory so that every thread it creates runs under the bindings in effect when the factory was wrapped. Passing a null scope, or an array containing one, throws ScopeException; a null or empty array runs the operation with no additional binding.

ScopeSnapshot

Immutable capture of the bindings on the calling thread, returned by ScopeFactory.snapshot(). run / call rebind 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. beforeEnter runs on the entering thread before the scope is bound; afterExit runs after the operation completes, normally or by throwing. With several scopes, beforeEnter runs in array order and afterExit in reverse order; a beforeEnter that throws, or a null element found later in the array, still triggers afterExit for the scopes already entered.

ExpectedScopes

Method-level annotation naming the Scope types 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 ExpectedScopes declaration or an attempt to bind a null scope. Also thrown by PerApplicationScope.resolve when 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 a PerApplicationScope (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-argument PerApplicationScopeContextLoaderListener when a different scope is already published in the servlet context.

PerApplicationScope

The ScopedValue counterpart to context.PerApplicationContext. Each instance owns a mutable, thread-safe map keyed by lang.PerApplicationDataManager class; the instance methods run / call bind that map for the extent of an operation, and the static setPerApplicationData / getPerApplicationData read and write whichever map is bound (setPerApplicationDataIfAbsent stores only into an empty key and returns the value then held, the atomic form for registries created on first use). The static isBound() reports whether any map is bound on the calling thread without throwing, and the instance method isBoundOnCurrentThread() reports whether the map bound there is this instance’s. Only the binding is scoped — the map is shared, so data stored in one run is visible in every later or concurrent run of the same instance and through every carrier taken from it. Constructing an instance binds nothing. The instance methods boundThreadFactory / boundExecutor decorate a ThreadFactory or Executor so 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 static wrapThreadFactory / wrapExecutor. The static getBound() returns the instance bound on the calling thread, or null. The static resolve(handed) is the rule every consumer that accepts a PerApplicationScope — 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 throws ScopeException; null returns the bound scope, or null when nothing is bound, in which case the consumer runs its threads and callbacks with no scope, carrying only whatever PerApplicationContext they 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 — resolves null unless a scope is handed to it. A Spring assembly refreshed inside a scope can hold the bound instance as a bean through factory-method="getBound"; see holding the scope as a bean.

PerApplicationScope.ApplicationCarrier

Returned by the static generateCarrier() on a bound thread; run / call rebind the same map on any other thread, any number of times. The static wrapThreadFactory decorates a ThreadFactory so every thread it creates runs its whole body inside the carrier. Both throw MissingPerApplicationScopeException when called on an unbound thread, so a missing binding fails at wiring time rather than on the first lookup. The static wrapExecutor decorates an Executor so each task runs inside a carrier taken from the submitting thread at submission; it throws the same exception from execute when the submitting thread is unbound.

MissingPerApplicationScopeException

Unchecked, thrown by the static accessors, generateCarrier, wrapThreadFactory, and the execute of a wrapExecutor executor when no per-application scope is bound.

PerApplicationScopeFilter (org.smallmind.nutsnbolts.scope.web)

Servlet filter that binds a PerApplicationScope for the extent of chain.doFilter on every request it is mapped to. Construct it with the scope instance, optionally with suppressConnectionClosedException, or use the no-arg constructor for container-declared filters. init settles the scope through PerApplicationScope.resolve, in order: the scope given to the constructor, else the servlet context attribute named PerApplicationScope.class.getName(), else the scope bound on the thread running init. It throws MissingPerApplicationScopeException only when all three are absent, and ScopeException when 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.start tasks and work handed to other threads are not bound, while an AsyncContext.dispatch leg is bound again when the filter is mapped for the ASYNC dispatcher. When suppressConnectionClosedException is true (default false), an IOException from the chain whose message is exactly "Connection is closed" is discarded instead of rethrown. The chaining setter setSuppressConnectionClosedException turns it on for an instance registered programmatically through addFilter(name, instance); the filter reads no init-params, so a container-declared filter cannot enable it. Requires jakarta.servlet.

PerApplicationScopeContextLoaderListener (org.smallmind.nutsnbolts.spring.web)

Spring ContextLoaderListener that runs the web application context’s refresh and shutdown inside a PerApplicationScope and publishes that scope under the servlet context attribute the filter reads. contextInitialized settles 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 throws ScopeException when a scope was given to the constructor and a different scope is already published, and, through PerApplicationScope.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. contextDestroyed runs Spring’s shutdown inside the same scope and leaves the attribute published. Requires spring.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.

Scope flavor
<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>
Context flavor
<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()));
  1. The scope is bound for exactly the duration of processRequest(). If processRequest throws a checked exception, callInScope throws that same type; there is nothing to pop in a finally.

  2. Returns the innermost bound CallerScope, or null when called outside any entry.

  3. 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)
  1. The instance owns the map. Construction binds nothing to the current thread.

  2. Writes into the bound map. Because the map is shared, this value is visible in every later run / call on applicationScope and on every thread the wrapped factory creates.

  3. 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 PerApplicationScope read fails with MissingPerApplicationScopeException, and a lookup through one of the library’s bridging *Manager classes falls back to whatever PerApplicationContext the thread inherited, or fails with MissingPerApplicationContextException when there is none (see Per-application registries).

  4. PerApplicationScopeFilter binds the scope for the extent of chain.doFilter on every request. ScopedValue.CallableOp carries a single checked exception type, so the filter declares X = Exception and rethrows IOException, 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(), and getInputStream(). The input stream may return null if the backing store does not locate the content (rather than throwing), and the scheme is suitable as a map key.

ResourceParser, ResourceGenerator

Parses scheme:path strings into Resource instances. A ResourceGenerator knows which schemes it can produce; the parser maps each scheme to exactly one generator.

ResourceFactory

A Spring FactoryBean<Resource> that reads a name property (a resource identifier string) and vends the parsed Resource as 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
}
  1. Or file:/etc/app/app.yml, or jar:…​. 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, an ignoreUnresolvableProperties flag, a SystemPropertyMode (OVERRIDE or FALLBACK), and a searchSystemEnvironment flag. Call expand(String) or expand(String, Map).

PropertyClosure

Delimiter configuration (default ${ / }) plus an optional Decryptor that 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) and FALLBACK (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)
  1. Placeholders are resolved left-to-right; nested placeholders such as ${prefix.${region}} are supported. Unknown keys throw because ignoreUnresolvableProperties is false.

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 ByteArrayInputStream and ByteArrayOutputStream views. Constructors allow choosing the segment size (default 1 024 bytes) or reusing an existing ByteArrayIOBuffer. 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 ByteArrayIOStream instances.

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();
}
  1. The output view and the input view share the underlying segmented buffer; there is no copy.

  2. 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")));
  1. Skip the header row. Otherwise the first handleFields call 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)
  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. With relative = true the 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 Path that template names are resolved against. setBasePath switches 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) or send(Mail, HashMap<String, Object>) for FreeMarker interpolation.

Mail

Addressing, subject, body, attachments. Multiple constructors for common shapes; setters for everything else. setHtml(true) emits text/html.

Authentication, AuthType

Authentication descriptor and the enum of supported strategies. Use the shared Authentication.NONE constant or construct via the no-argument constructor and populate setType(AuthType) / setData(String[]).

Protocol

SMTP / SMTPS. Used internally by Postman to build the Session.

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);
  1. STARTTLS/SMTPS.

  2. Body is a FreeMarker template because the interpolation map in send is non-null.

  3. 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)
  1. Five-second timeout. Throws IOException on 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 like convertToBlock for 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 by SnowflakeId and 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_256 is the one callers reach for most often. EdDSASigningAlgorithm.ED_DSA maps to the JCA EdDSA signature, which selects the Edwards curve from the supplied key.

AsymmetricKeyGenerator

Generates RSA/EC key pairs; AsymmetricKeySpec and AsymmetricKeyType describe the requested shape.

CertificateUtility

X.509 certificate helpers (requires Bouncy Castle).

SecurityProviderInitializingBean

Spring InitializingBean that registers a SecurityProvider with the JVM during context startup.

KeyStoreUtility, TrustManagerUtility

Build KeyStore, KeyManagerFactory, and TrustManagerFactory instances from configured material.

NaiveTrustManager, NaiveHostNameVerifier, NaiveSSLSocketFactory

Skip certificate and hostname validation. Test-only.

Important

Naive* in the ssl subpackage name is not ornamental. These classes accept every certificate. Do not use them in production, and do not register them as the default HostnameVerifier or SSLSocketFactory in long-running JVMs.

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
);
  1. RetryCall is a functional interface that may throw Throwable.

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 SecureClassLoader that delegates class resolution through a chain of ClassGate`s. Gates decide which resources a given child loader may see; a `ClasspathClassGate accepts 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 as CSVParseException, SpreadParserException, DotNotationException, MutationException) inherit this pattern so callers can write throw new FooException("Bad id(%s)", id) instead of pre-formatting.

WrappedException

Adapts a checked exception into a RuntimeException for propagation through functional APIs, with a convert(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 by http.HTMLUtility.convertThrowable and 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
  1. 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 ParaboxContainer adapter for the host GUI toolkit. Produces SerialBox and ParallelBox instances via serialBox(…​) and parallelBox(…​) factory methods and exposes the horizontal and vertical root boxes via setHorizontalBox / 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 Box as a child of a layout box. Concrete toolkits subclass ComponentParaboxElement to 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), and Constraint.stretch() (both). Use Constraint.create() for a mutable variant, or new Constraint(grow, shrink) for explicit weights.

Bias

HORIZONTAL or VERTICAL. 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);
  1. container is a ParaboxContainer supplied 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 BeanFactoryPostProcessor that runs the nutsnbolts PropertyExpander over 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 Converter that turns a String identifier into a nutsnbolts Resource. Enables @Value("classpath:config.xml") style injection into Resource-typed bean properties.

ExtensionLoader<E>

Loads a Spring XML context from a working directory, optionally installing a GatingClassLoader so 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 through lang.PerApplicationDataManager. The context flavor stores it in context.PerApplicationContext. The scope flavor has the same register / getSpringPropertyAccessor API resolved through PerApplicationScope (see scope) and throws MissingPerApplicationScopeException on an unbound thread. The two holders are unrelated. SpringPropertyAccessorManager bridges them under the rules in Per-application registries: register writes to every registry bound on the calling thread, and getSpringPropertyAccessor reads 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 with MissingPerApplicationContextException. PropertyPlaceholderConfigurer registers through the bridging manager, and the dynamic initializing beans read through it.

WebContextLoaderListener, PerApplicationScopeContextLoaderListener (spring.web)

ContextLoaderListener extensions for servlet deployments. The first attaches a context.PerApplicationContext map 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 attribute PerApplicationContextFilter reads. 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. contextDestroyed attaches 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 the nutsnbolts classes 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 in WEB-INF/lib to keep them apart. The second listener runs the refresh and shutdown inside a PerApplicationScope and publishes that scope for PerApplicationScopeFilter; 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 throws ScopeException when 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’s ExposedWebContextLoaderListener and ExposedPerApplicationScopeContextLoaderListener extend the two with the same flavor rules and filter pairing, and additionally expose the refreshed context (see WEB.adoc). All four require spring.web and jakarta.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-arg LRUMap(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. The reversed constructor 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 Comparable ordering 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 int counter with pre- and post-variants of incAndGet / getAndInc / decAndGet / getAndDec / addAndGet / getAndAdd / subtractAndGet / getAndSubtract. Not thread-safe — for that, use AtomicInteger.

Mutation<T,R> / MutationUtility

A Function-like functional interface whose apply is allowed to throw checked exceptions. MutationUtility runs a Mutation over arrays, iterators, iterables, and collections to produce arrays, lists, sets, maps, or Bag`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. Option is a Serializable interface with two implementations: Some, the present case, built with Option.of(value); and None, the absent case, a singleton obtained from Option.none() and typed to the caller’s element type. Because Some accepts a null value, isNone() (which of the two cases this is) and isEmpty() (whether get() returns null) are distinct questions — a present option can be empty. Unrelated to the command-line Option in org.smallmind.nutsnbolts.command.template, despite the shared simple name.

AnsiColor

Terminal color escape sequences.

Bytes

Big-endian conversion between primitive long / int / short values and fixed-width byte arrays, used by SnowflakeId and elsewhere to pack numeric identifiers. For hex encoding see HexCodec in the security package.

SelfDestructiveMap<K,V>

A map whose entries expire after a configurable TTL; uses SelfDestructiveKey under the hood.

NumberComparator

Cross-type numeric comparator that normalises across BigDecimal, BigInteger, floating-point, and integral primitive wrappers before comparing. Throws FormattedRuntimeException when handed a Number subtype it does not recognise.

DirectionalComparator<T> / NaturalDirectionalComparator<T>

Abstract base that carries a sort Direction (ASCENDING / DESCENDING), and a concrete subclass that delegates to Comparable.compareTo.

DotNotation

Compiles a glob-style dotted pattern (segments joined by ., with * and ? as wildcards) into a Pattern, and computes a bitmask value reflecting which segments matched. Rejects malformed input such as leading or trailing dots, consecutive dots, or wildcards mid-segment via DotNotationException.

Spread / NumericSpread / AlphaSpread

Expand comma-delimited range expressions such as "1,3..5,9" or "a,c..e,z" into arrays. Spread dispatches to the numeric or alphabetic variant based on the first character. Errors are surfaced as SpreadParserException.

MagicHash

XOR-shift hash mixer that reduces clustering and improves bit distribution for int hash codes. Useful when building custom hash tables over inputs whose natural hash code clusters in the low bits.

MartianBase34

Encodes non-negative long values into a 34-character custom alphabet, applying a per-Group additive mix constant. Three Group constants (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 SnowflakeId to embed a machine identifier in every generated id.

LocaleUtility, StringUtility, EnumUtility, ArrayUtility

Assorted helpers. EnumUtility.toEnumName converts free-form text into upper snake-case enum constant names with configurable digit-prefix handling. StringUtility covers display/camel-case conversion, Java-identifier validation, and ellipsis trimming. ArrayUtility clones, concatenates, and linear-searches generic arrays. LocaleUtility.forCountryISO3Code looks up a Locale by 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));
  1. 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

LazyFieldAspect requires AspectJ weaving (load-time or compile-time). The nutsnbolts POM configures the aspectj-maven-plugin for its own build; consumers who want lazy fields in their own code must configure weaving separately and must supply org.aspectj:aspectjrt, which is optional in the nutsnbolts POM. On the module path its module name is org.aspectj.runtime, and the package declaring a lazy field must be opened to org.smallmind.nutsnbolts unless the field has a public getter and setter (see Module Path).

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 — an LdapConnectionDetails and a user search path — taking them as constructor arguments, and exposes a protected getLdapContext bind helper to its subclasses. The group-to-role map is set afterwards via setGroupRoleMap. It also owns authorization: it reads the groups a subject belongs to (via the subclass hook getDirectoryGroups) and grants each subject the RoleType its 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 the userPassword attribute, 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, getDirectoryGroups searches 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: connectionDetails and searchPath (from the base), then the four group-schema arguments groupSearchPath, groupObjectClass, memberAttribute, and memberValueTemplate (the member value to match, with {0} replaced by the principal, e.g. uid={0},ou=people for full-DN members or {0} for posix memberUid). 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 the NamingException raised by that bind. Its constructor takes connectionDetails, searchPath, and the UPN domain, so it has no no-argument constructor. For authorization, getDirectoryGroups reads the user’s memberOf group 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/rootNamespace provider URL. Credentials are held in plain text for the life of the realm.

RoleType

Enum of grantable role codes (ADMIN, USER, GUEST), with a fromCode(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 through setGroupRoleMap. Add constants here to model additional roles.

DefaultLdapRealmFactoryBean, ActiveDirectoryLdapRealmFactoryBean (in …realm.spring)

One Spring FactoryBean per 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) or domain (ActiveDirectoryLdapRealm) — plus the optional groupRoleMap. Each builds its realm once in afterPropertiesSet(), returns it as a singleton, and reports the concrete realm class from getObjectType(). 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

ldap.user / ldap.password

Service-account bind credentials

ldap.host / ldap.port / ldap.root

Directory host, port, and root namespace

ldap.auth.search_path

Subtree under which user entries are searched

ldap.group.search_path

Subtree searched for group entries

ldap.group.object_class / ldap.group.member_attribute / ldap.group.member_value

Group object class, member attribute, and member-value template ({0} is replaced by the principal) — e.g. groupOfNames, member, uid={0},${ldap.auth.search_path}

ldap.admin.group

Group DN granted RoleType.ADMIN by the shipped groupRoleMap

Important

The shipped fragment builds a DefaultLdapRealm. To use Active Directory instead, override the ldapRealm bean with ActiveDirectoryLdapRealmFactoryBean — its constructor needs only the UPN domain, and groups come from memberOf:

<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 <entry> value is a RoleType constant name, which Spring converts automatically; without a groupRoleMap the realm grants no roles. ldapConnectionDetails is an LdapConnectionDetails bean carrying the ${ldap.user}, ${ldap.password}, ${ldap.host}, ${ldap.port}, and ${ldap.root} placeholders.

ByteArrayIOStream, CircularBufferIOStream, and their paired input/output views treat close() as a one-way latch. Once closed:

  • asInputStream() and asOutputStream() still return the view instances, but subsequent reads and writes throw IOException.

  • 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):

  1. Caller map (expand(expansion, expansionMap)).

  2. System properties (System.getProperty).

  3. Environment variables (System.getenv) if searchSystemEnvironment is true.

With SystemPropertyMode.OVERRIDE:

  1. System properties.

  2. Environment variables (if enabled).

  3. 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 NoClassDefFoundError or ClassNotFoundException on first use, not at application startup. Read the Optional Dependency Matrix before wiring a new subpackage into production.

Retry blocks the caller

Retry.execute runs 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.

Postman template cache has no eviction

See Email template caching.

ssl naive 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.

inject is not a DI container

@Service is a marker. @LazyField requires AspectJ weaving. Neither substitutes for Spring, CDI, or Guice.

namespace.shiro authorization must be configured

Roles come from the group-to-RoleType map set via setGroupRoleMap; an unconfigured map grants no roles. ActiveDirectoryLdapRealm derives groups from the user’s memberOf attribute; DefaultLdapRealm derives 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 through DefaultLdapRealmFactoryBean / ActiveDirectoryLdapRealmFactoryBean (or a direct <constructor-arg> bean). See namespace.shiro — Shiro LDAP realms.

layout is 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 ParaboxElement adapter for your toolkit (the smallmind-javafx module contains a JavaFX adapter as a reference).

scope bindings do not cross plain thread boundaries

Unlike ContextFactory, ScopeFactory bindings 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. Use ScopeFactory.snapshot() with ScopeSnapshot.run / call to rebind explicitly, submit through ScopeFactory.wrapExecutor(executor), or build the pool from ScopeFactory.wrapThreadFactory(threadFactory) when the bindings are fixed at pool construction. The same applies to PerApplicationScope: a thread pool you build yourself that resolves per-application data must be built from PerApplicationScope.wrapThreadFactory, receive its tasks through PerApplicationScope.wrapExecutor, or have them run through an ApplicationCarrier; unlike context.PerApplicationContext, nothing is inherited. The library’s own pools, transports, and servers that accept a PerApplicationScope bind 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.

PerApplicationContext adoption 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 the nutsnbolts classes and initializes them on one thread lets the second webapp’s WebContextLoaderListener adopt the first’s map, so the two share one registry. Give each webapp its own copy in WEB-INF/lib, or deploy one application per container.

PerApplicationContext maps are never detached

prepareThread and inheritance attach a map to a thread for the thread’s lifetime; no filter or carrier removes it. Where the nutsnbolts classes are shared at container level, a request thread that once served webapp A carries A’s map onto B’s paths that no PerApplicationContextFilter is mapped to, and onto ERROR dispatches, 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 with MissingPerApplicationContextException (Claxon excepted, which returns null registries and unplugged instrumentation). The same holds across a redeploy when the nutsnbolts classes are shared: WebContextLoaderListener attaches 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 in WEB-INF/lib nothing is adopted; the attached map instead pins the destroyed webapp’s class loader for the thread’s lifetime, as every request thread that ran PerApplicationContextFilter already does.

Both bindings in a plain servlet container

PerApplicationScopeContextLoaderListener binds 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 a PerApplicationContext to the deploy thread and publish it under the PerApplicationContext.class.getName() attribute before PerApplicationScopeContextLoaderListener runs — a ServletContextListener declared ahead of it that constructs a PerApplicationContext and sets the attribute — then map both PerApplicationScopeFilter and PerApplicationContextFilter; 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.

PerApplicationScopeFilter binds only the filter chain

The scope is bound for the extent of chain.doFilter and nothing else. An AsyncContext.dispatch leg is bound only when the filter is mapped for the ASYNC dispatcher with async support enabled, as servlet container wiring shows and as GrizzlyInitializingBean and JettyInitializingBean map 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 an ApplicationCarrier. The no-arg filter settles its scope in init from the servlet context attribute published by PerApplicationScopeContextLoaderListener or application code, else from the scope bound on the thread running init; with neither it fails with MissingPerApplicationScopeException, as it does not create one.

Optional modules on the module path

Every optional dependency is requires static in 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 with NoClassDefFoundError exactly as if the jar were missing. requires the module or pass --add-modules. See Module Path.

examples opens a package with no classes

The descriptor opens org.smallmind.nutsnbolts.examples so its resources stay loadable by path. javac reports [opens] package is empty or does not exist for that line while compiling this module; the warning is expected. At run time the package exists because the jar contains its resource files.

  • smallmind-nutsnbolts sits 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 inherits aspectjrt as optional from 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 is requires static (see Module Path).

  • The build configures the smallmind-license-maven-plugin (for dual AGPL/Apache licensing headers) and the aspectj-maven-plugin (because LazyFieldAspect is an AspectJ aspect woven at compile time for this jar). A consumer that uses @LazyField in 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 under org/smallmind/nutsnbolts/. Consumers import them with classpath: references.