Soklet Logo

Core Concepts

Value Conversions

Given an HTTP request...

GET /test?number=123

...and a corresponding Resource Method...

@GET("/test")
public String test(@QueryParameter Integer number) {
  return String.format("Hello %d", number);
}

...how does Soklet convert the query parameter number to an instance of java.lang.Integer?

The answer: it consults a ValueConverterRegistry which contains a set of ValueConverter<F,T>, each instance of which knows how to convert a "from" type F to a "to" type T.

Value conversions will be automatically applied to Resource Method parameters decorated with any of these annotations:

For ordinary HTTP request parameter binding, Soklet supports more than just scalar T values. Query parameters, form parameters, request headers, request cookies, and multipart fields may also be injected as Optional<T>, List<T>, or Optional<List<T>>. Repeated values bind naturally to lists, while repeated values for non-list parameters are rejected instead of silently picking one.

The same ValueConverterRegistry is also used by SSE Event Source Methods. An @SseEventSource method uses the normal resource-method binding pipeline, so @PathParameter, @QueryParameter, @RequestHeader, and @RequestCookie values are converted exactly the same way they would be for a regular HTTP method.

MCP input binding does not use this registry. Tool schemas and JSON binding are derived from supported Java types, while resource URI-template variables are exposed as strings through @McpResourceUriParameter or McpResourceReadContext::getUriTemplateVariables. See MCP for those rules and current API references.


Default Conversions

Via ValueConverterRegistry, Soklet provides out-of-the-box support for the following conversions to JDK types:

The set of default converters is programmatically accessible via ValueConverters::defaultValueConverters.

There are two other quality-of-life features provided by ValueConverterRegistry:

  1. A special reflexive ValueConverter<F,T> is automatically used for scenarios in which F is equal to T.

  2. For any String to Enum<E extends Enum<E>> conversions, a ValueConverter<F,T> is automatically generated if necessary and cached off. This is almost always what you want.

For example, given this declaration:

enum Testing {
  ONE,
  TWO,
  THREE
}

This code will "just work" without any additional setup:

@GET("/example")
public String example(@QueryParameter Testing testing) {
  return String.format("Hello %s", testing.name());
}

At runtime, Soklet will automatically generate and cache a ValueConverter<F,T> that knows how to convert a String to Testing.ONE, Testing.TWO, or Testing.THREE so you do not have to manually create and register a custom converter.

Enum auto-conversion applies the same Unicode space-separator trimming as the default string converters. Null or input consisting only of those spaces produces Optional.empty(); otherwise the trimmed value must match the exact, case-sensitive enum constant name via Enum::valueOf. VANILLA matches Flavor.VANILLA, while vanilla does not. Tabs, carriage returns, and line feeds are not trimmed. An explicitly registered string-to-enum converter takes precedence and controls its own parsing.

The default String converters for BigInteger, BigDecimal, and Number accept at most 4,096 characters after trimming. BigDecimal and Number also require the absolute scale and adjusted exponent (precision - scale - 1) to be at most 4,096. For example, 1e4097 exceeds the exponent bound despite its short spelling. Exceeding any of these limits fails binding with HTTP 400. Register an application converter to support different bounds.

Numeric and UUID conversion retains the JDK parsers' accepted forms, including NaN and infinity for floating-point values, supported Unicode digits for integral values, and the UUID forms accepted by UUID.fromString. Register a custom converter when your application requires finite numbers, ASCII-only digits, or canonical UUID text.

Common Binding Shapes

These are all valid uses of Soklet value conversion for HTTP parameters:

@GET("/search")
public Response search(
  @QueryParameter(name = "tag") List<String> tags,
  @QueryParameter(name = "limit") Optional<Integer> limit,
  @RequestHeader(name = "X-Tenant") Optional<UUID> tenantId
) {
  // ...
}

For multipart forms, list and optional-list binding work too:

@POST("/upload")
public void upload(
  @Multipart(name = "file") List<byte[]> files,
  @Multipart(name = "score") Optional<List<Integer>> scores
) {
  // ...
}

Blank Inputs and Whitespace

Soklet's default converters aggressively trim incoming string values before conversion. If you extend AbstractValueConverter or FromStringValueConverter, leading and trailing Unicode space-separator characters are removed first, and values made up entirely of those characters become null before your conversion logic runs.

This is meant to catch surprising Unicode spaces such as non-breaking spaces or narrow no-break spaces. It does not trim tabs, carriage returns, or line feeds.

That means:

  • A scalar query/form/header/cookie value of "" or " " behaves like a missing value.
  • If a custom converter returns Optional.empty() for a required scalar query, form, header or cookie binding, the request fails with HTTP 400. Optional bindings can still receive no value.
  • Blank entries inside repeated values are skipped when binding to List<T>.
  • If you need different trimming behavior, override the protected shouldTrimFromValues() method on AbstractValueConverter or implement ValueConverter directly. The published Javadoc lists public members, so this protected extension point is not a separate method entry there.

Blank-Slate Conversions

To acquire a strict registry without defaults, reflexive conversion, or automatic enum conversion, use the blank-slate factories:

