Repository navigation
Conversation
rar91279
added a commit
to rar91279/openapi-generator
that referenced
this pull request
Nov 11, 2026
…fixes Ports two okhttp-gson fixes that apply to the okhttp library as well: - OpenAPITools#25539 (1468a35): a oneOf with more than 100 variants made the anonymous Gson TypeAdapter capture one local per variant, exceeding the JVM's 255 constructor-argument limit (ClassFormatError "Too many arguments in method signature"). The okhttp oneof_model.mustache now opens the anonymous adapter before the per-variant adapters when the model carries x-gson-large-oneof, exactly like okhttp-gson. - OpenAPITools#25581 (b665c6f): parameters named basePath, localBasePaths, localCustomBaseUrl or localHostIndex collide with the locals of the generated call methods. The okhttp api template shares those locals, so toParamName renames them for okhttp too. OpenAPITools#25542 (primitive arrays in a Gson oneOf) needs no template change: the okhttp adapter already writes every variant through toJsonTree and the JsonElement adapter. The test now covers okhttp to prove it. The three master tests run for both libraries. No sample changes: the petstore specs have neither a 100+ variant oneOf nor a colliding parameter name.
wing328
added a commit
that referenced
this pull request
Nov 18, 2026
* [java][okhttp] Add okhttp library supporting Gson, Jackson 2/3 and JSON-B
Adds a new "okhttp" library to the Java client generator, forked from
"okhttp-gson" but decoupled from Gson: one template set emits clients for
Gson (default), Jackson 2, Jackson 3 and JSON-B, on OkHttp 5.4.0, and honours
the existing useJspecify option.
Templates (Java/libraries/okhttp/):
- JSON.mustache carries three parallel implementations - Gson (gson-fire +
TypeAdapterFactory), Jackson (ObjectMapper, jacksonPackage-parameterised for
2.x/3.x) and JSON-B (Yasson + JsonbAdapters, with a GenericType<T> helper
standing in for TypeToken).
- ApiClient holds JSON as an instance so serializer config is per-client,
passes request payloads to auth as byte[] rather than String, and signs
AWS4 last so it sees the final query string.
- auth/RetryingOAuth embeds its own TokenRequestBuilder and talks to OkHttp
directly, dropping the Apache Oltu dependency that okhttp-gson needs.
- api/pojo/oneof/anyof switch between TypeToken, TypeReference and
JSON.GenericType, and use the shared nullableArgument partials plus the
jSpecifyDatatype lambda already provided by AbstractJavaCodegen.
Templates that only differed cosmetically from their root-level counterparts
(Pair, StringUtil, ServerVariable, ServerConfiguration, maven.yml, travis,
git_push.sh) are deliberately not forked - mustache resolution falls back to
Java/ and the generated output is verified to include them.
JavaClientCodegen:
- registers the library, adds it to JSPECIFY_SUPPORTED_LIBRARIES and to the
useJackson3 allowlist, and reuses the okhttp-gson supporting-file branch
without forcing the serialization library.
- resolves isGson/isJackson/isJsonb after the serialization switch, where
getSerializationLibrary() is authoritative, instead of guessing earlier.
- forces openApiNullable off for JSON-B, since jackson-databind-nullable is
Jackson-only and the pom omits it there.
- applies the x-enum-as-string discriminator rewrite for every serialization
library (a narrowed discriminator otherwise generates a getter that cannot
override the parent's String getter), while keeping the JsonNullable and
JsonIgnore imports Jackson-only.
- extends the useSingleRequestParameter and oneOf/anyOf ModelNull handling to
the new library, both of which its templates support.
* [java] Rename okhttp-gson user-defined-templates config to match its library
bin/configs/java-okhttp-user-defined-templates.yaml generated the okhttp-gson
sample despite the neutral name; every other okhttp-gson config on master is
already named java-okhttp-gson-*. Renaming it keeps the naming consistent and
frees the java-okhttp-* prefix for the new okhttp library, without touching the
generated sample.
* [java][okhttp] Add sample configurations for the okhttp library
27 configs covering the new library: the four serialization variants (Gson,
Jackson 2, Jackson 3, JSON-B), JSpecify for each of Jackson 2/3 and JSON-B,
oneOf/anyOf, nullable-required, AWS4 signing, dynamic operations, grouped
parameters, parcelable models, streaming, swagger 1/2 annotations, OpenAPI 3.1,
the echo API and user-defined templates.
Fixes carried over from the prototype branch:
- java-okhttp-echo-api.yaml had "library" commented out, so it silently
generated with the default okhttp-gson library instead of okhttp.
- java-okhttp-jackson-nullable-required.yaml never set
serializationLibrary: jackson, making it a duplicate of the gson config.
- java-okhttp.yaml had "useReflectionEqualsHashCode::" with a double colon, so
the property never applied.
- java-okhttp-jackson3-oneOf.yaml wrote to others/java/oneOf-okhttp-jackson3,
breaking the okhttp-<serializer>-<feature> convention of its siblings, and
java-okhttp-jackson3-jspecify.yaml reused the artifactId of the non-jspecify
jackson3 config.
- java-okhttp-jsonb-jspecify.yaml set useJackson3 alongside JSON-B.
Every config names its serialization library explicitly, including the Gson
ones: JavaClientCodegen infers its internal "jackson" flag from the absence of
the property, so relying on the default would opt Gson output into
Jackson-specific nullable handling.
All 27 configs generate, and every generated sample compiles and passes its
tests under Maven.
* [java][okhttp] Wire okhttp samples into CI and refresh generator docs
- pom.xml: java-client-okhttp profile builds the four serialization variants,
java-client-okhttp-parcelable mirrors the okhttp-gson parcelable profile.
- Workflows: each okhttp-gson entry gains its okhttp counterpart, in both the
path triggers and the sample matrices. The petstore-server workflow gets the
three samples that mirror okhttp-gson there; the plain client workflow gets
the serialization, jspecify, oneOf, nullable-required, swagger, streaming,
AWS4, grouped-parameter and parcelable samples; echo-api, gradle and sbt get
their okhttp equivalents.
- docs/generators/java.md: regenerated - the library table gains okhttp and
useJspecify now lists it as supported.
* [java][okhttp] Regenerate samples for the okhttp library
Generated output for the 27 new bin/configs. Every sample compiles and passes
its tests under Maven, across all four serialization variants.
* [java][okhttp] Regenerate samples against a clean build
The previously committed samples were generated with a jar that still contained
seven okhttp templates from an earlier prototype build: Pair, StringUtil,
ServerVariable, ServerConfiguration, maven.yml, travis and git_push.sh. Those
templates are intentionally not part of this library - mustache resolution is
supposed to fall back to the shared Java/ and _common/ templates - but stale
target/classes output survived an incremental build and was shaded into the CLI
jar, where library-local templates take precedence.
Rebuilt with `mvn clean install` and regenerated. Only git_push.sh actually
differed in the output; it now matches _common/git_push.sh.mustache and is
byte-identical to the okhttp-gson sample, as are Pair, StringUtil,
ServerVariable, ServerConfiguration, maven.yml and travis.
* [java][okhttp] Fix defects found in review of the new library
Correctness fixes to the forked templates:
- GzipRequestInterceptor: restore the forceContentLength() wrapper dropped from
okhttp-gson. Without it the gzip body reports contentLength() == -1, OkHttp
falls back to Transfer-Encoding: chunked, and every compressed request fails
against servers that reject chunked request bodies. The unused okio.Buffer
import was the tell that the removal was accidental.
- ProgressResponseBody: restore the memoized bufferedSource field. OkHttp calls
source() again on close(), so without caching each call built a fresh
ForwardingSource over a partially consumed stream, resetting the progress
counter and risking double reads.
- ProgressRequestBody: CountingSink no longer reports done, so a known-length
body gets exactly one terminal callback instead of two (writeTo still emits
the terminal event, which is what unknown-length bodies rely on). Dropped the
unreachable private countingSink(Sink) helper.
- AWS4Auth: sign x-amz-* headers. They were never added to the signable
request, so SigV4 omitted them from SignedHeaders and AWS rejected the
signature. Content-Type is deliberately left unsigned because OkHttp's
BridgeInterceptor appends the multipart boundary after signing. This also
wires up the two-pass auth ordering in ApiClient, which until now had no
effect.
- JSON: register RFC3339JavaTimeModule for Jackson 2. The codegen already
emitted RFC3339InstantDeserializer and RFC3339JavaTimeModule, but nothing
installed them, so the space-separated RFC3339 normalization never ran. Every
other Jackson library registers it. Jackson 3 does not emit the classes and
is left untouched.
- additional_properties: replace Java `transient` with @JsonbTransient. The
transient keyword was added by this fork and made Java serialization drop all
undeclared properties when serializableModel=true; @JsonbTransient keeps
JSON-B from emitting the backing map without that side effect.
- ApiResponse: lowercase header keys in the caseInsensitiveResponseHeaders
branch, matching okhttp-gson, native, jersey2 and jersey3.
- pojo: stop emitting five Jackson imports that JavaClientCodegen already
contributes via model.imports, which produced duplicate import lines.
JsonTypeName is only contributed for Jackson 2, so it is still emitted from
the template under useJackson3.
Build files:
- build.gradle: add the com.google.android:android compileOnly dependency under
parcelableModel, mirroring the pom. Generated Parcelable models now compile
with a plain Gradle build.
- build.sbt: add the swagger-parser-v3 dependency under dynamicOperations and
the jakarta.validation-api dependency under useBeanValidation, both of which
the pom and Gradle builds already declared; gate jackson-annotations on
Jackson 2 so Jackson 3 clients take the version aligned by jackson-databind.
All 27 samples regenerated; each compiles and passes mvn test, and
JavaClientCodegenTest still passes 288 tests. okhttp-gson output is unchanged.
* [java][okhttp] Route the Jackson 3 JsonTypeName import through model.imports
The previous fix emitted the JsonTypeName import from pojo.mustache whenever
useJackson3 was set. AbstractJavaCodegen already adds that import for any model
whose classname was sanitized, regardless of Jackson version, so models such as
Apple, Banana and EnumTest ended up importing it twice.
Contribute it from JavaClientCodegen.postProcessModelProperty instead. Because
model.imports is a Set, the import is emitted exactly once whichever path asks
for it, and the template no longer hardcodes it.
Jackson-annotation duplicate imports across the okhttp samples drop from 19 to
1. The remaining one is JsonIgnore on a model that hits both the
additionalProperties template path and the shared nullable addImports path,
which appends to a List without de-duplicating - the same pre-existing
mechanism that leaves five duplicate imports in okhttp-gson-nullable-required
on master.
* Update generator docs: Add okhttp library details and support for `useJspecify`.
* [java][okhttp] Adopt generateInsecureTlsHook and the collection-format separator helper
Port two changes from master into the okhttp library:
- generateInsecureTlsHook (#24786): when set to false, the okhttp
ApiClient omits the verifyingSsl field, setVerifyingSsl/isVerifyingSsl
and the trust-all X509TrustManager/HostnameVerifier, for consumers
whose static analysis flags that code. The verifying TLS setup moves
into trustedTrustManagers()/trustedHostnameVerifier() so both template
variants share it.
- CollectionFormat helper (#24781): deduplicate the collection-format
delimiter lookup in parameterToPairs and collectionPathParameterToString
into a collectionFormatSeparator method.
* [java][okhttp] Regenerate samples after the master merge and template changes
Includes the churn from master (7.26.0-SNAPSHOT version bump, path
backslash removal, inline-enum resolver fix), the new ApiClient helpers,
and the RequiredAndNullable/FileContent files the jspecify samples were
missing since the spec gained them in #24711.
* [java][okhttp] Address review findings: jsonb additionalProperties, bearer-token NPE, modelCopy JsonTypeName
- JSON-B has no @JsonAnyGetter/@JsonAnySetter, so models with
'additionalProperties: true' silently dropped undeclared fields in both
directions. Generate a CustomJsonbSerializer/CustomJsonbDeserializer
into each such pojo and register them in the Jsonb config built by
JSON, mirroring what the Gson CustomTypeAdapterFactory does. Verified
with a runtime round trip against the generated okhttp-jsonb client.
- HttpBearerAuth.getBearerToken() threw NullPointerException before a
token was configured, although applyToParams treats an unset supplier
as valid unauthenticated state. Return null instead.
- @JsonTypeName was emitted as "java" when pojo.mustache is rendered as
a user-defined Model template (files config), because the bundle
root's "name" key holds the generator name. Resolve the model name
through the models/model scope, which works in both contexts.
- ApiResponse: use conventional 'private final' modifier order and fix
the "response bod" javadoc typo.
* [java][okhttp] Regenerate samples for the review fixes
* [java][okhttp] Fix the defects found in the five-agent sample review
Correctness fixes across the okhttp templates and JavaClientCodegen,
each verified by unit tests and runtime round trips against the
regenerated clients:
Gson:
- oneOf/anyOf branches typed List<X>/Map<String,X> had no validation
(bare matches++), and plain non-primitive branches (UUID, BigDecimal)
none at all, while String/Boolean accepted any primitive - valid
payloads failed with "N classes match result, expected 1". Branch
validation now checks the concrete JSON type, ported from the
okhttp-gson baseline.
- Serializing a null additional property crashed on
JsonNull.getAsJsonObject(); the baseline's isJsonNull branch is
restored.
- JSON.isInstanceOf(type, null) returned true, letting non-nullable
oneOf/anyOf wrappers accept null; nullable wrappers handle null in
setActualInstance, so null now matches nothing.
- new JSON() unconditionally rebuilt the shared static Gson, discarding
a setGson() customization on every ApiClient/RetryingOAuth
construction; the constructor now keeps an existing instance.
- CustomTypeAdapterFactory is no longer generated for parents with
children (it was never registered, matching the baseline guard).
Jackson:
- oneOf deserializers double-counted duplicated data types (the one
loop missing the x-duplicated-data-type guard), so such models could
never deserialize; jsonb loops had the same gap.
- errorObjectType's catch block gained the missing Jackson branch.
- Jackson 3 now gets RFC3339JavaTimeModule/RFC3339InstantDeserializer
like Jackson 2 (JavaClientCodegen whitelist + JSON.mustache).
- openApiNullable is forced off for the whole library: the templates
never emit JsonNullable, so the flag only produced dead
equalsNullable/hashCodeNullable helpers and duplicate imports.
JSON-B:
- Discriminator hierarchies were silently unsupported (a Cat response
typed Animal lost its fields). Yasson's native @JsonbTypeInfo cannot
be used because the discriminator is also a bean property (key
collision on both paths, "CHANGE naming conflict"), so hierarchy
roots now generate TypeSelector-style custom (de)serializers that
dispatch on the discriminator and bind subtypes through a second,
polymorphism-free Jsonb instance (JSON.getPlainJsonb()).
- The additionalProperties deserializer coerced explicit JSON null
into the field default, skipped readOnly properties, and read the
volatile Jsonb once per field; it now binds null, sets readOnly
fields reflectively, validates openapiRequiredFields (previously
dead for JSON-B), and captures the instance once per object.
- anyOf toUrlQueryString iterated composedSchemas.oneOf and always
returned null under supportUrlQuery.
ApiClient:
- executeStream() leaked the connection and discarded the error body
on non-2xx responses; it now mirrors handleResponse().
- dynamicOperations sent null optional header/cookie params as empty
strings; fillParametersFromOperation now skips null values.
- The dead public updateParamsForAuth() (stale-URI semantics diverging
from buildRequest's inline loop) is removed.
- build.gradle no longer declares the mockito dependency pom dropped.
* [java][okhttp] Regenerate samples for the review fixes
* [java][okhttp] Close the okhttp-gson parity gaps: composed fromJson/toJson, free-form validation
- oneOf wrapper models were missing the static fromJson(String)/toJson()
helpers that okhttp-gson (and this library's anyOf wrappers and plain
pojos) expose, an API-surface regression for migrating consumers. The
Gson block from anyof_model.mustache is mirrored into
oneof_model.mustache.
- The per-type branch validation rejected free-form values: Object is a
Java language-specific primitive, so an anyType branch or anyType
container item fell into the primitive check and its "must be Number"
fallback - a Map<String, Object> oneOf branch no longer accepted
string/boolean/object values. anyType branches and items now skip
validation entirely (any JSON value matches), like the okhttp-gson
baseline.
* [java][okhttp] Regenerate samples and port the invoker unit tests
Regenerated for the composed fromJson/toJson helpers and the anyType
validation fix.
Ports the 8 hand-maintained invoker tests from the okhttp-gson petstore
sample (ApiClient, Client, Configuration, JSON, StringUtil, ApiKeyAuth,
HttpBasicAuth, RetryingOAuth), adapted to this library: byte[] auth
payloads, the Oltu-free RetryingOAuth is exercised against a local
HttpServer instead of Mockito, JSONTest uses the composed-model
fromJson/toJson helpers and the library's fail-fast discriminator
messages, and equals() assertions avoid reflectionEquals (needs
--add-opens on JDK 9+). Suite: 501 tests, 0 failures.
* [java][okhttp] Repoint the jackson/jsonb samples off the http-signature spec, fix jsonb gaps
The three okhttp samples generated with a non-gson serializer took their spec from
3_0/java/native/petstore-...-with-http-signature.yaml, which declares an
`http_signature_test` scheme (type: http, scheme: signature). ApiClient.mustache only
registers basic/bearer/apiKey/oauth schemes, while api.mustache emits every scheme name
into localVarAuthNames, so PetApi.addPet, updatePet, findPetsByStatus and findPetsByTags
threw `RuntimeException: Authentication undefined: http_signature_test` on every generated
call surface (plain, WithHttpInfo and Async alike), with no way out: getAuthentications()
is an unmodifiable map, and the throw happens in buildRequest before any interceptor runs.
Point them at the spec java-okhttp.yaml already uses. That drops the unsatisfiable scheme
and, because all four serializers now generate from one spec, makes okhttp / okhttp-jackson
/ okhttp-jackson3 / okhttp-jsonb a like-for-like serializer matrix.
The richer spec exposed three jsonb defects, all fixed here:
* JSON.mustache registered no adapter for java.io.File, the mapping of `format: binary`.
JSON-B then treated File as a bean: serializing recursed through getAbsoluteFile()
("Recursive reference has been found in class java.io.File") and deserializing demanded
START_OBJECT where the schema carries a string. Adds a FileAdapter matching Jackson's
representation - getAbsolutePath() out, new File(String) in.
* oneof_model/anyof_model did not import JsonbTransient, which
additional_properties.mustache needs for its holder field. A pojo gets the import from
pojo.mustache; a composed model got none, so any composed schema with
additionalProperties failed to compile (40 errors).
* the composed deserializers called parser.getObject() unconditionally, which throws on
START_ARRAY, and routed every branch through ctx.deserialize, which Yasson cannot bind to
a root-level scalar. They now read a generic JsonValue and send structured values through
the context and scalars through the binding API.
Verified against a Prism mock per sample, driving every generated operation of all 42
okhttp-family samples (864 operations): all four serializers are now identical
operation-for-operation on the shared spec, all 14 okhttp/okhttp-gson pairs remain
identical, and no okhttp-gson template, sample or config is touched.
* [java][okhttp] Fix the defects found in the cubic review of the new library
Address the actionable findings from the 2026-09-07 review run, all confined
to the okhttp library templates:
- GzipRequestInterceptor: skip compression for AWS SigV4-signed requests.
AWS4Auth hashes the uncompressed payload and stamps the Authorization
header before the Request exists, so gzipping afterwards made the
transmitted bytes disagree with the signature and AWS rejected the call.
Guarded by withAWSV4Signature, so non-AWS clients are unchanged.
- GzipRequestInterceptor: keep upload progress truthful. Buffering to publish
a Content-Length drained the enclosing ProgressRequestBody, firing every
callback (terminal one included, with uncompressed totals) before a byte
reached the socket. Compress the wrapped delegate instead and re-wrap the
compressed buffer with the same callback, and replay it in segments so the
upload is reported as it happens. The in-memory buffering itself is
inherent to publishing a compressed length and is now documented.
- pojo.mustache: flatten additionalProperties for JSON-B models with
children. @JsonbTransient hides the holder and the flattening serializer
was registered only for non-hasChildren models, so an instance whose
runtime type is the discriminated root silently lost its extra properties.
- build.gradle.mustache: select Java 17 when useJackson3 is set, as the POM
already does; nothing derives the internal java17 property from it, so
Gradle clients targeted Java 8 with a Jackson 3 dependency.
- build.sbt.mustache: add the Parcelable and Bean Validation provider
dependencies that the POM and Gradle builds already declare.
- ProgressRequestBody: delegate isOneShot()/isDuplex() so a wrapped one-shot
or duplex body keeps its contract.
- ApiResponse.mustache: lower-case response header names with Locale.ROOT so
a Turkish/Azeri default locale cannot corrupt them.
- api_doc.mustache: import modelPackage rather than a non-existent
"<invokerPackage>.models" package, so the doc examples compile.
Samples regenerated for all 27 okhttp configs. okhttp-gson stays byte
identical to master.
* [java][okhttp] Build the jackson3 okhttp samples on JDK 17, not JDK 11
Jackson 3 requires Java 17, so the generated POM for a useJackson3 client
compiles with source/target 17. The three okhttp jackson3 samples were wired
into the JDK 11 sample workflow when okhttp CI coverage was added, and their
"Build with Maven" step has failed there ever since: a JDK 11 javac cannot
honour target 17.
Move them to the JDK 17 workflow, where every other library already keeps its
jackson3 sample (native-jackson3, apache-httpclient-jackson3, jersey3-jackson3):
- samples/client/petstore/java/okhttp-jackson3
- samples/client/petstore/java/okhttp-jackson3-jspecify
- samples/client/others/java/okhttp-jackson3-oneOf
The generated POMs are unchanged; only the CI wiring was wrong.
* fix from leak analyze of generated:
(ApiClient.java:1022-1032) — the real one. sink.writeAll(response.body().source()) never closes the body's source; on success the connection is only released because the stream happens to be read to exhaustion, but if an IOException hits mid-copy, both the BufferedSink (file descriptor) and the response body (pooled connection) leak. Needs try-with-resources on both
* fix from leak analysis of generated:
Close responses explicitly on failures
* Fix missing semicolons in response close calls to ensure proper syntax
* [java][okhttp] Add Jakarta EL and explicitly handle Bean Validation dependencies
- Updated template dependencies to select Jakarta EL or Glassfish EL dynamically based on useJakartaEe (5.x for Jakarta EE and 3.x for javax).
- Adjusted hibernate-validator versions for Jakarta vs. javax compatibility.
- Flattened additionalProperties handling for JSON-B models with inheritance.
- Added branch validation in composed models to prevent mismatched deserialization.
- Ensured correct library dependencies in all build scripts (Maven, Gradle, SBT) while maintaining compatibility configurations.
* [java][okhttp] Refactor imports, add unchecked JSON-B instance, improve required-field validation
- Delegate model symbol imports to JavaClientCodegen to eliminate duplicate import lines in templates.
- Introduce `uncheckedJsonb` instance to bypass additional properties enforcement during deserialization.
- Register custom JSON-B deserializers for models with required properties for stricter validation.
- Synchronize Java version source/target settings across build tools for `useJackson3`.
* [java][okhttp] Regenerate the okhttp samples after 82f8bfec184
82f8bfec184 edited build.sbt.mustache, api_doc.mustache, JavaClientCodegen.java
and the two java-okhttp-*-user-defined-templates.yaml configs, but regenerated
only the four JSON-B samples. Run the remaining 27 java-okhttp* configs so the
samples match the templates again. Generated output only, no template change:
- model imports deduplicated (JavaClientCodegen now contributes them)
- build.sbt pins -source/-target to the Maven and Gradle bytecode level
- the two user-defined-templates samples gain their README and api docs
* [java][okhttp] Fix four JSON-B deserialization validation gaps
1. A model that forbids additional properties never rejected an UNDECLARED
field. Yasson binds such a model by plain bean mapping, which drops an
unknown key silently, so a oneOf branch accepted a payload belonging to a
sibling branch: {"lengthCm":10,"mealy":true} bound BananaReq and discarded
`mealy`. Mirror the Gson type adapter's validateJsonElement and reject any
key outside openapiFields. The guard moves from hasRequired to "declares a
property", because a branch with no required field needs the check just as
much; a model with no declared property stays excluded so that an empty
openapiFields cannot reject every key.
2. Required-field checks did not survive nesting. `uncheckedJsonb` was built
before EVERY required-field deserializer, so a checked model binding through
it disabled the checks of all of its nested models too. A recursion guard
cannot fix that: a re-entrant whole-object bind has to land on some instance
that carries no checker, which is the defect itself. Drop uncheckedJsonb and
bind property by property through the fully configured instance instead -
the shape the additional-properties deserializer already used. That cannot
re-enter itself, since the target type is the property's and not the class'.
3. The root of a discriminated hierarchy enforced no required property, because
the registration block excludes every hasChildren model. Validate in the
discriminator deserializer, both for the unmapped-root fallback and for a
mapped subtype that has children of its own. A leaf subtype is covered by
registering the required-field deserializers BEFORE plainJsonb is built:
that instance now carries everything except the polymorphism roots, so a
subtype bound through it validates itself.
4. setJsonb()/setSerializer() called before the first JSON was constructed left
plainJsonb null, and every generated deserializer then failed with an NPE.
Build the companion instance first, and check it in the constructor too.
* [java][okhttp] Add the Jackson Joda datatype module to the generated builds
JSON.mustache imports com.fasterxml.jackson.datatype.joda.JodaModule (or
tools.jackson.datatype.joda.JodaModule under Jackson 3) and registers it on
the mapper whenever dateLibrary=joda is combined with a Jackson
serializationLibrary, but none of the three generated build files declared
that artifact -- they carried only joda-time. A client generated that way
failed to compile with "package com.fasterxml.jackson.datatype.joda does not
exist".
The omission was inherited from okhttp-gson, whose JSON.mustache is Gson-only
and handles Joda with hand-written DateTimeTypeAdapters, so joda-time alone
was correct there. It stops being correct once the same build files serve the
Jackson serializers.
jackson-datatype-joda is published for both generations at the versions this
library already pins -- com.fasterxml.jackson.datatype:2.22.1 and
tools.jackson.datatype:3.2.1 -- so the dependency follows the jackson-core and
jackson-databind pattern and needs no useJackson3 gate, unlike
jackson-datatype-jsr310.
No sample sets dateLibrary: joda, so this path has no CI coverage; verified by
generating a client for each Jackson generation and compiling both.
* [java][okhttp] Delete stale user-defined-templates doc output
82f8bfec184 dropped the README.mustache -> info.md and api_doc.mustache ->
Documentation.md filename mappings from the two user-defined-templates
configs, and 49d04bea222 regenerated the samples. That run added the new
README.md and docs/*Api.md outputs but left the old ones in place, so both
spellings have been sitting side by side since.
The generator only rewrites or removes files listed in
.openapi-generator/FILES, and these seven per sample are not listed, so they
would have survived every future regeneration. The manifests themselves are
already correct and need no change.
Removes info.md and docs/{Auth,Body,Form,Header,Path,Query}ApiDocumentation.md
from both okhttp-user-defined-templates and
okhttp-jackson-user-defined-templates. Nothing references them: they are not
in either FILES manifest, not linked from README.md, and not part of the pom
or gradle build.
* [java][okhttp] Fix two JSON-B additionalProperties serialization defects
Both live in the discriminator-root serializer that pojo.mustache generates
for a hasChildren model with additionalProperties: true.
A nested value lost its additional properties when its runtime type was a
hierarchy root. JSON registers a CustomJsonbSerializer for every
non-hasChildren model before building plainJsonb and adds the roots only
afterwards, so a nested Cat or Dog kept its flattening but a nested Animal or
GrandparentAnimal fell through to plain bean mapping, where the @JsonbTransient
holder is dropped. Additional-property values now render through a separate
toNestedJsonValue() on the configured Jsonb; the outer value stays on
plainJsonb, which is what keeps the serializer from re-entering itself. This
follows the delegation deserializeBranch already uses.
An additional property could also take a subtype's declared name. The guard
tested the root's openapiFields and then whether the key was already in the
serialized output, but a subtype serializer omits a declared property whose
value is null -- so declawed=null together with
putAdditionalProperty("declawed", x) wrote x under the declared name and, on
the way back, migrated it into the declared field. A generated
declaredFields() helper now resolves the runtime type's own openapiFields by
exact class match over the discriminator mappings, so the declared name wins
whether or not the subtype emitted it. Exact matching rather than instanceof
keeps a mid-level subtype from shadowing its own children.
The second defect only surfaces when the subtype has no serializer of its own,
which is why the petstore hierarchy does not show it: Cat and Dog are
additionalProperties: true and Yasson dispatches to their own serializers.
Regenerating the okhttp samples touches only Animal and GrandparentAnimal, the
two models that are both a discriminator root and additionalProperties: true.
* [java][okhttp] Fix seven defects found by a live PetClinic parameter matrix
Found by generating the okhttp client for a live spring-petclinic-rest server
across all four serialization libraries x 17 parameter combinations (68 runs),
then compiling and exercising each against the running server. All changes are
confined to Java/libraries/okhttp/ plus one okhttp-gated block in
JavaClientCodegen; okhttp-gson and the shared root Java/*.mustache are untouched.
pojo.mustache / JSON.mustache
* readOnly properties never deserialized on Jackson 2 and Jackson 3. The field
carried @JsonProperty(access = Access.READ_ONLY), which is the SERVER reading
of OpenAPI readOnly - it means "serialize out, ignore on input", so Jackson
discarded exactly the values a client needs. Setters are suppressed for
readOnly vars and the readonly-args constructor had no @JsonCreator, so all
three paths into the field were closed. Drop the access attribute (matching
the shared root pojo.mustache, the only other emitter) and annotate the
constructor. Every id, plus Owner.pets/Pet.visits/ProblemDetail, was null.
* serializationLibrary=jsonb + dateLibrary=joda did not compile: the joda format
imports were {{#isGson}}-gated while the JSON-B adapters, their fields and
their setters all reference DateTimeFormatter - eight unresolved symbols. The
joda adapters were also registered only when a format had been set explicitly,
so Yasson (which has no joda support) fell back to bean mapping; register them
unconditionally with ISO defaults, as the FileAdapter already does.
* dateLibrary=legacy corrupted every format: date value. legacy maps both date
and date-time onto java.util.Date, so the mapper-wide RFC3339 format applied
to date-only properties: at Europe/Berlin, 2020-01-15 went out as
"2020-01-14T23:00:00.000+00:00" - simultaneously a full timestamp the server
rejects and a one-day backward shift. Select the representation per property
instead, through one shared dateOnlyFormat() so all four serializers agree on
the wire. Note a bare @JsonFormat pattern is insufficient: with no explicit
timezone it resolves against the mapper default, which Jackson sets to UTC
rather than the JVM zone, and the day still shifts.
* The generated JSON-B CustomJsonbDeserializer binds each property by declared
type, so a field-level @JsonbTypeAdapter is never consulted; date-only
properties now bind through an explicit helper.
* RFC3339JavaTimeModule registers its deserializers after calling
super.setupModule(), and SimpleModule forwards _deserializers only if that
lazily-created map is already non-null - so on Jackson 2 the lenient RFC3339
parsing never took effect at all. Build the equivalent module locally rather
than patching a template shared by six libraries. The upstream fix belongs in
RFC3339JavaTimeModule itself.
* generateBuilders and generateConstructorWithAllArgs were silently inert:
neither flag appeared anywhere in the okhttp pojo template, unlike restclient,
resttemplate, webclient and native. Wire up the shared javaBuilder partial and
the all-args constructor.
api.mustache
* performBeanValidation removed the required-parameter null checks instead of
adding to them - they lived inside the inverted section - and the substituted
validator never fires for a plain null argument, so a clear ApiException
became a NullPointerException or the null reached the server. The checks are
now unconditional and validation is additive.
JavaClientCodegen
* defaultToEmptyContainer is a rule string, but DefaultCodegen only logs
unrecognised tokens and then sets the flag unconditionally, so the boolean
spelling every other option uses - defaultToEmptyContainer=true - matched no
rule and silently produced the OPPOSITE of the documented behaviour. Reject
it with a message naming the real syntax. Validating this for every generator
belongs upstream; this is gated to okhttp.
Verified: 42 okhttp configs regenerated, all samples compile, 501 okhttp invoker
tests and 434 okhttp-jsonb tests green, JavaClientCodegenTest green, and each
fix reproduced before/after against the live server. Zero okhttp-gson diff and
zero shared-template diff.
* [java][okhttp] Keep additionalProperties across toBuilder()
toBuilder() chained only the declared vars, so instance.toBuilder().build()
returned a model whose additionalProperties map was null and silently dropped
every undeclared property the response had carried. All three serializers read
that map back when writing the request, so the data was lost on the wire.
The shared Java/javaBuilder.mustache has had this gap since the builder pattern
landed in #18650 and it affects native, restclient, resttemplate and webclient
the same way. Fixing it there would put master-owned samples in this PR, so the
okhttp library gets a local override instead; the shared template is untouched.
The Builder setter routes values through putAdditionalProperty rather than
assigning the field: a subclass declares its own holder that shadows the
parent's, and only the virtual call reaches the field the subclass getter
reads. The setter is a covariant override in a child Builder, and a null map
is left alone.
okhttp-gson has no builders at all - its pojo.mustache never includes
javaBuilder - so it is untouched.
Verified by round-tripping a payload with undeclared fields through a plain
model and through Cat extends Animal on okhttp-jackson, okhttp-jackson3 and
okhttp-jsonb: the properties survive toBuilder().build() and reappear in the
reserialized JSON.
* [java][okhttp] Stop setting useReflectionEqualsHashCode in okhttp configs
EqualsBuilder.reflectionEquals(this, o, false, null, true) passes
testRecursive=true, so commons-lang3 reflects into the field values rather
than comparing them. On JDK 16+ any List or Map field makes that throw
InaccessibleObjectException - module java.base does not open java.util - so
equals() is unusable on nearly every generated model. HashCodeBuilder is not
recursive and is unaffected.
The call comes from the shared Java/pojo.mustache and is inherited, not
introduced here: 408 sample files across native, jersey2/3, feign,
microprofile and okhttp-gson carry it verbatim. Changing the shared template
would pull master-owned samples into this PR, so the seven okhttp sample
configs simply stop setting the option and the samples fall back to the
explicit Objects.equals/Objects.hash bodies. commons-lang3 disappears from
the generated pom, build.gradle and build.sbt, which already guarded that
dependency on this option.
Nothing was really covered by the option: no generated test calls equals() on
a model with a container field, which is why every suite passed with it on.
okhttp-gson keeps its existing setting and stays byte-identical.
* [java][okhttp] Regenerate okhttp-3.1 sample after merging master
Picks up #24935, which maps the OAS 3.1 null type to Object instead of a
never-generated ModelNull. The 3.1 test spec gained a third_property
declaring the null type as the OAS 3.1 quoted string, so the sample now
carries that property as Object.
Regenerating all 129 java configs and exporting the generator docs produced
no other change.
* [java][okhttp] Regenerate okhttp samples and docs after merging master
All 843 sample configs regenerated; only the four okhttp-family
NestedArrayWithDefaultValues models changed (master's complex default value
fix, #25001). docs/generators/java*.md re-exported so the okhttp library
entries are restored on top of master's text.
* [java][okhttp] List okhttp in the useJackson3 option description
The validation check, its error message and the okhttp library description
already advertise Jackson 3 support for the okhttp library; only the CliOption
text (and therefore docs/generators/java*.md) still omitted it.
* [test][swift6] Pin generateAliasAsModel=false in nestedMapRefTypeTest
The assertion in Swift6ClientCodegenModelTest.nestedMapRefTypeTest relies on
ModelUtils.unaliasSchema() unwrapping the NestedStringMap alias, which it only does
while the static GlobalSettings flag generateAliasAsModel is false. Other tests
(e.g. CodegenConfiguratorTest.shouldSetConfigProperties) set that flag to true via
DefaultCodegen.processOpts() and it survives across test classes in the same JVM, so
depending on class order the test fails with
"expected [[String: [String: String]]] but found [NestedStringMap]".
The order comes from a HashSet<Class> inside TestNG (identity hashes) and flips with
unrelated classpath changes (it flipped on master with the test-scoped gson dependency
added in #24973, and differs between JDK versions).
Pin the flag to false for the duration of this test only and restore the previous
value (or absence) afterwards, so the test neither depends on nor changes global state.
* [java][okhttp] Serialize JSON header parameter content
Port of 099d598b7f10bc671a8bedb6e55ac7851fc904ee "fix(java): serialize JSON header
parameter content (#25056)" by Andrey Markelov <[email protected]> from the
okhttp-gson library to the okhttp library: header parameters declared with
`content: application/json` are serialized with the configured JSON serializer and
escaped to ASCII (parameterToJsonString) instead of String.valueOf(); the
dynamicOperations path does the same. The only deviation from the original is the
serializer call (`this.json.serialize` instead of okhttp-gson's static `JSON.serialize`).
Adds the okhttp variants of the two JavaClientCodegenTest cases and the four
ApiClientTest cases from the original commit.
* [java][okhttp] Escape JavaDoc default values in generated API docs
Port of 655824af827 "Escape JavaDoc default values safely (#24890)" by Kunal to the
okhttp library's api.mustache: the five `default to {{.}}` JavaDoc fragments now go
through the escapeJavaDoc lambda like every other Java client library.
* [java][okhttp] Do not seed addItem/putItem with the container default
Port of 1ec1f1aee1f "[BUG][JAVA] Fix generation of complex default values
(fixes #24993) (#25001)" by Jorge Rodríguez Martín to the okhttp library's
pojo.mustache: the lazy initialisation inside add{{Name}}Item/put{{Name}}Item
creates an empty container instead of re-applying the schema default, matching
the other Java client libraries. Adds the okhttp variant of the JavaClientCodegenTest
case from the original commit.
* [java][okhttp] Port the two inner-enum fixes from okhttp-gson
Ports two commits by Ori to the okhttp library's modelInnerEnum.mustache:
- bc2368e7fed "fix(java): honor case-insensitive matching for formatted inner enums
(#24937)": fromValue() compares formatted (UUID/URI/...) enum values through
toString() when useEnumCaseInsensitive is set.
- 41b3d639584 "[Java][okhttp-gson] Fix UUID inner enum compilation (#24973)": the
Gson TypeAdapter and validateJsonElement() handle `format: uuid` enums
(UUID.fromString on read, toString on write).
The four affected template lines were byte-identical to okhttp-gson's pre-fix lines,
so the fixed lines were transplanted verbatim. The okhttp library is added to
JavaInnerEnumComparisonTest and JavaOkHttpGsonUuidEnumTest.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
* [java][okhttp] Update jackson-databind-nullable to 0.2.12
Port of 3fdd2ce64b5 "Update jackson-databind-nullable to 0.2.12 (#25096)" by
Oleksandr Nikolaichuk to the okhttp library's pom, build.gradle and build.sbt templates.
Note: JavaClientCodegen forces openApiNullable=false for the okhttp library, so this
dependency block is currently never rendered (no sample changes); the bump only keeps
the template in step with okhttp-gson.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
* [java][okhttp] Make Gson oneOf/anyOf TypeAdapters null-safe
The anonymous TypeAdapter returned by the oneOf/anyOf CustomTypeAdapterFactory lost
okhttp-gson's `.nullSafe()` wrapper, so a JSON null for a property typed with a
composed schema (e.g. Drawing.shapeOrNull, which the spec marks nullable) reached
read() and failed in jsonElement.getAsJsonObject() with IllegalStateException
"Not a JSON Object: null" (discriminator oneOfs) or IOException "0 classes match"
(plain oneOfs/anyOfs); writing a null threw as well.
Wrap the adapters with nullSafe() as okhttp-gson does (all 32 generated composed
models change identically) and add a JSONTest case to the hand-maintained okhttp
sample tests. Found by code review of the generated samples.
* [java][okhttp] Build the shared serializer eagerly in JSON
JSON.getGson()/getMapper()/getJsonb() are static and the generated models call them
statically (Pet.fromJson(), toJson(), the Gson TypeAdapters and JSON-B deserializers),
but the shared instance was only built in the JSON() constructor. Application code that
touched a model before constructing an ApiClient (unit tests, consumers that only use
the model classes, JSON.setDateFormat() on the Jackson variant) hit a NullPointerException;
okhttp-gson initialises its Gson in a static block.
Move the constructor body into a synchronized ensureInitialized() that runs from a
static initializer as well as from the constructor. setGson()/setMapper()/setJsonb()
still replace the default instance afterwards. Verified with a probe per serializer
that deserializes a model before any JSON/ApiClient instance exists. Found by code
review of the generated samples.
* [java][okhttp] Detect byte[] responses independently of the serializer
ApiClient.handleResponse() recognised binary responses with
`"byte[]".equals(returnType.toString())`, which only holds for Gson's TypeToken.
Jackson's TypeReference and the JSON-B GenericType resolve byte[] to the raw class
(toString() is "class [B"), so with serializationLibrary=jackson/jackson3/jsonb a
`format: binary` response body was handed to the JSON parser instead of being returned
as bytes. Compare against byte[].class as well and add a JavaClientCodegenTest case over
all three serializers. Found by code review of the generated samples.
* [java][okhttp] Report OAuth token endpoint failures instead of sending unauthenticated
RetryingOAuth.updateAccessToken() ignored every token-endpoint answer that was not a
2xx with a parseable access_token: the request then went out without an Authorization
header and the caller only saw the resource server's 401, with nothing pointing at the
failed token request (which was repeated on every call). A 2xx body that is not JSON
escaped as an unchecked JsonParseException from inside the interceptor. okhttp-gson
wrapped these cases into an IOException naming the OAuth error.
Throw an IOException carrying the token endpoint URL, status and body for non-2xx
answers, for unparseable bodies and for responses without access_token, so execute()
maps it to an ApiException. Adds two RetryingOAuthTest cases to the hand-maintained
okhttp sample tests. Found by code review of the generated samples.
* [java][okhttp] Pass the token a request was sent with to updateAccessToken
retryingIntercept() applied getAccessToken() to the request but re-read
getAccessToken() only after a 401/403 came back, and passed that value to
updateAccessToken(). If another thread had refreshed the token in the meantime the
guard "refresh only if nobody refreshed since" compared the fresh token with itself,
so the token endpoint was called a second time; when it issued the same token the
method returned false and the request was not retried, surfacing the 401. okhttp-gson
captures the token before building the request.
Capture the token once, send it, and hand exactly that value to updateAccessToken().
Adds a deterministic RetryingOAuthTest case (second 401 arrives after the first
refresh completed; token endpoint must be hit once and both requests must succeed).
Found by code review of the generated samples.
* [java][okhttp] Emit @XmlEnumValue from the raw enum value
Port of 994a84297b0 "[Java] Fix XmlEnumValue generation for URI enums (#24919)" by Ori
to the okhttp library's modelEnum.mustache and modelInnerEnum.mustache, which still
used the pre-fix `@XmlEnumValue({{{value}}})` form. With withXml=true a URI, UUID or
BigDecimal enum rendered `@XmlEnumValue(URI.create("..."))`, a non-constant annotation
argument that does not compile. Use the javaStringLiteral lambda over rawValue like the
shared templates, and add the okhttp library to testHandleURIEnumWithXml. No sample
changes: no okhttp sample config sets withXml. Found by code review of the generated
samples.
* [java][okhttp] Serialize byte[] as base64 in the JSON-B variant
The JSON-B JsonbConfig never set a BinaryDataStrategy, so Yasson used its default
(BYTE) and wrote `format: byte` properties as JSON arrays of numbers while rejecting
the spec-conformant base64 string on input ("Received event: VALUE_STRING Allowed:
[START_ARRAY]"). The Gson variant (ByteArrayAdapter) and Jackson (default) both use
base64. Configure BinaryDataStrategy.BASE_64, and limit the okio.ByteString import to
the Gson variant that uses it. Adds a hand-written JSONTest to the okhttp-jsonb sample
with a base64 round trip. Found by code review of the generated samples.
* [java][okhttp] Fall back to the raw body for String results in the JSON-B variant
JSON.deserialize(String, Type) in the JSON-B variant was a bare jsonb.fromJson()
passthrough. ApiClient.deserialize() defaults a missing Content-Type to JSON, treats
`*/*` as JSON and relies on this method's String fallback for plain-text bodies, so an
operation returning String (e.g. fakeOuterStringSerialize) threw an unchecked
JsonbException out of execute() instead of returning the body. Catch JsonbException
and return the body for String return types, as the Gson and Jackson variants do.
Adds a JSONTest case to the okhttp-jsonb sample. Found by code review of the
generated samples.
* [java][okhttp] Omit the openapiFields sets from Jackson models
pojo.mustache emitted `openapiFields`/`openapiRequiredFields` plus their static
initializer (and the HashSet import) into every model regardless of serializer. The
Gson TypeAdapter and the JSON-B deserializer use them for required/undeclared-field
validation, but the Jackson variants bind through annotations and never read them, so
the 205 Jackson model files carried dead static state. Gate the block and the import
on {{^isJackson}}; the change is deletions only. Found by code review of the
generated samples.
* Fix cubicAI review concerns
- ProgressRequestBody: a duplex body may keep writing after writeTo() returns, so the
terminal onUploadProgress(done=true) is now emitted when the delegate closes the sink
instead of when writeTo() returns (new ProgressRequestBodyTest in the okhttp sample).
- pojo: validateJsonElement(null) returns after the required-field check instead of
falling through to getAsJsonObject() and throwing NullPointerException for models
without required fields (JSONTest case).
- javaBuilder: the additional-properties helper is named putAdditionalProperties so it
cannot collide with the builder setter of a declared property called
additionalProperties (JavaClientCodegenTest case).
- pom/build.sbt: depend on com.squareup.okhttp3:okhttp-jvm. OkHttp 5 publishes
`okhttp` as an empty Kotlin-multiplatform root artifact that only Gradle module
metadata redirects; Maven and sbt compiled only because logging-interceptor pulls in
okhttp-jvm transitively. build.gradle keeps `okhttp`.
Regenerated all okhttp sample configs; generator docs unchanged.
* [java][okhttp] Import Arrays and Map in Jackson models only when used
Jackson models render neither openapiFields nor the Gson/JSON-B Map.Entry
loops, so Arrays is only needed for byte[] equals/hashCode and the
JsonNullable hash helper, and Map only for the additionalProperties holder.
Drops the unused imports from the okhttp-jackson* samples.
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
* [java][okhttp] Handle JSON-B parents without a discriminator
A model with children but no discriminator (x-parent, or a single allOf
$ref) got neither the leaf (de)serializers, which skip every model with
children, nor the hierarchy-root ones, which required a discriminator. It
fell back to plain bean mapping and lost its required-field checks and
additionalProperties. The root (de)serializers now cover every parent; with
no discriminator the deserializer binds the root itself. Subtypes still
delegate to the polymorphism-free instance, so Yasson's superclass lookup
cannot narrow them to the parent. No sample defines such a parent.
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
* [java][okhttp] Validate string enum values excluded by not (port of #25066)
Gson's validateJsonElement and the leaf JSON-B deserializers now reject a
string property value listed in its `not: enum` (inline or $ref), so a oneOf
with complementary branches resolves to exactly one of them. Jackson is left
as is, like the other Jackson-based Java libraries.
* [java][okhttp] Enforce inherited not-enum constraints in Gson models
validateJsonElement ran the `not: enum` check in the vars loop, so a child
model skipped the constraints of properties inherited from its parent while
already enforcing their required fields (openapiRequiredFields covers
allVars) and while the JSON-B deserializer checks allVars. The check now
iterates allVars, reading from jsonElement since jsonObj is only declared
for models with own vars.
* [java][okhttp] Regenerate okhttp samples after merging master
Regenerated the 27 java-okhttp* configs with the merged generator
(7.28.0-SNAPSHOT). Beyond the generator version string the merge changed
three things in the okhttp samples, all driven by master commits in the
shared codegen:
- api/openapi.yaml examples: empty objects are emitted as {} instead of
the string "{}" (#25253)
- okhttp-streaming SomeObj.TypeEnum now implements Serializable under
serializableModel (#24814)
- okhttp-3.1 api/openapi.yaml gains an `example: {}` line (#25253)
Co-Authored-By: Claude Fable 5.1 <[email protected]>
* [java][okhttp] Declare the additionalProperties bag once per allOf hierarchy
Port of #24895 and #25156 (okhttp-gson) to the okhttp library. With
disallowAdditionalPropertiesIfNotPresent=false every model declared its
own private Map<String, Object> additionalProperties, so an allOf child
carried the field twice and Gson refused the class before the model's
TypeAdapterFactory could run:
IllegalArgumentException: Class Cat declares multiple JSON fields
named 'additionalProperties'; conflict is caused by fields
Cat#additionalProperties and Animal#additionalProperties
Every allOf child was undeserializable and unserializable in the Gson
variant of the library (verified against the petstore sample).
JavaClientCodegen now tags okhttp descendants of a model that has the bag
with x-inherits-additional-properties, and the okhttp templates render
those models like okhttp-gson does: the bag, its getters and its
equals/hashCode/toString contribution live on the topmost ancestor, the
descendant only overrides putAdditionalProperty to keep the covariant
return type. The Jackson @JsonAnySetter/@JsonAnyGetter and the JSON-B
@JsonbTransient annotations stay on the declaring class; Jackson inherits
them through the override and the generated JSON-B (de)serializers use
the inherited accessors.
Two differences from okhttp-gson: the okhttp oneOf/anyOf wrapper does
declare the bag (it keeps the properties the matched schema did not
consume), so for okhttp the ancestor walk continues through a composed
parent instead of stopping there, and a wrapper itself is never tagged
because it extends AbstractOpenApiSchema and has no super bag to call.
Tests: master's three ...ForGson tests run for okhttp-gson and okhttp;
the composed-parent expectation differs, so okhttp has its own test.
Verified with a Cat round-trip probe (deserialize, serialize, polymorphic
Animal read, equals/hashCode) on the Gson, Jackson 2 and JSON-B petstore
samples, and with the three sample test suites (512/434/436 tests).
Regenerated the 27 java-okhttp* configs: Cat, Dog and ParentPet change in
the okhttp, okhttp-jackson, okhttp-jackson3 and okhttp-jsonb petstore
samples, Cat and Dog in okhttp-3.1. No okhttp-gson file changes.
Co-Authored-By: Claude Fable 5.1 <[email protected]>
* [java][okhttp] Port the large-oneOf adapter and call-local parameter fixes
Ports two okhttp-gson fixes that apply to the okhttp library as well:
- #25539 (1468a35da59): a oneOf with more than 100 variants made the
anonymous Gson TypeAdapter capture one local per variant, exceeding the
JVM's 255 constructor-argument limit (ClassFormatError "Too many
arguments in method signature"). The okhttp oneof_model.mustache now
opens the anonymous adapter before the per-variant adapters when the
model carries x-gson-large-oneof, exactly like okhttp-gson.
- #25581 (b665c6f4b2b): parameters named basePath, localBasePaths,
localCustomBaseUrl or localHostIndex collide with the locals of the
generated call methods. The okhttp api template shares those locals, so
toParamName renames them for okhttp too.
#25542 (primitive arrays in a Gson oneOf) needs no template change: the
okhttp adapter already writes every variant through toJsonTree and the
JsonElement adapter. The test now covers okhttp to prove it.
The three master tests run for both libraries. No sample changes: the
petstore specs have neither a 100+ variant oneOf nor a colliding
parameter name.
* [java][okhttp] Report deserialization failures as ApiException, drop unused imports
ApiClient.deserialize now wraps every failure to read or parse a response
body in an ApiException that keeps the response status and headers, with
the original exception as cause. Before, a 2xx response with an unexpected
body surfaced differently per serializer: unchecked exceptions for Gson,
JSON-B and Jackson 3, and an ApiException with code 0 for Jackson 2.
Unused imports are removed from the okhttp templates, or made conditional
on the serializer and options that use them. Imports the generator adds to
every model (JsonAdapter, JsonValue, JsonCreator, SerializedName, Arrays,
List, Map, sibling models) are pruned for the okhttp library when the
rendered model does not reference them.
Only okhttp library templates and okhttp-gated generator code change;
okhttp-gson is untouched. Samples regenerated.
* [java][okhttp] Address review: progress completion, basic auth charset, AWS config, JDK 17 profile
- ProgressResponseBody reports done=true once; further reads of the
exhausted source no longer repeat the completion callback.
- HttpBasicAuth encodes credentials as UTF-8, like the shared Java
template, where Credentials.basic defaulted to ISO-8859-1.
- AWS4Auth throws ApiException when only part of credentials, region and
service is configured, where it used to send the request unsigned.
- okhttp-jackson3 needs Java 17, so it moves to its own root pom profile
that is activated by env=java only on JDK 17 or newer.
Samples regenerated; tests added to the okhttp petstore sample.
* [java][okhttp] State the basic auth charset difference accurately
The comment in HttpBasicAuth claimed the other Java client libraries
encode credentials as UTF-8. Only the shared Java template does;
okhttp-gson and retrofit2 keep the ISO-8859-1 default. The comment now
says so, and that okhttp differs from okhttp-gson on purpose.
Comment only; samples regenerated.
* cleanup tests, workflows
* update workflow
* update samples
* update samples
* update samples
---------
Co-authored-by: rar91279 <[email protected]>
Co-authored-by: Roman Mertyn <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
Fixes #25541
Fix Java
okhttp-gsonserialization of aoneOfcontaining an array of primitive strings. The generated adapter now writes the array as aJsonArrayinstead of trying to convert it to aJsonPrimitive.This reproduces on master independently of #25539. Empty array values have a separate existing limitation in
setActualInstanceand are outside this change.Tests
okhttp-gson-oneOf-arraysample tests: 3 passed, 1 skipped.Summary by cubic
Fixes #25541: Java
okhttp-gsongeneration previously serialized aoneOfcontaining a primitive string array by callinggetAsJsonPrimitive()on the array's JSON tree, which threw an exception. The generated adapter now writes the array as aJsonArray, so the schema round-trips correctly.oneof_model.mustachetemplate to handle array types separately from other primitives.okhttp-gsonsamples.setActualInstanceand are not addressed here.Written for commit c5cb902. Summary will update on new commits.