Fix NPE in request body (#17055)

* fix null request body NPE

* fix typo
This commit is contained in:
William Cheng 2023-11-14 10:41:21 +08:00 committed by GitHub
parent 6da264b0f8
commit 91ac75ff05
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 290 additions and 11 deletions

View File

@ -4656,18 +4656,19 @@ public class DefaultCodegen implements CodegenConfig {
bodyParameterName = (String) op.vendorExtensions.get("x-codegen-request-body-name");
}
bodyParam = fromRequestBody(requestBody, imports, bodyParameterName);
bodyParam.description = escapeText(requestBody.getDescription());
postProcessParameter(bodyParam);
bodyParams.add(bodyParam);
if (bodyParam != null) {
bodyParam.description = escapeText(requestBody.getDescription());
postProcessParameter(bodyParam);
bodyParams.add(bodyParam);
if (prependFormOrBodyParameters) {
allParams.add(bodyParam);
}
if (prependFormOrBodyParameters) {
allParams.add(bodyParam);
}
// add example
if (schemas != null && !isSkipOperationExample()) {
op.requestBodyExamples = new ExampleGenerator(schemas, this.openAPI).generate(null, new ArrayList<>(getConsumesInfo(this.openAPI, operation)), bodyParam.baseType);
// add example
if (schemas != null && !isSkipOperationExample()) {
op.requestBodyExamples = new ExampleGenerator(schemas, this.openAPI).generate(null, new ArrayList<>(getConsumesInfo(this.openAPI, operation)), bodyParam.baseType);
}
}
}
}
@ -7596,6 +7597,10 @@ public class DefaultCodegen implements CodegenConfig {
String name = null;
LOGGER.debug("Request body = {}", body);
Schema schema = ModelUtils.getSchemaFromRequestBody(body);
if (schema == null) {
LOGGER.error("Schema cannot be null in the request body: {}", body);
return null;
}
Schema original = null;
// check if it's allOf (only 1 sub schema) with or without default/nullable/etc set in the top level
if (ModelUtils.isAllOf(schema) && schema.getAllOf().size() == 1 &&

View File

@ -1848,7 +1848,7 @@ public class ModelUtils {
* @return true if allOf is not empty
*/
public static boolean hasAllOf(Schema schema) {
if (schema.getAllOf() != null && !schema.getAllOf().isEmpty()) {
if (schema != null && schema.getAllOf() != null && !schema.getAllOf().isEmpty()) {
return true;
}

View File

@ -1196,6 +1196,52 @@ paths:
responses:
200:
description: OK
/fake/null-request-body:
get:
tags:
- another_fake
summary: null request body
operationId: null-request-body
parameters:
- name: Accept-Language
in: header
schema:
type: string
example: application/json
requestBody:
content:
text/plain:
examples:
Generar Orden por External ID:
value: |-
{
"external_reference": "{{external_order_ref}}",
"notification_url": "www.yourserver.com/yourendpoint",
"sponsor_id": 446566691,
"items": [
{
"title": "Papas frita",
"currency_id": "{{currency_id}}",
"unit_price": 6000,
"quantity": 1
},
{
"title": "Gaseosa",
"currency_id": "{{currency_id}}",
"unit_price": 3000,
"quantity": 1
}
]/*,
"taxes": [
{
"value": 0,
"type": "IVA"
}
]*/
}
responses:
'200':
description: ''
/values:
get:
tags:

View File

@ -116,6 +116,7 @@ Class | Method | HTTP request | Description
*AnotherFakeApi* | [**call123testSpecialTags**](docs/AnotherFakeApi.md#call123testSpecialTags) | **PATCH** /another-fake/dummy | To test special tags
*AnotherFakeApi* | [**getParameterArrayNumber**](docs/AnotherFakeApi.md#getParameterArrayNumber) | **GET** /fake/parameter-array-number | parameter array number default value
*AnotherFakeApi* | [**getParameterStringNumber**](docs/AnotherFakeApi.md#getParameterStringNumber) | **GET** /fake/parameter-string-number | parameter string number
*AnotherFakeApi* | [**nullRequestBody**](docs/AnotherFakeApi.md#nullRequestBody) | **GET** /fake/null-request-body | null request body
*DefaultApi* | [**fooGet**](docs/DefaultApi.md#fooGet) | **GET** /foo |
*FakeApi* | [**fakeHealthGet**](docs/FakeApi.md#fakeHealthGet) | **GET** /fake/health | Health check endpoint
*FakeApi* | [**fakeOuterBooleanSerialize**](docs/FakeApi.md#fakeOuterBooleanSerialize) | **POST** /fake/outer/boolean |

View File

@ -1230,6 +1230,56 @@ paths:
tags:
- another_fake
x-accepts: application/json
/fake/null-request-body:
get:
operationId: null-request-body
parameters:
- explode: false
in: header
name: Accept-Language
required: false
schema:
example: application/json
type: string
style: simple
requestBody:
content:
text/plain:
examples:
Generar Orden por External ID:
value: |-
{
"external_reference": "{{external_order_ref}}",
"notification_url": "www.yourserver.com/yourendpoint",
"sponsor_id": 446566691,
"items": [
{
"title": "Papas frita",
"currency_id": "{{currency_id}}",
"unit_price": 6000,
"quantity": 1
},
{
"title": "Gaseosa",
"currency_id": "{{currency_id}}",
"unit_price": 3000,
"quantity": 1
}
]/*,
"taxes": [
{
"value": 0,
"type": "IVA"
}
]*/
}
responses:
"200":
description: ""
summary: null request body
tags:
- another_fake
x-accepts: application/json
/values:
get:
description: ""

View File

@ -7,6 +7,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2*
| [**call123testSpecialTags**](AnotherFakeApi.md#call123testSpecialTags) | **PATCH** /another-fake/dummy | To test special tags |
| [**getParameterArrayNumber**](AnotherFakeApi.md#getParameterArrayNumber) | **GET** /fake/parameter-array-number | parameter array number default value |
| [**getParameterStringNumber**](AnotherFakeApi.md#getParameterStringNumber) | **GET** /fake/parameter-string-number | parameter string number |
| [**nullRequestBody**](AnotherFakeApi.md#nullRequestBody) | **GET** /fake/null-request-body | null request body |
<a id="call123testSpecialTags"></a>
@ -189,3 +190,62 @@ No authorization required
|-------------|-------------|------------------|
| **200** | OK | - |
<a id="nullRequestBody"></a>
# **nullRequestBody**
> nullRequestBody(acceptLanguage)
null request body
### Example
```java
// Import classes:
import org.openapitools.client.ApiClient;
import org.openapitools.client.ApiException;
import org.openapitools.client.Configuration;
import org.openapitools.client.models.*;
import org.openapitools.client.api.AnotherFakeApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("http://petstore.swagger.io:80/v2");
AnotherFakeApi apiInstance = new AnotherFakeApi(defaultClient);
String acceptLanguage = "application/json"; // String |
try {
apiInstance.nullRequestBody(acceptLanguage);
} catch (ApiException e) {
System.err.println("Exception when calling AnotherFakeApi#nullRequestBody");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
| Name | Type | Description | Notes |
|------------- | ------------- | ------------- | -------------|
| **acceptLanguage** | **String**| | [optional] |
### Return type
null (empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: text/plain
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | | - |

View File

@ -438,4 +438,121 @@ public class AnotherFakeApi {
localVarApiClient.executeAsync(localVarCall, _callback);
return localVarCall;
}
/**
* Build call for nullRequestBody
* @param acceptLanguage (optional)
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> </td><td> - </td></tr>
</table>
*/
public okhttp3.Call nullRequestBodyCall(String acceptLanguage, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
// Determine Base Path to Use
if (localCustomBaseUrl != null){
basePath = localCustomBaseUrl;
} else if ( localBasePaths.length > 0 ) {
basePath = localBasePaths[localHostIndex];
} else {
basePath = null;
}
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/fake/null-request-body";
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
Map<String, String> localVarCookieParams = new HashMap<String, String>();
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
if (acceptLanguage != null) {
localVarHeaderParams.put("Accept-Language", localVarApiClient.parameterToString(acceptLanguage));
}
final String[] localVarAccepts = {
};
final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
"text/plain"
};
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
if (localVarContentType != null) {
localVarHeaderParams.put("Content-Type", localVarContentType);
}
String[] localVarAuthNames = new String[] { };
return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback);
}
@SuppressWarnings("rawtypes")
private okhttp3.Call nullRequestBodyValidateBeforeCall(String acceptLanguage, final ApiCallback _callback) throws ApiException {
return nullRequestBodyCall(acceptLanguage, _callback);
}
/**
* null request body
*
* @param acceptLanguage (optional)
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> </td><td> - </td></tr>
</table>
*/
public void nullRequestBody(String acceptLanguage) throws ApiException {
nullRequestBodyWithHttpInfo(acceptLanguage);
}
/**
* null request body
*
* @param acceptLanguage (optional)
* @return ApiResponse&lt;Void&gt;
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> </td><td> - </td></tr>
</table>
*/
public ApiResponse<Void> nullRequestBodyWithHttpInfo(String acceptLanguage) throws ApiException {
okhttp3.Call localVarCall = nullRequestBodyValidateBeforeCall(acceptLanguage, null);
return localVarApiClient.execute(localVarCall);
}
/**
* null request body (asynchronously)
*
* @param acceptLanguage (optional)
* @param _callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
<tr><td> 200 </td><td> </td><td> - </td></tr>
</table>
*/
public okhttp3.Call nullRequestBodyAsync(String acceptLanguage, final ApiCallback<Void> _callback) throws ApiException {
okhttp3.Call localVarCall = nullRequestBodyValidateBeforeCall(acceptLanguage, _callback);
localVarApiClient.executeAsync(localVarCall, _callback);
return localVarCall;
}
}