// True blank slate: no conversions performed
ValueConverterRegistry registry = ValueConverterRegistry.fromBlankSlate();

// Blank slate plus only those converters you explicitly specify
ValueConverterRegistry supplemented =
  ValueConverterRegistry.fromBlankSlateSupplementedBy(
    Set.of(/* Custom ValueConverters here */)
  );

Default @RequestBody Conversion

Soklet's default RequestBodyMarshaler is intentionally simple. It reads the raw request body as a string and then looks for a String -> T converter in the ValueConverterRegistry.

That is useful for plain-text payloads such as:

  • Numbers
  • Dates and times
  • UUIDs
  • Your own custom textual formats

It is not a general JSON object mapper.

If you want to parse JSON, XML, protobuf, or any other structured content type, supply your own RequestBodyMarshaler as described in Request Handling.

Custom Conversions

Register at most one custom converter for each equivalent source/target type pair. Primitive and boxed types are equivalent: String → int and String → Integer count as the same pair, so registering both is rejected. A single custom converter still overrides the corresponding built-in converter.

Suppose we want to accept a typed JWT, which is comprised of 3 Base64-URL-encoded segments separated by a . character, e.g. a.b.c. Let's create a record to represent it:

public record Jwt(
  String header,
  String payload,
  String signature
) {}

Next, we need to make a ValueConverter<String, Jwt>. We could directly implement the interface, but using Soklet's abstract convenience class FromStringValueConverter<T> takes care of the boilerplate and lets us focus solely on the conversion code:

ValueConverter<String, Jwt> jwtVc = new FromStringValueConverter<>() {
  @NonNull
  public Optional<Jwt> performConversion(@Nullable String from) throws Exception {
    if(from == null)
      return Optional.empty();

    // JWT is of the form "a.b.c", break it into pieces
    String[] components = from.split("\\.");
    Jwt jwt = new Jwt(components[0], components[1], components[2]);
    return Optional.of(jwt);
  }
};

Soklet now needs to know about our custom ValueConverter<String, Jwt>. We create a ValueConverterRegistry - which already is prefilled with default Value Converters - and provide it with our additional custom converter:

// Create a ValueConverterRegistry, supplemented with our custom converter
ValueConverterRegistry valueConverterRegistry =
  ValueConverterRegistry.fromDefaultsSupplementedBy(Set.of(jwtVc));

// Configure Soklet to use our registry
SokletConfig config = SokletConfig.withHttpServer(
  HttpServer.fromPort(8080)
).valueConverterRegistry(valueConverterRegistry)
 .build();

Everything is in place. We can now accept our new Jwt type anywhere that Soklet injects values.

@GET("/jwt/{jwt}/payload")
public String jwtPayload(@PathParameter Jwt jwt) {
  return jwt.payload();
}

Verify that it works:

% curl -i 'http://localhost:8080/jwt/a.b.c/payload'
HTTP/1.1 200 OK
Content-Length: 1
Content-Type: text/plain; charset=UTF-8
Date: Sun, 21 Mar 2024 16:19:01 GMT

b

And verify behavior if conversion fails:

% curl -i 'http://localhost:8080/jwt/abc/payload'
HTTP/1.1 400 Bad Request
Content-Length: 21
Content-Type: text/plain; charset=UTF-8
Date: Sun, 21 Mar 2024 16:19:01 GMT

HTTP 400: Bad Request

We can see that if an exception occurs during value conversion, Soklet detects this and re-throws a subclass of BadRequestException with a detailed description of the problem and fields that contain the offending name and value (in this case, IllegalPathParameterException). Your exception handling code will have everything it needs to gracefully process the error and surface a user-friendly error message.

com.soklet.exception.IllegalPathParameterException: A path parameter could not be converted to the resource method parameter type.
    at com.soklet.DefaultResourceMethodParameterProvider.extractParameterValueToPassToResourceMethod(...)
...

The exception's public name/value fields retain the binding context, but the framework-generated message omits the submitted value and does not attach the converter's cause. Treat those fields as sensitive when logging them.

Generic Type Lookups

If you interact with ValueConverterRegistry directly and need a converter for a generic type, use TypeReference<T>. Java cannot express something like List<Integer>.class, so the type token has to carry that generic information.

Optional<ValueConverter<String, List<Integer>>> converter =
  registry.get(
    new TypeReference<String>() {},
    new TypeReference<List<Integer>>() {}
  );

Limitations

Soklet infers a converter's F and T types by reflection when the converter is constructed. Subclasses of AbstractValueConverter or FromStringValueConverter may use intermediate generic base classes, as long as the class you instantiate fixes both types.

Inference fails when a type is still a type variable in the class you instantiate:

class TokenConverter<T> extends AbstractValueConverter<String, T> {
  @Override
  public Optional<T> performConversion(@Nullable String from) throws Exception {
    // ...
    return Optional.empty();
  }
}

Here new TokenConverter<Jwt>() throws an IllegalStateException, because T is erased at run time. A subclass that fixes the type works, including an anonymous one: class JwtConverter extends TokenConverter<Jwt> {} or new TokenConverter<Jwt>() {}. You can also implement ValueConverter directly.

Previous
Instance Creation