From 2980bb135b0856532858891859635df58bc7d17a Mon Sep 17 00:00:00 2001 From: Matteo Molinari Date: Mon, 5 Oct 2026 09:46:44 +0200 Subject: [PATCH 1/2] fix(java): serialize jersey multipart object parts as JSON and honor encoding --- .../Java/libraries/jersey2/ApiClient.mustache | 182 ++++++++++++++++-- .../Java/libraries/jersey2/api.mustache | 6 +- .../Java/libraries/jersey3/ApiClient.mustache | 182 ++++++++++++++++-- .../Java/libraries/jersey3/api.mustache | 6 +- .../codegen/java/JavaClientCodegenTest.java | 56 ++++++ .../3_0/java/multipart-encoding.yaml | 49 +++++ .../org/openapitools/client/ApiClient.java | 182 ++++++++++++++++-- .../org/openapitools/client/ApiClient.java | 182 ++++++++++++++++-- .../org/openapitools/client/ApiClient.java | 182 ++++++++++++++++-- .../org/openapitools/client/api/FakeApi.java | 9 +- .../org/openapitools/client/api/PetApi.java | 9 +- .../org/openapitools/client/ApiClient.java | 182 ++++++++++++++++-- .../org/openapitools/client/api/FakeApi.java | 9 +- .../org/openapitools/client/api/PetApi.java | 9 +- .../org/openapitools/client/ApiClient.java | 182 ++++++++++++++++-- .../org/openapitools/client/api/FakeApi.java | 9 +- .../org/openapitools/client/api/PetApi.java | 9 +- .../org/openapitools/client/ApiClient.java | 182 ++++++++++++++++-- .../org/openapitools/client/ApiClient.java | 182 ++++++++++++++++-- .../org/openapitools/client/api/FakeApi.java | 9 +- .../org/openapitools/client/api/PetApi.java | 9 +- .../openapitools/client/ApiClientTest.java | 81 ++++++++ .../org/openapitools/client/ApiClient.java | 182 ++++++++++++++++-- .../org/openapitools/client/ApiClient.java | 182 ++++++++++++++++-- .../org/openapitools/client/ApiClient.java | 182 ++++++++++++++++-- .../org/openapitools/client/api/PetApi.java | 6 +- .../org/openapitools/client/ApiClient.java | 182 ++++++++++++++++-- .../org/openapitools/client/api/PetApi.java | 6 +- .../org/openapitools/client/ApiClient.java | 182 ++++++++++++++++-- .../org/openapitools/client/api/FakeApi.java | 9 +- .../org/openapitools/client/api/PetApi.java | 9 +- 31 files changed, 2648 insertions(+), 200 deletions(-) create mode 100644 modules/openapi-generator/src/test/resources/3_0/java/multipart-encoding.yaml diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/ApiClient.mustache index 538eb6abc5fd..cf5020bebbbe 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/ApiClient.mustache @@ -1019,18 +1019,39 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { * @param obj Object * @param formParams Form parameters * @param contentType Context type + * @param isBodyNullable True if the body is nullable * @return Entity * @throws ApiException API exception */ public Entity serialize(Object obj, Map formParams, String contentType, boolean isBodyNullable) throws ApiException { + return serialize(obj, formParams, Collections.emptyMap(), contentType, isBodyNullable); + } + + /** + * Serialize the given Java object into string entity according the given + * Content-Type (only JSON is supported for now). + * + * @param obj Object + * @param formParams Form parameters + * @param formParamContentTypes Content types of the multipart form parameters, as declared by the encoding of the request body + * @param contentType Context type + * @param isBodyNullable True if the body is nullable + * @return Entity + * @throws ApiException API exception + */ + public Entity serialize(Object obj, Map formParams, Map formParamContentTypes, String contentType, boolean isBodyNullable) throws ApiException { Entity entity; if (contentType.startsWith("multipart/form-data")) { MultiPart multiPart = new MultiPart(); for (Entry param: formParams.entrySet()) { - if (param.getValue() instanceof Iterable) { - ((Iterable)param.getValue()).forEach(v -> addParamToMultipart(v, param.getKey(), multiPart)); + MediaType partType = parsePartMediaType(formParamContentTypes == null ? null : formParamContentTypes.get(param.getKey())); + // a JSON encoded array is sent as a single part instead of one part per item + if (param.getValue() instanceof Iterable && !isJsonPartType(partType)) { + for (Object v : (Iterable) param.getValue()) { + addParamToMultipart(v, param.getKey(), multiPart, partType); + } } else { - addParamToMultipart(param.getValue(), param.getKey(), multiPart); + addParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); } } entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); @@ -1063,11 +1084,27 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { * Adds the object with the provided key to the MultiPart. * Based on the object type sets Content-Disposition and Content-Type. * - * @param obj Object + * @param value Object + * @param key Key of the object + * @param multiPart MultiPart to add the form param to + * @throws ApiException if the value cannot be serialized to JSON + */ + protected void addParamToMultipart(Object value, String key, MultiPart multiPart) throws ApiException { + addParamToMultipart(value, key, multiPart, null); + } + + /** + * Adds the object with the provided key to the MultiPart. + * The declared part type (from the encoding of the request body) takes precedence, + * otherwise the Content-Type is derived from the object type. + * + * @param value Object * @param key Key of the object * @param multiPart MultiPart to add the form param to + * @param partType Declared Content-Type of the part, or null if not declared + * @throws ApiException if the value cannot be serialized to JSON */ - protected void addParamToMultipart(Object value, String key, MultiPart multiPart) { + protected void addParamToMultipart(Object value, String key, MultiPart multiPart, MediaType partType) throws ApiException { if (value instanceof File) { File file = (File) value; FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key) @@ -1075,18 +1112,99 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { // Attempt to probe the content type for the file so that the form part is more correctly // and precisely identified, but fall back to application/octet-stream if that fails. - MediaType type; - try { - type = MediaType.valueOf(Files.probeContentType(file.toPath())); - } catch (IOException | IllegalArgumentException e) { - type = MediaType.APPLICATION_OCTET_STREAM_TYPE; + MediaType type = partType; + if (type == null) { + try { + type = MediaType.valueOf(Files.probeContentType(file.toPath())); + } catch (IOException | IllegalArgumentException e) { + type = MediaType.APPLICATION_OCTET_STREAM_TYPE; + } } multiPart.bodyPart(new FormDataBodyPart(contentDisp, file, type)); + } else if (isJsonPartType(partType)) { + // the encoding asks for JSON: strings are expected to already contain JSON, everything else is serialized + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); + String jsonValue = value instanceof String ? (String) value : serializeToJson(value); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, jsonValue, partType)); + } else if (isPlainFormValue(value)) { + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); + if (partType == null) { + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value))); + } else { + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value), partType)); + } } else { + // Complex objects (models, maps, ...) are sent as JSON parts instead of their toString() output FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); - multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value))); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, serializeToJson(value), MediaType.APPLICATION_JSON_TYPE)); + } + } + + /** + * Serialize the given object to a JSON string. + * + * @param value Object + * @return JSON string + * @throws ApiException if the value cannot be serialized to JSON + */ + protected String serializeToJson(Object value) throws ApiException { + try { + return json.getMapper().writeValueAsString(value); + } catch (Exception e) { + throw new ApiException(e); + } + } + + /** + * Parse the Content-Type declared for a multipart part. + * Only the first entry of a comma separated list is used, wildcard or invalid types are ignored. + * + * @param partContentType Declared Content-Type, may be null + * @return The parsed media type, or null if none could be used + */ + protected MediaType parsePartMediaType(String partContentType) { + if (partContentType == null) { + return null; + } + String first = partContentType.split(",")[0].trim(); + if (first.isEmpty() || first.contains("*")) { + return null; } + try { + return MediaType.valueOf(first); + } catch (IllegalArgumentException e) { + return null; + } + } + + /** + * Check whether the given part type is a JSON type. + * + * @param partType Part media type, may be null + * @return True if the part must be sent as JSON + */ + protected boolean isJsonPartType(MediaType partType) { + return partType != null && isJsonMime(partType.toString()); + } + + /** + * Check whether the given form value should be sent as a plain text part. + * + * @param value Object + * @return true if the value is a scalar that can be sent as text + */ + protected boolean isPlainFormValue(Object value) { + return value == null + || value instanceof String + || value instanceof Number + || value instanceof Boolean + || value instanceof Character + || value instanceof Enum + || value instanceof Date + || value instanceof java.time.temporal.TemporalAccessor + || value instanceof java.util.UUID + || value instanceof java.net.URI; } /** @@ -1251,6 +1369,46 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { GenericType returnType, boolean isBodyNullable) throws ApiException { + return invokeAPI(operation, path, method, queryParams, body, headerParams, cookieParams, formParams, Collections.emptyMap(), accept, contentType, authNames, returnType, isBodyNullable); + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param Type + * @param operation The qualified name of the operation + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "POST", "PUT", "HEAD" and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param formParamContentTypes The declared Content-Types of the multipart form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response + * @param isBodyNullable True if the body is nullable + * @return The response body in type of string + * @throws ApiException API exception + */ + public ApiResponse invokeAPI( + String operation, + String path, + String method, + List queryParams, + Object body, + Map headerParams, + Map cookieParams, + Map formParams, + Map formParamContentTypes, + String accept, + String contentType, + String[] authNames, + GenericType returnType, + boolean isBodyNullable) + throws ApiException { String targetURL; List serverConfigurations; @@ -1321,7 +1479,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { } } - Entity entity = serialize(body, formParams, contentType, isBodyNullable); + Entity entity = serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); for (Entry entry : allHeaderParams.entrySet()) { String value = entry.getValue(); diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/api.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/api.mustache index e4a150a23ef6..05b90e22091d 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/api.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/api.mustache @@ -182,10 +182,14 @@ public class {{classname}} { {{#-first}} // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); {{/-first}} {{^required}}if ({{paramName}} != null) { {{/required}}localVarFormParams.put("{{baseName}}", {{paramName}});{{^required}} }{{/required}} + {{#contentType}} + localVarFormParamContentTypes.put("{{baseName}}", "{{{contentType}}}"); + {{/contentType}} {{#-last}} {{/-last}} @@ -199,7 +203,7 @@ public class {{classname}} { GenericType<{{{returnType}}}> localVarReturnType = new GenericType<{{{returnType}}}>() {}; {{/returnType}} return apiClient.invokeAPI("{{classname}}.{{operationId}}", {{#hasPathParams}}localVarPath{{/hasPathParams}}{{^hasPathParams}}"{{{path}}}"{{/hasPathParams}}, "{{httpMethod}}", {{#queryParams}}{{#-first}}localVarQueryParams{{/-first}}{{/queryParams}}{{^queryParams}}new ArrayList<>(){{/queryParams}}, {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}, - {{#headerParams}}{{#-first}}localVarHeaderParams{{/-first}}{{/headerParams}}{{^headerParams}}new LinkedHashMap<>(){{/headerParams}}, {{#cookieParams}}{{#-first}}localVarCookieParams{{/-first}}{{/cookieParams}}{{^cookieParams}}new LinkedHashMap<>(){{/cookieParams}}, {{#formParams}}{{#-first}}localVarFormParams{{/-first}}{{/formParams}}{{^formParams}}new LinkedHashMap<>(){{/formParams}}, localVarAccept, localVarContentType, + {{#headerParams}}{{#-first}}localVarHeaderParams{{/-first}}{{/headerParams}}{{^headerParams}}new LinkedHashMap<>(){{/headerParams}}, {{#cookieParams}}{{#-first}}localVarCookieParams{{/-first}}{{/cookieParams}}{{^cookieParams}}new LinkedHashMap<>(){{/cookieParams}}, {{#formParams}}{{#-first}}localVarFormParams, localVarFormParamContentTypes{{/-first}}{{/formParams}}{{^formParams}}new LinkedHashMap<>(){{/formParams}}, localVarAccept, localVarContentType, {{#hasAuthMethods}}localVarAuthNames{{/hasAuthMethods}}{{^hasAuthMethods}}null{{/hasAuthMethods}}, {{#returnType}}localVarReturnType{{/returnType}}{{^returnType}}null{{/returnType}}, {{#bodyParam}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/bodyParam}}{{^bodyParam}}false{{/bodyParam}}); } {{#vendorExtensions.x-group-parameters}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey3/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey3/ApiClient.mustache index 867e869e7eee..7b3d4ab81919 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/jersey3/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey3/ApiClient.mustache @@ -1025,18 +1025,39 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { * @param obj Object * @param formParams Form parameters * @param contentType Context type + * @param isBodyNullable True if the body is nullable * @return Entity * @throws ApiException API exception */ public Entity serialize(Object obj, Map formParams, String contentType, boolean isBodyNullable) throws ApiException { + return serialize(obj, formParams, Collections.emptyMap(), contentType, isBodyNullable); + } + + /** + * Serialize the given Java object into string entity according the given + * Content-Type (only JSON is supported for now). + * + * @param obj Object + * @param formParams Form parameters + * @param formParamContentTypes Content types of the multipart form parameters, as declared by the encoding of the request body + * @param contentType Context type + * @param isBodyNullable True if the body is nullable + * @return Entity + * @throws ApiException API exception + */ + public Entity serialize(Object obj, Map formParams, Map formParamContentTypes, String contentType, boolean isBodyNullable) throws ApiException { Entity entity; if (contentType.startsWith("multipart/form-data")) { MultiPart multiPart = new MultiPart(); for (Entry param: formParams.entrySet()) { - if (param.getValue() instanceof Iterable) { - ((Iterable)param.getValue()).forEach(v -> addParamToMultipart(v, param.getKey(), multiPart)); + MediaType partType = parsePartMediaType(formParamContentTypes == null ? null : formParamContentTypes.get(param.getKey())); + // a JSON encoded array is sent as a single part instead of one part per item + if (param.getValue() instanceof Iterable && !isJsonPartType(partType)) { + for (Object v : (Iterable) param.getValue()) { + addParamToMultipart(v, param.getKey(), multiPart, partType); + } } else { - addParamToMultipart(param.getValue(), param.getKey(), multiPart); + addParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); } } entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); @@ -1072,8 +1093,24 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { * @param value Object * @param key Key of the object * @param multiPart MultiPart to add the form param to + * @throws ApiException if the value cannot be serialized to JSON + */ + protected void addParamToMultipart(Object value, String key, MultiPart multiPart) throws ApiException { + addParamToMultipart(value, key, multiPart, null); + } + + /** + * Adds the object with the provided key to the MultiPart. + * The declared part type (from the encoding of the request body) takes precedence, + * otherwise the Content-Type is derived from the object type. + * + * @param value Object + * @param key Key of the object + * @param multiPart MultiPart to add the form param to + * @param partType Declared Content-Type of the part, or null if not declared + * @throws ApiException if the value cannot be serialized to JSON */ - protected void addParamToMultipart(Object value, String key, MultiPart multiPart) { + protected void addParamToMultipart(Object value, String key, MultiPart multiPart, MediaType partType) throws ApiException { if (value instanceof File) { File file = (File) value; FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key) @@ -1081,18 +1118,99 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { // Attempt to probe the content type for the file so that the form part is more correctly // and precisely identified, but fall back to application/octet-stream if that fails. - MediaType type; - try { - type = MediaType.valueOf(Files.probeContentType(file.toPath())); - } catch (IOException | IllegalArgumentException e) { - type = MediaType.APPLICATION_OCTET_STREAM_TYPE; + MediaType type = partType; + if (type == null) { + try { + type = MediaType.valueOf(Files.probeContentType(file.toPath())); + } catch (IOException | IllegalArgumentException e) { + type = MediaType.APPLICATION_OCTET_STREAM_TYPE; + } } multiPart.bodyPart(new FormDataBodyPart(contentDisp, file, type)); + } else if (isJsonPartType(partType)) { + // the encoding asks for JSON: strings are expected to already contain JSON, everything else is serialized + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); + String jsonValue = value instanceof String ? (String) value : serializeToJson(value); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, jsonValue, partType)); + } else if (isPlainFormValue(value)) { + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); + if (partType == null) { + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value))); + } else { + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value), partType)); + } } else { + // Complex objects (models, maps, ...) are sent as JSON parts instead of their toString() output FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); - multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value))); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, serializeToJson(value), MediaType.APPLICATION_JSON_TYPE)); + } + } + + /** + * Serialize the given object to a JSON string. + * + * @param value Object + * @return JSON string + * @throws ApiException if the value cannot be serialized to JSON + */ + protected String serializeToJson(Object value) throws ApiException { + try { + return json.getMapper().writeValueAsString(value); + } catch (Exception e) { + throw new ApiException(e); + } + } + + /** + * Parse the Content-Type declared for a multipart part. + * Only the first entry of a comma separated list is used, wildcard or invalid types are ignored. + * + * @param partContentType Declared Content-Type, may be null + * @return The parsed media type, or null if none could be used + */ + protected MediaType parsePartMediaType(String partContentType) { + if (partContentType == null) { + return null; + } + String first = partContentType.split(",")[0].trim(); + if (first.isEmpty() || first.contains("*")) { + return null; + } + try { + return MediaType.valueOf(first); + } catch (IllegalArgumentException e) { + return null; } + } + + /** + * Check whether the given part type is a JSON type. + * + * @param partType Part media type, may be null + * @return True if the part must be sent as JSON + */ + protected boolean isJsonPartType(MediaType partType) { + return partType != null && isJsonMime(partType.toString()); + } + + /** + * Check whether the given form value should be sent as a plain text part. + * + * @param value Object + * @return true if the value is a scalar that can be sent as text + */ + protected boolean isPlainFormValue(Object value) { + return value == null + || value instanceof String + || value instanceof Number + || value instanceof Boolean + || value instanceof Character + || value instanceof Enum + || value instanceof Date + || value instanceof java.time.temporal.TemporalAccessor + || value instanceof java.util.UUID + || value instanceof java.net.URI; } /** @@ -1257,6 +1375,48 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { String[] authNames, GenericType returnType, boolean isBodyNullable, + Map errorTypes) + throws ApiException { + return invokeAPI(operation, path, method, queryParams, body, headerParams, cookieParams, formParams, Collections.emptyMap(), accept, contentType, authNames, returnType, isBodyNullable, errorTypes); + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param Type + * @param operation The qualified name of the operation + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "POST", "PUT", "HEAD" and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param formParamContentTypes The declared Content-Types of the multipart form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response + * @param isBodyNullable True if the body is nullable + * @param errorTypes Mapping of error codes to types into which to deserialize the response + * @return The response body in type of string + * @throws ApiException API exception + */ + public ApiResponse invokeAPI( + String operation, + String path, + String method, + List queryParams, + Object body, + Map headerParams, + Map cookieParams, + Map formParams, + Map formParamContentTypes, + String accept, + String contentType, + String[] authNames, + GenericType returnType, + boolean isBodyNullable, Map errorTypes ) throws ApiException { @@ -1330,7 +1490,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { } } - Entity entity = serialize(body, formParams, contentType, isBodyNullable); + Entity entity = serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); for (Entry entry : allHeaderParams.entrySet()) { String value = entry.getValue(); diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey3/api.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey3/api.mustache index 9f8592a14ac6..53f338c6e932 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/jersey3/api.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey3/api.mustache @@ -182,10 +182,14 @@ public class {{classname}} { {{#-first}} // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); {{/-first}} {{^required}}if ({{paramName}} != null) { {{/required}}localVarFormParams.put("{{baseName}}", {{paramName}});{{^required}} }{{/required}} + {{#contentType}} + localVarFormParamContentTypes.put("{{baseName}}", "{{{contentType}}}"); + {{/contentType}} {{#-last}} {{/-last}} @@ -205,7 +209,7 @@ public class {{classname}} { GenericType<{{{returnType}}}> localVarReturnType = new GenericType<{{{returnType}}}>() {}; {{/returnType}} return apiClient.invokeAPI("{{classname}}.{{operationId}}", {{#hasPathParams}}localVarPath{{/hasPathParams}}{{^hasPathParams}}"{{{path}}}"{{/hasPathParams}}, "{{httpMethod}}", {{#queryParams}}{{#-first}}localVarQueryParams{{/-first}}{{/queryParams}}{{^queryParams}}new ArrayList<>(){{/queryParams}}, {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}, - {{#headerParams}}{{#-first}}localVarHeaderParams{{/-first}}{{/headerParams}}{{^headerParams}}new LinkedHashMap<>(){{/headerParams}}, {{#cookieParams}}{{#-first}}localVarCookieParams{{/-first}}{{/cookieParams}}{{^cookieParams}}new LinkedHashMap<>(){{/cookieParams}}, {{#formParams}}{{#-first}}localVarFormParams{{/-first}}{{/formParams}}{{^formParams}}new LinkedHashMap<>(){{/formParams}}, localVarAccept, localVarContentType, + {{#headerParams}}{{#-first}}localVarHeaderParams{{/-first}}{{/headerParams}}{{^headerParams}}new LinkedHashMap<>(){{/headerParams}}, {{#cookieParams}}{{#-first}}localVarCookieParams{{/-first}}{{/cookieParams}}{{^cookieParams}}new LinkedHashMap<>(){{/cookieParams}}, {{#formParams}}{{#-first}}localVarFormParams, localVarFormParamContentTypes{{/-first}}{{/formParams}}{{^formParams}}new LinkedHashMap<>(){{/formParams}}, localVarAccept, localVarContentType, {{#hasAuthMethods}}localVarAuthNames{{/hasAuthMethods}}{{^hasAuthMethods}}null{{/hasAuthMethods}}, {{#returnType}}localVarReturnType{{/returnType}}{{^returnType}}null{{/returnType}}, {{#bodyParam}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/bodyParam}}{{^bodyParam}}false{{/bodyParam}}, localVarErrorTypes); } {{#vendorExtensions.x-group-parameters}} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java index f22474c10066..616fb2895f04 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java @@ -5995,6 +5995,62 @@ public void testArrayPathParamSerializedAsCollection(String library) { .assertMethod("collectionPathParameterToString", "String", "Collection"); } + @Test(dataProvider = "jerseyLibraries") + public void testMultipartObjectPartSerializedAsJson(String library) { + Path output = newTempFolder(); + CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName(JAVA_GENERATOR) + .setLibrary(library) + .addAdditionalProperty(CodegenConstants.INVOKER_PACKAGE, "xyz.abcdef.invoker") + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .setInputSpec("src/test/resources/3_0/form-multipart-binary-array.yaml") + .setOutputDir(output.toString().replace("\\", "/")); + + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); + + validateJavaSourceFiles(files); + assertThat(output.resolve("src/main/java/xyz/abcdef/api/MultipartApi.java")).content() + .contains("localVarFormParams.put(\"marker\", marker);"); + // complex parts must be sent as JSON, not via toString() + assertThat(output.resolve("src/main/java/xyz/abcdef/invoker/ApiClient.java")).content() + .contains("} else if (isPlainFormValue(value)) {") + .contains("return json.getMapper().writeValueAsString(value);") + .contains("new FormDataBodyPart(contentDisp, serializeToJson(value), MediaType.APPLICATION_JSON_TYPE)"); + JavaFileAssert.assertThat(output.resolve("src/main/java/xyz/abcdef/invoker/ApiClient.java").toFile()) + .assertMethod("isPlainFormValue", "Object"); + } + + @Test(dataProvider = "jerseyLibraries") + public void testMultipartEncodingContentTypePassedToApiClient(String library) { + Path output = newTempFolder(); + CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName(JAVA_GENERATOR) + .setLibrary(library) + .addAdditionalProperty(CodegenConstants.INVOKER_PACKAGE, "xyz.abcdef.invoker") + .addAdditionalProperty(CodegenConstants.API_PACKAGE, "xyz.abcdef.api") + .setInputSpec("src/test/resources/3_0/java/multipart-encoding.yaml") + .setOutputDir(output.toString().replace("\\", "/")); + + List files = new DefaultGenerator().opts(configurator.toClientOptInput()).generate(); + + validateJavaSourceFiles(files); + assertThat(output.resolve("src/main/java/xyz/abcdef/api/DefaultApi.java")).content() + .contains("localVarFormParamContentTypes.put(\"metadata\", \"application/json\");") + .contains("localVarFormParamContentTypes.put(\"ids\", \"application/json\");") + .contains("localVarFormParamContentTypes.put(\"marker\", \"application/json\");") + .contains("localVarFormParamContentTypes.put(\"image\", \"image/png\");") + .doesNotContain("localVarFormParamContentTypes.put(\"note\"") + .contains("localVarFormParams, localVarFormParamContentTypes, localVarAccept"); + // the previous signatures are kept and delegate to the new overloads + assertThat(output.resolve("src/main/java/xyz/abcdef/invoker/ApiClient.java")).content() + .contains("Entity entity = serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable);") + .contains("public Entity serialize(Object obj, Map formParams, String contentType, boolean isBodyNullable)") + .contains("return serialize(obj, formParams, Collections.emptyMap(), contentType, isBodyNullable);") + .contains("protected void addParamToMultipart(Object value, String key, MultiPart multiPart) throws ApiException {") + .contains("addParamToMultipart(value, key, multiPart, null);") + .contains("} else if (isJsonPartType(partType)) {"); + } + private static Path generateJerseyClient(String library, Boolean generateInsecureTlsHook) { Path output = newTempFolder(); CodegenConfigurator configurator = new CodegenConfigurator() diff --git a/modules/openapi-generator/src/test/resources/3_0/java/multipart-encoding.yaml b/modules/openapi-generator/src/test/resources/3_0/java/multipart-encoding.yaml new file mode 100644 index 000000000000..f6a38ac1789e --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/java/multipart-encoding.yaml @@ -0,0 +1,49 @@ +openapi: 3.0.3 +info: + title: multipart encoding + version: 1.0.0 +paths: + /multipart-encoding: + post: + operationId: multipartEncoding + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + metadata: + description: "a string that already contains JSON" + type: string + ids: + type: array + items: + type: integer + description: "an array sent as a single JSON part" + marker: + $ref: '#/components/schemas/Marker' + image: + type: string + format: binary + note: + description: "no encoding, sent as text" + type: string + encoding: + metadata: + contentType: application/json + ids: + contentType: application/json + marker: + contentType: application/json + image: + contentType: image/png + responses: + '204': + description: Successful operation +components: + schemas: + Marker: + type: object + properties: + name: + type: string diff --git a/samples/client/others/java/jersey2-oneOf-Mixed/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/others/java/jersey2-oneOf-Mixed/src/main/java/org/openapitools/client/ApiClient.java index fa0b4b321647..2bc28130893d 100644 --- a/samples/client/others/java/jersey2-oneOf-Mixed/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/others/java/jersey2-oneOf-Mixed/src/main/java/org/openapitools/client/ApiClient.java @@ -795,18 +795,39 @@ public String collectionPathParameterToString(String collectionFormat, Collectio * @param obj Object * @param formParams Form parameters * @param contentType Context type + * @param isBodyNullable True if the body is nullable * @return Entity * @throws ApiException API exception */ public Entity serialize(Object obj, Map formParams, String contentType, boolean isBodyNullable) throws ApiException { + return serialize(obj, formParams, Collections.emptyMap(), contentType, isBodyNullable); + } + + /** + * Serialize the given Java object into string entity according the given + * Content-Type (only JSON is supported for now). + * + * @param obj Object + * @param formParams Form parameters + * @param formParamContentTypes Content types of the multipart form parameters, as declared by the encoding of the request body + * @param contentType Context type + * @param isBodyNullable True if the body is nullable + * @return Entity + * @throws ApiException API exception + */ + public Entity serialize(Object obj, Map formParams, Map formParamContentTypes, String contentType, boolean isBodyNullable) throws ApiException { Entity entity; if (contentType.startsWith("multipart/form-data")) { MultiPart multiPart = new MultiPart(); for (Entry param: formParams.entrySet()) { - if (param.getValue() instanceof Iterable) { - ((Iterable)param.getValue()).forEach(v -> addParamToMultipart(v, param.getKey(), multiPart)); + MediaType partType = parsePartMediaType(formParamContentTypes == null ? null : formParamContentTypes.get(param.getKey())); + // a JSON encoded array is sent as a single part instead of one part per item + if (param.getValue() instanceof Iterable && !isJsonPartType(partType)) { + for (Object v : (Iterable) param.getValue()) { + addParamToMultipart(v, param.getKey(), multiPart, partType); + } } else { - addParamToMultipart(param.getValue(), param.getKey(), multiPart); + addParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); } } entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); @@ -839,11 +860,27 @@ public Entity serialize(Object obj, Map formParams, String co * Adds the object with the provided key to the MultiPart. * Based on the object type sets Content-Disposition and Content-Type. * - * @param obj Object + * @param value Object + * @param key Key of the object + * @param multiPart MultiPart to add the form param to + * @throws ApiException if the value cannot be serialized to JSON + */ + protected void addParamToMultipart(Object value, String key, MultiPart multiPart) throws ApiException { + addParamToMultipart(value, key, multiPart, null); + } + + /** + * Adds the object with the provided key to the MultiPart. + * The declared part type (from the encoding of the request body) takes precedence, + * otherwise the Content-Type is derived from the object type. + * + * @param value Object * @param key Key of the object * @param multiPart MultiPart to add the form param to + * @param partType Declared Content-Type of the part, or null if not declared + * @throws ApiException if the value cannot be serialized to JSON */ - protected void addParamToMultipart(Object value, String key, MultiPart multiPart) { + protected void addParamToMultipart(Object value, String key, MultiPart multiPart, MediaType partType) throws ApiException { if (value instanceof File) { File file = (File) value; FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key) @@ -851,18 +888,99 @@ protected void addParamToMultipart(Object value, String key, MultiPart multiPart // Attempt to probe the content type for the file so that the form part is more correctly // and precisely identified, but fall back to application/octet-stream if that fails. - MediaType type; - try { - type = MediaType.valueOf(Files.probeContentType(file.toPath())); - } catch (IOException | IllegalArgumentException e) { - type = MediaType.APPLICATION_OCTET_STREAM_TYPE; + MediaType type = partType; + if (type == null) { + try { + type = MediaType.valueOf(Files.probeContentType(file.toPath())); + } catch (IOException | IllegalArgumentException e) { + type = MediaType.APPLICATION_OCTET_STREAM_TYPE; + } } multiPart.bodyPart(new FormDataBodyPart(contentDisp, file, type)); + } else if (isJsonPartType(partType)) { + // the encoding asks for JSON: strings are expected to already contain JSON, everything else is serialized + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); + String jsonValue = value instanceof String ? (String) value : serializeToJson(value); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, jsonValue, partType)); + } else if (isPlainFormValue(value)) { + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); + if (partType == null) { + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value))); + } else { + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value), partType)); + } } else { + // Complex objects (models, maps, ...) are sent as JSON parts instead of their toString() output FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); - multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value))); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, serializeToJson(value), MediaType.APPLICATION_JSON_TYPE)); + } + } + + /** + * Serialize the given object to a JSON string. + * + * @param value Object + * @return JSON string + * @throws ApiException if the value cannot be serialized to JSON + */ + protected String serializeToJson(Object value) throws ApiException { + try { + return json.getMapper().writeValueAsString(value); + } catch (Exception e) { + throw new ApiException(e); + } + } + + /** + * Parse the Content-Type declared for a multipart part. + * Only the first entry of a comma separated list is used, wildcard or invalid types are ignored. + * + * @param partContentType Declared Content-Type, may be null + * @return The parsed media type, or null if none could be used + */ + protected MediaType parsePartMediaType(String partContentType) { + if (partContentType == null) { + return null; + } + String first = partContentType.split(",")[0].trim(); + if (first.isEmpty() || first.contains("*")) { + return null; } + try { + return MediaType.valueOf(first); + } catch (IllegalArgumentException e) { + return null; + } + } + + /** + * Check whether the given part type is a JSON type. + * + * @param partType Part media type, may be null + * @return True if the part must be sent as JSON + */ + protected boolean isJsonPartType(MediaType partType) { + return partType != null && isJsonMime(partType.toString()); + } + + /** + * Check whether the given form value should be sent as a plain text part. + * + * @param value Object + * @return true if the value is a scalar that can be sent as text + */ + protected boolean isPlainFormValue(Object value) { + return value == null + || value instanceof String + || value instanceof Number + || value instanceof Boolean + || value instanceof Character + || value instanceof Enum + || value instanceof Date + || value instanceof java.time.temporal.TemporalAccessor + || value instanceof java.util.UUID + || value instanceof java.net.URI; } /** @@ -1027,6 +1145,46 @@ public ApiResponse invokeAPI( GenericType returnType, boolean isBodyNullable) throws ApiException { + return invokeAPI(operation, path, method, queryParams, body, headerParams, cookieParams, formParams, Collections.emptyMap(), accept, contentType, authNames, returnType, isBodyNullable); + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param Type + * @param operation The qualified name of the operation + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "POST", "PUT", "HEAD" and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param formParamContentTypes The declared Content-Types of the multipart form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response + * @param isBodyNullable True if the body is nullable + * @return The response body in type of string + * @throws ApiException API exception + */ + public ApiResponse invokeAPI( + String operation, + String path, + String method, + List queryParams, + Object body, + Map headerParams, + Map cookieParams, + Map formParams, + Map formParamContentTypes, + String accept, + String contentType, + String[] authNames, + GenericType returnType, + boolean isBodyNullable) + throws ApiException { String targetURL; List serverConfigurations; @@ -1092,7 +1250,7 @@ public ApiResponse invokeAPI( } } - Entity entity = serialize(body, formParams, contentType, isBodyNullable); + Entity entity = serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); for (Entry entry : allHeaderParams.entrySet()) { String value = entry.getValue(); diff --git a/samples/client/others/java/jersey2-oneOf-duplicates/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/others/java/jersey2-oneOf-duplicates/src/main/java/org/openapitools/client/ApiClient.java index fa0b4b321647..2bc28130893d 100644 --- a/samples/client/others/java/jersey2-oneOf-duplicates/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/others/java/jersey2-oneOf-duplicates/src/main/java/org/openapitools/client/ApiClient.java @@ -795,18 +795,39 @@ public String collectionPathParameterToString(String collectionFormat, Collectio * @param obj Object * @param formParams Form parameters * @param contentType Context type + * @param isBodyNullable True if the body is nullable * @return Entity * @throws ApiException API exception */ public Entity serialize(Object obj, Map formParams, String contentType, boolean isBodyNullable) throws ApiException { + return serialize(obj, formParams, Collections.emptyMap(), contentType, isBodyNullable); + } + + /** + * Serialize the given Java object into string entity according the given + * Content-Type (only JSON is supported for now). + * + * @param obj Object + * @param formParams Form parameters + * @param formParamContentTypes Content types of the multipart form parameters, as declared by the encoding of the request body + * @param contentType Context type + * @param isBodyNullable True if the body is nullable + * @return Entity + * @throws ApiException API exception + */ + public Entity serialize(Object obj, Map formParams, Map formParamContentTypes, String contentType, boolean isBodyNullable) throws ApiException { Entity entity; if (contentType.startsWith("multipart/form-data")) { MultiPart multiPart = new MultiPart(); for (Entry param: formParams.entrySet()) { - if (param.getValue() instanceof Iterable) { - ((Iterable)param.getValue()).forEach(v -> addParamToMultipart(v, param.getKey(), multiPart)); + MediaType partType = parsePartMediaType(formParamContentTypes == null ? null : formParamContentTypes.get(param.getKey())); + // a JSON encoded array is sent as a single part instead of one part per item + if (param.getValue() instanceof Iterable && !isJsonPartType(partType)) { + for (Object v : (Iterable) param.getValue()) { + addParamToMultipart(v, param.getKey(), multiPart, partType); + } } else { - addParamToMultipart(param.getValue(), param.getKey(), multiPart); + addParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); } } entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); @@ -839,11 +860,27 @@ public Entity serialize(Object obj, Map formParams, String co * Adds the object with the provided key to the MultiPart. * Based on the object type sets Content-Disposition and Content-Type. * - * @param obj Object + * @param value Object + * @param key Key of the object + * @param multiPart MultiPart to add the form param to + * @throws ApiException if the value cannot be serialized to JSON + */ + protected void addParamToMultipart(Object value, String key, MultiPart multiPart) throws ApiException { + addParamToMultipart(value, key, multiPart, null); + } + + /** + * Adds the object with the provided key to the MultiPart. + * The declared part type (from the encoding of the request body) takes precedence, + * otherwise the Content-Type is derived from the object type. + * + * @param value Object * @param key Key of the object * @param multiPart MultiPart to add the form param to + * @param partType Declared Content-Type of the part, or null if not declared + * @throws ApiException if the value cannot be serialized to JSON */ - protected void addParamToMultipart(Object value, String key, MultiPart multiPart) { + protected void addParamToMultipart(Object value, String key, MultiPart multiPart, MediaType partType) throws ApiException { if (value instanceof File) { File file = (File) value; FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key) @@ -851,18 +888,99 @@ protected void addParamToMultipart(Object value, String key, MultiPart multiPart // Attempt to probe the content type for the file so that the form part is more correctly // and precisely identified, but fall back to application/octet-stream if that fails. - MediaType type; - try { - type = MediaType.valueOf(Files.probeContentType(file.toPath())); - } catch (IOException | IllegalArgumentException e) { - type = MediaType.APPLICATION_OCTET_STREAM_TYPE; + MediaType type = partType; + if (type == null) { + try { + type = MediaType.valueOf(Files.probeContentType(file.toPath())); + } catch (IOException | IllegalArgumentException e) { + type = MediaType.APPLICATION_OCTET_STREAM_TYPE; + } } multiPart.bodyPart(new FormDataBodyPart(contentDisp, file, type)); + } else if (isJsonPartType(partType)) { + // the encoding asks for JSON: strings are expected to already contain JSON, everything else is serialized + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); + String jsonValue = value instanceof String ? (String) value : serializeToJson(value); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, jsonValue, partType)); + } else if (isPlainFormValue(value)) { + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); + if (partType == null) { + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value))); + } else { + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value), partType)); + } } else { + // Complex objects (models, maps, ...) are sent as JSON parts instead of their toString() output FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); - multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value))); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, serializeToJson(value), MediaType.APPLICATION_JSON_TYPE)); + } + } + + /** + * Serialize the given object to a JSON string. + * + * @param value Object + * @return JSON string + * @throws ApiException if the value cannot be serialized to JSON + */ + protected String serializeToJson(Object value) throws ApiException { + try { + return json.getMapper().writeValueAsString(value); + } catch (Exception e) { + throw new ApiException(e); + } + } + + /** + * Parse the Content-Type declared for a multipart part. + * Only the first entry of a comma separated list is used, wildcard or invalid types are ignored. + * + * @param partContentType Declared Content-Type, may be null + * @return The parsed media type, or null if none could be used + */ + protected MediaType parsePartMediaType(String partContentType) { + if (partContentType == null) { + return null; + } + String first = partContentType.split(",")[0].trim(); + if (first.isEmpty() || first.contains("*")) { + return null; } + try { + return MediaType.valueOf(first); + } catch (IllegalArgumentException e) { + return null; + } + } + + /** + * Check whether the given part type is a JSON type. + * + * @param partType Part media type, may be null + * @return True if the part must be sent as JSON + */ + protected boolean isJsonPartType(MediaType partType) { + return partType != null && isJsonMime(partType.toString()); + } + + /** + * Check whether the given form value should be sent as a plain text part. + * + * @param value Object + * @return true if the value is a scalar that can be sent as text + */ + protected boolean isPlainFormValue(Object value) { + return value == null + || value instanceof String + || value instanceof Number + || value instanceof Boolean + || value instanceof Character + || value instanceof Enum + || value instanceof Date + || value instanceof java.time.temporal.TemporalAccessor + || value instanceof java.util.UUID + || value instanceof java.net.URI; } /** @@ -1027,6 +1145,46 @@ public ApiResponse invokeAPI( GenericType returnType, boolean isBodyNullable) throws ApiException { + return invokeAPI(operation, path, method, queryParams, body, headerParams, cookieParams, formParams, Collections.emptyMap(), accept, contentType, authNames, returnType, isBodyNullable); + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param Type + * @param operation The qualified name of the operation + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "POST", "PUT", "HEAD" and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param formParamContentTypes The declared Content-Types of the multipart form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response + * @param isBodyNullable True if the body is nullable + * @return The response body in type of string + * @throws ApiException API exception + */ + public ApiResponse invokeAPI( + String operation, + String path, + String method, + List queryParams, + Object body, + Map headerParams, + Map cookieParams, + Map formParams, + Map formParamContentTypes, + String accept, + String contentType, + String[] authNames, + GenericType returnType, + boolean isBodyNullable) + throws ApiException { String targetURL; List serverConfigurations; @@ -1092,7 +1250,7 @@ public ApiResponse invokeAPI( } } - Entity entity = serialize(body, formParams, contentType, isBodyNullable); + Entity entity = serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); for (Entry entry : allHeaderParams.entrySet()) { String value = entry.getValue(); diff --git a/samples/client/petstore/java/jersey2-java8-localdatetime/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/jersey2-java8-localdatetime/src/main/java/org/openapitools/client/ApiClient.java index e4d28c376def..f7ed27c3193a 100644 --- a/samples/client/petstore/java/jersey2-java8-localdatetime/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/jersey2-java8-localdatetime/src/main/java/org/openapitools/client/ApiClient.java @@ -936,18 +936,39 @@ public String collectionPathParameterToString(String collectionFormat, Collectio * @param obj Object * @param formParams Form parameters * @param contentType Context type + * @param isBodyNullable True if the body is nullable * @return Entity * @throws ApiException API exception */ public Entity serialize(Object obj, Map formParams, String contentType, boolean isBodyNullable) throws ApiException { + return serialize(obj, formParams, Collections.emptyMap(), contentType, isBodyNullable); + } + + /** + * Serialize the given Java object into string entity according the given + * Content-Type (only JSON is supported for now). + * + * @param obj Object + * @param formParams Form parameters + * @param formParamContentTypes Content types of the multipart form parameters, as declared by the encoding of the request body + * @param contentType Context type + * @param isBodyNullable True if the body is nullable + * @return Entity + * @throws ApiException API exception + */ + public Entity serialize(Object obj, Map formParams, Map formParamContentTypes, String contentType, boolean isBodyNullable) throws ApiException { Entity entity; if (contentType.startsWith("multipart/form-data")) { MultiPart multiPart = new MultiPart(); for (Entry param: formParams.entrySet()) { - if (param.getValue() instanceof Iterable) { - ((Iterable)param.getValue()).forEach(v -> addParamToMultipart(v, param.getKey(), multiPart)); + MediaType partType = parsePartMediaType(formParamContentTypes == null ? null : formParamContentTypes.get(param.getKey())); + // a JSON encoded array is sent as a single part instead of one part per item + if (param.getValue() instanceof Iterable && !isJsonPartType(partType)) { + for (Object v : (Iterable) param.getValue()) { + addParamToMultipart(v, param.getKey(), multiPart, partType); + } } else { - addParamToMultipart(param.getValue(), param.getKey(), multiPart); + addParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); } } entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); @@ -980,11 +1001,27 @@ public Entity serialize(Object obj, Map formParams, String co * Adds the object with the provided key to the MultiPart. * Based on the object type sets Content-Disposition and Content-Type. * - * @param obj Object + * @param value Object + * @param key Key of the object + * @param multiPart MultiPart to add the form param to + * @throws ApiException if the value cannot be serialized to JSON + */ + protected void addParamToMultipart(Object value, String key, MultiPart multiPart) throws ApiException { + addParamToMultipart(value, key, multiPart, null); + } + + /** + * Adds the object with the provided key to the MultiPart. + * The declared part type (from the encoding of the request body) takes precedence, + * otherwise the Content-Type is derived from the object type. + * + * @param value Object * @param key Key of the object * @param multiPart MultiPart to add the form param to + * @param partType Declared Content-Type of the part, or null if not declared + * @throws ApiException if the value cannot be serialized to JSON */ - protected void addParamToMultipart(Object value, String key, MultiPart multiPart) { + protected void addParamToMultipart(Object value, String key, MultiPart multiPart, MediaType partType) throws ApiException { if (value instanceof File) { File file = (File) value; FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key) @@ -992,18 +1029,99 @@ protected void addParamToMultipart(Object value, String key, MultiPart multiPart // Attempt to probe the content type for the file so that the form part is more correctly // and precisely identified, but fall back to application/octet-stream if that fails. - MediaType type; - try { - type = MediaType.valueOf(Files.probeContentType(file.toPath())); - } catch (IOException | IllegalArgumentException e) { - type = MediaType.APPLICATION_OCTET_STREAM_TYPE; + MediaType type = partType; + if (type == null) { + try { + type = MediaType.valueOf(Files.probeContentType(file.toPath())); + } catch (IOException | IllegalArgumentException e) { + type = MediaType.APPLICATION_OCTET_STREAM_TYPE; + } } multiPart.bodyPart(new FormDataBodyPart(contentDisp, file, type)); + } else if (isJsonPartType(partType)) { + // the encoding asks for JSON: strings are expected to already contain JSON, everything else is serialized + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); + String jsonValue = value instanceof String ? (String) value : serializeToJson(value); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, jsonValue, partType)); + } else if (isPlainFormValue(value)) { + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); + if (partType == null) { + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value))); + } else { + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value), partType)); + } } else { + // Complex objects (models, maps, ...) are sent as JSON parts instead of their toString() output FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); - multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value))); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, serializeToJson(value), MediaType.APPLICATION_JSON_TYPE)); + } + } + + /** + * Serialize the given object to a JSON string. + * + * @param value Object + * @return JSON string + * @throws ApiException if the value cannot be serialized to JSON + */ + protected String serializeToJson(Object value) throws ApiException { + try { + return json.getMapper().writeValueAsString(value); + } catch (Exception e) { + throw new ApiException(e); + } + } + + /** + * Parse the Content-Type declared for a multipart part. + * Only the first entry of a comma separated list is used, wildcard or invalid types are ignored. + * + * @param partContentType Declared Content-Type, may be null + * @return The parsed media type, or null if none could be used + */ + protected MediaType parsePartMediaType(String partContentType) { + if (partContentType == null) { + return null; + } + String first = partContentType.split(",")[0].trim(); + if (first.isEmpty() || first.contains("*")) { + return null; } + try { + return MediaType.valueOf(first); + } catch (IllegalArgumentException e) { + return null; + } + } + + /** + * Check whether the given part type is a JSON type. + * + * @param partType Part media type, may be null + * @return True if the part must be sent as JSON + */ + protected boolean isJsonPartType(MediaType partType) { + return partType != null && isJsonMime(partType.toString()); + } + + /** + * Check whether the given form value should be sent as a plain text part. + * + * @param value Object + * @return true if the value is a scalar that can be sent as text + */ + protected boolean isPlainFormValue(Object value) { + return value == null + || value instanceof String + || value instanceof Number + || value instanceof Boolean + || value instanceof Character + || value instanceof Enum + || value instanceof Date + || value instanceof java.time.temporal.TemporalAccessor + || value instanceof java.util.UUID + || value instanceof java.net.URI; } /** @@ -1168,6 +1286,46 @@ public ApiResponse invokeAPI( GenericType returnType, boolean isBodyNullable) throws ApiException { + return invokeAPI(operation, path, method, queryParams, body, headerParams, cookieParams, formParams, Collections.emptyMap(), accept, contentType, authNames, returnType, isBodyNullable); + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param Type + * @param operation The qualified name of the operation + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "POST", "PUT", "HEAD" and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param formParamContentTypes The declared Content-Types of the multipart form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response + * @param isBodyNullable True if the body is nullable + * @return The response body in type of string + * @throws ApiException API exception + */ + public ApiResponse invokeAPI( + String operation, + String path, + String method, + List queryParams, + Object body, + Map headerParams, + Map cookieParams, + Map formParams, + Map formParamContentTypes, + String accept, + String contentType, + String[] authNames, + GenericType returnType, + boolean isBodyNullable) + throws ApiException { String targetURL; List serverConfigurations; @@ -1233,7 +1391,7 @@ public ApiResponse invokeAPI( } } - Entity entity = serialize(body, formParams, contentType, isBodyNullable); + Entity entity = serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); for (Entry entry : allHeaderParams.entrySet()) { String value = entry.getValue(); diff --git a/samples/client/petstore/java/jersey2-java8-localdatetime/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/jersey2-java8-localdatetime/src/main/java/org/openapitools/client/api/FakeApi.java index c72a5c0551b6..14033633389d 100644 --- a/samples/client/petstore/java/jersey2-java8-localdatetime/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/jersey2-java8-localdatetime/src/main/java/org/openapitools/client/api/FakeApi.java @@ -456,6 +456,7 @@ public ApiResponse testEndpointParametersWithHttpInfo(@javax.annotation.No // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); if (integer != null) { localVarFormParams.put("integer", integer); } @@ -495,7 +496,7 @@ public ApiResponse testEndpointParametersWithHttpInfo(@javax.annotation.No String localVarContentType = apiClient.selectHeaderContentType("application/x-www-form-urlencoded"); String[] localVarAuthNames = new String[] {"http_basic_test"}; return apiClient.invokeAPI("FakeApi.testEndpointParameters", "/fake", "POST", new ArrayList<>(), null, - new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, localVarAuthNames, null, false); } /** @@ -563,6 +564,7 @@ public ApiResponse testEnumParametersWithHttpInfo(@javax.annotation.Nullab // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); if (enumFormStringArray != null) { localVarFormParams.put("enum_form_string_array", enumFormStringArray); } @@ -573,7 +575,7 @@ public ApiResponse testEnumParametersWithHttpInfo(@javax.annotation.Nullab String localVarAccept = apiClient.selectHeaderAccept(); String localVarContentType = apiClient.selectHeaderContentType("application/x-www-form-urlencoded"); return apiClient.invokeAPI("FakeApi.testEnumParameters", "/fake", "GET", localVarQueryParams, null, - localVarHeaderParams, new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + localVarHeaderParams, new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, null, null, false); } @@ -816,13 +818,14 @@ public ApiResponse testJsonFormDataWithHttpInfo(@javax.annotation.Nonnull // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); localVarFormParams.put("param", param); localVarFormParams.put("param2", param2); String localVarAccept = apiClient.selectHeaderAccept(); String localVarContentType = apiClient.selectHeaderContentType("application/x-www-form-urlencoded"); return apiClient.invokeAPI("FakeApi.testJsonFormData", "/fake/jsonFormData", "GET", new ArrayList<>(), null, - new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, null, null, false); } /** diff --git a/samples/client/petstore/java/jersey2-java8-localdatetime/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java/jersey2-java8-localdatetime/src/main/java/org/openapitools/client/api/PetApi.java index 271507239baa..6bc94fdb5ebe 100644 --- a/samples/client/petstore/java/jersey2-java8-localdatetime/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/client/petstore/java/jersey2-java8-localdatetime/src/main/java/org/openapitools/client/api/PetApi.java @@ -400,6 +400,7 @@ public ApiResponse updatePetWithFormWithHttpInfo(@javax.annotation.Nonnull // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); if (name != null) { localVarFormParams.put("name", name); } @@ -411,7 +412,7 @@ public ApiResponse updatePetWithFormWithHttpInfo(@javax.annotation.Nonnull String localVarContentType = apiClient.selectHeaderContentType("application/x-www-form-urlencoded"); String[] localVarAuthNames = new String[] {"petstore_auth"}; return apiClient.invokeAPI("PetApi.updatePetWithForm", localVarPath, "POST", new ArrayList<>(), null, - new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, localVarAuthNames, null, false); } /** @@ -460,6 +461,7 @@ public ApiResponse uploadFileWithHttpInfo(@javax.annotation.No // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); if (additionalMetadata != null) { localVarFormParams.put("additionalMetadata", additionalMetadata); } @@ -472,7 +474,7 @@ public ApiResponse uploadFileWithHttpInfo(@javax.annotation.No String[] localVarAuthNames = new String[] {"petstore_auth"}; GenericType localVarReturnType = new GenericType() {}; return apiClient.invokeAPI("PetApi.uploadFile", localVarPath, "POST", new ArrayList<>(), null, - new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType, false); } /** @@ -524,6 +526,7 @@ public ApiResponse uploadFileWithRequiredFileWithHttpInfo(@jav // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); if (additionalMetadata != null) { localVarFormParams.put("additionalMetadata", additionalMetadata); } @@ -534,7 +537,7 @@ public ApiResponse uploadFileWithRequiredFileWithHttpInfo(@jav String[] localVarAuthNames = new String[] {"petstore_auth"}; GenericType localVarReturnType = new GenericType() {}; return apiClient.invokeAPI("PetApi.uploadFileWithRequiredFile", localVarPath, "POST", new ArrayList<>(), null, - new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType, false); } } diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java index e4d28c376def..f7ed27c3193a 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java @@ -936,18 +936,39 @@ public String collectionPathParameterToString(String collectionFormat, Collectio * @param obj Object * @param formParams Form parameters * @param contentType Context type + * @param isBodyNullable True if the body is nullable * @return Entity * @throws ApiException API exception */ public Entity serialize(Object obj, Map formParams, String contentType, boolean isBodyNullable) throws ApiException { + return serialize(obj, formParams, Collections.emptyMap(), contentType, isBodyNullable); + } + + /** + * Serialize the given Java object into string entity according the given + * Content-Type (only JSON is supported for now). + * + * @param obj Object + * @param formParams Form parameters + * @param formParamContentTypes Content types of the multipart form parameters, as declared by the encoding of the request body + * @param contentType Context type + * @param isBodyNullable True if the body is nullable + * @return Entity + * @throws ApiException API exception + */ + public Entity serialize(Object obj, Map formParams, Map formParamContentTypes, String contentType, boolean isBodyNullable) throws ApiException { Entity entity; if (contentType.startsWith("multipart/form-data")) { MultiPart multiPart = new MultiPart(); for (Entry param: formParams.entrySet()) { - if (param.getValue() instanceof Iterable) { - ((Iterable)param.getValue()).forEach(v -> addParamToMultipart(v, param.getKey(), multiPart)); + MediaType partType = parsePartMediaType(formParamContentTypes == null ? null : formParamContentTypes.get(param.getKey())); + // a JSON encoded array is sent as a single part instead of one part per item + if (param.getValue() instanceof Iterable && !isJsonPartType(partType)) { + for (Object v : (Iterable) param.getValue()) { + addParamToMultipart(v, param.getKey(), multiPart, partType); + } } else { - addParamToMultipart(param.getValue(), param.getKey(), multiPart); + addParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); } } entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); @@ -980,11 +1001,27 @@ public Entity serialize(Object obj, Map formParams, String co * Adds the object with the provided key to the MultiPart. * Based on the object type sets Content-Disposition and Content-Type. * - * @param obj Object + * @param value Object + * @param key Key of the object + * @param multiPart MultiPart to add the form param to + * @throws ApiException if the value cannot be serialized to JSON + */ + protected void addParamToMultipart(Object value, String key, MultiPart multiPart) throws ApiException { + addParamToMultipart(value, key, multiPart, null); + } + + /** + * Adds the object with the provided key to the MultiPart. + * The declared part type (from the encoding of the request body) takes precedence, + * otherwise the Content-Type is derived from the object type. + * + * @param value Object * @param key Key of the object * @param multiPart MultiPart to add the form param to + * @param partType Declared Content-Type of the part, or null if not declared + * @throws ApiException if the value cannot be serialized to JSON */ - protected void addParamToMultipart(Object value, String key, MultiPart multiPart) { + protected void addParamToMultipart(Object value, String key, MultiPart multiPart, MediaType partType) throws ApiException { if (value instanceof File) { File file = (File) value; FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key) @@ -992,18 +1029,99 @@ protected void addParamToMultipart(Object value, String key, MultiPart multiPart // Attempt to probe the content type for the file so that the form part is more correctly // and precisely identified, but fall back to application/octet-stream if that fails. - MediaType type; - try { - type = MediaType.valueOf(Files.probeContentType(file.toPath())); - } catch (IOException | IllegalArgumentException e) { - type = MediaType.APPLICATION_OCTET_STREAM_TYPE; + MediaType type = partType; + if (type == null) { + try { + type = MediaType.valueOf(Files.probeContentType(file.toPath())); + } catch (IOException | IllegalArgumentException e) { + type = MediaType.APPLICATION_OCTET_STREAM_TYPE; + } } multiPart.bodyPart(new FormDataBodyPart(contentDisp, file, type)); + } else if (isJsonPartType(partType)) { + // the encoding asks for JSON: strings are expected to already contain JSON, everything else is serialized + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); + String jsonValue = value instanceof String ? (String) value : serializeToJson(value); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, jsonValue, partType)); + } else if (isPlainFormValue(value)) { + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); + if (partType == null) { + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value))); + } else { + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value), partType)); + } } else { + // Complex objects (models, maps, ...) are sent as JSON parts instead of their toString() output FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); - multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value))); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, serializeToJson(value), MediaType.APPLICATION_JSON_TYPE)); + } + } + + /** + * Serialize the given object to a JSON string. + * + * @param value Object + * @return JSON string + * @throws ApiException if the value cannot be serialized to JSON + */ + protected String serializeToJson(Object value) throws ApiException { + try { + return json.getMapper().writeValueAsString(value); + } catch (Exception e) { + throw new ApiException(e); + } + } + + /** + * Parse the Content-Type declared for a multipart part. + * Only the first entry of a comma separated list is used, wildcard or invalid types are ignored. + * + * @param partContentType Declared Content-Type, may be null + * @return The parsed media type, or null if none could be used + */ + protected MediaType parsePartMediaType(String partContentType) { + if (partContentType == null) { + return null; + } + String first = partContentType.split(",")[0].trim(); + if (first.isEmpty() || first.contains("*")) { + return null; } + try { + return MediaType.valueOf(first); + } catch (IllegalArgumentException e) { + return null; + } + } + + /** + * Check whether the given part type is a JSON type. + * + * @param partType Part media type, may be null + * @return True if the part must be sent as JSON + */ + protected boolean isJsonPartType(MediaType partType) { + return partType != null && isJsonMime(partType.toString()); + } + + /** + * Check whether the given form value should be sent as a plain text part. + * + * @param value Object + * @return true if the value is a scalar that can be sent as text + */ + protected boolean isPlainFormValue(Object value) { + return value == null + || value instanceof String + || value instanceof Number + || value instanceof Boolean + || value instanceof Character + || value instanceof Enum + || value instanceof Date + || value instanceof java.time.temporal.TemporalAccessor + || value instanceof java.util.UUID + || value instanceof java.net.URI; } /** @@ -1168,6 +1286,46 @@ public ApiResponse invokeAPI( GenericType returnType, boolean isBodyNullable) throws ApiException { + return invokeAPI(operation, path, method, queryParams, body, headerParams, cookieParams, formParams, Collections.emptyMap(), accept, contentType, authNames, returnType, isBodyNullable); + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param Type + * @param operation The qualified name of the operation + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "POST", "PUT", "HEAD" and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param formParamContentTypes The declared Content-Types of the multipart form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response + * @param isBodyNullable True if the body is nullable + * @return The response body in type of string + * @throws ApiException API exception + */ + public ApiResponse invokeAPI( + String operation, + String path, + String method, + List queryParams, + Object body, + Map headerParams, + Map cookieParams, + Map formParams, + Map formParamContentTypes, + String accept, + String contentType, + String[] authNames, + GenericType returnType, + boolean isBodyNullable) + throws ApiException { String targetURL; List serverConfigurations; @@ -1233,7 +1391,7 @@ public ApiResponse invokeAPI( } } - Entity entity = serialize(body, formParams, contentType, isBodyNullable); + Entity entity = serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); for (Entry entry : allHeaderParams.entrySet()) { String value = entry.getValue(); diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/api/FakeApi.java index c2502e7c69d1..ce270f03efe2 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/api/FakeApi.java @@ -456,6 +456,7 @@ public ApiResponse testEndpointParametersWithHttpInfo(@javax.annotation.No // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); if (integer != null) { localVarFormParams.put("integer", integer); } @@ -495,7 +496,7 @@ public ApiResponse testEndpointParametersWithHttpInfo(@javax.annotation.No String localVarContentType = apiClient.selectHeaderContentType("application/x-www-form-urlencoded"); String[] localVarAuthNames = new String[] {"http_basic_test"}; return apiClient.invokeAPI("FakeApi.testEndpointParameters", "/fake", "POST", new ArrayList<>(), null, - new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, localVarAuthNames, null, false); } /** @@ -563,6 +564,7 @@ public ApiResponse testEnumParametersWithHttpInfo(@javax.annotation.Nullab // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); if (enumFormStringArray != null) { localVarFormParams.put("enum_form_string_array", enumFormStringArray); } @@ -573,7 +575,7 @@ public ApiResponse testEnumParametersWithHttpInfo(@javax.annotation.Nullab String localVarAccept = apiClient.selectHeaderAccept(); String localVarContentType = apiClient.selectHeaderContentType("application/x-www-form-urlencoded"); return apiClient.invokeAPI("FakeApi.testEnumParameters", "/fake", "GET", localVarQueryParams, null, - localVarHeaderParams, new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + localVarHeaderParams, new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, null, null, false); } @@ -816,13 +818,14 @@ public ApiResponse testJsonFormDataWithHttpInfo(@javax.annotation.Nonnull // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); localVarFormParams.put("param", param); localVarFormParams.put("param2", param2); String localVarAccept = apiClient.selectHeaderAccept(); String localVarContentType = apiClient.selectHeaderContentType("application/x-www-form-urlencoded"); return apiClient.invokeAPI("FakeApi.testJsonFormData", "/fake/jsonFormData", "GET", new ArrayList<>(), null, - new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, null, null, false); } /** diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/api/PetApi.java index 271507239baa..6bc94fdb5ebe 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/api/PetApi.java @@ -400,6 +400,7 @@ public ApiResponse updatePetWithFormWithHttpInfo(@javax.annotation.Nonnull // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); if (name != null) { localVarFormParams.put("name", name); } @@ -411,7 +412,7 @@ public ApiResponse updatePetWithFormWithHttpInfo(@javax.annotation.Nonnull String localVarContentType = apiClient.selectHeaderContentType("application/x-www-form-urlencoded"); String[] localVarAuthNames = new String[] {"petstore_auth"}; return apiClient.invokeAPI("PetApi.updatePetWithForm", localVarPath, "POST", new ArrayList<>(), null, - new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, localVarAuthNames, null, false); } /** @@ -460,6 +461,7 @@ public ApiResponse uploadFileWithHttpInfo(@javax.annotation.No // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); if (additionalMetadata != null) { localVarFormParams.put("additionalMetadata", additionalMetadata); } @@ -472,7 +474,7 @@ public ApiResponse uploadFileWithHttpInfo(@javax.annotation.No String[] localVarAuthNames = new String[] {"petstore_auth"}; GenericType localVarReturnType = new GenericType() {}; return apiClient.invokeAPI("PetApi.uploadFile", localVarPath, "POST", new ArrayList<>(), null, - new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType, false); } /** @@ -524,6 +526,7 @@ public ApiResponse uploadFileWithRequiredFileWithHttpInfo(@jav // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); if (additionalMetadata != null) { localVarFormParams.put("additionalMetadata", additionalMetadata); } @@ -534,7 +537,7 @@ public ApiResponse uploadFileWithRequiredFileWithHttpInfo(@jav String[] localVarAuthNames = new String[] {"petstore_auth"}; GenericType localVarReturnType = new GenericType() {}; return apiClient.invokeAPI("PetApi.uploadFileWithRequiredFile", localVarPath, "POST", new ArrayList<>(), null, - new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType, false); } } diff --git a/samples/client/petstore/java/jersey3-jackson3/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/jersey3-jackson3/src/main/java/org/openapitools/client/ApiClient.java index a38a7d12634e..2cb4b2d4163f 100644 --- a/samples/client/petstore/java/jersey3-jackson3/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/jersey3-jackson3/src/main/java/org/openapitools/client/ApiClient.java @@ -1019,18 +1019,39 @@ public String collectionPathParameterToString(String collectionFormat, Collectio * @param obj Object * @param formParams Form parameters * @param contentType Context type + * @param isBodyNullable True if the body is nullable * @return Entity * @throws ApiException API exception */ public Entity serialize(Object obj, Map formParams, String contentType, boolean isBodyNullable) throws ApiException { + return serialize(obj, formParams, Collections.emptyMap(), contentType, isBodyNullable); + } + + /** + * Serialize the given Java object into string entity according the given + * Content-Type (only JSON is supported for now). + * + * @param obj Object + * @param formParams Form parameters + * @param formParamContentTypes Content types of the multipart form parameters, as declared by the encoding of the request body + * @param contentType Context type + * @param isBodyNullable True if the body is nullable + * @return Entity + * @throws ApiException API exception + */ + public Entity serialize(Object obj, Map formParams, Map formParamContentTypes, String contentType, boolean isBodyNullable) throws ApiException { Entity entity; if (contentType.startsWith("multipart/form-data")) { MultiPart multiPart = new MultiPart(); for (Entry param: formParams.entrySet()) { - if (param.getValue() instanceof Iterable) { - ((Iterable)param.getValue()).forEach(v -> addParamToMultipart(v, param.getKey(), multiPart)); + MediaType partType = parsePartMediaType(formParamContentTypes == null ? null : formParamContentTypes.get(param.getKey())); + // a JSON encoded array is sent as a single part instead of one part per item + if (param.getValue() instanceof Iterable && !isJsonPartType(partType)) { + for (Object v : (Iterable) param.getValue()) { + addParamToMultipart(v, param.getKey(), multiPart, partType); + } } else { - addParamToMultipart(param.getValue(), param.getKey(), multiPart); + addParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); } } entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); @@ -1066,8 +1087,24 @@ public Entity serialize(Object obj, Map formParams, String co * @param value Object * @param key Key of the object * @param multiPart MultiPart to add the form param to + * @throws ApiException if the value cannot be serialized to JSON + */ + protected void addParamToMultipart(Object value, String key, MultiPart multiPart) throws ApiException { + addParamToMultipart(value, key, multiPart, null); + } + + /** + * Adds the object with the provided key to the MultiPart. + * The declared part type (from the encoding of the request body) takes precedence, + * otherwise the Content-Type is derived from the object type. + * + * @param value Object + * @param key Key of the object + * @param multiPart MultiPart to add the form param to + * @param partType Declared Content-Type of the part, or null if not declared + * @throws ApiException if the value cannot be serialized to JSON */ - protected void addParamToMultipart(Object value, String key, MultiPart multiPart) { + protected void addParamToMultipart(Object value, String key, MultiPart multiPart, MediaType partType) throws ApiException { if (value instanceof File) { File file = (File) value; FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key) @@ -1075,18 +1112,99 @@ protected void addParamToMultipart(Object value, String key, MultiPart multiPart // Attempt to probe the content type for the file so that the form part is more correctly // and precisely identified, but fall back to application/octet-stream if that fails. - MediaType type; - try { - type = MediaType.valueOf(Files.probeContentType(file.toPath())); - } catch (IOException | IllegalArgumentException e) { - type = MediaType.APPLICATION_OCTET_STREAM_TYPE; + MediaType type = partType; + if (type == null) { + try { + type = MediaType.valueOf(Files.probeContentType(file.toPath())); + } catch (IOException | IllegalArgumentException e) { + type = MediaType.APPLICATION_OCTET_STREAM_TYPE; + } } multiPart.bodyPart(new FormDataBodyPart(contentDisp, file, type)); + } else if (isJsonPartType(partType)) { + // the encoding asks for JSON: strings are expected to already contain JSON, everything else is serialized + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); + String jsonValue = value instanceof String ? (String) value : serializeToJson(value); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, jsonValue, partType)); + } else if (isPlainFormValue(value)) { + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); + if (partType == null) { + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value))); + } else { + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value), partType)); + } } else { + // Complex objects (models, maps, ...) are sent as JSON parts instead of their toString() output FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); - multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value))); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, serializeToJson(value), MediaType.APPLICATION_JSON_TYPE)); + } + } + + /** + * Serialize the given object to a JSON string. + * + * @param value Object + * @return JSON string + * @throws ApiException if the value cannot be serialized to JSON + */ + protected String serializeToJson(Object value) throws ApiException { + try { + return json.getMapper().writeValueAsString(value); + } catch (Exception e) { + throw new ApiException(e); + } + } + + /** + * Parse the Content-Type declared for a multipart part. + * Only the first entry of a comma separated list is used, wildcard or invalid types are ignored. + * + * @param partContentType Declared Content-Type, may be null + * @return The parsed media type, or null if none could be used + */ + protected MediaType parsePartMediaType(String partContentType) { + if (partContentType == null) { + return null; + } + String first = partContentType.split(",")[0].trim(); + if (first.isEmpty() || first.contains("*")) { + return null; + } + try { + return MediaType.valueOf(first); + } catch (IllegalArgumentException e) { + return null; } + } + + /** + * Check whether the given part type is a JSON type. + * + * @param partType Part media type, may be null + * @return True if the part must be sent as JSON + */ + protected boolean isJsonPartType(MediaType partType) { + return partType != null && isJsonMime(partType.toString()); + } + + /** + * Check whether the given form value should be sent as a plain text part. + * + * @param value Object + * @return true if the value is a scalar that can be sent as text + */ + protected boolean isPlainFormValue(Object value) { + return value == null + || value instanceof String + || value instanceof Number + || value instanceof Boolean + || value instanceof Character + || value instanceof Enum + || value instanceof Date + || value instanceof java.time.temporal.TemporalAccessor + || value instanceof java.util.UUID + || value instanceof java.net.URI; } /** @@ -1251,6 +1369,48 @@ public ApiResponse invokeAPI( String[] authNames, GenericType returnType, boolean isBodyNullable, + Map errorTypes) + throws ApiException { + return invokeAPI(operation, path, method, queryParams, body, headerParams, cookieParams, formParams, Collections.emptyMap(), accept, contentType, authNames, returnType, isBodyNullable, errorTypes); + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param Type + * @param operation The qualified name of the operation + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "POST", "PUT", "HEAD" and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param formParamContentTypes The declared Content-Types of the multipart form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response + * @param isBodyNullable True if the body is nullable + * @param errorTypes Mapping of error codes to types into which to deserialize the response + * @return The response body in type of string + * @throws ApiException API exception + */ + public ApiResponse invokeAPI( + String operation, + String path, + String method, + List queryParams, + Object body, + Map headerParams, + Map cookieParams, + Map formParams, + Map formParamContentTypes, + String accept, + String contentType, + String[] authNames, + GenericType returnType, + boolean isBodyNullable, Map errorTypes ) throws ApiException { @@ -1319,7 +1479,7 @@ public ApiResponse invokeAPI( } } - Entity entity = serialize(body, formParams, contentType, isBodyNullable); + Entity entity = serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); for (Entry entry : allHeaderParams.entrySet()) { String value = entry.getValue(); diff --git a/samples/client/petstore/java/jersey3-jackson3/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/jersey3-jackson3/src/main/java/org/openapitools/client/api/FakeApi.java index 69e0b2600e23..23754c7d1895 100644 --- a/samples/client/petstore/java/jersey3-jackson3/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/jersey3-jackson3/src/main/java/org/openapitools/client/api/FakeApi.java @@ -587,6 +587,7 @@ public ApiResponse testEndpointParametersWithHttpInfo(@jakarta.annotation. // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); if (integer != null) { localVarFormParams.put("integer", integer); } @@ -627,7 +628,7 @@ public ApiResponse testEndpointParametersWithHttpInfo(@jakarta.annotation. String[] localVarAuthNames = new String[] {"http_basic_test"}; final Map localVarErrorTypes = new HashMap(); return apiClient.invokeAPI("FakeApi.testEndpointParameters", "/fake", "POST", new ArrayList<>(), null, - new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, localVarAuthNames, null, false, localVarErrorTypes); } /** @@ -695,6 +696,7 @@ public ApiResponse testEnumParametersWithHttpInfo(@jakarta.annotation.Null // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); if (enumFormStringArray != null) { localVarFormParams.put("enum_form_string_array", enumFormStringArray); } @@ -706,7 +708,7 @@ public ApiResponse testEnumParametersWithHttpInfo(@jakarta.annotation.Null String localVarContentType = apiClient.selectHeaderContentType("application/x-www-form-urlencoded"); final Map localVarErrorTypes = new HashMap(); return apiClient.invokeAPI("FakeApi.testEnumParameters", "/fake", "GET", localVarQueryParams, null, - localVarHeaderParams, new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + localVarHeaderParams, new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, null, null, false, localVarErrorTypes); } @@ -994,6 +996,7 @@ public ApiResponse testJsonFormDataWithHttpInfo(@jakarta.annotation.Nonnul // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); localVarFormParams.put("param", param); localVarFormParams.put("param2", param2); @@ -1001,7 +1004,7 @@ public ApiResponse testJsonFormDataWithHttpInfo(@jakarta.annotation.Nonnul String localVarContentType = apiClient.selectHeaderContentType("application/x-www-form-urlencoded"); final Map localVarErrorTypes = new HashMap(); return apiClient.invokeAPI("FakeApi.testJsonFormData", "/fake/jsonFormData", "GET", new ArrayList<>(), null, - new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, null, null, false, localVarErrorTypes); } /** diff --git a/samples/client/petstore/java/jersey3-jackson3/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java/jersey3-jackson3/src/main/java/org/openapitools/client/api/PetApi.java index d5df52705772..f868d2b4f1de 100644 --- a/samples/client/petstore/java/jersey3-jackson3/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/client/petstore/java/jersey3-jackson3/src/main/java/org/openapitools/client/api/PetApi.java @@ -405,6 +405,7 @@ public ApiResponse updatePetWithFormWithHttpInfo(@jakarta.annotation.Nonnu // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); if (name != null) { localVarFormParams.put("name", name); } @@ -417,7 +418,7 @@ public ApiResponse updatePetWithFormWithHttpInfo(@jakarta.annotation.Nonnu String[] localVarAuthNames = new String[] {"petstore_auth"}; final Map localVarErrorTypes = new HashMap(); return apiClient.invokeAPI("PetApi.updatePetWithForm", localVarPath, "POST", new ArrayList<>(), null, - new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, localVarAuthNames, null, false, localVarErrorTypes); } /** @@ -466,6 +467,7 @@ public ApiResponse uploadFileWithHttpInfo(@jakarta.annotation. // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); if (additionalMetadata != null) { localVarFormParams.put("additionalMetadata", additionalMetadata); } @@ -480,7 +482,7 @@ public ApiResponse uploadFileWithHttpInfo(@jakarta.annotation. localVarErrorTypes.put("200", new GenericType() {}); GenericType localVarReturnType = new GenericType() {}; return apiClient.invokeAPI("PetApi.uploadFile", localVarPath, "POST", new ArrayList<>(), null, - new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType, false, localVarErrorTypes); } /** @@ -532,6 +534,7 @@ public ApiResponse uploadFileWithRequiredFileWithHttpInfo(@jak // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); if (additionalMetadata != null) { localVarFormParams.put("additionalMetadata", additionalMetadata); } @@ -544,7 +547,7 @@ public ApiResponse uploadFileWithRequiredFileWithHttpInfo(@jak localVarErrorTypes.put("200", new GenericType() {}); GenericType localVarReturnType = new GenericType() {}; return apiClient.invokeAPI("PetApi.uploadFileWithRequiredFile", localVarPath, "POST", new ArrayList<>(), null, - new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType, false, localVarErrorTypes); } } diff --git a/samples/client/petstore/java/jersey3-oneOf/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/jersey3-oneOf/src/main/java/org/openapitools/client/ApiClient.java index d47ac1bbd459..a7ccd9d14ec9 100644 --- a/samples/client/petstore/java/jersey3-oneOf/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/jersey3-oneOf/src/main/java/org/openapitools/client/ApiClient.java @@ -796,18 +796,39 @@ public String collectionPathParameterToString(String collectionFormat, Collectio * @param obj Object * @param formParams Form parameters * @param contentType Context type + * @param isBodyNullable True if the body is nullable * @return Entity * @throws ApiException API exception */ public Entity serialize(Object obj, Map formParams, String contentType, boolean isBodyNullable) throws ApiException { + return serialize(obj, formParams, Collections.emptyMap(), contentType, isBodyNullable); + } + + /** + * Serialize the given Java object into string entity according the given + * Content-Type (only JSON is supported for now). + * + * @param obj Object + * @param formParams Form parameters + * @param formParamContentTypes Content types of the multipart form parameters, as declared by the encoding of the request body + * @param contentType Context type + * @param isBodyNullable True if the body is nullable + * @return Entity + * @throws ApiException API exception + */ + public Entity serialize(Object obj, Map formParams, Map formParamContentTypes, String contentType, boolean isBodyNullable) throws ApiException { Entity entity; if (contentType.startsWith("multipart/form-data")) { MultiPart multiPart = new MultiPart(); for (Entry param: formParams.entrySet()) { - if (param.getValue() instanceof Iterable) { - ((Iterable)param.getValue()).forEach(v -> addParamToMultipart(v, param.getKey(), multiPart)); + MediaType partType = parsePartMediaType(formParamContentTypes == null ? null : formParamContentTypes.get(param.getKey())); + // a JSON encoded array is sent as a single part instead of one part per item + if (param.getValue() instanceof Iterable && !isJsonPartType(partType)) { + for (Object v : (Iterable) param.getValue()) { + addParamToMultipart(v, param.getKey(), multiPart, partType); + } } else { - addParamToMultipart(param.getValue(), param.getKey(), multiPart); + addParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); } } entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); @@ -843,8 +864,24 @@ public Entity serialize(Object obj, Map formParams, String co * @param value Object * @param key Key of the object * @param multiPart MultiPart to add the form param to + * @throws ApiException if the value cannot be serialized to JSON */ - protected void addParamToMultipart(Object value, String key, MultiPart multiPart) { + protected void addParamToMultipart(Object value, String key, MultiPart multiPart) throws ApiException { + addParamToMultipart(value, key, multiPart, null); + } + + /** + * Adds the object with the provided key to the MultiPart. + * The declared part type (from the encoding of the request body) takes precedence, + * otherwise the Content-Type is derived from the object type. + * + * @param value Object + * @param key Key of the object + * @param multiPart MultiPart to add the form param to + * @param partType Declared Content-Type of the part, or null if not declared + * @throws ApiException if the value cannot be serialized to JSON + */ + protected void addParamToMultipart(Object value, String key, MultiPart multiPart, MediaType partType) throws ApiException { if (value instanceof File) { File file = (File) value; FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key) @@ -852,18 +889,99 @@ protected void addParamToMultipart(Object value, String key, MultiPart multiPart // Attempt to probe the content type for the file so that the form part is more correctly // and precisely identified, but fall back to application/octet-stream if that fails. - MediaType type; - try { - type = MediaType.valueOf(Files.probeContentType(file.toPath())); - } catch (IOException | IllegalArgumentException e) { - type = MediaType.APPLICATION_OCTET_STREAM_TYPE; + MediaType type = partType; + if (type == null) { + try { + type = MediaType.valueOf(Files.probeContentType(file.toPath())); + } catch (IOException | IllegalArgumentException e) { + type = MediaType.APPLICATION_OCTET_STREAM_TYPE; + } } multiPart.bodyPart(new FormDataBodyPart(contentDisp, file, type)); + } else if (isJsonPartType(partType)) { + // the encoding asks for JSON: strings are expected to already contain JSON, everything else is serialized + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); + String jsonValue = value instanceof String ? (String) value : serializeToJson(value); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, jsonValue, partType)); + } else if (isPlainFormValue(value)) { + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); + if (partType == null) { + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value))); + } else { + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value), partType)); + } } else { + // Complex objects (models, maps, ...) are sent as JSON parts instead of their toString() output FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); - multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value))); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, serializeToJson(value), MediaType.APPLICATION_JSON_TYPE)); } + } + + /** + * Serialize the given object to a JSON string. + * + * @param value Object + * @return JSON string + * @throws ApiException if the value cannot be serialized to JSON + */ + protected String serializeToJson(Object value) throws ApiException { + try { + return json.getMapper().writeValueAsString(value); + } catch (Exception e) { + throw new ApiException(e); + } + } + + /** + * Parse the Content-Type declared for a multipart part. + * Only the first entry of a comma separated list is used, wildcard or invalid types are ignored. + * + * @param partContentType Declared Content-Type, may be null + * @return The parsed media type, or null if none could be used + */ + protected MediaType parsePartMediaType(String partContentType) { + if (partContentType == null) { + return null; + } + String first = partContentType.split(",")[0].trim(); + if (first.isEmpty() || first.contains("*")) { + return null; + } + try { + return MediaType.valueOf(first); + } catch (IllegalArgumentException e) { + return null; + } + } + + /** + * Check whether the given part type is a JSON type. + * + * @param partType Part media type, may be null + * @return True if the part must be sent as JSON + */ + protected boolean isJsonPartType(MediaType partType) { + return partType != null && isJsonMime(partType.toString()); + } + + /** + * Check whether the given form value should be sent as a plain text part. + * + * @param value Object + * @return true if the value is a scalar that can be sent as text + */ + protected boolean isPlainFormValue(Object value) { + return value == null + || value instanceof String + || value instanceof Number + || value instanceof Boolean + || value instanceof Character + || value instanceof Enum + || value instanceof Date + || value instanceof java.time.temporal.TemporalAccessor + || value instanceof java.util.UUID + || value instanceof java.net.URI; } /** @@ -1028,6 +1146,48 @@ public ApiResponse invokeAPI( String[] authNames, GenericType returnType, boolean isBodyNullable, + Map errorTypes) + throws ApiException { + return invokeAPI(operation, path, method, queryParams, body, headerParams, cookieParams, formParams, Collections.emptyMap(), accept, contentType, authNames, returnType, isBodyNullable, errorTypes); + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param Type + * @param operation The qualified name of the operation + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "POST", "PUT", "HEAD" and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param formParamContentTypes The declared Content-Types of the multipart form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response + * @param isBodyNullable True if the body is nullable + * @param errorTypes Mapping of error codes to types into which to deserialize the response + * @return The response body in type of string + * @throws ApiException API exception + */ + public ApiResponse invokeAPI( + String operation, + String path, + String method, + List queryParams, + Object body, + Map headerParams, + Map cookieParams, + Map formParams, + Map formParamContentTypes, + String accept, + String contentType, + String[] authNames, + GenericType returnType, + boolean isBodyNullable, Map errorTypes ) throws ApiException { @@ -1096,7 +1256,7 @@ public ApiResponse invokeAPI( } } - Entity entity = serialize(body, formParams, contentType, isBodyNullable); + Entity entity = serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); for (Entry entry : allHeaderParams.entrySet()) { String value = entry.getValue(); diff --git a/samples/client/petstore/java/jersey3/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/jersey3/src/main/java/org/openapitools/client/ApiClient.java index f3e1182d74e9..8a09bed81341 100644 --- a/samples/client/petstore/java/jersey3/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/jersey3/src/main/java/org/openapitools/client/ApiClient.java @@ -1019,18 +1019,39 @@ public String collectionPathParameterToString(String collectionFormat, Collectio * @param obj Object * @param formParams Form parameters * @param contentType Context type + * @param isBodyNullable True if the body is nullable * @return Entity * @throws ApiException API exception */ public Entity serialize(Object obj, Map formParams, String contentType, boolean isBodyNullable) throws ApiException { + return serialize(obj, formParams, Collections.emptyMap(), contentType, isBodyNullable); + } + + /** + * Serialize the given Java object into string entity according the given + * Content-Type (only JSON is supported for now). + * + * @param obj Object + * @param formParams Form parameters + * @param formParamContentTypes Content types of the multipart form parameters, as declared by the encoding of the request body + * @param contentType Context type + * @param isBodyNullable True if the body is nullable + * @return Entity + * @throws ApiException API exception + */ + public Entity serialize(Object obj, Map formParams, Map formParamContentTypes, String contentType, boolean isBodyNullable) throws ApiException { Entity entity; if (contentType.startsWith("multipart/form-data")) { MultiPart multiPart = new MultiPart(); for (Entry param: formParams.entrySet()) { - if (param.getValue() instanceof Iterable) { - ((Iterable)param.getValue()).forEach(v -> addParamToMultipart(v, param.getKey(), multiPart)); + MediaType partType = parsePartMediaType(formParamContentTypes == null ? null : formParamContentTypes.get(param.getKey())); + // a JSON encoded array is sent as a single part instead of one part per item + if (param.getValue() instanceof Iterable && !isJsonPartType(partType)) { + for (Object v : (Iterable) param.getValue()) { + addParamToMultipart(v, param.getKey(), multiPart, partType); + } } else { - addParamToMultipart(param.getValue(), param.getKey(), multiPart); + addParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); } } entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); @@ -1066,8 +1087,24 @@ public Entity serialize(Object obj, Map formParams, String co * @param value Object * @param key Key of the object * @param multiPart MultiPart to add the form param to + * @throws ApiException if the value cannot be serialized to JSON + */ + protected void addParamToMultipart(Object value, String key, MultiPart multiPart) throws ApiException { + addParamToMultipart(value, key, multiPart, null); + } + + /** + * Adds the object with the provided key to the MultiPart. + * The declared part type (from the encoding of the request body) takes precedence, + * otherwise the Content-Type is derived from the object type. + * + * @param value Object + * @param key Key of the object + * @param multiPart MultiPart to add the form param to + * @param partType Declared Content-Type of the part, or null if not declared + * @throws ApiException if the value cannot be serialized to JSON */ - protected void addParamToMultipart(Object value, String key, MultiPart multiPart) { + protected void addParamToMultipart(Object value, String key, MultiPart multiPart, MediaType partType) throws ApiException { if (value instanceof File) { File file = (File) value; FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key) @@ -1075,18 +1112,99 @@ protected void addParamToMultipart(Object value, String key, MultiPart multiPart // Attempt to probe the content type for the file so that the form part is more correctly // and precisely identified, but fall back to application/octet-stream if that fails. - MediaType type; - try { - type = MediaType.valueOf(Files.probeContentType(file.toPath())); - } catch (IOException | IllegalArgumentException e) { - type = MediaType.APPLICATION_OCTET_STREAM_TYPE; + MediaType type = partType; + if (type == null) { + try { + type = MediaType.valueOf(Files.probeContentType(file.toPath())); + } catch (IOException | IllegalArgumentException e) { + type = MediaType.APPLICATION_OCTET_STREAM_TYPE; + } } multiPart.bodyPart(new FormDataBodyPart(contentDisp, file, type)); + } else if (isJsonPartType(partType)) { + // the encoding asks for JSON: strings are expected to already contain JSON, everything else is serialized + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); + String jsonValue = value instanceof String ? (String) value : serializeToJson(value); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, jsonValue, partType)); + } else if (isPlainFormValue(value)) { + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); + if (partType == null) { + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value))); + } else { + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value), partType)); + } } else { + // Complex objects (models, maps, ...) are sent as JSON parts instead of their toString() output FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); - multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value))); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, serializeToJson(value), MediaType.APPLICATION_JSON_TYPE)); + } + } + + /** + * Serialize the given object to a JSON string. + * + * @param value Object + * @return JSON string + * @throws ApiException if the value cannot be serialized to JSON + */ + protected String serializeToJson(Object value) throws ApiException { + try { + return json.getMapper().writeValueAsString(value); + } catch (Exception e) { + throw new ApiException(e); + } + } + + /** + * Parse the Content-Type declared for a multipart part. + * Only the first entry of a comma separated list is used, wildcard or invalid types are ignored. + * + * @param partContentType Declared Content-Type, may be null + * @return The parsed media type, or null if none could be used + */ + protected MediaType parsePartMediaType(String partContentType) { + if (partContentType == null) { + return null; + } + String first = partContentType.split(",")[0].trim(); + if (first.isEmpty() || first.contains("*")) { + return null; + } + try { + return MediaType.valueOf(first); + } catch (IllegalArgumentException e) { + return null; } + } + + /** + * Check whether the given part type is a JSON type. + * + * @param partType Part media type, may be null + * @return True if the part must be sent as JSON + */ + protected boolean isJsonPartType(MediaType partType) { + return partType != null && isJsonMime(partType.toString()); + } + + /** + * Check whether the given form value should be sent as a plain text part. + * + * @param value Object + * @return true if the value is a scalar that can be sent as text + */ + protected boolean isPlainFormValue(Object value) { + return value == null + || value instanceof String + || value instanceof Number + || value instanceof Boolean + || value instanceof Character + || value instanceof Enum + || value instanceof Date + || value instanceof java.time.temporal.TemporalAccessor + || value instanceof java.util.UUID + || value instanceof java.net.URI; } /** @@ -1251,6 +1369,48 @@ public ApiResponse invokeAPI( String[] authNames, GenericType returnType, boolean isBodyNullable, + Map errorTypes) + throws ApiException { + return invokeAPI(operation, path, method, queryParams, body, headerParams, cookieParams, formParams, Collections.emptyMap(), accept, contentType, authNames, returnType, isBodyNullable, errorTypes); + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param Type + * @param operation The qualified name of the operation + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "POST", "PUT", "HEAD" and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param formParamContentTypes The declared Content-Types of the multipart form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response + * @param isBodyNullable True if the body is nullable + * @param errorTypes Mapping of error codes to types into which to deserialize the response + * @return The response body in type of string + * @throws ApiException API exception + */ + public ApiResponse invokeAPI( + String operation, + String path, + String method, + List queryParams, + Object body, + Map headerParams, + Map cookieParams, + Map formParams, + Map formParamContentTypes, + String accept, + String contentType, + String[] authNames, + GenericType returnType, + boolean isBodyNullable, Map errorTypes ) throws ApiException { @@ -1319,7 +1479,7 @@ public ApiResponse invokeAPI( } } - Entity entity = serialize(body, formParams, contentType, isBodyNullable); + Entity entity = serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); for (Entry entry : allHeaderParams.entrySet()) { String value = entry.getValue(); diff --git a/samples/client/petstore/java/jersey3/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/jersey3/src/main/java/org/openapitools/client/api/FakeApi.java index 69e0b2600e23..23754c7d1895 100644 --- a/samples/client/petstore/java/jersey3/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/jersey3/src/main/java/org/openapitools/client/api/FakeApi.java @@ -587,6 +587,7 @@ public ApiResponse testEndpointParametersWithHttpInfo(@jakarta.annotation. // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); if (integer != null) { localVarFormParams.put("integer", integer); } @@ -627,7 +628,7 @@ public ApiResponse testEndpointParametersWithHttpInfo(@jakarta.annotation. String[] localVarAuthNames = new String[] {"http_basic_test"}; final Map localVarErrorTypes = new HashMap(); return apiClient.invokeAPI("FakeApi.testEndpointParameters", "/fake", "POST", new ArrayList<>(), null, - new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, localVarAuthNames, null, false, localVarErrorTypes); } /** @@ -695,6 +696,7 @@ public ApiResponse testEnumParametersWithHttpInfo(@jakarta.annotation.Null // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); if (enumFormStringArray != null) { localVarFormParams.put("enum_form_string_array", enumFormStringArray); } @@ -706,7 +708,7 @@ public ApiResponse testEnumParametersWithHttpInfo(@jakarta.annotation.Null String localVarContentType = apiClient.selectHeaderContentType("application/x-www-form-urlencoded"); final Map localVarErrorTypes = new HashMap(); return apiClient.invokeAPI("FakeApi.testEnumParameters", "/fake", "GET", localVarQueryParams, null, - localVarHeaderParams, new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + localVarHeaderParams, new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, null, null, false, localVarErrorTypes); } @@ -994,6 +996,7 @@ public ApiResponse testJsonFormDataWithHttpInfo(@jakarta.annotation.Nonnul // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); localVarFormParams.put("param", param); localVarFormParams.put("param2", param2); @@ -1001,7 +1004,7 @@ public ApiResponse testJsonFormDataWithHttpInfo(@jakarta.annotation.Nonnul String localVarContentType = apiClient.selectHeaderContentType("application/x-www-form-urlencoded"); final Map localVarErrorTypes = new HashMap(); return apiClient.invokeAPI("FakeApi.testJsonFormData", "/fake/jsonFormData", "GET", new ArrayList<>(), null, - new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, null, null, false, localVarErrorTypes); } /** diff --git a/samples/client/petstore/java/jersey3/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java/jersey3/src/main/java/org/openapitools/client/api/PetApi.java index d5df52705772..f868d2b4f1de 100644 --- a/samples/client/petstore/java/jersey3/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/client/petstore/java/jersey3/src/main/java/org/openapitools/client/api/PetApi.java @@ -405,6 +405,7 @@ public ApiResponse updatePetWithFormWithHttpInfo(@jakarta.annotation.Nonnu // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); if (name != null) { localVarFormParams.put("name", name); } @@ -417,7 +418,7 @@ public ApiResponse updatePetWithFormWithHttpInfo(@jakarta.annotation.Nonnu String[] localVarAuthNames = new String[] {"petstore_auth"}; final Map localVarErrorTypes = new HashMap(); return apiClient.invokeAPI("PetApi.updatePetWithForm", localVarPath, "POST", new ArrayList<>(), null, - new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, localVarAuthNames, null, false, localVarErrorTypes); } /** @@ -466,6 +467,7 @@ public ApiResponse uploadFileWithHttpInfo(@jakarta.annotation. // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); if (additionalMetadata != null) { localVarFormParams.put("additionalMetadata", additionalMetadata); } @@ -480,7 +482,7 @@ public ApiResponse uploadFileWithHttpInfo(@jakarta.annotation. localVarErrorTypes.put("200", new GenericType() {}); GenericType localVarReturnType = new GenericType() {}; return apiClient.invokeAPI("PetApi.uploadFile", localVarPath, "POST", new ArrayList<>(), null, - new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType, false, localVarErrorTypes); } /** @@ -532,6 +534,7 @@ public ApiResponse uploadFileWithRequiredFileWithHttpInfo(@jak // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); if (additionalMetadata != null) { localVarFormParams.put("additionalMetadata", additionalMetadata); } @@ -544,7 +547,7 @@ public ApiResponse uploadFileWithRequiredFileWithHttpInfo(@jak localVarErrorTypes.put("200", new GenericType() {}); GenericType localVarReturnType = new GenericType() {}; return apiClient.invokeAPI("PetApi.uploadFileWithRequiredFile", localVarPath, "POST", new ArrayList<>(), null, - new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType, false, localVarErrorTypes); } } diff --git a/samples/client/petstore/java/jersey3/src/test/java/org/openapitools/client/ApiClientTest.java b/samples/client/petstore/java/jersey3/src/test/java/org/openapitools/client/ApiClientTest.java index 662d62dd456c..27e413c2ab99 100644 --- a/samples/client/petstore/java/jersey3/src/test/java/org/openapitools/client/ApiClientTest.java +++ b/samples/client/petstore/java/jersey3/src/test/java/org/openapitools/client/ApiClientTest.java @@ -13,6 +13,11 @@ import org.glassfish.jersey.client.ClientProperties; import org.glassfish.jersey.apache.connector.ApacheConnectorProvider; +import org.glassfish.jersey.media.multipart.BodyPart; +import org.glassfish.jersey.media.multipart.FormDataBodyPart; +import org.glassfish.jersey.media.multipart.MultiPart; +import jakarta.ws.rs.client.Entity; +import jakarta.ws.rs.core.MediaType; import org.tomitribe.auth.signatures.Algorithm; import org.tomitribe.auth.signatures.Signer; import org.tomitribe.auth.signatures.SigningAlgorithm; @@ -138,4 +143,80 @@ public void testCollectionPathParameterToString() { assertEquals("", apiClient.collectionPathParameterToString("csv", Collections.emptyList())); assertEquals("", apiClient.collectionPathParameterToString("csv", null)); } + + @Test + public void testMultipartComplexPartSerializedAsJson() throws Exception { + Category category = new Category().id(1L).name("dogs"); + Map formParams = new LinkedHashMap<>(); + formParams.put("name", "doggie"); + formParams.put("category", category); + formParams.put("tags", Arrays.asList("a", "b")); + + Entity entity = apiClient.serialize(null, formParams, "multipart/form-data", false); + List parts = ((MultiPart) entity.getEntity()).getBodyParts(); + assertEquals(4, parts.size()); + + // scalars stay plain text parts + FormDataBodyPart name = (FormDataBodyPart) parts.get(0); + assertEquals("name", name.getName()); + assertEquals(MediaType.TEXT_PLAIN_TYPE, name.getMediaType()); + assertEquals("doggie", name.getEntity()); + + // complex objects are sent as JSON, not via toString() + FormDataBodyPart categoryPart = (FormDataBodyPart) parts.get(1); + assertEquals("category", categoryPart.getName()); + assertEquals(MediaType.APPLICATION_JSON_TYPE, categoryPart.getMediaType()); + assertEquals("{\"id\":1,\"name\":\"dogs\"}", categoryPart.getEntity()); + + // list items become one part each + assertEquals("a", ((FormDataBodyPart) parts.get(2)).getEntity()); + assertEquals("b", ((FormDataBodyPart) parts.get(3)).getEntity()); + } + + @Test + public void testMultipartEncodingContentTypeIsHonoured() throws Exception { + java.io.File image = java.io.File.createTempFile("upload", ".bin"); + image.deleteOnExit(); + Map formParams = new LinkedHashMap<>(); + formParams.put("metadata", "{\"raw\":true}"); + formParams.put("ids", Arrays.asList(1, 2)); + formParams.put("image", image); + formParams.put("count", 5); + formParams.put("note", "plain"); + Map formParamContentTypes = new HashMap<>(); + formParamContentTypes.put("metadata", "application/json"); + formParamContentTypes.put("ids", "application/json"); + formParamContentTypes.put("image", "image/png"); + formParamContentTypes.put("count", "text/csv"); + + Entity entity = apiClient.serialize(null, formParams, formParamContentTypes, "multipart/form-data", false); + List parts = ((MultiPart) entity.getEntity()).getBodyParts(); + assertEquals(5, parts.size()); + + // a string declared as JSON is sent as-is, not double encoded + FormDataBodyPart metadata = (FormDataBodyPart) parts.get(0); + assertEquals("metadata", metadata.getName()); + assertEquals(MediaType.APPLICATION_JSON_TYPE, metadata.getMediaType()); + assertEquals("{\"raw\":true}", metadata.getEntity()); + + // an array declared as JSON is a single JSON part + FormDataBodyPart ids = (FormDataBodyPart) parts.get(1); + assertEquals("ids", ids.getName()); + assertEquals(MediaType.APPLICATION_JSON_TYPE, ids.getMediaType()); + assertEquals("[1,2]", ids.getEntity()); + + // the declared type replaces the probed file type + FormDataBodyPart imagePart = (FormDataBodyPart) parts.get(2); + assertEquals(MediaType.valueOf("image/png"), imagePart.getMediaType()); + + // scalars keep their text value with the declared type + FormDataBodyPart count = (FormDataBodyPart) parts.get(3); + assertEquals(MediaType.valueOf("text/csv"), count.getMediaType()); + assertEquals("5", count.getEntity()); + + // no encoding: plain text as before + FormDataBodyPart note = (FormDataBodyPart) parts.get(4); + assertEquals(MediaType.TEXT_PLAIN_TYPE, note.getMediaType()); + assertEquals("plain", note.getEntity()); + } } diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java index 47cdcd40351d..894bab1521a7 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java @@ -844,18 +844,39 @@ public String collectionPathParameterToString(String collectionFormat, Collectio * @param obj Object * @param formParams Form parameters * @param contentType Context type + * @param isBodyNullable True if the body is nullable * @return Entity * @throws ApiException API exception */ public Entity serialize(Object obj, Map formParams, String contentType, boolean isBodyNullable) throws ApiException { + return serialize(obj, formParams, Collections.emptyMap(), contentType, isBodyNullable); + } + + /** + * Serialize the given Java object into string entity according the given + * Content-Type (only JSON is supported for now). + * + * @param obj Object + * @param formParams Form parameters + * @param formParamContentTypes Content types of the multipart form parameters, as declared by the encoding of the request body + * @param contentType Context type + * @param isBodyNullable True if the body is nullable + * @return Entity + * @throws ApiException API exception + */ + public Entity serialize(Object obj, Map formParams, Map formParamContentTypes, String contentType, boolean isBodyNullable) throws ApiException { Entity entity; if (contentType.startsWith("multipart/form-data")) { MultiPart multiPart = new MultiPart(); for (Entry param: formParams.entrySet()) { - if (param.getValue() instanceof Iterable) { - ((Iterable)param.getValue()).forEach(v -> addParamToMultipart(v, param.getKey(), multiPart)); + MediaType partType = parsePartMediaType(formParamContentTypes == null ? null : formParamContentTypes.get(param.getKey())); + // a JSON encoded array is sent as a single part instead of one part per item + if (param.getValue() instanceof Iterable && !isJsonPartType(partType)) { + for (Object v : (Iterable) param.getValue()) { + addParamToMultipart(v, param.getKey(), multiPart, partType); + } } else { - addParamToMultipart(param.getValue(), param.getKey(), multiPart); + addParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); } } entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); @@ -888,11 +909,27 @@ public Entity serialize(Object obj, Map formParams, String co * Adds the object with the provided key to the MultiPart. * Based on the object type sets Content-Disposition and Content-Type. * - * @param obj Object + * @param value Object + * @param key Key of the object + * @param multiPart MultiPart to add the form param to + * @throws ApiException if the value cannot be serialized to JSON + */ + protected void addParamToMultipart(Object value, String key, MultiPart multiPart) throws ApiException { + addParamToMultipart(value, key, multiPart, null); + } + + /** + * Adds the object with the provided key to the MultiPart. + * The declared part type (from the encoding of the request body) takes precedence, + * otherwise the Content-Type is derived from the object type. + * + * @param value Object * @param key Key of the object * @param multiPart MultiPart to add the form param to + * @param partType Declared Content-Type of the part, or null if not declared + * @throws ApiException if the value cannot be serialized to JSON */ - protected void addParamToMultipart(Object value, String key, MultiPart multiPart) { + protected void addParamToMultipart(Object value, String key, MultiPart multiPart, MediaType partType) throws ApiException { if (value instanceof File) { File file = (File) value; FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key) @@ -900,18 +937,99 @@ protected void addParamToMultipart(Object value, String key, MultiPart multiPart // Attempt to probe the content type for the file so that the form part is more correctly // and precisely identified, but fall back to application/octet-stream if that fails. - MediaType type; - try { - type = MediaType.valueOf(Files.probeContentType(file.toPath())); - } catch (IOException | IllegalArgumentException e) { - type = MediaType.APPLICATION_OCTET_STREAM_TYPE; + MediaType type = partType; + if (type == null) { + try { + type = MediaType.valueOf(Files.probeContentType(file.toPath())); + } catch (IOException | IllegalArgumentException e) { + type = MediaType.APPLICATION_OCTET_STREAM_TYPE; + } } multiPart.bodyPart(new FormDataBodyPart(contentDisp, file, type)); + } else if (isJsonPartType(partType)) { + // the encoding asks for JSON: strings are expected to already contain JSON, everything else is serialized + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); + String jsonValue = value instanceof String ? (String) value : serializeToJson(value); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, jsonValue, partType)); + } else if (isPlainFormValue(value)) { + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); + if (partType == null) { + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value))); + } else { + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value), partType)); + } } else { + // Complex objects (models, maps, ...) are sent as JSON parts instead of their toString() output FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); - multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value))); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, serializeToJson(value), MediaType.APPLICATION_JSON_TYPE)); + } + } + + /** + * Serialize the given object to a JSON string. + * + * @param value Object + * @return JSON string + * @throws ApiException if the value cannot be serialized to JSON + */ + protected String serializeToJson(Object value) throws ApiException { + try { + return json.getMapper().writeValueAsString(value); + } catch (Exception e) { + throw new ApiException(e); + } + } + + /** + * Parse the Content-Type declared for a multipart part. + * Only the first entry of a comma separated list is used, wildcard or invalid types are ignored. + * + * @param partContentType Declared Content-Type, may be null + * @return The parsed media type, or null if none could be used + */ + protected MediaType parsePartMediaType(String partContentType) { + if (partContentType == null) { + return null; + } + String first = partContentType.split(",")[0].trim(); + if (first.isEmpty() || first.contains("*")) { + return null; } + try { + return MediaType.valueOf(first); + } catch (IllegalArgumentException e) { + return null; + } + } + + /** + * Check whether the given part type is a JSON type. + * + * @param partType Part media type, may be null + * @return True if the part must be sent as JSON + */ + protected boolean isJsonPartType(MediaType partType) { + return partType != null && isJsonMime(partType.toString()); + } + + /** + * Check whether the given form value should be sent as a plain text part. + * + * @param value Object + * @return true if the value is a scalar that can be sent as text + */ + protected boolean isPlainFormValue(Object value) { + return value == null + || value instanceof String + || value instanceof Number + || value instanceof Boolean + || value instanceof Character + || value instanceof Enum + || value instanceof Date + || value instanceof java.time.temporal.TemporalAccessor + || value instanceof java.util.UUID + || value instanceof java.net.URI; } /** @@ -1076,6 +1194,46 @@ public ApiResponse invokeAPI( GenericType returnType, boolean isBodyNullable) throws ApiException { + return invokeAPI(operation, path, method, queryParams, body, headerParams, cookieParams, formParams, Collections.emptyMap(), accept, contentType, authNames, returnType, isBodyNullable); + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param Type + * @param operation The qualified name of the operation + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "POST", "PUT", "HEAD" and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param formParamContentTypes The declared Content-Types of the multipart form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response + * @param isBodyNullable True if the body is nullable + * @return The response body in type of string + * @throws ApiException API exception + */ + public ApiResponse invokeAPI( + String operation, + String path, + String method, + List queryParams, + Object body, + Map headerParams, + Map cookieParams, + Map formParams, + Map formParamContentTypes, + String accept, + String contentType, + String[] authNames, + GenericType returnType, + boolean isBodyNullable) + throws ApiException { String targetURL; List serverConfigurations; @@ -1141,7 +1299,7 @@ public ApiResponse invokeAPI( } } - Entity entity = serialize(body, formParams, contentType, isBodyNullable); + Entity entity = serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); for (Entry entry : allHeaderParams.entrySet()) { String value = entry.getValue(); diff --git a/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/src/main/java/org/openapitools/client/ApiClient.java b/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/src/main/java/org/openapitools/client/ApiClient.java index 734826087ac8..284b3ba46dc1 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/src/main/java/org/openapitools/client/ApiClient.java @@ -795,18 +795,39 @@ public String collectionPathParameterToString(String collectionFormat, Collectio * @param obj Object * @param formParams Form parameters * @param contentType Context type + * @param isBodyNullable True if the body is nullable * @return Entity * @throws ApiException API exception */ public Entity serialize(Object obj, Map formParams, String contentType, boolean isBodyNullable) throws ApiException { + return serialize(obj, formParams, Collections.emptyMap(), contentType, isBodyNullable); + } + + /** + * Serialize the given Java object into string entity according the given + * Content-Type (only JSON is supported for now). + * + * @param obj Object + * @param formParams Form parameters + * @param formParamContentTypes Content types of the multipart form parameters, as declared by the encoding of the request body + * @param contentType Context type + * @param isBodyNullable True if the body is nullable + * @return Entity + * @throws ApiException API exception + */ + public Entity serialize(Object obj, Map formParams, Map formParamContentTypes, String contentType, boolean isBodyNullable) throws ApiException { Entity entity; if (contentType.startsWith("multipart/form-data")) { MultiPart multiPart = new MultiPart(); for (Entry param: formParams.entrySet()) { - if (param.getValue() instanceof Iterable) { - ((Iterable)param.getValue()).forEach(v -> addParamToMultipart(v, param.getKey(), multiPart)); + MediaType partType = parsePartMediaType(formParamContentTypes == null ? null : formParamContentTypes.get(param.getKey())); + // a JSON encoded array is sent as a single part instead of one part per item + if (param.getValue() instanceof Iterable && !isJsonPartType(partType)) { + for (Object v : (Iterable) param.getValue()) { + addParamToMultipart(v, param.getKey(), multiPart, partType); + } } else { - addParamToMultipart(param.getValue(), param.getKey(), multiPart); + addParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); } } entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); @@ -839,11 +860,27 @@ public Entity serialize(Object obj, Map formParams, String co * Adds the object with the provided key to the MultiPart. * Based on the object type sets Content-Disposition and Content-Type. * - * @param obj Object + * @param value Object + * @param key Key of the object + * @param multiPart MultiPart to add the form param to + * @throws ApiException if the value cannot be serialized to JSON + */ + protected void addParamToMultipart(Object value, String key, MultiPart multiPart) throws ApiException { + addParamToMultipart(value, key, multiPart, null); + } + + /** + * Adds the object with the provided key to the MultiPart. + * The declared part type (from the encoding of the request body) takes precedence, + * otherwise the Content-Type is derived from the object type. + * + * @param value Object * @param key Key of the object * @param multiPart MultiPart to add the form param to + * @param partType Declared Content-Type of the part, or null if not declared + * @throws ApiException if the value cannot be serialized to JSON */ - protected void addParamToMultipart(Object value, String key, MultiPart multiPart) { + protected void addParamToMultipart(Object value, String key, MultiPart multiPart, MediaType partType) throws ApiException { if (value instanceof File) { File file = (File) value; FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key) @@ -851,18 +888,99 @@ protected void addParamToMultipart(Object value, String key, MultiPart multiPart // Attempt to probe the content type for the file so that the form part is more correctly // and precisely identified, but fall back to application/octet-stream if that fails. - MediaType type; - try { - type = MediaType.valueOf(Files.probeContentType(file.toPath())); - } catch (IOException | IllegalArgumentException e) { - type = MediaType.APPLICATION_OCTET_STREAM_TYPE; + MediaType type = partType; + if (type == null) { + try { + type = MediaType.valueOf(Files.probeContentType(file.toPath())); + } catch (IOException | IllegalArgumentException e) { + type = MediaType.APPLICATION_OCTET_STREAM_TYPE; + } } multiPart.bodyPart(new FormDataBodyPart(contentDisp, file, type)); + } else if (isJsonPartType(partType)) { + // the encoding asks for JSON: strings are expected to already contain JSON, everything else is serialized + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); + String jsonValue = value instanceof String ? (String) value : serializeToJson(value); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, jsonValue, partType)); + } else if (isPlainFormValue(value)) { + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); + if (partType == null) { + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value))); + } else { + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value), partType)); + } } else { + // Complex objects (models, maps, ...) are sent as JSON parts instead of their toString() output FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); - multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value))); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, serializeToJson(value), MediaType.APPLICATION_JSON_TYPE)); + } + } + + /** + * Serialize the given object to a JSON string. + * + * @param value Object + * @return JSON string + * @throws ApiException if the value cannot be serialized to JSON + */ + protected String serializeToJson(Object value) throws ApiException { + try { + return json.getMapper().writeValueAsString(value); + } catch (Exception e) { + throw new ApiException(e); + } + } + + /** + * Parse the Content-Type declared for a multipart part. + * Only the first entry of a comma separated list is used, wildcard or invalid types are ignored. + * + * @param partContentType Declared Content-Type, may be null + * @return The parsed media type, or null if none could be used + */ + protected MediaType parsePartMediaType(String partContentType) { + if (partContentType == null) { + return null; + } + String first = partContentType.split(",")[0].trim(); + if (first.isEmpty() || first.contains("*")) { + return null; } + try { + return MediaType.valueOf(first); + } catch (IllegalArgumentException e) { + return null; + } + } + + /** + * Check whether the given part type is a JSON type. + * + * @param partType Part media type, may be null + * @return True if the part must be sent as JSON + */ + protected boolean isJsonPartType(MediaType partType) { + return partType != null && isJsonMime(partType.toString()); + } + + /** + * Check whether the given form value should be sent as a plain text part. + * + * @param value Object + * @return true if the value is a scalar that can be sent as text + */ + protected boolean isPlainFormValue(Object value) { + return value == null + || value instanceof String + || value instanceof Number + || value instanceof Boolean + || value instanceof Character + || value instanceof Enum + || value instanceof Date + || value instanceof java.time.temporal.TemporalAccessor + || value instanceof java.util.UUID + || value instanceof java.net.URI; } /** @@ -1027,6 +1145,46 @@ public ApiResponse invokeAPI( GenericType returnType, boolean isBodyNullable) throws ApiException { + return invokeAPI(operation, path, method, queryParams, body, headerParams, cookieParams, formParams, Collections.emptyMap(), accept, contentType, authNames, returnType, isBodyNullable); + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param Type + * @param operation The qualified name of the operation + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "POST", "PUT", "HEAD" and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param formParamContentTypes The declared Content-Types of the multipart form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response + * @param isBodyNullable True if the body is nullable + * @return The response body in type of string + * @throws ApiException API exception + */ + public ApiResponse invokeAPI( + String operation, + String path, + String method, + List queryParams, + Object body, + Map headerParams, + Map cookieParams, + Map formParams, + Map formParamContentTypes, + String accept, + String contentType, + String[] authNames, + GenericType returnType, + boolean isBodyNullable) + throws ApiException { String targetURL; List serverConfigurations; @@ -1092,7 +1250,7 @@ public ApiResponse invokeAPI( } } - Entity entity = serialize(body, formParams, contentType, isBodyNullable); + Entity entity = serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); for (Entry entry : allHeaderParams.entrySet()) { String value = entry.getValue(); diff --git a/samples/openapi3/client/petstore/java/jersey2-java8-swagger1/src/main/java/org/openapitools/client/ApiClient.java b/samples/openapi3/client/petstore/java/jersey2-java8-swagger1/src/main/java/org/openapitools/client/ApiClient.java index 5ee43ccdf6dd..67358f3bcb6d 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8-swagger1/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/openapi3/client/petstore/java/jersey2-java8-swagger1/src/main/java/org/openapitools/client/ApiClient.java @@ -920,18 +920,39 @@ public String collectionPathParameterToString(String collectionFormat, Collectio * @param obj Object * @param formParams Form parameters * @param contentType Context type + * @param isBodyNullable True if the body is nullable * @return Entity * @throws ApiException API exception */ public Entity serialize(Object obj, Map formParams, String contentType, boolean isBodyNullable) throws ApiException { + return serialize(obj, formParams, Collections.emptyMap(), contentType, isBodyNullable); + } + + /** + * Serialize the given Java object into string entity according the given + * Content-Type (only JSON is supported for now). + * + * @param obj Object + * @param formParams Form parameters + * @param formParamContentTypes Content types of the multipart form parameters, as declared by the encoding of the request body + * @param contentType Context type + * @param isBodyNullable True if the body is nullable + * @return Entity + * @throws ApiException API exception + */ + public Entity serialize(Object obj, Map formParams, Map formParamContentTypes, String contentType, boolean isBodyNullable) throws ApiException { Entity entity; if (contentType.startsWith("multipart/form-data")) { MultiPart multiPart = new MultiPart(); for (Entry param: formParams.entrySet()) { - if (param.getValue() instanceof Iterable) { - ((Iterable)param.getValue()).forEach(v -> addParamToMultipart(v, param.getKey(), multiPart)); + MediaType partType = parsePartMediaType(formParamContentTypes == null ? null : formParamContentTypes.get(param.getKey())); + // a JSON encoded array is sent as a single part instead of one part per item + if (param.getValue() instanceof Iterable && !isJsonPartType(partType)) { + for (Object v : (Iterable) param.getValue()) { + addParamToMultipart(v, param.getKey(), multiPart, partType); + } } else { - addParamToMultipart(param.getValue(), param.getKey(), multiPart); + addParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); } } entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); @@ -964,11 +985,27 @@ public Entity serialize(Object obj, Map formParams, String co * Adds the object with the provided key to the MultiPart. * Based on the object type sets Content-Disposition and Content-Type. * - * @param obj Object + * @param value Object + * @param key Key of the object + * @param multiPart MultiPart to add the form param to + * @throws ApiException if the value cannot be serialized to JSON + */ + protected void addParamToMultipart(Object value, String key, MultiPart multiPart) throws ApiException { + addParamToMultipart(value, key, multiPart, null); + } + + /** + * Adds the object with the provided key to the MultiPart. + * The declared part type (from the encoding of the request body) takes precedence, + * otherwise the Content-Type is derived from the object type. + * + * @param value Object * @param key Key of the object * @param multiPart MultiPart to add the form param to + * @param partType Declared Content-Type of the part, or null if not declared + * @throws ApiException if the value cannot be serialized to JSON */ - protected void addParamToMultipart(Object value, String key, MultiPart multiPart) { + protected void addParamToMultipart(Object value, String key, MultiPart multiPart, MediaType partType) throws ApiException { if (value instanceof File) { File file = (File) value; FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key) @@ -976,18 +1013,99 @@ protected void addParamToMultipart(Object value, String key, MultiPart multiPart // Attempt to probe the content type for the file so that the form part is more correctly // and precisely identified, but fall back to application/octet-stream if that fails. - MediaType type; - try { - type = MediaType.valueOf(Files.probeContentType(file.toPath())); - } catch (IOException | IllegalArgumentException e) { - type = MediaType.APPLICATION_OCTET_STREAM_TYPE; + MediaType type = partType; + if (type == null) { + try { + type = MediaType.valueOf(Files.probeContentType(file.toPath())); + } catch (IOException | IllegalArgumentException e) { + type = MediaType.APPLICATION_OCTET_STREAM_TYPE; + } } multiPart.bodyPart(new FormDataBodyPart(contentDisp, file, type)); + } else if (isJsonPartType(partType)) { + // the encoding asks for JSON: strings are expected to already contain JSON, everything else is serialized + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); + String jsonValue = value instanceof String ? (String) value : serializeToJson(value); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, jsonValue, partType)); + } else if (isPlainFormValue(value)) { + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); + if (partType == null) { + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value))); + } else { + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value), partType)); + } } else { + // Complex objects (models, maps, ...) are sent as JSON parts instead of their toString() output FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); - multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value))); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, serializeToJson(value), MediaType.APPLICATION_JSON_TYPE)); + } + } + + /** + * Serialize the given object to a JSON string. + * + * @param value Object + * @return JSON string + * @throws ApiException if the value cannot be serialized to JSON + */ + protected String serializeToJson(Object value) throws ApiException { + try { + return json.getMapper().writeValueAsString(value); + } catch (Exception e) { + throw new ApiException(e); + } + } + + /** + * Parse the Content-Type declared for a multipart part. + * Only the first entry of a comma separated list is used, wildcard or invalid types are ignored. + * + * @param partContentType Declared Content-Type, may be null + * @return The parsed media type, or null if none could be used + */ + protected MediaType parsePartMediaType(String partContentType) { + if (partContentType == null) { + return null; + } + String first = partContentType.split(",")[0].trim(); + if (first.isEmpty() || first.contains("*")) { + return null; } + try { + return MediaType.valueOf(first); + } catch (IllegalArgumentException e) { + return null; + } + } + + /** + * Check whether the given part type is a JSON type. + * + * @param partType Part media type, may be null + * @return True if the part must be sent as JSON + */ + protected boolean isJsonPartType(MediaType partType) { + return partType != null && isJsonMime(partType.toString()); + } + + /** + * Check whether the given form value should be sent as a plain text part. + * + * @param value Object + * @return true if the value is a scalar that can be sent as text + */ + protected boolean isPlainFormValue(Object value) { + return value == null + || value instanceof String + || value instanceof Number + || value instanceof Boolean + || value instanceof Character + || value instanceof Enum + || value instanceof Date + || value instanceof java.time.temporal.TemporalAccessor + || value instanceof java.util.UUID + || value instanceof java.net.URI; } /** @@ -1152,6 +1270,46 @@ public ApiResponse invokeAPI( GenericType returnType, boolean isBodyNullable) throws ApiException { + return invokeAPI(operation, path, method, queryParams, body, headerParams, cookieParams, formParams, Collections.emptyMap(), accept, contentType, authNames, returnType, isBodyNullable); + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param Type + * @param operation The qualified name of the operation + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "POST", "PUT", "HEAD" and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param formParamContentTypes The declared Content-Types of the multipart form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response + * @param isBodyNullable True if the body is nullable + * @return The response body in type of string + * @throws ApiException API exception + */ + public ApiResponse invokeAPI( + String operation, + String path, + String method, + List queryParams, + Object body, + Map headerParams, + Map cookieParams, + Map formParams, + Map formParamContentTypes, + String accept, + String contentType, + String[] authNames, + GenericType returnType, + boolean isBodyNullable) + throws ApiException { String targetURL; List serverConfigurations; @@ -1217,7 +1375,7 @@ public ApiResponse invokeAPI( } } - Entity entity = serialize(body, formParams, contentType, isBodyNullable); + Entity entity = serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); for (Entry entry : allHeaderParams.entrySet()) { String value = entry.getValue(); diff --git a/samples/openapi3/client/petstore/java/jersey2-java8-swagger1/src/main/java/org/openapitools/client/api/PetApi.java b/samples/openapi3/client/petstore/java/jersey2-java8-swagger1/src/main/java/org/openapitools/client/api/PetApi.java index 5bd4b5017c8c..d85b316db111 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8-swagger1/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/openapi3/client/petstore/java/jersey2-java8-swagger1/src/main/java/org/openapitools/client/api/PetApi.java @@ -405,6 +405,7 @@ public ApiResponse updatePetWithFormWithHttpInfo(@javax.annotation.Nonnull // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); if (name != null) { localVarFormParams.put("name", name); } @@ -416,7 +417,7 @@ public ApiResponse updatePetWithFormWithHttpInfo(@javax.annotation.Nonnull String localVarContentType = apiClient.selectHeaderContentType("application/x-www-form-urlencoded"); String[] localVarAuthNames = new String[] {"petstore_auth"}; return apiClient.invokeAPI("PetApi.updatePetWithForm", localVarPath, "POST", new ArrayList<>(), null, - new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, localVarAuthNames, null, false); } /** @@ -465,6 +466,7 @@ public ApiResponse uploadFileWithHttpInfo(@javax.annotation.No // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); if (additionalMetadata != null) { localVarFormParams.put("additionalMetadata", additionalMetadata); } @@ -477,7 +479,7 @@ public ApiResponse uploadFileWithHttpInfo(@javax.annotation.No String[] localVarAuthNames = new String[] {"petstore_auth"}; GenericType localVarReturnType = new GenericType() {}; return apiClient.invokeAPI("PetApi.uploadFile", localVarPath, "POST", new ArrayList<>(), null, - new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType, false); } } diff --git a/samples/openapi3/client/petstore/java/jersey2-java8-swagger2/src/main/java/org/openapitools/client/ApiClient.java b/samples/openapi3/client/petstore/java/jersey2-java8-swagger2/src/main/java/org/openapitools/client/ApiClient.java index 5ee43ccdf6dd..67358f3bcb6d 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8-swagger2/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/openapi3/client/petstore/java/jersey2-java8-swagger2/src/main/java/org/openapitools/client/ApiClient.java @@ -920,18 +920,39 @@ public String collectionPathParameterToString(String collectionFormat, Collectio * @param obj Object * @param formParams Form parameters * @param contentType Context type + * @param isBodyNullable True if the body is nullable * @return Entity * @throws ApiException API exception */ public Entity serialize(Object obj, Map formParams, String contentType, boolean isBodyNullable) throws ApiException { + return serialize(obj, formParams, Collections.emptyMap(), contentType, isBodyNullable); + } + + /** + * Serialize the given Java object into string entity according the given + * Content-Type (only JSON is supported for now). + * + * @param obj Object + * @param formParams Form parameters + * @param formParamContentTypes Content types of the multipart form parameters, as declared by the encoding of the request body + * @param contentType Context type + * @param isBodyNullable True if the body is nullable + * @return Entity + * @throws ApiException API exception + */ + public Entity serialize(Object obj, Map formParams, Map formParamContentTypes, String contentType, boolean isBodyNullable) throws ApiException { Entity entity; if (contentType.startsWith("multipart/form-data")) { MultiPart multiPart = new MultiPart(); for (Entry param: formParams.entrySet()) { - if (param.getValue() instanceof Iterable) { - ((Iterable)param.getValue()).forEach(v -> addParamToMultipart(v, param.getKey(), multiPart)); + MediaType partType = parsePartMediaType(formParamContentTypes == null ? null : formParamContentTypes.get(param.getKey())); + // a JSON encoded array is sent as a single part instead of one part per item + if (param.getValue() instanceof Iterable && !isJsonPartType(partType)) { + for (Object v : (Iterable) param.getValue()) { + addParamToMultipart(v, param.getKey(), multiPart, partType); + } } else { - addParamToMultipart(param.getValue(), param.getKey(), multiPart); + addParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); } } entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); @@ -964,11 +985,27 @@ public Entity serialize(Object obj, Map formParams, String co * Adds the object with the provided key to the MultiPart. * Based on the object type sets Content-Disposition and Content-Type. * - * @param obj Object + * @param value Object + * @param key Key of the object + * @param multiPart MultiPart to add the form param to + * @throws ApiException if the value cannot be serialized to JSON + */ + protected void addParamToMultipart(Object value, String key, MultiPart multiPart) throws ApiException { + addParamToMultipart(value, key, multiPart, null); + } + + /** + * Adds the object with the provided key to the MultiPart. + * The declared part type (from the encoding of the request body) takes precedence, + * otherwise the Content-Type is derived from the object type. + * + * @param value Object * @param key Key of the object * @param multiPart MultiPart to add the form param to + * @param partType Declared Content-Type of the part, or null if not declared + * @throws ApiException if the value cannot be serialized to JSON */ - protected void addParamToMultipart(Object value, String key, MultiPart multiPart) { + protected void addParamToMultipart(Object value, String key, MultiPart multiPart, MediaType partType) throws ApiException { if (value instanceof File) { File file = (File) value; FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key) @@ -976,18 +1013,99 @@ protected void addParamToMultipart(Object value, String key, MultiPart multiPart // Attempt to probe the content type for the file so that the form part is more correctly // and precisely identified, but fall back to application/octet-stream if that fails. - MediaType type; - try { - type = MediaType.valueOf(Files.probeContentType(file.toPath())); - } catch (IOException | IllegalArgumentException e) { - type = MediaType.APPLICATION_OCTET_STREAM_TYPE; + MediaType type = partType; + if (type == null) { + try { + type = MediaType.valueOf(Files.probeContentType(file.toPath())); + } catch (IOException | IllegalArgumentException e) { + type = MediaType.APPLICATION_OCTET_STREAM_TYPE; + } } multiPart.bodyPart(new FormDataBodyPart(contentDisp, file, type)); + } else if (isJsonPartType(partType)) { + // the encoding asks for JSON: strings are expected to already contain JSON, everything else is serialized + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); + String jsonValue = value instanceof String ? (String) value : serializeToJson(value); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, jsonValue, partType)); + } else if (isPlainFormValue(value)) { + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); + if (partType == null) { + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value))); + } else { + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value), partType)); + } } else { + // Complex objects (models, maps, ...) are sent as JSON parts instead of their toString() output FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); - multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value))); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, serializeToJson(value), MediaType.APPLICATION_JSON_TYPE)); + } + } + + /** + * Serialize the given object to a JSON string. + * + * @param value Object + * @return JSON string + * @throws ApiException if the value cannot be serialized to JSON + */ + protected String serializeToJson(Object value) throws ApiException { + try { + return json.getMapper().writeValueAsString(value); + } catch (Exception e) { + throw new ApiException(e); + } + } + + /** + * Parse the Content-Type declared for a multipart part. + * Only the first entry of a comma separated list is used, wildcard or invalid types are ignored. + * + * @param partContentType Declared Content-Type, may be null + * @return The parsed media type, or null if none could be used + */ + protected MediaType parsePartMediaType(String partContentType) { + if (partContentType == null) { + return null; + } + String first = partContentType.split(",")[0].trim(); + if (first.isEmpty() || first.contains("*")) { + return null; } + try { + return MediaType.valueOf(first); + } catch (IllegalArgumentException e) { + return null; + } + } + + /** + * Check whether the given part type is a JSON type. + * + * @param partType Part media type, may be null + * @return True if the part must be sent as JSON + */ + protected boolean isJsonPartType(MediaType partType) { + return partType != null && isJsonMime(partType.toString()); + } + + /** + * Check whether the given form value should be sent as a plain text part. + * + * @param value Object + * @return true if the value is a scalar that can be sent as text + */ + protected boolean isPlainFormValue(Object value) { + return value == null + || value instanceof String + || value instanceof Number + || value instanceof Boolean + || value instanceof Character + || value instanceof Enum + || value instanceof Date + || value instanceof java.time.temporal.TemporalAccessor + || value instanceof java.util.UUID + || value instanceof java.net.URI; } /** @@ -1152,6 +1270,46 @@ public ApiResponse invokeAPI( GenericType returnType, boolean isBodyNullable) throws ApiException { + return invokeAPI(operation, path, method, queryParams, body, headerParams, cookieParams, formParams, Collections.emptyMap(), accept, contentType, authNames, returnType, isBodyNullable); + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param Type + * @param operation The qualified name of the operation + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "POST", "PUT", "HEAD" and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param formParamContentTypes The declared Content-Types of the multipart form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response + * @param isBodyNullable True if the body is nullable + * @return The response body in type of string + * @throws ApiException API exception + */ + public ApiResponse invokeAPI( + String operation, + String path, + String method, + List queryParams, + Object body, + Map headerParams, + Map cookieParams, + Map formParams, + Map formParamContentTypes, + String accept, + String contentType, + String[] authNames, + GenericType returnType, + boolean isBodyNullable) + throws ApiException { String targetURL; List serverConfigurations; @@ -1217,7 +1375,7 @@ public ApiResponse invokeAPI( } } - Entity entity = serialize(body, formParams, contentType, isBodyNullable); + Entity entity = serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); for (Entry entry : allHeaderParams.entrySet()) { String value = entry.getValue(); diff --git a/samples/openapi3/client/petstore/java/jersey2-java8-swagger2/src/main/java/org/openapitools/client/api/PetApi.java b/samples/openapi3/client/petstore/java/jersey2-java8-swagger2/src/main/java/org/openapitools/client/api/PetApi.java index 5bd4b5017c8c..d85b316db111 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8-swagger2/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/openapi3/client/petstore/java/jersey2-java8-swagger2/src/main/java/org/openapitools/client/api/PetApi.java @@ -405,6 +405,7 @@ public ApiResponse updatePetWithFormWithHttpInfo(@javax.annotation.Nonnull // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); if (name != null) { localVarFormParams.put("name", name); } @@ -416,7 +417,7 @@ public ApiResponse updatePetWithFormWithHttpInfo(@javax.annotation.Nonnull String localVarContentType = apiClient.selectHeaderContentType("application/x-www-form-urlencoded"); String[] localVarAuthNames = new String[] {"petstore_auth"}; return apiClient.invokeAPI("PetApi.updatePetWithForm", localVarPath, "POST", new ArrayList<>(), null, - new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, localVarAuthNames, null, false); } /** @@ -465,6 +466,7 @@ public ApiResponse uploadFileWithHttpInfo(@javax.annotation.No // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); if (additionalMetadata != null) { localVarFormParams.put("additionalMetadata", additionalMetadata); } @@ -477,7 +479,7 @@ public ApiResponse uploadFileWithHttpInfo(@javax.annotation.No String[] localVarAuthNames = new String[] {"petstore_auth"}; GenericType localVarReturnType = new GenericType() {}; return apiClient.invokeAPI("PetApi.uploadFile", localVarPath, "POST", new ArrayList<>(), null, - new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType, false); } } diff --git a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java index ae8de42ca7bc..942a0ec30d97 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java @@ -1018,18 +1018,39 @@ public String collectionPathParameterToString(String collectionFormat, Collectio * @param obj Object * @param formParams Form parameters * @param contentType Context type + * @param isBodyNullable True if the body is nullable * @return Entity * @throws ApiException API exception */ public Entity serialize(Object obj, Map formParams, String contentType, boolean isBodyNullable) throws ApiException { + return serialize(obj, formParams, Collections.emptyMap(), contentType, isBodyNullable); + } + + /** + * Serialize the given Java object into string entity according the given + * Content-Type (only JSON is supported for now). + * + * @param obj Object + * @param formParams Form parameters + * @param formParamContentTypes Content types of the multipart form parameters, as declared by the encoding of the request body + * @param contentType Context type + * @param isBodyNullable True if the body is nullable + * @return Entity + * @throws ApiException API exception + */ + public Entity serialize(Object obj, Map formParams, Map formParamContentTypes, String contentType, boolean isBodyNullable) throws ApiException { Entity entity; if (contentType.startsWith("multipart/form-data")) { MultiPart multiPart = new MultiPart(); for (Entry param: formParams.entrySet()) { - if (param.getValue() instanceof Iterable) { - ((Iterable)param.getValue()).forEach(v -> addParamToMultipart(v, param.getKey(), multiPart)); + MediaType partType = parsePartMediaType(formParamContentTypes == null ? null : formParamContentTypes.get(param.getKey())); + // a JSON encoded array is sent as a single part instead of one part per item + if (param.getValue() instanceof Iterable && !isJsonPartType(partType)) { + for (Object v : (Iterable) param.getValue()) { + addParamToMultipart(v, param.getKey(), multiPart, partType); + } } else { - addParamToMultipart(param.getValue(), param.getKey(), multiPart); + addParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); } } entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); @@ -1062,11 +1083,27 @@ public Entity serialize(Object obj, Map formParams, String co * Adds the object with the provided key to the MultiPart. * Based on the object type sets Content-Disposition and Content-Type. * - * @param obj Object + * @param value Object + * @param key Key of the object + * @param multiPart MultiPart to add the form param to + * @throws ApiException if the value cannot be serialized to JSON + */ + protected void addParamToMultipart(Object value, String key, MultiPart multiPart) throws ApiException { + addParamToMultipart(value, key, multiPart, null); + } + + /** + * Adds the object with the provided key to the MultiPart. + * The declared part type (from the encoding of the request body) takes precedence, + * otherwise the Content-Type is derived from the object type. + * + * @param value Object * @param key Key of the object * @param multiPart MultiPart to add the form param to + * @param partType Declared Content-Type of the part, or null if not declared + * @throws ApiException if the value cannot be serialized to JSON */ - protected void addParamToMultipart(Object value, String key, MultiPart multiPart) { + protected void addParamToMultipart(Object value, String key, MultiPart multiPart, MediaType partType) throws ApiException { if (value instanceof File) { File file = (File) value; FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key) @@ -1074,18 +1111,99 @@ protected void addParamToMultipart(Object value, String key, MultiPart multiPart // Attempt to probe the content type for the file so that the form part is more correctly // and precisely identified, but fall back to application/octet-stream if that fails. - MediaType type; - try { - type = MediaType.valueOf(Files.probeContentType(file.toPath())); - } catch (IOException | IllegalArgumentException e) { - type = MediaType.APPLICATION_OCTET_STREAM_TYPE; + MediaType type = partType; + if (type == null) { + try { + type = MediaType.valueOf(Files.probeContentType(file.toPath())); + } catch (IOException | IllegalArgumentException e) { + type = MediaType.APPLICATION_OCTET_STREAM_TYPE; + } } multiPart.bodyPart(new FormDataBodyPart(contentDisp, file, type)); + } else if (isJsonPartType(partType)) { + // the encoding asks for JSON: strings are expected to already contain JSON, everything else is serialized + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); + String jsonValue = value instanceof String ? (String) value : serializeToJson(value); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, jsonValue, partType)); + } else if (isPlainFormValue(value)) { + FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); + if (partType == null) { + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value))); + } else { + multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value), partType)); + } } else { + // Complex objects (models, maps, ...) are sent as JSON parts instead of their toString() output FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); - multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value))); + multiPart.bodyPart(new FormDataBodyPart(contentDisp, serializeToJson(value), MediaType.APPLICATION_JSON_TYPE)); + } + } + + /** + * Serialize the given object to a JSON string. + * + * @param value Object + * @return JSON string + * @throws ApiException if the value cannot be serialized to JSON + */ + protected String serializeToJson(Object value) throws ApiException { + try { + return json.getMapper().writeValueAsString(value); + } catch (Exception e) { + throw new ApiException(e); + } + } + + /** + * Parse the Content-Type declared for a multipart part. + * Only the first entry of a comma separated list is used, wildcard or invalid types are ignored. + * + * @param partContentType Declared Content-Type, may be null + * @return The parsed media type, or null if none could be used + */ + protected MediaType parsePartMediaType(String partContentType) { + if (partContentType == null) { + return null; + } + String first = partContentType.split(",")[0].trim(); + if (first.isEmpty() || first.contains("*")) { + return null; } + try { + return MediaType.valueOf(first); + } catch (IllegalArgumentException e) { + return null; + } + } + + /** + * Check whether the given part type is a JSON type. + * + * @param partType Part media type, may be null + * @return True if the part must be sent as JSON + */ + protected boolean isJsonPartType(MediaType partType) { + return partType != null && isJsonMime(partType.toString()); + } + + /** + * Check whether the given form value should be sent as a plain text part. + * + * @param value Object + * @return true if the value is a scalar that can be sent as text + */ + protected boolean isPlainFormValue(Object value) { + return value == null + || value instanceof String + || value instanceof Number + || value instanceof Boolean + || value instanceof Character + || value instanceof Enum + || value instanceof Date + || value instanceof java.time.temporal.TemporalAccessor + || value instanceof java.util.UUID + || value instanceof java.net.URI; } /** @@ -1250,6 +1368,46 @@ public ApiResponse invokeAPI( GenericType returnType, boolean isBodyNullable) throws ApiException { + return invokeAPI(operation, path, method, queryParams, body, headerParams, cookieParams, formParams, Collections.emptyMap(), accept, contentType, authNames, returnType, isBodyNullable); + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param Type + * @param operation The qualified name of the operation + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "POST", "PUT", "HEAD" and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param formParamContentTypes The declared Content-Types of the multipart form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response + * @param isBodyNullable True if the body is nullable + * @return The response body in type of string + * @throws ApiException API exception + */ + public ApiResponse invokeAPI( + String operation, + String path, + String method, + List queryParams, + Object body, + Map headerParams, + Map cookieParams, + Map formParams, + Map formParamContentTypes, + String accept, + String contentType, + String[] authNames, + GenericType returnType, + boolean isBodyNullable) + throws ApiException { String targetURL; List serverConfigurations; @@ -1315,7 +1473,7 @@ public ApiResponse invokeAPI( } } - Entity entity = serialize(body, formParams, contentType, isBodyNullable); + Entity entity = serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); for (Entry entry : allHeaderParams.entrySet()) { String value = entry.getValue(); diff --git a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/api/FakeApi.java index fee6bfac61ba..e581ec9ba239 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/api/FakeApi.java @@ -566,6 +566,7 @@ public ApiResponse testEndpointParametersWithHttpInfo(@javax.annotation.No // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); if (integer != null) { localVarFormParams.put("integer", integer); } @@ -605,7 +606,7 @@ public ApiResponse testEndpointParametersWithHttpInfo(@javax.annotation.No String localVarContentType = apiClient.selectHeaderContentType("application/x-www-form-urlencoded"); String[] localVarAuthNames = new String[] {"http_basic_test"}; return apiClient.invokeAPI("FakeApi.testEndpointParameters", "/fake", "POST", new ArrayList<>(), null, - new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, localVarAuthNames, null, false); } /** @@ -673,6 +674,7 @@ public ApiResponse testEnumParametersWithHttpInfo(@javax.annotation.Nullab // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); if (enumFormStringArray != null) { localVarFormParams.put("enum_form_string_array", enumFormStringArray); } @@ -683,7 +685,7 @@ public ApiResponse testEnumParametersWithHttpInfo(@javax.annotation.Nullab String localVarAccept = apiClient.selectHeaderAccept(); String localVarContentType = apiClient.selectHeaderContentType("application/x-www-form-urlencoded"); return apiClient.invokeAPI("FakeApi.testEnumParameters", "/fake", "GET", localVarQueryParams, null, - localVarHeaderParams, new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + localVarHeaderParams, new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, null, null, false); } @@ -968,13 +970,14 @@ public ApiResponse testJsonFormDataWithHttpInfo(@javax.annotation.Nonnull // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); localVarFormParams.put("param", param); localVarFormParams.put("param2", param2); String localVarAccept = apiClient.selectHeaderAccept(); String localVarContentType = apiClient.selectHeaderContentType("application/x-www-form-urlencoded"); return apiClient.invokeAPI("FakeApi.testJsonFormData", "/fake/jsonFormData", "GET", new ArrayList<>(), null, - new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, null, null, false); } /** diff --git a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/api/PetApi.java b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/api/PetApi.java index 01c2df52cc08..01403f8a49f0 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/api/PetApi.java @@ -393,6 +393,7 @@ public ApiResponse updatePetWithFormWithHttpInfo(@javax.annotation.Nonnull // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); if (name != null) { localVarFormParams.put("name", name); } @@ -404,7 +405,7 @@ public ApiResponse updatePetWithFormWithHttpInfo(@javax.annotation.Nonnull String localVarContentType = apiClient.selectHeaderContentType("application/x-www-form-urlencoded"); String[] localVarAuthNames = new String[] {"petstore_auth"}; return apiClient.invokeAPI("PetApi.updatePetWithForm", localVarPath, "POST", new ArrayList<>(), null, - new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, localVarAuthNames, null, false); } /** @@ -453,6 +454,7 @@ public ApiResponse uploadFileWithHttpInfo(@javax.annotation.No // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); if (additionalMetadata != null) { localVarFormParams.put("additionalMetadata", additionalMetadata); } @@ -465,7 +467,7 @@ public ApiResponse uploadFileWithHttpInfo(@javax.annotation.No String[] localVarAuthNames = new String[] {"petstore_auth"}; GenericType localVarReturnType = new GenericType() {}; return apiClient.invokeAPI("PetApi.uploadFile", localVarPath, "POST", new ArrayList<>(), null, - new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType, false); } /** @@ -517,6 +519,7 @@ public ApiResponse uploadFileWithRequiredFileWithHttpInfo(@jav // Form parameters Map localVarFormParams = new LinkedHashMap<>(); + Map localVarFormParamContentTypes = new HashMap<>(); if (additionalMetadata != null) { localVarFormParams.put("additionalMetadata", additionalMetadata); } @@ -527,7 +530,7 @@ public ApiResponse uploadFileWithRequiredFileWithHttpInfo(@jav String[] localVarAuthNames = new String[] {"petstore_auth"}; GenericType localVarReturnType = new GenericType() {}; return apiClient.invokeAPI("PetApi.uploadFileWithRequiredFile", localVarPath, "POST", new ArrayList<>(), null, - new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarAccept, localVarContentType, + new LinkedHashMap<>(), new LinkedHashMap<>(), localVarFormParams, localVarFormParamContentTypes, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType, false); } } From 701823a68598579b67f530a0a5aae732023ed71d Mon Sep 17 00:00:00 2001 From: Matteo Molinari Date: Mon, 5 Oct 2026 10:09:03 +0200 Subject: [PATCH 2/2] Review findings --- .../Java/libraries/jersey2/ApiClient.mustache | 30 +++++++++++++++---- .../Java/libraries/jersey3/ApiClient.mustache | 30 +++++++++++++++---- .../codegen/java/JavaClientCodegenTest.java | 7 +++-- .../org/openapitools/client/ApiClient.java | 30 +++++++++++++++---- .../org/openapitools/client/ApiClient.java | 30 +++++++++++++++---- .../org/openapitools/client/ApiClient.java | 30 +++++++++++++++---- .../org/openapitools/client/ApiClient.java | 30 +++++++++++++++---- .../org/openapitools/client/ApiClient.java | 30 +++++++++++++++---- .../org/openapitools/client/ApiClient.java | 30 +++++++++++++++---- .../org/openapitools/client/ApiClient.java | 30 +++++++++++++++---- .../openapitools/client/ApiClientTest.java | 22 ++++++++++++++ .../org/openapitools/client/ApiClient.java | 30 +++++++++++++++---- .../org/openapitools/client/ApiClient.java | 30 +++++++++++++++---- .../org/openapitools/client/ApiClient.java | 30 +++++++++++++++---- .../org/openapitools/client/ApiClient.java | 30 +++++++++++++++---- .../org/openapitools/client/ApiClient.java | 30 +++++++++++++++---- 16 files changed, 363 insertions(+), 86 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/ApiClient.mustache index cf5020bebbbe..047971bf8138 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/ApiClient.mustache @@ -1048,10 +1048,10 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { // a JSON encoded array is sent as a single part instead of one part per item if (param.getValue() instanceof Iterable && !isJsonPartType(partType)) { for (Object v : (Iterable) param.getValue()) { - addParamToMultipart(v, param.getKey(), multiPart, partType); + addFormParamToMultipart(v, param.getKey(), multiPart, partType); } } else { - addParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); + addFormParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); } } entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); @@ -1080,6 +1080,18 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { return entity; } + /** + * Calls the overload without part type when no part type is declared, + * so that subclasses overriding it keep working. + */ + private void addFormParamToMultipart(Object value, String key, MultiPart multiPart, MediaType partType) throws ApiException { + if (partType == null) { + addParamToMultipart(value, key, multiPart); + } else { + addParamToMultipart(value, key, multiPart, partType); + } + } + /** * Adds the object with the provided key to the MultiPart. * Based on the object type sets Content-Disposition and Content-Type. @@ -1095,8 +1107,10 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { /** * Adds the object with the provided key to the MultiPart. - * The declared part type (from the encoding of the request body) takes precedence, - * otherwise the Content-Type is derived from the object type. + * The declared part type (from the encoding of the request body) is used for files, + * plain values and JSON parts. Complex objects are always serialized as JSON and sent + * as application/json, since no other serializer is available for them. + * Without a declared part type the Content-Type is derived from the object type. * * @param value Object * @param key Key of the object @@ -1135,7 +1149,8 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value), partType)); } } else { - // Complex objects (models, maps, ...) are sent as JSON parts instead of their toString() output + // Complex objects (models, maps, ...) are sent as JSON parts instead of their toString() output. + // A declared non-JSON part type is not applied, as it would mislabel the JSON content. FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); multiPart.bodyPart(new FormDataBodyPart(contentDisp, serializeToJson(value), MediaType.APPLICATION_JSON_TYPE)); } @@ -1479,7 +1494,10 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { } } - Entity entity = serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); + // without declared part types, go through the old overload so that subclasses overriding it keep working + Entity entity = formParamContentTypes == null || formParamContentTypes.isEmpty() + ? serialize(body, formParams, contentType, isBodyNullable) + : serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); for (Entry entry : allHeaderParams.entrySet()) { String value = entry.getValue(); diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey3/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey3/ApiClient.mustache index 7b3d4ab81919..c010bfa40ea5 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/jersey3/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey3/ApiClient.mustache @@ -1054,10 +1054,10 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { // a JSON encoded array is sent as a single part instead of one part per item if (param.getValue() instanceof Iterable && !isJsonPartType(partType)) { for (Object v : (Iterable) param.getValue()) { - addParamToMultipart(v, param.getKey(), multiPart, partType); + addFormParamToMultipart(v, param.getKey(), multiPart, partType); } } else { - addParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); + addFormParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); } } entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); @@ -1086,6 +1086,18 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { return entity; } + /** + * Calls the overload without part type when no part type is declared, + * so that subclasses overriding it keep working. + */ + private void addFormParamToMultipart(Object value, String key, MultiPart multiPart, MediaType partType) throws ApiException { + if (partType == null) { + addParamToMultipart(value, key, multiPart); + } else { + addParamToMultipart(value, key, multiPart, partType); + } + } + /** * Adds the object with the provided key to the MultiPart. * Based on the object type sets Content-Disposition and Content-Type. @@ -1101,8 +1113,10 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { /** * Adds the object with the provided key to the MultiPart. - * The declared part type (from the encoding of the request body) takes precedence, - * otherwise the Content-Type is derived from the object type. + * The declared part type (from the encoding of the request body) is used for files, + * plain values and JSON parts. Complex objects are always serialized as JSON and sent + * as application/json, since no other serializer is available for them. + * Without a declared part type the Content-Type is derived from the object type. * * @param value Object * @param key Key of the object @@ -1141,7 +1155,8 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { multiPart.bodyPart(new FormDataBodyPart(contentDisp, parameterToString(value), partType)); } } else { - // Complex objects (models, maps, ...) are sent as JSON parts instead of their toString() output + // Complex objects (models, maps, ...) are sent as JSON parts instead of their toString() output. + // A declared non-JSON part type is not applied, as it would mislabel the JSON content. FormDataContentDisposition contentDisp = FormDataContentDisposition.name(key).build(); multiPart.bodyPart(new FormDataBodyPart(contentDisp, serializeToJson(value), MediaType.APPLICATION_JSON_TYPE)); } @@ -1490,7 +1505,10 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { } } - Entity entity = serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); + // without declared part types, go through the old overload so that subclasses overriding it keep working + Entity entity = formParamContentTypes == null || formParamContentTypes.isEmpty() + ? serialize(body, formParams, contentType, isBodyNullable) + : serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); for (Entry entry : allHeaderParams.entrySet()) { String value = entry.getValue(); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java index 616fb2895f04..83f7f8c1f13a 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java @@ -6011,7 +6011,8 @@ public void testMultipartObjectPartSerializedAsJson(String library) { validateJavaSourceFiles(files); assertThat(output.resolve("src/main/java/xyz/abcdef/api/MultipartApi.java")).content() .contains("localVarFormParams.put(\"marker\", marker);"); - // complex parts must be sent as JSON, not via toString() + // the generated ApiClient has the code path sending complex parts as JSON instead of toString(); + // the wire format is checked at runtime by the jersey3 sample's ApiClientTest assertThat(output.resolve("src/main/java/xyz/abcdef/invoker/ApiClient.java")).content() .contains("} else if (isPlainFormValue(value)) {") .contains("return json.getMapper().writeValueAsString(value);") @@ -6043,7 +6044,9 @@ public void testMultipartEncodingContentTypePassedToApiClient(String library) { .contains("localVarFormParams, localVarFormParamContentTypes, localVarAccept"); // the previous signatures are kept and delegate to the new overloads assertThat(output.resolve("src/main/java/xyz/abcdef/invoker/ApiClient.java")).content() - .contains("Entity entity = serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable);") + .contains("? serialize(body, formParams, contentType, isBodyNullable)") + .contains(": serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable);") + .contains("addParamToMultipart(value, key, multiPart);") .contains("public Entity serialize(Object obj, Map formParams, String contentType, boolean isBodyNullable)") .contains("return serialize(obj, formParams, Collections.emptyMap(), contentType, isBodyNullable);") .contains("protected void addParamToMultipart(Object value, String key, MultiPart multiPart) throws ApiException {") diff --git a/samples/client/others/java/jersey2-oneOf-Mixed/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/others/java/jersey2-oneOf-Mixed/src/main/java/org/openapitools/client/ApiClient.java index 2bc28130893d..1f3bc563a9a3 100644 --- a/samples/client/others/java/jersey2-oneOf-Mixed/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/others/java/jersey2-oneOf-Mixed/src/main/java/org/openapitools/client/ApiClient.java @@ -824,10 +824,10 @@ public Entity serialize(Object obj, Map formParams, Map && !isJsonPartType(partType)) { for (Object v : (Iterable) param.getValue()) { - addParamToMultipart(v, param.getKey(), multiPart, partType); + addFormParamToMultipart(v, param.getKey(), multiPart, partType); } } else { - addParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); + addFormParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); } } entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); @@ -856,6 +856,18 @@ public Entity serialize(Object obj, Map formParams, Map ApiResponse invokeAPI( } } - Entity entity = serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); + // without declared part types, go through the old overload so that subclasses overriding it keep working + Entity entity = formParamContentTypes == null || formParamContentTypes.isEmpty() + ? serialize(body, formParams, contentType, isBodyNullable) + : serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); for (Entry entry : allHeaderParams.entrySet()) { String value = entry.getValue(); diff --git a/samples/client/others/java/jersey2-oneOf-duplicates/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/others/java/jersey2-oneOf-duplicates/src/main/java/org/openapitools/client/ApiClient.java index 2bc28130893d..1f3bc563a9a3 100644 --- a/samples/client/others/java/jersey2-oneOf-duplicates/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/others/java/jersey2-oneOf-duplicates/src/main/java/org/openapitools/client/ApiClient.java @@ -824,10 +824,10 @@ public Entity serialize(Object obj, Map formParams, Map && !isJsonPartType(partType)) { for (Object v : (Iterable) param.getValue()) { - addParamToMultipart(v, param.getKey(), multiPart, partType); + addFormParamToMultipart(v, param.getKey(), multiPart, partType); } } else { - addParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); + addFormParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); } } entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); @@ -856,6 +856,18 @@ public Entity serialize(Object obj, Map formParams, Map ApiResponse invokeAPI( } } - Entity entity = serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); + // without declared part types, go through the old overload so that subclasses overriding it keep working + Entity entity = formParamContentTypes == null || formParamContentTypes.isEmpty() + ? serialize(body, formParams, contentType, isBodyNullable) + : serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); for (Entry entry : allHeaderParams.entrySet()) { String value = entry.getValue(); diff --git a/samples/client/petstore/java/jersey2-java8-localdatetime/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/jersey2-java8-localdatetime/src/main/java/org/openapitools/client/ApiClient.java index f7ed27c3193a..5645a2a405db 100644 --- a/samples/client/petstore/java/jersey2-java8-localdatetime/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/jersey2-java8-localdatetime/src/main/java/org/openapitools/client/ApiClient.java @@ -965,10 +965,10 @@ public Entity serialize(Object obj, Map formParams, Map && !isJsonPartType(partType)) { for (Object v : (Iterable) param.getValue()) { - addParamToMultipart(v, param.getKey(), multiPart, partType); + addFormParamToMultipart(v, param.getKey(), multiPart, partType); } } else { - addParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); + addFormParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); } } entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); @@ -997,6 +997,18 @@ public Entity serialize(Object obj, Map formParams, Map ApiResponse invokeAPI( } } - Entity entity = serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); + // without declared part types, go through the old overload so that subclasses overriding it keep working + Entity entity = formParamContentTypes == null || formParamContentTypes.isEmpty() + ? serialize(body, formParams, contentType, isBodyNullable) + : serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); for (Entry entry : allHeaderParams.entrySet()) { String value = entry.getValue(); diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java index f7ed27c3193a..5645a2a405db 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java @@ -965,10 +965,10 @@ public Entity serialize(Object obj, Map formParams, Map && !isJsonPartType(partType)) { for (Object v : (Iterable) param.getValue()) { - addParamToMultipart(v, param.getKey(), multiPart, partType); + addFormParamToMultipart(v, param.getKey(), multiPart, partType); } } else { - addParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); + addFormParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); } } entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); @@ -997,6 +997,18 @@ public Entity serialize(Object obj, Map formParams, Map ApiResponse invokeAPI( } } - Entity entity = serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); + // without declared part types, go through the old overload so that subclasses overriding it keep working + Entity entity = formParamContentTypes == null || formParamContentTypes.isEmpty() + ? serialize(body, formParams, contentType, isBodyNullable) + : serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); for (Entry entry : allHeaderParams.entrySet()) { String value = entry.getValue(); diff --git a/samples/client/petstore/java/jersey3-jackson3/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/jersey3-jackson3/src/main/java/org/openapitools/client/ApiClient.java index 2cb4b2d4163f..41699512299d 100644 --- a/samples/client/petstore/java/jersey3-jackson3/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/jersey3-jackson3/src/main/java/org/openapitools/client/ApiClient.java @@ -1048,10 +1048,10 @@ public Entity serialize(Object obj, Map formParams, Map && !isJsonPartType(partType)) { for (Object v : (Iterable) param.getValue()) { - addParamToMultipart(v, param.getKey(), multiPart, partType); + addFormParamToMultipart(v, param.getKey(), multiPart, partType); } } else { - addParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); + addFormParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); } } entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); @@ -1080,6 +1080,18 @@ public Entity serialize(Object obj, Map formParams, Map ApiResponse invokeAPI( } } - Entity entity = serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); + // without declared part types, go through the old overload so that subclasses overriding it keep working + Entity entity = formParamContentTypes == null || formParamContentTypes.isEmpty() + ? serialize(body, formParams, contentType, isBodyNullable) + : serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); for (Entry entry : allHeaderParams.entrySet()) { String value = entry.getValue(); diff --git a/samples/client/petstore/java/jersey3-oneOf/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/jersey3-oneOf/src/main/java/org/openapitools/client/ApiClient.java index a7ccd9d14ec9..6e5725346aba 100644 --- a/samples/client/petstore/java/jersey3-oneOf/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/jersey3-oneOf/src/main/java/org/openapitools/client/ApiClient.java @@ -825,10 +825,10 @@ public Entity serialize(Object obj, Map formParams, Map && !isJsonPartType(partType)) { for (Object v : (Iterable) param.getValue()) { - addParamToMultipart(v, param.getKey(), multiPart, partType); + addFormParamToMultipart(v, param.getKey(), multiPart, partType); } } else { - addParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); + addFormParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); } } entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); @@ -857,6 +857,18 @@ public Entity serialize(Object obj, Map formParams, Map ApiResponse invokeAPI( } } - Entity entity = serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); + // without declared part types, go through the old overload so that subclasses overriding it keep working + Entity entity = formParamContentTypes == null || formParamContentTypes.isEmpty() + ? serialize(body, formParams, contentType, isBodyNullable) + : serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); for (Entry entry : allHeaderParams.entrySet()) { String value = entry.getValue(); diff --git a/samples/client/petstore/java/jersey3/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/jersey3/src/main/java/org/openapitools/client/ApiClient.java index 8a09bed81341..5d17507221d0 100644 --- a/samples/client/petstore/java/jersey3/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/jersey3/src/main/java/org/openapitools/client/ApiClient.java @@ -1048,10 +1048,10 @@ public Entity serialize(Object obj, Map formParams, Map && !isJsonPartType(partType)) { for (Object v : (Iterable) param.getValue()) { - addParamToMultipart(v, param.getKey(), multiPart, partType); + addFormParamToMultipart(v, param.getKey(), multiPart, partType); } } else { - addParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); + addFormParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); } } entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); @@ -1080,6 +1080,18 @@ public Entity serialize(Object obj, Map formParams, Map ApiResponse invokeAPI( } } - Entity entity = serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); + // without declared part types, go through the old overload so that subclasses overriding it keep working + Entity entity = formParamContentTypes == null || formParamContentTypes.isEmpty() + ? serialize(body, formParams, contentType, isBodyNullable) + : serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); for (Entry entry : allHeaderParams.entrySet()) { String value = entry.getValue(); diff --git a/samples/client/petstore/java/jersey3/src/test/java/org/openapitools/client/ApiClientTest.java b/samples/client/petstore/java/jersey3/src/test/java/org/openapitools/client/ApiClientTest.java index 27e413c2ab99..233eb1d6fd78 100644 --- a/samples/client/petstore/java/jersey3/src/test/java/org/openapitools/client/ApiClientTest.java +++ b/samples/client/petstore/java/jersey3/src/test/java/org/openapitools/client/ApiClientTest.java @@ -219,4 +219,26 @@ public void testMultipartEncodingContentTypeIsHonoured() throws Exception { assertEquals(MediaType.TEXT_PLAIN_TYPE, note.getMediaType()); assertEquals("plain", note.getEntity()); } + + @Test + public void testMultipartOverrideWithoutPartTypeIsCalled() throws Exception { + List overridden = new ArrayList<>(); + ApiClient client = new ApiClient() { + @Override + protected void addParamToMultipart(Object value, String key, MultiPart multiPart) throws ApiException { + overridden.add(key); + super.addParamToMultipart(value, key, multiPart); + } + }; + Map formParams = new LinkedHashMap<>(); + formParams.put("note", "plain"); + formParams.put("metadata", "{}"); + Map formParamContentTypes = new HashMap<>(); + formParamContentTypes.put("metadata", "application/json"); + + client.serialize(null, formParams, formParamContentTypes, "multipart/form-data", false); + + // the old overload is still called for parts without a declared type + assertEquals(Collections.singletonList("note"), overridden); + } } diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java index 894bab1521a7..94881ce27219 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java @@ -873,10 +873,10 @@ public Entity serialize(Object obj, Map formParams, Map && !isJsonPartType(partType)) { for (Object v : (Iterable) param.getValue()) { - addParamToMultipart(v, param.getKey(), multiPart, partType); + addFormParamToMultipart(v, param.getKey(), multiPart, partType); } } else { - addParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); + addFormParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); } } entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); @@ -905,6 +905,18 @@ public Entity serialize(Object obj, Map formParams, Map ApiResponse invokeAPI( } } - Entity entity = serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); + // without declared part types, go through the old overload so that subclasses overriding it keep working + Entity entity = formParamContentTypes == null || formParamContentTypes.isEmpty() + ? serialize(body, formParams, contentType, isBodyNullable) + : serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); for (Entry entry : allHeaderParams.entrySet()) { String value = entry.getValue(); diff --git a/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/src/main/java/org/openapitools/client/ApiClient.java b/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/src/main/java/org/openapitools/client/ApiClient.java index 284b3ba46dc1..28c3bb0c9b25 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/src/main/java/org/openapitools/client/ApiClient.java @@ -824,10 +824,10 @@ public Entity serialize(Object obj, Map formParams, Map && !isJsonPartType(partType)) { for (Object v : (Iterable) param.getValue()) { - addParamToMultipart(v, param.getKey(), multiPart, partType); + addFormParamToMultipart(v, param.getKey(), multiPart, partType); } } else { - addParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); + addFormParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); } } entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); @@ -856,6 +856,18 @@ public Entity serialize(Object obj, Map formParams, Map ApiResponse invokeAPI( } } - Entity entity = serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); + // without declared part types, go through the old overload so that subclasses overriding it keep working + Entity entity = formParamContentTypes == null || formParamContentTypes.isEmpty() + ? serialize(body, formParams, contentType, isBodyNullable) + : serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); for (Entry entry : allHeaderParams.entrySet()) { String value = entry.getValue(); diff --git a/samples/openapi3/client/petstore/java/jersey2-java8-swagger1/src/main/java/org/openapitools/client/ApiClient.java b/samples/openapi3/client/petstore/java/jersey2-java8-swagger1/src/main/java/org/openapitools/client/ApiClient.java index 67358f3bcb6d..7c6dc7ba45bc 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8-swagger1/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/openapi3/client/petstore/java/jersey2-java8-swagger1/src/main/java/org/openapitools/client/ApiClient.java @@ -949,10 +949,10 @@ public Entity serialize(Object obj, Map formParams, Map && !isJsonPartType(partType)) { for (Object v : (Iterable) param.getValue()) { - addParamToMultipart(v, param.getKey(), multiPart, partType); + addFormParamToMultipart(v, param.getKey(), multiPart, partType); } } else { - addParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); + addFormParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); } } entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); @@ -981,6 +981,18 @@ public Entity serialize(Object obj, Map formParams, Map ApiResponse invokeAPI( } } - Entity entity = serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); + // without declared part types, go through the old overload so that subclasses overriding it keep working + Entity entity = formParamContentTypes == null || formParamContentTypes.isEmpty() + ? serialize(body, formParams, contentType, isBodyNullable) + : serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); for (Entry entry : allHeaderParams.entrySet()) { String value = entry.getValue(); diff --git a/samples/openapi3/client/petstore/java/jersey2-java8-swagger2/src/main/java/org/openapitools/client/ApiClient.java b/samples/openapi3/client/petstore/java/jersey2-java8-swagger2/src/main/java/org/openapitools/client/ApiClient.java index 67358f3bcb6d..7c6dc7ba45bc 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8-swagger2/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/openapi3/client/petstore/java/jersey2-java8-swagger2/src/main/java/org/openapitools/client/ApiClient.java @@ -949,10 +949,10 @@ public Entity serialize(Object obj, Map formParams, Map && !isJsonPartType(partType)) { for (Object v : (Iterable) param.getValue()) { - addParamToMultipart(v, param.getKey(), multiPart, partType); + addFormParamToMultipart(v, param.getKey(), multiPart, partType); } } else { - addParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); + addFormParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); } } entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); @@ -981,6 +981,18 @@ public Entity serialize(Object obj, Map formParams, Map ApiResponse invokeAPI( } } - Entity entity = serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); + // without declared part types, go through the old overload so that subclasses overriding it keep working + Entity entity = formParamContentTypes == null || formParamContentTypes.isEmpty() + ? serialize(body, formParams, contentType, isBodyNullable) + : serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); for (Entry entry : allHeaderParams.entrySet()) { String value = entry.getValue(); diff --git a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java index 942a0ec30d97..5af557f71170 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/ApiClient.java @@ -1047,10 +1047,10 @@ public Entity serialize(Object obj, Map formParams, Map && !isJsonPartType(partType)) { for (Object v : (Iterable) param.getValue()) { - addParamToMultipart(v, param.getKey(), multiPart, partType); + addFormParamToMultipart(v, param.getKey(), multiPart, partType); } } else { - addParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); + addFormParamToMultipart(param.getValue(), param.getKey(), multiPart, partType); } } entity = Entity.entity(multiPart, MediaType.MULTIPART_FORM_DATA_TYPE); @@ -1079,6 +1079,18 @@ public Entity serialize(Object obj, Map formParams, Map ApiResponse invokeAPI( } } - Entity entity = serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); + // without declared part types, go through the old overload so that subclasses overriding it keep working + Entity entity = formParamContentTypes == null || formParamContentTypes.isEmpty() + ? serialize(body, formParams, contentType, isBodyNullable) + : serialize(body, formParams, formParamContentTypes, contentType, isBodyNullable); for (Entry entry : allHeaderParams.entrySet()) { String value = entry.getValue();