Loading…
Loading…
Generates example string values that satisfy schema constraints such as pattern, minLength, and maxLength. Ensures API examples are valid against their
The ConstrainedStringSampler is a stateless utility that generates example string values that conform to a given set of schema constraints. It solves the problem of API specifications containing example values that are invalid according to the schema rules (pattern, length, minLength, maxLength) defined for those values.
This component is used internally by other platform services, such as the OpenAPI specification generator (OpenApiService) and the contract example generator (ContractExampleService), to ensure that generated examples are self-consistent and pass schema validation.
For an API publisher, this means that the example values shown in generated API documentation will be valid and usable. This prevents situations where an API consumer might try an example from the documentation only to have it rejected by the API gateway for violating schema rules that were also in the documentation.
The ConstrainedStringSampler generates a valid string by creating a list of candidate values and returning the first one that satisfies all provided constraints. If no candidate can be found, it returns a best-effort fallback value.
The core logic resides in the static sample method.
flowchart TD
subgraph "Input"
A[Base Value & Schema Constraints <br/>(pattern, min/max length)]
end
subgraph "Processing"
B{Any constraints provided?}
A --> B
B -- No --> C[Return Base Value]
B -- Yes --> D[Determine Target Length]
D --> E[Generate Candidate List]
E --> F{Iterate through candidates}
subgraph "Candidate Generation"
style E fill:#f9f,stroke:#333,stroke-width:2px
E1[1. Heuristics for simple regex patterns]
E2[2. Base Value, adjusted for length]
E3[3. Simple repeating character strings ('111', 'AAA')]
E4[4. Alternating alphanumeric string ('A1A1')]
E5[5. Advanced regex generator for complex patterns]
end
F --> G{Is candidate valid?}
G -- No --> F
subgraph "Validation"
style G fill:#ccf,stroke:#333,stroke-width:2px
G1[Within length bounds?]
G2[Matches regex pattern?]
end
G -- Yes --> H[Return First Valid Candidate]
end
subgraph "Output"
F -- All candidates invalid --> I[Return Fallback Value <br/>(length-adjusted base value)]
C --> Z[Final String Example]
H --> Z
I --> Z
endpattern, exactLength, minLength, maxLength) are provided. If not, the original baseValue is returned immediately.targetLength. This length respects exactLength if present, otherwise it is derived from the baseValue's length, minLength, maxLength, and a fallbackLength. The resulting length is always at least 1.pattern is provided, the sampler first attempts to generate candidates using heuristics for common regular expressions (e.g., [0-9]+, [A-Z]{5}, \d{1,10}). This includes a generic handler for single character classes (e.g., [A-Za-z0-9_-]+).baseValue is truncated or padded to meet the targetLength.'111...', 'AAA...').'A1A1A').RegexExampleGenerator is invoked. This is a last-resort attempt and its results are added to the end of the candidate list.exactLength, minLength, and maxLength.pattern was provided, it validates the string against the regular expression using the ContractPatternValidator.baseValue as a final fallback. This fallback value will respect length constraints but may not satisfy the pattern constraint.This example demonstrates how the sampler corrects an example value that is too long for its schema constraint.
Given an input baseValue of "sample-SHILDA" (13 characters) and a maxLength constraint of 10.
Invocation:
String result = ConstrainedStringSampler.sample(
"sample-SHILDA", // baseValue
null, // pattern
null, // exactLength
null, // minLength
10, // maxLength
8 // fallbackLength
);
Execution:
maxLength: 10), so the process continues.targetLength is resolved. The baseValue length (13) is greater than maxLength (10), so the targetLength is capped at 10.baseValue. The adjustToLength method truncates "sample-SHILDA" to respect the maxLength of 10. The resulting candidate is "sample-SHI"."sample-SHI" is validated. Its length is 10, which is not greater than maxLength (10). The length check passes.pattern to validate against.Expected Result:
The method returns the string "sample-SHI".
The component exposes a single static method, sample.
samplepublic static String sample(String baseValue, String pattern, Integer exactLength, Integer minLength, Integer maxLength, int fallbackLength)
Fits a base string value to the supplied schema facets, returning a new string that satisfies the constraints.
| Name | Type | Default | Required | Description |
|---|---|---|---|---|
baseValue | String | — | Yes | The unconstrained candidate string (e.g., a field name). Can be null. Used as-is if no constraints are provided. |
pattern | String | — | Yes | The regular expression pattern (XSD/OpenAPI format) the string must match. Can be null or blank if not applicable. |
exactLength | Integer | — | Yes | The exact required length of the string (xs:length). Overrides minLength and maxLength. Can be null. |
minLength | Integer | — | Yes | The minimum required length of the string (xs:minLength). Can be null. |
maxLength | Integer | — | Yes | The maximum allowed length of the string (xs:maxLength). Can be null. |
fallbackLength | int | — | Yes | The target length to use when baseValue is blank and no exactLength or minLength constraint provides a floor. This argument is a primitive and cannot be null. |
A String that satisfies the provided constraints. If no generated candidate is fully compliant, it returns a best-effort fallback string that respects length constraints but may not match the pattern.
The ConstrainedStringSampler uses a series of heuristics to generate a valid example. While it covers many common cases, it is possible for it to fail to produce a string that satisfies a very complex pattern constraint.
If the sampler fails to find a valid candidate, it returns a fallback value. This fallback is the initial baseValue adjusted for length constraints (minLength, maxLength, exactLength). This fallback value is not guaranteed to match the pattern constraint.
The source code indicates that several improvements have been made to handle cases that previously failed:
RegexExampleGenerator to handle patterns with optional groups that could otherwise generate a string exceeding maxLength.[A-Z0-9-]{1,10}) was added to handle patterns not covered by the initial, more specific heuristics.If you encounter an example in a generated specification that is invalid, it may be due to a pattern that is too complex for the sampler's current capabilities.
ContractExampleService: A service that uses this sampler to generate examples for API contracts.OpenApiService: A service that uses this sampler to generate examples within OpenAPI specifications.ContractPatternValidator: The utility used internally by the sampler to check if a string matches a given regular expression.RegexExampleGenerator: A utility used by the sampler as a last resort to generate examples for complex regular expression patterns.