[java][Okhttp] replace okhttp-gson with okhttp-gson-nextgen (#11538)

* replace okhttp-gson with okhttp-gson-nextgen

* add new files

* update doc

* clean up pom

* update test

* restore error handling in doc

* add back changes

* uncomment tests

* update samples
This commit is contained in:
William Cheng
2022-02-08 00:05:44 +08:00
committed by GitHub
parent 949b4e2008
commit 51800471fa
598 changed files with 18766 additions and 42285 deletions

View File

@@ -1,8 +0,0 @@
generatorName: java
outputDir: samples/client/petstore/java/okhttp-gson-nextgen
library: okhttp-gson-nextgen
inputSpec: modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-with-http-signature-okhttp-gson-nextgen.yaml
templateDir: modules/openapi-generator/src/main/resources/Java
additionalProperties:
artifactId: petstore-okhttp-gson-nextgen
hideGenerationTimestamp: "true"

View File

@@ -1,7 +1,7 @@
generatorName: java
outputDir: samples/client/petstore/java/okhttp-gson
library: okhttp-gson
inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml
inputSpec: modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-with-http-signature-okhttp-gson.yaml
templateDir: modules/openapi-generator/src/main/resources/Java
additionalProperties:
artifactId: petstore-okhttp-gson

View File

@@ -51,7 +51,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
|invokerPackage|root package for generated code| |org.openapitools.client|
|java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|<dl><dt>**true**</dt><dd>Use Java 8 classes such as Base64</dd><dt>**false**</dt><dd>Various third party libraries as needed</dd></dl>|true|
|legacyDiscriminatorBehavior|Set to false for generators with better support for discriminators. (Python, Java, Go, PowerShell, C#have this enabled by default).|<dl><dt>**true**</dt><dd>The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.</dd><dt>**false**</dt><dd>The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.</dd></dl>|true|
|library|library template (sub-template) to use|<dl><dt>**jersey1**</dt><dd>HTTP client: Jersey client 1.19.x. JSON processing: Jackson 2.9.x. Enable gzip request encoding using '-DuseGzipFeature=true'. IMPORTANT NOTE: jersey 1.x is no longer actively maintained so please upgrade to 'jersey2' or other HTTP libraries instead.</dd><dt>**jersey2**</dt><dd>HTTP client: Jersey client 2.25.1. JSON processing: Jackson 2.9.x</dd><dt>**feign**</dt><dd>HTTP client: OpenFeign 10.x. JSON processing: Jackson 2.9.x.</dd><dt>**okhttp-gson**</dt><dd>[DEFAULT] HTTP client: OkHttp 3.x. JSON processing: Gson 2.8.x. Enable Parcelable models on Android using '-DparcelableModel=true'. Enable gzip request encoding using '-DuseGzipFeature=true'.</dd><dt>**okhttp-gson-nextgen**</dt><dd>HTTP client: OkHttp 3.x. JSON processing: Gson 2.8.x.'. Better support for oneOf/anyOf with breaking changes. Will replace `okhttp-gson` in the 6.0.0 release. IMPORTANT: this may subject to breaking changes without further notice.</dd><dt>**retrofit2**</dt><dd>HTTP client: OkHttp 3.x. JSON processing: Gson 2.x (Retrofit 2.3.0). Enable the RxJava adapter using '-DuseRxJava[2/3]=true'. (RxJava 1.x or 2.x or 3.x)</dd><dt>**resttemplate**</dt><dd>HTTP client: Spring RestTemplate 4.x. JSON processing: Jackson 2.9.x</dd><dt>**webclient**</dt><dd>HTTP client: Spring WebClient 5.x. JSON processing: Jackson 2.9.x</dd><dt>**resteasy**</dt><dd>HTTP client: Resteasy client 3.x. JSON processing: Jackson 2.9.x</dd><dt>**vertx**</dt><dd>HTTP client: VertX client 3.x. JSON processing: Jackson 2.9.x</dd><dt>**google-api-client**</dt><dd>HTTP client: Google API client 1.x. JSON processing: Jackson 2.9.x</dd><dt>**rest-assured**</dt><dd>HTTP client: rest-assured : 4.x. JSON processing: Gson 2.x or Jackson 2.10.x. Only for Java 8</dd><dt>**native**</dt><dd>HTTP client: Java native HttpClient. JSON processing: Jackson 2.9.x. Only for Java11+</dd><dt>**microprofile**</dt><dd>HTTP client: Microprofile client 1.x. JSON processing: JSON-B</dd><dt>**apache-httpclient**</dt><dd>HTTP client: Apache httpclient 4.x</dd></dl>|okhttp-gson|
|library|library template (sub-template) to use|<dl><dt>**jersey1**</dt><dd>HTTP client: Jersey client 1.19.x. JSON processing: Jackson 2.9.x. Enable gzip request encoding using '-DuseGzipFeature=true'. IMPORTANT NOTE: jersey 1.x is no longer actively maintained so please upgrade to 'jersey2' or other HTTP libraries instead.</dd><dt>**jersey2**</dt><dd>HTTP client: Jersey client 2.25.1. JSON processing: Jackson 2.9.x</dd><dt>**feign**</dt><dd>HTTP client: OpenFeign 10.x. JSON processing: Jackson 2.9.x.</dd><dt>**okhttp-gson**</dt><dd>[DEFAULT] HTTP client: OkHttp 3.x. JSON processing: Gson 2.8.x. Enable Parcelable models on Android using '-DparcelableModel=true'. Enable gzip request encoding using '-DuseGzipFeature=true'.</dd><dt>**retrofit2**</dt><dd>HTTP client: OkHttp 3.x. JSON processing: Gson 2.x (Retrofit 2.3.0). Enable the RxJava adapter using '-DuseRxJava[2/3]=true'. (RxJava 1.x or 2.x or 3.x)</dd><dt>**resttemplate**</dt><dd>HTTP client: Spring RestTemplate 4.x. JSON processing: Jackson 2.9.x</dd><dt>**webclient**</dt><dd>HTTP client: Spring WebClient 5.x. JSON processing: Jackson 2.9.x</dd><dt>**resteasy**</dt><dd>HTTP client: Resteasy client 3.x. JSON processing: Jackson 2.9.x</dd><dt>**vertx**</dt><dd>HTTP client: VertX client 3.x. JSON processing: Jackson 2.9.x</dd><dt>**google-api-client**</dt><dd>HTTP client: Google API client 1.x. JSON processing: Jackson 2.9.x</dd><dt>**rest-assured**</dt><dd>HTTP client: rest-assured : 4.x. JSON processing: Gson 2.x or Jackson 2.10.x. Only for Java 8</dd><dt>**native**</dt><dd>HTTP client: Java native HttpClient. JSON processing: Jackson 2.9.x. Only for Java11+</dd><dt>**microprofile**</dt><dd>HTTP client: Microprofile client 1.x. JSON processing: JSON-B</dd><dt>**apache-httpclient**</dt><dd>HTTP client: Apache httpclient 4.x</dd></dl>|okhttp-gson|
|licenseName|The name of the license| |Unlicense|
|licenseUrl|The URL of the license| |http://unlicense.org|
|microprofileFramework|Framework for microprofile. Possible values &quot;kumuluzee&quot;| |null|

View File

@@ -76,7 +76,6 @@ public class JavaClientCodegen extends AbstractJavaCodegen
public static final String JERSEY2 = "jersey2";
public static final String NATIVE = "native";
public static final String OKHTTP_GSON = "okhttp-gson";
public static final String OKHTTP_GSON_NEXTGEN = "okhttp-gson-nextgen";
public static final String RESTEASY = "resteasy";
public static final String RESTTEMPLATE = "resttemplate";
public static final String WEBCLIENT = "webclient";
@@ -165,7 +164,6 @@ public class JavaClientCodegen extends AbstractJavaCodegen
supportedLibraries.put(JERSEY2, "HTTP client: Jersey client 2.25.1. JSON processing: Jackson 2.9.x");
supportedLibraries.put(FEIGN, "HTTP client: OpenFeign 10.x. JSON processing: Jackson 2.9.x.");
supportedLibraries.put(OKHTTP_GSON, "[DEFAULT] HTTP client: OkHttp 3.x. JSON processing: Gson 2.8.x. Enable Parcelable models on Android using '-DparcelableModel=true'. Enable gzip request encoding using '-DuseGzipFeature=true'.");
supportedLibraries.put(OKHTTP_GSON_NEXTGEN, "HTTP client: OkHttp 3.x. JSON processing: Gson 2.8.x.'. Better support for oneOf/anyOf with breaking changes. Will replace `okhttp-gson` in the 6.0.0 release. IMPORTANT: this may subject to breaking changes without further notice.");
supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 3.x. JSON processing: Gson 2.x (Retrofit 2.3.0). Enable the RxJava adapter using '-DuseRxJava[2/3]=true'. (RxJava 1.x or 2.x or 3.x)");
supportedLibraries.put(RESTTEMPLATE, "HTTP client: Spring RestTemplate 4.x. JSON processing: Jackson 2.9.x");
supportedLibraries.put(WEBCLIENT, "HTTP client: Spring WebClient 5.x. JSON processing: Jackson 2.9.x");
@@ -421,7 +419,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
supportingFiles.add(new SupportingFile("ParamExpander.mustache", invokerFolder, "ParamExpander.java"));
supportingFiles.add(new SupportingFile("EncodingUtils.mustache", invokerFolder, "EncodingUtils.java"));
supportingFiles.add(new SupportingFile("auth/DefaultApi20Impl.mustache", authFolder, "DefaultApi20Impl.java"));
} else if (OKHTTP_GSON.equals(getLibrary()) || StringUtils.isEmpty(getLibrary()) || OKHTTP_GSON_NEXTGEN.equals(getLibrary())) {
} else if (OKHTTP_GSON.equals(getLibrary()) || StringUtils.isEmpty(getLibrary())) {
// the "okhttp-gson" library template requires "ApiCallback.mustache" for async call
supportingFiles.add(new SupportingFile("ApiCallback.mustache", invokerFolder, "ApiCallback.java"));
supportingFiles.add(new SupportingFile("ApiResponse.mustache", invokerFolder, "ApiResponse.java"));
@@ -429,7 +427,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
supportingFiles.add(new SupportingFile("ProgressRequestBody.mustache", invokerFolder, "ProgressRequestBody.java"));
supportingFiles.add(new SupportingFile("ProgressResponseBody.mustache", invokerFolder, "ProgressResponseBody.java"));
supportingFiles.add(new SupportingFile("GzipRequestInterceptor.mustache", invokerFolder, "GzipRequestInterceptor.java"));
if (OKHTTP_GSON_NEXTGEN.equals(getLibrary())) {
if (OKHTTP_GSON.equals(getLibrary())) {
supportingFiles.add(new SupportingFile("AbstractOpenApiSchema.mustache", modelsFolder, "AbstractOpenApiSchema.java"));
}
@@ -589,7 +587,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
// has OAuth defined
if (ProcessUtils.hasOAuthMethods(openAPI)) {
// for okhttp-gson (default), check to see if OAuth is defined and included OAuth-related files accordingly
if ((OKHTTP_GSON.equals(getLibrary()) || StringUtils.isEmpty(getLibrary())) || OKHTTP_GSON_NEXTGEN.equals(getLibrary())) {
if ((OKHTTP_GSON.equals(getLibrary()) || StringUtils.isEmpty(getLibrary()))) {
supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java"));
supportingFiles.add(new SupportingFile("auth/RetryingOAuth.mustache", authFolder, "RetryingOAuth.java"));
}
@@ -890,7 +888,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen
CodegenModel cm = (CodegenModel) mo.get("model");
cm.getVendorExtensions().putIfAbsent("x-implements", new ArrayList<String>());
if (JERSEY2.equals(getLibrary()) || NATIVE.equals(getLibrary()) || OKHTTP_GSON_NEXTGEN.equals(getLibrary())) {
if (JERSEY2.equals(getLibrary()) || NATIVE.equals(getLibrary()) || OKHTTP_GSON.equals(getLibrary())) {
cm.getVendorExtensions().put("x-implements", new ArrayList<String>());
if (cm.oneOf != null && !cm.oneOf.isEmpty() && cm.oneOf.contains("ModelNull")) {

View File

@@ -1,51 +0,0 @@
{{>licenseInfo}}
package {{invokerPackage}};
import java.io.IOException;
import java.util.Map;
import java.util.List;
/**
* Callback for asynchronous API call.
*
* @param <T> The return type
*/
public interface ApiCallback<T> {
/**
* This is called when the API call fails.
*
* @param e The exception causing the failure
* @param statusCode Status code of the response if available, otherwise it would be 0
* @param responseHeaders Headers of the response if available, otherwise it would be null
*/
void onFailure(ApiException e, int statusCode, Map<String, List<String>> responseHeaders);
/**
* This is called when the API call succeeded.
*
* @param result The result deserialized from response
* @param statusCode Status code of the response
* @param responseHeaders Headers of the response
*/
void onSuccess(T result, int statusCode, Map<String, List<String>> responseHeaders);
/**
* This is called when the API upload processing.
*
* @param bytesWritten bytes Written
* @param contentLength content length of request body
* @param done write end
*/
void onUploadProgress(long bytesWritten, long contentLength, boolean done);
/**
* This is called when the API download processing.
*
* @param bytesRead bytes Read
* @param contentLength content length of the response
* @param done Read end
*/
void onDownloadProgress(long bytesRead, long contentLength, boolean done);
}

View File

@@ -1,75 +0,0 @@
{{>licenseInfo}}
package {{invokerPackage}};
import java.util.List;
import java.util.Map;
{{#caseInsensitiveResponseHeaders}}
import java.util.Map.Entry;
import java.util.TreeMap;
{{/caseInsensitiveResponseHeaders}}
/**
* API response returned by API call.
*/
public class ApiResponse<T> {
final private int statusCode;
final private Map<String, List<String>> headers;
final private T data;
/**
* <p>Constructor for ApiResponse.</p>
*
* @param statusCode The status code of HTTP response
* @param headers The headers of HTTP response
*/
public ApiResponse(int statusCode, Map<String, List<String>> headers) {
this(statusCode, headers, null);
}
/**
* <p>Constructor for ApiResponse.</p>
*
* @param statusCode The status code of HTTP response
* @param headers The headers of HTTP response
* @param data The object deserialized from response bod
*/
public ApiResponse(int statusCode, Map<String, List<String>> headers, T data) {
this.statusCode = statusCode;
{{#caseInsensitiveResponseHeaders}}
Map<String, List<String>> responseHeaders = new TreeMap<String, List<String>>(String.CASE_INSENSITIVE_ORDER);
for(Entry<String, List<String>> entry : headers.entrySet()){
responseHeaders.put(entry.getKey().toLowerCase(), entry.getValue());
}
{{/caseInsensitiveResponseHeaders}}
this.headers = {{#caseInsensitiveResponseHeaders}}responseHeaders{{/caseInsensitiveResponseHeaders}}{{^caseInsensitiveResponseHeaders}}headers{{/caseInsensitiveResponseHeaders}};
this.data = data;
}
/**
* <p>Get the <code>status code</code>.</p>
*
* @return the status code
*/
public int getStatusCode() {
return statusCode;
}
/**
* <p>Get the <code>headers</code>.</p>
*
* @return a {@link java.util.Map} of headers
*/
public Map<String, List<String>> getHeaders() {
return headers;
}
/**
* <p>Get the <code>data</code>.</p>
*
* @return the data
*/
public T getData() {
return data;
}
}

View File

@@ -1,74 +0,0 @@
{{>licenseInfo}}
package {{invokerPackage}};
import okhttp3.*;
import okio.Buffer;
import okio.BufferedSink;
import okio.GzipSink;
import okio.Okio;
import java.io.IOException;
/**
* Encodes request bodies using gzip.
*
* Taken from https://github.com/square/okhttp/issues/350
*/
class GzipRequestInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) {
return chain.proceed(originalRequest);
}
Request compressedRequest = originalRequest.newBuilder()
.header("Content-Encoding", "gzip")
.method(originalRequest.method(), forceContentLength(gzip(originalRequest.body())))
.build();
return chain.proceed(compressedRequest);
}
private RequestBody forceContentLength(final RequestBody requestBody) throws IOException {
final Buffer buffer = new Buffer();
requestBody.writeTo(buffer);
return new RequestBody() {
@Override
public MediaType contentType() {
return requestBody.contentType();
}
@Override
public long contentLength() {
return buffer.size();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
sink.write(buffer.snapshot());
}
};
}
private RequestBody gzip(final RequestBody body) {
return new RequestBody() {
@Override
public MediaType contentType() {
return body.contentType();
}
@Override
public long contentLength() {
return -1; // We don't know the compressed length in advance!
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
body.writeTo(gzipSink);
gzipSink.close();
}
};
}
}

View File

@@ -1,62 +0,0 @@
{{>licenseInfo}}
package {{invokerPackage}};
import okhttp3.MediaType;
import okhttp3.RequestBody;
import java.io.IOException;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;
public class ProgressRequestBody extends RequestBody {
private final RequestBody requestBody;
private final ApiCallback callback;
public ProgressRequestBody(RequestBody requestBody, ApiCallback callback) {
this.requestBody = requestBody;
this.callback = callback;
}
@Override
public MediaType contentType() {
return requestBody.contentType();
}
@Override
public long contentLength() throws IOException {
return requestBody.contentLength();
}
@Override
public void writeTo(BufferedSink sink) throws IOException {
BufferedSink bufferedSink = Okio.buffer(sink(sink));
requestBody.writeTo(bufferedSink);
bufferedSink.flush();
}
private Sink sink(Sink sink) {
return new ForwardingSink(sink) {
long bytesWritten = 0L;
long contentLength = 0L;
@Override
public void write(Buffer source, long byteCount) throws IOException {
super.write(source, byteCount);
if (contentLength == 0) {
contentLength = contentLength();
}
bytesWritten += byteCount;
callback.onUploadProgress(bytesWritten, contentLength, bytesWritten == contentLength);
}
};
}
}

View File

@@ -1,59 +0,0 @@
{{>licenseInfo}}
package {{invokerPackage}};
import okhttp3.MediaType;
import okhttp3.ResponseBody;
import java.io.IOException;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;
public class ProgressResponseBody extends ResponseBody {
private final ResponseBody responseBody;
private final ApiCallback callback;
private BufferedSource bufferedSource;
public ProgressResponseBody(ResponseBody responseBody, ApiCallback callback) {
this.responseBody = responseBody;
this.callback = callback;
}
@Override
public MediaType contentType() {
return responseBody.contentType();
}
@Override
public long contentLength() {
return responseBody.contentLength();
}
@Override
public BufferedSource source() {
if (bufferedSource == null) {
bufferedSource = Okio.buffer(source(responseBody.source()));
}
return bufferedSource;
}
private Source source(Source source) {
return new ForwardingSource(source) {
long totalBytesRead = 0L;
@Override
public long read(Buffer sink, long byteCount) throws IOException {
long bytesRead = super.read(sink, byteCount);
// read() returns the number of bytes read, or -1 if this source is exhausted.
totalBytesRead += bytesRead != -1 ? bytesRead : 0;
callback.onDownloadProgress(totalBytesRead, responseBody.contentLength(), bytesRead == -1);
return bytesRead;
}
};
}
}

View File

@@ -1,183 +0,0 @@
# {{artifactId}}
{{appName}}
- API version: {{appVersion}}
{{^hideGenerationTimestamp}}
- Build date: {{generatedDate}}
{{/hideGenerationTimestamp}}
{{{appDescriptionWithNewLines}}}
{{#infoUrl}}
For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}})
{{/infoUrl}}
*Automatically generated by the [OpenAPI Generator](https://openapi-generator.tech)*
## Requirements
Building the API client library requires:
1. Java {{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}}+
2. Maven (3.8.3+)/Gradle (7.2+)
## Installation
To install the API client library to your local Maven repository, simply execute:
```shell
mvn clean install
```
To deploy it to a remote Maven repository instead, configure the settings of the repository and execute:
```shell
mvn clean deploy
```
Refer to the [OSSRH Guide](http://central.sonatype.org/pages/ossrh-guide.html) for more information.
### Maven users
Add this dependency to your project's POM:
```xml
<dependency>
<groupId>{{{groupId}}}</groupId>
<artifactId>{{{artifactId}}}</artifactId>
<version>{{{artifactVersion}}}</version>
<scope>compile</scope>
</dependency>
```
### Gradle users
Add this dependency to your project's build file:
```groovy
repositories {
mavenCentral() // Needed if the '{{{artifactId}}}' jar has been published to maven central.
mavenLocal() // Needed if the '{{{artifactId}}}' jar has been published to the local maven repo.
}
dependencies {
implementation "{{{groupId}}}:{{{artifactId}}}:{{{artifactVersion}}}"
}
```
### Others
At first generate the JAR by executing:
```shell
mvn clean package
```
Then manually install the following JARs:
* `target/{{{artifactId}}}-{{{artifactVersion}}}.jar`
* `target/lib/*.jar`
## Getting Started
Please follow the [installation](#installation) instruction and execute the following Java code:
```java
{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}
// Import classes:
import {{{invokerPackage}}}.ApiClient;
import {{{invokerPackage}}}.ApiException;
import {{{invokerPackage}}}.Configuration;{{#hasAuthMethods}}
import {{{invokerPackage}}}.auth.*;{{/hasAuthMethods}}
import {{{invokerPackage}}}.models.*;
import {{{package}}}.{{{classname}}};
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("{{{basePath}}}");
{{#hasAuthMethods}}
{{#authMethods}}{{#isBasic}}{{#isBasicBasic}}
// Configure HTTP basic authorization: {{{name}}}
HttpBasicAuth {{{name}}} = (HttpBasicAuth) defaultClient.getAuthentication("{{{name}}}");
{{{name}}}.setUsername("YOUR USERNAME");
{{{name}}}.setPassword("YOUR PASSWORD");{{/isBasicBasic}}{{#isBasicBearer}}
// Configure HTTP bearer authorization: {{{name}}}
HttpBearerAuth {{{name}}} = (HttpBearerAuth) defaultClient.getAuthentication("{{{name}}}");
{{{name}}}.setBearerToken("BEARER TOKEN");{{/isBasicBearer}}{{/isBasic}}{{#isApiKey}}
// Configure API key authorization: {{{name}}}
ApiKeyAuth {{{name}}} = (ApiKeyAuth) defaultClient.getAuthentication("{{{name}}}");
{{{name}}}.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//{{{name}}}.setApiKeyPrefix("Token");{{/isApiKey}}{{#isOAuth}}
// Configure OAuth2 access token for authorization: {{{name}}}
OAuth {{{name}}} = (OAuth) defaultClient.getAuthentication("{{{name}}}");
{{{name}}}.setAccessToken("YOUR ACCESS TOKEN");{{/isOAuth}}
{{/authMethods}}
{{/hasAuthMethods}}
{{{classname}}} apiInstance = new {{{classname}}}(defaultClient);
{{#allParams}}
{{{dataType}}} {{{paramName}}} = {{{example}}}; // {{{dataType}}} | {{{description}}}
{{/allParams}}
try {
{{#returnType}}{{{.}}} result = {{/returnType}}apiInstance.{{{operationId}}}{{^vendorExtensions.x-group-parameters}}({{#allParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}});{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}({{#requiredParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}){{#optionalParams}}
.{{{paramName}}}({{{paramName}}}){{/optionalParams}}
.execute();{{/vendorExtensions.x-group-parameters}}{{#returnType}}
System.out.println(result);{{/returnType}}
} catch (ApiException e) {
System.err.println("Exception when calling {{{classname}}}#{{{operationId}}}");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}}
```
## Documentation for API Endpoints
All URIs are relative to *{{basePath}}*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{summary}}
{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}
## Documentation for Models
{{#models}}{{#model}} - [{{classname}}]({{modelDocPath}}{{classname}}.md)
{{/model}}{{/models}}
## Documentation for Authorization
{{^authMethods}}All endpoints do not require authorization.
{{/authMethods}}Authentication schemes defined for the API:
{{#authMethods}}### {{name}}
{{#isApiKey}}- **Type**: API key
- **API key parameter name**: {{keyParamName}}
- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}}
{{/isApiKey}}
{{#isBasic}}- **Type**: HTTP basic authentication
{{/isBasic}}
{{#isOAuth}}- **Type**: OAuth
- **Flow**: {{flow}}
- **Authorization URL**: {{authorizationUrl}}
- **Scopes**: {{^scopes}}N/A{{/scopes}}
{{#scopes}} - {{scope}}: {{description}}
{{/scopes}}
{{/isOAuth}}
{{/authMethods}}
## Recommendation
It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues.
## Author
{{#apiInfo}}{{#apis}}{{#-last}}{{infoEmail}}
{{/-last}}{{/apis}}{{/apiInfo}}

View File

@@ -1,520 +0,0 @@
{{>licenseInfo}}
package {{package}};
import {{invokerPackage}}.ApiCallback;
import {{invokerPackage}}.ApiClient;
import {{invokerPackage}}.ApiException;
{{#dynamicOperations}}
import {{invokerPackage}}.ApiOperation;
{{/dynamicOperations}}
import {{invokerPackage}}.ApiResponse;
import {{invokerPackage}}.Configuration;
import {{invokerPackage}}.Pair;
import {{invokerPackage}}.ProgressRequestBody;
import {{invokerPackage}}.ProgressResponseBody;
{{#performBeanValidation}}
import {{invokerPackage}}.BeanValidationException;
{{/performBeanValidation}}
import com.google.gson.reflect.TypeToken;
{{#dynamicOperations}}
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.parameters.Parameter;
{{/dynamicOperations}}
import java.io.IOException;
{{#useBeanValidation}}
import javax.validation.constraints.*;
{{/useBeanValidation}}
{{#performBeanValidation}}
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import javax.validation.executable.ExecutableValidator;
import java.util.Set;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
{{/performBeanValidation}}
{{#imports}}import {{import}};
{{/imports}}
import java.lang.reflect.Type;
{{^fullJavaUtil}}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
{{#supportStreaming}}
import java.io.InputStream;
{{/supportStreaming}}
{{/fullJavaUtil}}
import javax.ws.rs.core.GenericType;
{{#operations}}
public class {{classname}} {
private ApiClient localVarApiClient;
public {{classname}}() {
this(Configuration.getDefaultApiClient());
}
public {{classname}}(ApiClient apiClient) {
this.localVarApiClient = apiClient;
}
public ApiClient getApiClient() {
return localVarApiClient;
}
public void setApiClient(ApiClient apiClient) {
this.localVarApiClient = apiClient;
}
{{#operation}}
{{^vendorExtensions.x-group-parameters}}/**
* Build call for {{operationId}}{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{^isContainer}}{{#defaultValue}}, default to {{.}}{{/defaultValue}}{{/isContainer}}){{/required}}{{/allParams}}
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
{{#responses.0}}
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
{{#responses}}
<tr><td> {{code}} </td><td> {{message}} </td><td> {{#headers}} * {{baseName}} - {{description}} <br> {{/headers}}{{^headers.0}} - {{/headers.0}} </td></tr>
{{/responses}}
</table>
{{/responses.0}}
{{#isDeprecated}}
* @deprecated
{{/isDeprecated}}
{{#externalDocs}}
* {{description}}
* @see <a href="{{url}}">{{summary}} Documentation</a>
{{/externalDocs}}
*/
{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
public{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}private{{/vendorExtensions.x-group-parameters}} okhttp3.Call {{operationId}}Call({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback _callback) throws ApiException {
Object localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
// create path and map variables
{{^dynamicOperations}}
String localVarPath = "{{{path}}}"{{#pathParams}}
.replaceAll("\\{" + "{{baseName}}" + "\\}", localVarApiClient.escapeString({{#collectionFormat}}localVarApiClient.collectionPathParameterToString("{{{collectionFormat}}}", {{{paramName}}}){{/collectionFormat}}{{^collectionFormat}}{{{paramName}}}.toString(){{/collectionFormat}})){{/pathParams}};
{{/dynamicOperations}}
{{#dynamicOperations}}
ApiOperation apiOperation = localVarApiClient.getOperationLookupMap().get("{{{operationId}}}");
if (apiOperation == null) {
throw new ApiException("Operation not found in OAS");
}
Operation operation = apiOperation.getOperation();
String localVarPath = apiOperation.getPath();
Map<String, Object> paramMap = new HashMap<>();
{{#allParams}}
{{^isFormParam}}
{{^isBodyParam}}
paramMap.put("{{baseName}}", {{paramName}});
{{/isBodyParam}}
{{/isFormParam}}
{{/allParams}}
{{/dynamicOperations}}
{{javaUtilPrefix}}List<Pair> localVarQueryParams = new {{javaUtilPrefix}}ArrayList<Pair>();
{{javaUtilPrefix}}List<Pair> localVarCollectionQueryParams = new {{javaUtilPrefix}}ArrayList<Pair>();
{{javaUtilPrefix}}Map<String, String> localVarHeaderParams = new {{javaUtilPrefix}}HashMap<String, String>();
{{javaUtilPrefix}}Map<String, String> localVarCookieParams = new {{javaUtilPrefix}}HashMap<String, String>();
{{javaUtilPrefix}}Map<String, Object> localVarFormParams = new {{javaUtilPrefix}}HashMap<String, Object>();
{{#formParams}}
if ({{paramName}} != null) {
localVarFormParams.put("{{baseName}}", {{paramName}});
}
{{/formParams}}
{{^dynamicOperations}}
{{#queryParams}}
if ({{paramName}} != null) {
{{#collectionFormat}}localVarCollectionQueryParams.addAll(localVarApiClient.parameterToPairs("{{{.}}}", {{/collectionFormat}}{{^collectionFormat}}localVarQueryParams.addAll(localVarApiClient.parameterToPair({{/collectionFormat}}"{{baseName}}", {{paramName}}));
}
{{/queryParams}}
{{#headerParams}}
if ({{paramName}} != null) {
localVarHeaderParams.put("{{baseName}}", localVarApiClient.parameterToString({{paramName}}));
}
{{/headerParams}}
{{#cookieParams}}
if ({{paramName}} != null) {
localVarCookieParams.put("{{baseName}}", localVarApiClient.parameterToString({{paramName}}));
}
{{/cookieParams}}
{{/dynamicOperations}}
{{#dynamicOperations}}
localVarPath = localVarApiClient.fillParametersFromOperation(operation, paramMap, localVarPath, localVarQueryParams, localVarCollectionQueryParams, localVarHeaderParams, localVarCookieParams);
{{/dynamicOperations}}
final String[] localVarAccepts = {
{{#produces}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/produces}}
};
final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) {
localVarHeaderParams.put("Accept", localVarAccept);
}
final String[] localVarContentTypes = {
{{#consumes}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/consumes}}
};
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
if (localVarContentType != null) {
localVarHeaderParams.put("Content-Type", localVarContentType);
}
String[] localVarAuthNames = new String[] { {{#authMethods}}"{{name}}"{{^-last}}, {{/-last}}{{/authMethods}} };
return localVarApiClient.buildCall(localVarPath, {{^dynamicOperations}}"{{httpMethod}}"{{/dynamicOperations}}{{#dynamicOperations}}apiOperation.getMethod(){{/dynamicOperations}}, localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback);
}
{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
@SuppressWarnings("rawtypes")
private okhttp3.Call {{operationId}}ValidateBeforeCall({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback _callback) throws ApiException {
{{^performBeanValidation}}
{{#allParams}}{{#required}}
// verify the required parameter '{{paramName}}' is set
if ({{paramName}} == null) {
throw new ApiException("Missing the required parameter '{{paramName}}' when calling {{operationId}}(Async)");
}
{{/required}}{{/allParams}}
okhttp3.Call localVarCall = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}_callback);
return localVarCall;
{{/performBeanValidation}}
{{#performBeanValidation}}
try {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
ExecutableValidator executableValidator = factory.getValidator().forExecutables();
Object[] parameterValues = { {{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}} };
Method method = this.getClass().getMethod("{{operationId}}WithHttpInfo"{{#allParams}}, {{#isArray}}java.util.List{{/isArray}}{{#isMap}}java.util.Map{{/isMap}}{{^isArray}}{{^isMap}}{{{dataType}}}{{/isMap}}{{/isArray}}.class{{/allParams}});
Set<ConstraintViolation<{{classname}}>> violations = executableValidator.validateParameters(this, method,
parameterValues);
if (violations.size() == 0) {
okhttp3.Call localVarCall = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}_callback);
return localVarCall;
} else {
throw new BeanValidationException((Set) violations);
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
throw new ApiException(e.getMessage());
} catch (SecurityException e) {
e.printStackTrace();
throw new ApiException(e.getMessage());
}
{{/performBeanValidation}}
}
{{^vendorExtensions.x-group-parameters}}
/**
* {{summary}}
* {{notes}}{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{^isContainer}}{{#defaultValue}}, default to {{.}}{{/defaultValue}}{{/isContainer}}){{/required}}{{/allParams}}{{#returnType}}
* @return {{.}}{{/returnType}}
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
{{#responses.0}}
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
{{#responses}}
<tr><td> {{code}} </td><td> {{message}} </td><td> {{#headers}} * {{baseName}} - {{description}} <br> {{/headers}}{{^headers.0}} - {{/headers.0}} </td></tr>
{{/responses}}
</table>
{{/responses.0}}
{{#isDeprecated}}
* @deprecated
{{/isDeprecated}}
{{#externalDocs}}
* {{description}}
* @see <a href="{{url}}">{{summary}} Documentation</a>
{{/externalDocs}}
*/
{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
{{#vendorExtensions.x-streaming}}
public {{#returnType}}InputStream {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws ApiException {
{{#returnType}}InputStream localVarResp = {{/returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{#returnType}}
return localVarResp;{{/returnType}}
}
{{/vendorExtensions.x-streaming}}
{{^vendorExtensions.x-streaming}}
public {{#returnType}}{{{.}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws ApiException {
{{#returnType}}ApiResponse<{{{.}}}> localVarResp = {{/returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{#returnType}}
return localVarResp.getData();{{/returnType}}
}
{{/vendorExtensions.x-streaming}}
{{/vendorExtensions.x-group-parameters}}
{{^vendorExtensions.x-group-parameters}}/**
* {{summary}}
* {{notes}}{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{^isContainer}}{{#defaultValue}}, default to {{.}}{{/defaultValue}}{{/isContainer}}){{/required}}{{/allParams}}
* @return ApiResponse&lt;{{returnType}}{{^returnType}}Void{{/returnType}}&gt;
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
{{#responses.0}}
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
{{#responses}}
<tr><td> {{code}} </td><td> {{message}} </td><td> {{#headers}} * {{baseName}} - {{description}} <br> {{/headers}}{{^headers.0}} - {{/headers.0}} </td></tr>
{{/responses}}
</table>
{{/responses.0}}
{{#isDeprecated}}
* @deprecated
{{/isDeprecated}}
{{#externalDocs}}
* {{description}}
* @see <a href="{{url}}">{{summary}} Documentation</a>
{{/externalDocs}}
*/
{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
public{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}private{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-streaming}} InputStream {{operationId}}WithHttpInfo({{#allParams}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws ApiException {
okhttp3.Call localVarCall = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}null);
{{#returnType}}
try {
Type localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType();
return localVarApiClient.executeStream(localVarCall, localVarReturnType);
} catch (ApiException e) {
e.setErrorObject(localVarApiClient.getJSON().getGson().fromJson(e.getResponseBody(), new TypeToken<{{{errorObjectType}}}{{^errorObjectType}}{{{returnType}}}{{/errorObjectType}}>(){}.getType()));
e.setErrorObjectType(new GenericType<{{{errorObjectType}}}{{^errorObjectType}}{{{returnType}}}{{/errorObjectType}}>(){});
throw e;
}
{{/returnType}}
}
{{/vendorExtensions.x-streaming}}{{^vendorExtensions.x-streaming}} ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws ApiException {
okhttp3.Call localVarCall = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}null);
{{^returnType}}
return localVarApiClient.execute(localVarCall);
{{/returnType}}
{{#returnType}}
try {
Type localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
} catch (ApiException e) {
e.setErrorObject(localVarApiClient.getJSON().getGson().fromJson(e.getResponseBody(), new TypeToken<{{{errorObjectType}}}{{^errorObjectType}}{{{returnType}}}{{/errorObjectType}}>(){}.getType()));
e.setErrorObjectType(new GenericType<{{{errorObjectType}}}{{^errorObjectType}}{{{returnType}}}{{/errorObjectType}}>(){});
throw e;
}
{{/returnType}}
}
{{/vendorExtensions.x-streaming}}
{{^vendorExtensions.x-group-parameters}}/**
* {{summary}} (asynchronously)
* {{notes}}{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{^isContainer}}{{#defaultValue}}, default to {{.}}{{/defaultValue}}{{/isContainer}}){{/required}}{{/allParams}}
* @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
{{#responses.0}}
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
{{#responses}}
<tr><td> {{code}} </td><td> {{message}} </td><td> {{#headers}} * {{baseName}} - {{description}} <br> {{/headers}}{{^headers.0}} - {{/headers.0}} </td></tr>
{{/responses}}
</table>
{{/responses.0}}
{{#isDeprecated}}
* @deprecated
{{/isDeprecated}}
{{#externalDocs}}
* {{description}}
* @see <a href="{{url}}">{{summary}} Documentation</a>
{{/externalDocs}}
*/
{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
public{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}private{{/vendorExtensions.x-group-parameters}} okhttp3.Call {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback<{{{returnType}}}{{^returnType}}Void{{/returnType}}> _callback) throws ApiException {
okhttp3.Call localVarCall = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}_callback);
{{#returnType}}Type localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType();
localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback);{{/returnType}}{{^returnType}}localVarApiClient.executeAsync(localVarCall, _callback);{{/returnType}}
return localVarCall;
}
{{#vendorExtensions.x-group-parameters}}
public class API{{operationId}}Request {
{{#requiredParams}}
private final {{{dataType}}} {{paramName}};
{{/requiredParams}}
{{#optionalParams}}
private {{{dataType}}} {{paramName}};
{{/optionalParams}}
private API{{operationId}}Request({{#requiredParams}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/requiredParams}}) {
{{#requiredParams}}
this.{{paramName}} = {{paramName}};
{{/requiredParams}}
}
{{#optionalParams}}
/**
* Set {{paramName}}
* @param {{paramName}} {{description}} (optional{{^isContainer}}{{#defaultValue}}, default to {{.}}{{/defaultValue}}{{/isContainer}})
* @return API{{operationId}}Request
*/
public API{{operationId}}Request {{paramName}}({{{dataType}}} {{paramName}}) {
this.{{paramName}} = {{paramName}};
return this;
}
{{/optionalParams}}
/**
* Build call for {{operationId}}
* @param _callback ApiCallback API callback
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
{{#responses.0}}
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
{{#responses}}
<tr><td> {{code}} </td><td> {{message}} </td><td> {{#headers}} * {{baseName}} - {{description}} <br> {{/headers}}{{^headers.0}} - {{/headers.0}} </td></tr>
{{/responses}}
</table>
{{/responses.0}}
{{#isDeprecated}}
* @deprecated
{{/isDeprecated}}
*/
{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
public okhttp3.Call buildCall(final ApiCallback _callback) throws ApiException {
return {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}_callback);
}
/**
* Execute {{operationId}} request{{#returnType}}
* @return {{.}}{{/returnType}}
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
{{#responses.0}}
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
{{#responses}}
<tr><td> {{code}} </td><td> {{message}} </td><td> {{#headers}} * {{baseName}} - {{description}} <br> {{/headers}}{{^headers.0}} - {{/headers.0}} </td></tr>
{{/responses}}
</table>
{{/responses.0}}
{{#isDeprecated}}
* @deprecated
{{/isDeprecated}}
*/
{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
public {{{returnType}}}{{^returnType}}void{{/returnType}} execute() throws ApiException {
{{#returnType}}ApiResponse<{{{.}}}> localVarResp = {{/returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{#returnType}}
return localVarResp.getData();{{/returnType}}
}
/**
* Execute {{operationId}} request with HTTP info returned
* @return ApiResponse&lt;{{returnType}}{{^returnType}}Void{{/returnType}}&gt;
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
{{#responses.0}}
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
{{#responses}}
<tr><td> {{code}} </td><td> {{message}} </td><td> {{#headers}} * {{baseName}} - {{description}} <br> {{/headers}}{{^headers.0}} - {{/headers.0}} </td></tr>
{{/responses}}
</table>
{{/responses.0}}
{{#isDeprecated}}
* @deprecated
{{/isDeprecated}}
*/
{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
public ApiResponse<{{{returnType}}}{{^returnType}}Void{{/returnType}}> executeWithHttpInfo() throws ApiException {
return {{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});
}
/**
* Execute {{operationId}} request (asynchronously)
* @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
{{#responses.0}}
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
{{#responses}}
<tr><td> {{code}} </td><td> {{message}} </td><td> {{#headers}} * {{baseName}} - {{description}} <br> {{/headers}}{{^headers.0}} - {{/headers.0}} </td></tr>
{{/responses}}
</table>
{{/responses.0}}
{{#isDeprecated}}
* @deprecated
{{/isDeprecated}}
*/
{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
public okhttp3.Call executeAsync(final ApiCallback<{{{returnType}}}{{^returnType}}Void{{/returnType}}> _callback) throws ApiException {
return {{operationId}}Async({{#allParams}}{{paramName}}, {{/allParams}}_callback);
}
}
/**
* {{summary}}
* {{notes}}{{#requiredParams}}
* @param {{paramName}} {{description}} (required){{/requiredParams}}
* @return API{{operationId}}Request
{{#responses.0}}
* @http.response.details
<table summary="Response Details" border="1">
<tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr>
{{#responses}}
<tr><td> {{code}} </td><td> {{message}} </td><td> {{#headers}} * {{baseName}} - {{description}} <br> {{/headers}}{{^headers.0}} - {{/headers.0}} </td></tr>
{{/responses}}
</table>
{{/responses.0}}
{{#isDeprecated}}
* @deprecated
{{/isDeprecated}}
{{#externalDocs}}
* {{description}}
* @see <a href="{{url}}">{{summary}} Documentation</a>
{{/externalDocs}}
*/
{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
public API{{operationId}}Request {{operationId}}({{#requiredParams}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/requiredParams}}) {
return new API{{operationId}}Request({{#requiredParams}}{{paramName}}{{^-last}}, {{/-last}}{{/requiredParams}});
}
{{/vendorExtensions.x-group-parameters}}
{{/operation}}
}
{{/operations}}

View File

@@ -1,199 +0,0 @@
{{>licenseInfo}}
package {{invokerPackage}};
import java.util.Map;
import java.util.List;
{{#caseInsensitiveResponseHeaders}}
import java.util.Map.Entry;
import java.util.TreeMap;
{{/caseInsensitiveResponseHeaders}}
import javax.ws.rs.core.GenericType;
/**
* <p>ApiException class.</p>
*/
@SuppressWarnings("serial")
{{>generatedAnnotation}}
public class ApiException extends{{#useRuntimeException}} RuntimeException {{/useRuntimeException}}{{^useRuntimeException}} Exception {{/useRuntimeException}}{
private int code = 0;
private Map<String, List<String>> responseHeaders = null;
private String responseBody = null;
private {{{errorObjectType}}}{{^errorObjectType}}Object{{/errorObjectType}} errorObject = null;
private GenericType errorObjectType = null;
/**
* <p>Constructor for ApiException.</p>
*/
public ApiException() {}
/**
* <p>Constructor for ApiException.</p>
*
* @param throwable a {@link java.lang.Throwable} object
*/
public ApiException(Throwable throwable) {
super(throwable);
}
/**
* <p>Constructor for ApiException.</p>
*
* @param message the error message
*/
public ApiException(String message) {
super(message);
}
/**
* <p>Constructor for ApiException.</p>
*
* @param message the error message
* @param throwable a {@link java.lang.Throwable} object
* @param code HTTP status code
* @param responseHeaders a {@link java.util.Map} of HTTP response headers
* @param responseBody the response body
*/
public ApiException(String message, Throwable throwable, int code, Map<String, List<String>> responseHeaders, String responseBody) {
super(message, throwable);
this.code = code;
{{#caseInsensitiveResponseHeaders}}
Map<String, List<String>> headers = new TreeMap<String, List<String>>(String.CASE_INSENSITIVE_ORDER);
for(Entry<String, List<String>> entry : responseHeaders.entrySet()){
headers.put(entry.getKey().toLowerCase(), entry.getValue());
}
{{/caseInsensitiveResponseHeaders}}
this.responseHeaders = {{#caseInsensitiveResponseHeaders}}headers{{/caseInsensitiveResponseHeaders}}{{^caseInsensitiveResponseHeaders}}responseHeaders{{/caseInsensitiveResponseHeaders}};
this.responseBody = responseBody;
}
/**
* <p>Constructor for ApiException.</p>
*
* @param message the error message
* @param code HTTP status code
* @param responseHeaders a {@link java.util.Map} of HTTP response headers
* @param responseBody the response body
*/
public ApiException(String message, int code, Map<String, List<String>> responseHeaders, String responseBody) {
this(message, (Throwable) null, code, responseHeaders, responseBody);
}
/**
* <p>Constructor for ApiException.</p>
*
* @param message the error message
* @param throwable a {@link java.lang.Throwable} object
* @param code HTTP status code
* @param responseHeaders a {@link java.util.Map} of HTTP response headers
*/
public ApiException(String message, Throwable throwable, int code, Map<String, List<String>> responseHeaders) {
this(message, throwable, code, responseHeaders, null);
}
/**
* <p>Constructor for ApiException.</p>
*
* @param code HTTP status code
* @param responseHeaders a {@link java.util.Map} of HTTP response headers
* @param responseBody the response body
*/
public ApiException(int code, Map<String, List<String>> responseHeaders, String responseBody) {
this((String) null, (Throwable) null, code, responseHeaders, responseBody);
}
/**
* <p>Constructor for ApiException.</p>
*
* @param code HTTP status code
* @param message a {@link java.lang.String} object
*/
public ApiException(int code, String message) {
super(message);
this.code = code;
}
/**
* <p>Constructor for ApiException.</p>
*
* @param code HTTP status code
* @param message the error message
* @param responseHeaders a {@link java.util.Map} of HTTP response headers
* @param responseBody the response body
*/
public ApiException(int code, String message, Map<String, List<String>> responseHeaders, String responseBody) {
this(code, message);
{{#caseInsensitiveResponseHeaders}}
Map<String, List<String>> headers = new TreeMap<String, List<String>>(String.CASE_INSENSITIVE_ORDER);
for(Entry<String, List<String>> entry : responseHeaders.entrySet()){
headers.put(entry.getKey().toLowerCase(), entry.getValue());
}
{{/caseInsensitiveResponseHeaders}}
this.responseHeaders = {{#caseInsensitiveResponseHeaders}}headers{{/caseInsensitiveResponseHeaders}}{{^caseInsensitiveResponseHeaders}}responseHeaders{{/caseInsensitiveResponseHeaders}};
this.responseBody = responseBody;
}
/**
* Get the HTTP status code.
*
* @return HTTP status code
*/
public int getCode() {
return code;
}
/**
* Get the HTTP response headers.
*
* @return A map of list of string
*/
public Map<String, List<String>> getResponseHeaders() {
return responseHeaders;
}
/**
* Get the HTTP response body.
*
* @return Response body in the form of string
*/
public String getResponseBody() {
return responseBody;
}
/**
* Get the error object type.
*
* @return Error object type
*/
public GenericType getErrorObjectType() {
return errorObjectType;
}
/**
* Set the error object type.
*
* @param errorObjectType object type
*/
public void setErrorObjectType(GenericType errorObjectType) {
this.errorObjectType = errorObjectType;
}
/**
* Get the error object.
*
* @return Error object
*/
public {{{errorObjectType}}}{{^errorObjectType}}Object{{/errorObjectType}} getErrorObject() {
return errorObject;
}
/**
* Get the error object.
*
* @param errorObject Error object
*/
public void setErrorObject({{{errorObjectType}}}{{^errorObjectType}}Object{{/errorObjectType}} errorObject) {
this.errorObject = errorObject;
}
}

View File

@@ -1,118 +0,0 @@
# {{classname}}{{#description}}
{{.}}{{/description}}
All URIs are relative to *{{basePath}}*
Method | HTTP request | Description
------------- | ------------- | -------------
{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{summary}}
{{/operation}}{{/operations}}
{{#operations}}
{{#operation}}
<a name="{{operationId}}"></a>
# **{{operationId}}**{{^vendorExtensions.x-group-parameters}}
> {{#returnType}}{{.}} {{/returnType}}{{operationId}}({{#allParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}){{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}
> {{#returnType}}{{.}} {{/returnType}}{{operationId}}({{#requiredParams}}{{paramName}}{{^-last}}, {{/-last}}{{/requiredParams}}){{#optionalParams}}.{{paramName}}({{paramName}}){{/optionalParams}}.execute();{{/vendorExtensions.x-group-parameters}}
{{summary}}{{#notes}}
{{.}}{{/notes}}
### Example
```java
// Import classes:
import {{{invokerPackage}}}.ApiClient;
import {{{invokerPackage}}}.ApiException;
import {{{invokerPackage}}}.Configuration;{{#hasAuthMethods}}
import {{{invokerPackage}}}.auth.*;{{/hasAuthMethods}}
import {{{invokerPackage}}}.models.*;
import {{{package}}}.{{{classname}}};
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("{{{basePath}}}");
{{#hasAuthMethods}}
{{#authMethods}}{{#isBasic}}{{#isBasicBasic}}
// Configure HTTP basic authorization: {{{name}}}
HttpBasicAuth {{{name}}} = (HttpBasicAuth) defaultClient.getAuthentication("{{{name}}}");
{{{name}}}.setUsername("YOUR USERNAME");
{{{name}}}.setPassword("YOUR PASSWORD");{{/isBasicBasic}}{{#isBasicBearer}}
// Configure HTTP bearer authorization: {{{name}}}
HttpBearerAuth {{{name}}} = (HttpBearerAuth) defaultClient.getAuthentication("{{{name}}}");
{{{name}}}.setBearerToken("BEARER TOKEN");{{/isBasicBearer}}{{/isBasic}}{{#isApiKey}}
// Configure API key authorization: {{{name}}}
ApiKeyAuth {{{name}}} = (ApiKeyAuth) defaultClient.getAuthentication("{{{name}}}");
{{{name}}}.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//{{{name}}}.setApiKeyPrefix("Token");{{/isApiKey}}{{#isOAuth}}
// Configure OAuth2 access token for authorization: {{{name}}}
OAuth {{{name}}} = (OAuth) defaultClient.getAuthentication("{{{name}}}");
{{{name}}}.setAccessToken("YOUR ACCESS TOKEN");{{/isOAuth}}
{{/authMethods}}
{{/hasAuthMethods}}
{{{classname}}} apiInstance = new {{{classname}}}(defaultClient);
{{#allParams}}
{{{dataType}}} {{{paramName}}} = {{{example}}}; // {{{dataType}}} | {{{description}}}
{{/allParams}}
try {
{{#returnType}}{{{.}}} result = {{/returnType}}apiInstance.{{{operationId}}}{{^vendorExtensions.x-group-parameters}}({{#allParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}});{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}({{#requiredParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}){{#optionalParams}}
.{{{paramName}}}({{{paramName}}}){{/optionalParams}}
.execute();{{/vendorExtensions.x-group-parameters}}{{#returnType}}
System.out.println(result);{{/returnType}}
} catch (ApiException e) {
{{=< >=}}
<#errorObjectSubtype>
<^-first>} else </-first>if (e.getErrorObject() instanceof <&.>) {
// do something here
<#-last>
} else {
// something else happened
System.err.println("Exception when calling {{{classname}}}#{{{operationId}}}");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
</-last>
</errorObjectSubtype>
<={{ }}=>
}
}
}
```
### Parameters
{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}}
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}}
{{#allParams}} **{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isFile}}**{{dataType}}**{{/isFile}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} |{{^required}} [optional]{{/required}}{{^isContainer}}{{#defaultValue}} [default to {{.}}]{{/defaultValue}}{{/isContainer}}{{#allowableValues}} [enum: {{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}]{{/allowableValues}}
{{/allParams}}
### Return type
{{#returnType}}{{#returnTypeIsPrimitive}}**{{returnType}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{returnType}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}null (empty response body){{/returnType}}
### Authorization
{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{name}}](../README.md#{{name}}){{^-last}}, {{/-last}}{{/authMethods}}
### HTTP request headers
- **Content-Type**: {{#consumes}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/consumes}}{{^consumes}}Not defined{{/consumes}}
- **Accept**: {{#produces}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/produces}}{{^produces}}Not defined{{/produces}}
{{#responses.0}}
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
{{#responses}}
**{{code}}** | {{message}} | {{#headers}} * {{baseName}} - {{description}} <br> {{/headers}}{{^headers.0}} - {{/headers.0}} |
{{/responses}}
{{/responses.0}}
{{/operation}}
{{/operations}}

View File

@@ -1,56 +0,0 @@
{{>licenseInfo}}
package {{package}};
import {{invokerPackage}}.ApiException;
{{#imports}}import {{import}};
{{/imports}}
import org.junit.Test;
import org.junit.Ignore;
{{^fullJavaUtil}}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
{{#supportStreaming}}
import java.io.InputStream;
{{/supportStreaming}}
{{/fullJavaUtil}}
/**
* API tests for {{classname}}
*/
@Ignore
public class {{classname}}Test {
private final {{classname}} api = new {{classname}}();
{{#operations}}{{#operation}}
/**
* {{summary}}
*
* {{notes}}
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void {{operationId}}Test() throws ApiException {
{{#allParams}}
{{{dataType}}} {{paramName}} = null;
{{/allParams}}
{{#vendorExtensions.x-streaming}}
InputStream response = api.{{operationId}}{{^vendorExtensions.x-group-parameters}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}({{#requiredParams}}{{paramName}}{{^-last}}, {{/-last}}{{/requiredParams}}){{#optionalParams}}
.{{paramName}}({{paramName}}){{/optionalParams}}
.execute();{{/vendorExtensions.x-group-parameters}}
{{/vendorExtensions.x-streaming}}
{{^vendorExtensions.x-streaming}}
{{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}{{^vendorExtensions.x-group-parameters}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}({{#requiredParams}}{{paramName}}{{^-last}}, {{/-last}}{{/requiredParams}}){{#optionalParams}}
.{{paramName}}({{paramName}}){{/optionalParams}}
.execute();{{/vendorExtensions.x-group-parameters}}
{{/vendorExtensions.x-streaming}}
// TODO: test validations
}
{{/operation}}{{/operations}}
}

View File

@@ -1,69 +0,0 @@
{{>licenseInfo}}
package {{invokerPackage}}.auth;
import {{invokerPackage}}.ApiException;
import {{invokerPackage}}.Pair;
import java.net.URI;
import java.util.Map;
import java.util.List;
{{>generatedAnnotation}}
public class ApiKeyAuth implements Authentication {
private final String location;
private final String paramName;
private String apiKey;
private String apiKeyPrefix;
public ApiKeyAuth(String location, String paramName) {
this.location = location;
this.paramName = paramName;
}
public String getLocation() {
return location;
}
public String getParamName() {
return paramName;
}
public String getApiKey() {
return apiKey;
}
public void setApiKey(String apiKey) {
this.apiKey = apiKey;
}
public String getApiKeyPrefix() {
return apiKeyPrefix;
}
public void setApiKeyPrefix(String apiKeyPrefix) {
this.apiKeyPrefix = apiKeyPrefix;
}
@Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams,
String payload, String method, URI uri) throws ApiException {
if (apiKey == null) {
return;
}
String value;
if (apiKeyPrefix != null) {
value = apiKeyPrefix + " " + apiKey;
} else {
value = apiKey;
}
if ("query".equals(location)) {
queryParams.add(new Pair(paramName, value));
} else if ("header".equals(location)) {
headerParams.put(paramName, value);
} else if ("cookie".equals(location)) {
cookieParams.put(paramName, value);
}
}
}

View File

@@ -1,25 +0,0 @@
{{>licenseInfo}}
package {{invokerPackage}}.auth;
import {{invokerPackage}}.Pair;
import {{invokerPackage}}.ApiException;
import java.net.URI;
import java.util.Map;
import java.util.List;
public interface Authentication {
/**
* Apply authentication settings to header and query params.
*
* @param queryParams List of query parameters
* @param headerParams Map of header parameters
* @param cookieParams Map of cookie parameters
* @param payload HTTP request body
* @param method HTTP method
* @param uri URI
* @throws ApiException if failed to update the parameters
*/
void applyToParams(List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams, String payload, String method, URI uri) throws ApiException;
}

View File

@@ -1,46 +0,0 @@
{{>licenseInfo}}
package {{invokerPackage}}.auth;
import {{invokerPackage}}.Pair;
import {{invokerPackage}}.ApiException;
import okhttp3.Credentials;
import java.net.URI;
import java.util.Map;
import java.util.List;
import java.io.UnsupportedEncodingException;
public class HttpBasicAuth implements Authentication {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams,
String payload, String method, URI uri) throws ApiException {
if (username == null && password == null) {
return;
}
headerParams.put("Authorization", Credentials.basic(
username == null ? "" : username,
password == null ? "" : password));
}
}

View File

@@ -1,52 +0,0 @@
{{>licenseInfo}}
package {{invokerPackage}}.auth;
import {{invokerPackage}}.ApiException;
import {{invokerPackage}}.Pair;
import java.net.URI;
import java.util.Map;
import java.util.List;
{{>generatedAnnotation}}
public class HttpBearerAuth implements Authentication {
private final String scheme;
private String bearerToken;
public HttpBearerAuth(String scheme) {
this.scheme = scheme;
}
/**
* Gets the token, which together with the scheme, will be sent as the value of the Authorization header.
*
* @return The bearer token
*/
public String getBearerToken() {
return bearerToken;
}
/**
* Sets the token, which together with the scheme, will be sent as the value of the Authorization header.
*
* @param bearerToken The bearer token to send in the Authorization header
*/
public void setBearerToken(String bearerToken) {
this.bearerToken = bearerToken;
}
@Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams,
String payload, String method, URI uri) throws ApiException {
if (bearerToken == null) {
return;
}
headerParams.put("Authorization", (scheme != null ? upperCaseBearer(scheme) + " " : "") + bearerToken);
}
private static String upperCaseBearer(String scheme) {
return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme;
}
}

View File

@@ -1,31 +0,0 @@
{{>licenseInfo}}
package {{invokerPackage}}.auth;
import {{invokerPackage}}.Pair;
import {{invokerPackage}}.ApiException;
import java.net.URI;
import java.util.Map;
import java.util.List;
{{>generatedAnnotation}}
public class OAuth implements Authentication {
private String accessToken;
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
@Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams,
String payload, String method, URI uri) throws ApiException {
if (accessToken != null) {
headerParams.put("Authorization", "Bearer " + accessToken);
}
}
}

View File

@@ -1,70 +0,0 @@
{{#hasOAuthMethods}}
package {{invokerPackage}}.auth;
import okhttp3.OkHttpClient;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.apache.oltu.oauth2.client.HttpClient;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.client.response.OAuthClientResponse;
import org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
public class OAuthOkHttpClient implements HttpClient {
private OkHttpClient client;
public OAuthOkHttpClient() {
this.client = new OkHttpClient();
}
public OAuthOkHttpClient(OkHttpClient client) {
this.client = client;
}
@Override
public <T extends OAuthClientResponse> T execute(OAuthClientRequest request, Map<String, String> headers,
String requestMethod, Class<T> responseClass)
throws OAuthSystemException, OAuthProblemException {
MediaType mediaType = MediaType.parse("application/json");
Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri());
if(headers != null) {
for (Entry<String, String> entry : headers.entrySet()) {
if (entry.getKey().equalsIgnoreCase("Content-Type")) {
mediaType = MediaType.parse(entry.getValue());
} else {
requestBuilder.addHeader(entry.getKey(), entry.getValue());
}
}
}
RequestBody body = request.getBody() != null ? RequestBody.create(request.getBody(), mediaType) : null;
requestBuilder.method(requestMethod, body);
try {
Response response = client.newCall(requestBuilder.build()).execute();
return OAuthClientResponseFactory.createCustomResponse(
response.body().string(),
response.body().contentType().toString(),
response.code(),
responseClass);
} catch (IOException e) {
throw new OAuthSystemException(e);
}
}
@Override
public void shutdown() {
// Nothing to do here
}
}
{{/hasOAuthMethods}}

View File

@@ -1,213 +0,0 @@
{{#hasOAuthMethods}}
package {{invokerPackage}}.auth;
import {{invokerPackage}}.ApiException;
import {{invokerPackage}}.Pair;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.apache.oltu.oauth2.client.OAuthClient;
import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest;
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder;
import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.util.Map;
import java.util.List;
public class RetryingOAuth extends OAuth implements Interceptor {
private OAuthClient oAuthClient;
private TokenRequestBuilder tokenRequestBuilder;
/**
* @param client An OkHttp client
* @param tokenRequestBuilder A token request builder
*/
public RetryingOAuth(OkHttpClient client, TokenRequestBuilder tokenRequestBuilder) {
this.oAuthClient = new OAuthClient(new OAuthOkHttpClient(client));
this.tokenRequestBuilder = tokenRequestBuilder;
}
/**
* @param tokenRequestBuilder A token request builder
*/
public RetryingOAuth(TokenRequestBuilder tokenRequestBuilder) {
this(new OkHttpClient(), tokenRequestBuilder);
}
/**
* @param tokenUrl The token URL to be used for this OAuth2 flow.
* Applicable to the following OAuth2 flows: "password", "clientCredentials" and "authorizationCode".
* The value must be an absolute URL.
* @param clientId The OAuth2 client ID for the "clientCredentials" flow.
* @param flow OAuth flow.
* @param clientSecret The OAuth2 client secret for the "clientCredentials" flow.
* @param parameters A map of string.
*/
public RetryingOAuth(
String tokenUrl,
String clientId,
OAuthFlow flow,
String clientSecret,
Map<String, String> parameters
) {
this(OAuthClientRequest.tokenLocation(tokenUrl)
.setClientId(clientId)
.setClientSecret(clientSecret));
setFlow(flow);
if (parameters != null) {
for (String paramName : parameters.keySet()) {
tokenRequestBuilder.setParameter(paramName, parameters.get(paramName));
}
}
}
/**
* Set the OAuth flow
*
* @param flow The OAuth flow.
*/
public void setFlow(OAuthFlow flow) {
switch(flow) {
case ACCESS_CODE:
tokenRequestBuilder.setGrantType(GrantType.AUTHORIZATION_CODE);
break;
case IMPLICIT:
tokenRequestBuilder.setGrantType(GrantType.IMPLICIT);
break;
case PASSWORD:
tokenRequestBuilder.setGrantType(GrantType.PASSWORD);
break;
case APPLICATION:
tokenRequestBuilder.setGrantType(GrantType.CLIENT_CREDENTIALS);
break;
default:
break;
}
}
@Override
public Response intercept(Chain chain) throws IOException {
return retryingIntercept(chain, true);
}
private Response retryingIntercept(Chain chain, boolean updateTokenAndRetryOnAuthorizationFailure) throws IOException {
Request request = chain.request();
// If the request already has an authorization (e.g. Basic auth), proceed with the request as is
if (request.header("Authorization") != null) {
return chain.proceed(request);
}
// Get the token if it has not yet been acquired
if (getAccessToken() == null) {
updateAccessToken(null);
}
OAuthClientRequest oAuthRequest;
if (getAccessToken() != null) {
// Build the request
Request.Builder requestBuilder = request.newBuilder();
String requestAccessToken = getAccessToken();
try {
oAuthRequest =
new OAuthBearerClientRequest(request.url().toString()).
setAccessToken(requestAccessToken).
buildHeaderMessage();
} catch (OAuthSystemException e) {
throw new IOException(e);
}
Map<String, String> headers = oAuthRequest.getHeaders();
for (String headerName : headers.keySet()) {
requestBuilder.addHeader(headerName, headers.get(headerName));
}
requestBuilder.url(oAuthRequest.getLocationUri());
// Execute the request
Response response = chain.proceed(requestBuilder.build());
// 401/403 response codes most likely indicate an expired access token, unless it happens two times in a row
if (
response != null &&
( response.code() == HttpURLConnection.HTTP_UNAUTHORIZED ||
response.code() == HttpURLConnection.HTTP_FORBIDDEN ) &&
updateTokenAndRetryOnAuthorizationFailure
) {
try {
if (updateAccessToken(requestAccessToken)) {
response.body().close();
return retryingIntercept(chain, false);
}
} catch (Exception e) {
response.body().close();
throw e;
}
}
return response;
}
else {
return chain.proceed(chain.request());
}
}
/**
* Returns true if the access token has been updated
*
* @param requestAccessToken the request access token
* @return True if the update is successful
* @throws java.io.IOException If fail to update the access token
*/
public synchronized boolean updateAccessToken(String requestAccessToken) throws IOException {
if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) {
try {
OAuthJSONAccessTokenResponse accessTokenResponse =
oAuthClient.accessToken(tokenRequestBuilder.buildBodyMessage());
if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) {
setAccessToken(accessTokenResponse.getAccessToken());
}
} catch (OAuthSystemException | OAuthProblemException e) {
throw new IOException(e);
}
}
return getAccessToken() == null || !getAccessToken().equals(requestAccessToken);
}
/**
* Gets the token request builder
*
* @return A token request builder
* @throws java.io.IOException If fail to update the access token
*/
public TokenRequestBuilder getTokenRequestBuilder() {
return tokenRequestBuilder;
}
/**
* Sets the token request builder
*
* @param tokenRequestBuilder Token request builder
*/
public void setTokenRequestBuilder(TokenRequestBuilder tokenRequestBuilder) {
this.tokenRequestBuilder = tokenRequestBuilder;
}
// Applying authorization to parameters is performed in the retryingIntercept method
@Override
public void applyToParams(List<Pair> queryParams, Map<String, String> headerParams, Map<String, String> cookieParams,
String payload, String method, URI uri) throws ApiException {
// No implementation necessary
}
}
{{/hasOAuthMethods}}

View File

@@ -1,169 +0,0 @@
apply plugin: 'idea'
apply plugin: 'eclipse'
{{#sourceFolder}}
apply plugin: 'java'
{{/sourceFolder}}
apply plugin: 'com.diffplug.spotless'
group = '{{groupId}}'
version = '{{artifactVersion}}'
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.+'
classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5'
classpath 'com.diffplug.spotless:spotless-plugin-gradle:5.17.1'
}
}
repositories {
mavenCentral()
}
{{#sourceFolder}}
sourceSets {
main.java.srcDirs = ['{{sourceFolder}}']
}
{{/sourceFolder}}
if(hasProperty('target') && target == 'android') {
apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven'
android {
compileSdkVersion 25
buildToolsVersion '25.0.2'
defaultConfig {
minSdkVersion 14
targetSdkVersion 25
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
// Rename the aar correctly
libraryVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith('.aar')) {
def fileName = "${project.name}-${variant.baseName}-${version}.aar"
output.outputFile = new File(outputFile.parent, fileName)
}
}
}
dependencies {
provided "jakarta.annotation:jakarta.annotation-api:$jakarta_annotation_version"
}
}
afterEvaluate {
android.libraryVariants.all { variant ->
def task = project.tasks.create "jar${variant.name.capitalize()}", Jar
task.description = "Create jar artifact for ${variant.name}"
task.dependsOn variant.javaCompile
task.from variant.javaCompile.destinationDir
task.destinationDir = project.file("${project.buildDir}/outputs/jar")
task.archiveName = "${project.name}-${variant.baseName}-${version}.jar"
artifacts.add('archives', task);
}
}
task sourcesJar(type: Jar) {
from android.sourceSets.main.java.srcDirs
classifier = 'sources'
}
artifacts {
archives sourcesJar
}
} else {
apply plugin: 'java'
apply plugin: 'maven-publish'
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
publishing {
publications {
maven(MavenPublication) {
artifactId = '{{artifactId}}'
from components.java
}
}
}
task execute(type:JavaExec) {
main = System.getProperty('mainClass')
classpath = sourceSets.main.runtimeClasspath
}
}
ext {
jakarta_annotation_version = "1.3.5"
}
dependencies {
implementation 'io.swagger:swagger-annotations:1.5.24'
implementation "com.google.code.findbugs:jsr305:3.0.2"
implementation 'com.squareup.okhttp3:okhttp:4.9.1'
implementation 'com.squareup.okhttp3:logging-interceptor:4.9.1'
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'io.gsonfire:gson-fire:1.8.4'
{{#openApiNullable}}
implementation 'org.openapitools:jackson-databind-nullable:0.2.1'
{{/openApiNullable}}
{{#hasOAuthMethods}}
implementation group: 'org.apache.oltu.oauth2', name: 'org.apache.oltu.oauth2.client', version: '1.0.1'
{{/hasOAuthMethods}}
implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.10'
{{#joda}}
implementation 'joda-time:joda-time:2.9.9'
{{/joda}}
{{#threetenbp}}
implementation 'org.threeten:threetenbp:1.4.3'
{{/threetenbp}}
{{#dynamicOperations}}
implementation 'io.swagger.parser.v3:swagger-parser-v3:2.0.23'
{{/dynamicOperations}}
implementation "jakarta.annotation:jakarta.annotation-api:$jakarta_annotation_version"
testImplementation 'junit:junit:4.13.1'
testImplementation 'org.mockito:mockito-core:3.11.2'
}
javadoc {
options.tags = [ "http.response.details:a:Http Response Details" ]
}
// Use spotless plugin to automatically format code, remove unused import, etc
// To apply changes directly to the file, run `gradlew spotlessApply`
// Ref: https://github.com/diffplug/spotless/tree/main/plugin-gradle
spotless {
// comment out below to run spotless as part of the `check` task
enforceCheck false
format 'misc', {
// define the files (e.g. '*.gradle', '*.md') to apply `misc` to
target '.gitignore'
// define the steps to apply to those files
trimTrailingWhitespace()
indentWithSpaces() // Takes an integer argument if you don't like 4
endWithNewline()
}
java {
// don't need to set target, it is inferred from java
// apply a specific flavor of google-java-format
googleJavaFormat('1.8').aosp().reflowLongStrings()
removeUnusedImports()
importOrder()
}
}

View File

@@ -1,39 +0,0 @@
lazy val root = (project in file(".")).
settings(
organization := "{{groupId}}",
name := "{{artifactId}}",
version := "{{artifactVersion}}",
scalaVersion := "2.11.4",
scalacOptions ++= Seq("-feature"),
javacOptions in compile ++= Seq("-Xlint:deprecation"),
publishArtifact in (Compile, packageDoc) := false,
resolvers += Resolver.mavenLocal,
libraryDependencies ++= Seq(
"io.swagger" % "swagger-annotations" % "1.5.24",
"com.squareup.okhttp3" % "okhttp" % "4.9.1",
"com.squareup.okhttp3" % "logging-interceptor" % "4.9.1",
"com.google.code.gson" % "gson" % "2.8.6",
"org.apache.commons" % "commons-lang3" % "3.10",
{{#openApiNullable}}
"org.openapitools" % "jackson-databind-nullable" % "0.2.2",
{{/openApiNullable}}
{{#hasOAuthMethods}}
"org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1",
{{/hasOAuthMethods}}
{{#joda}}
"joda-time" % "joda-time" % "2.9.9" % "compile",
{{/joda}}
{{#threetenbp}}
"org.threeten" % "threetenbp" % "1.4.3" % "compile",
{{/threetenbp}}
{{#dynamicOperations}}
"io.swagger.parser.v3" % "swagger-parser-v3" "2.0.23" % "compile"
{{/dynamicOperations}}
"io.gsonfire" % "gson-fire" % "1.8.3" % "compile",
"jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile",
"com.google.code.findbugs" % "jsr305" % "3.0.2" % "compile",
"jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile",
"junit" % "junit" % "4.13.1" % "test",
"com.novocode" % "junit-interface" % "0.10" % "test"
)
)

View File

@@ -1,420 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>{{groupId}}</groupId>
<artifactId>{{artifactId}}</artifactId>
<packaging>jar</packaging>
<name>{{artifactId}}</name>
<version>{{artifactVersion}}</version>
<url>{{artifactUrl}}</url>
<description>{{artifactDescription}}</description>
<scm>
<connection>{{scmConnection}}</connection>
<developerConnection>{{scmDeveloperConnection}}</developerConnection>
<url>{{scmUrl}}</url>
</scm>
{{#parentOverridden}}
<parent>
<groupId>{{{parentGroupId}}}</groupId>
<artifactId>{{{parentArtifactId}}}</artifactId>
<version>{{{parentVersion}}}</version>
</parent>
{{/parentOverridden}}
<licenses>
<license>
<name>{{licenseName}}</name>
<url>{{licenseUrl}}</url>
<distribution>repo</distribution>
</license>
</licenses>
<developers>
<developer>
<name>{{developerName}}</name>
<email>{{developerEmail}}</email>
<organization>{{developerOrganization}}</organization>
<organizationUrl>{{developerOrganizationUrl}}</organizationUrl>
</developer>
</developers>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<fork>true</fork>
<meminitial>128m</meminitial>
<maxmem>512m</maxmem>
<compilerArgs>
<arg>-Xlint:all</arg>
<arg>-J-Xss4m</arg><!-- Compiling the generated JSON.java file may require larger stack size. -->
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<id>enforce-maven</id>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<requireMavenVersion>
<version>2.2.0</version>
</requireMavenVersion>
</rules>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
<configuration>
<systemProperties>
<property>
<name>loggerPath</name>
<value>conf/log4j.properties</value>
</property>
</systemProperties>
<argLine>-Xms512m -Xmx1500m</argLine>
<parallel>methods</parallel>
<threadCount>10</threadCount>
</configuration>
</plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<!-- attach test jar -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<goals>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
<configuration>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<id>add_sources</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>{{{sourceFolder}}}</source>
</sources>
</configuration>
</execution>
<execution>
<id>add_test_sources</id>
<phase>generate-test-sources</phase>
<goals>
<goal>add-test-source</goal>
</goals>
<configuration>
<sources>
<source>src/test/java</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.3.1</version>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
<configuration>
<doclint>none</doclint>
<tags>
<tag>
<name>http.response.details</name>
<placement>a</placement>
<head>Http Response Details:</head>
</tag>
</tags>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- Use spotless plugin to automatically format code, remove unused import, etc
To apply changes directly to the file, run `mvn spotless:apply`
Ref: https://github.com/diffplug/spotless/tree/main/plugin-maven
-->
<plugin>
<groupId>com.diffplug.spotless</groupId>
<artifactId>spotless-maven-plugin</artifactId>
<version>${spotless.version}</version>
<configuration>
<formats>
<!-- you can define as many formats as you want, each is independent -->
<format>
<!-- define the files to apply to -->
<includes>
<include>.gitignore</include>
</includes>
<!-- define the steps to apply to those files -->
<trimTrailingWhitespace/>
<endWithNewline/>
<indent>
<spaces>true</spaces> <!-- or <tabs>true</tabs> -->
<spacesPerTab>4</spacesPerTab> <!-- optional, default is 4 -->
</indent>
</format>
</formats>
<!-- define a language-specific format -->
<java>
<!-- no need to specify files, inferred automatically, but you can if you want -->
<!-- apply a specific flavor of google-java-format and reflow long strings -->
<googleJavaFormat>
<version>1.8</version>
<style>AOSP</style>
<reflowLongStrings>true</reflowLongStrings>
</googleJavaFormat>
<removeUnusedImports/>
<importOrder/>
</java>
</configuration>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>sign-artifacts</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>3.0.1</version>
<executions>
<execution>
<id>sign-artifacts</id>
<phase>verify</phase>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
<dependencies>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>${swagger-core-version}</version>
</dependency>
<!-- @Nullable annotation -->
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>${okhttp-version}</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>logging-interceptor</artifactId>
<version>${okhttp-version}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson-version}</version>
</dependency>
<dependency>
<groupId>io.gsonfire</groupId>
<artifactId>gson-fire</artifactId>
<version>${gson-fire-version}</version>
</dependency>
{{#hasOAuthMethods}}
<dependency>
<groupId>org.apache.oltu.oauth2</groupId>
<artifactId>org.apache.oltu.oauth2.client</artifactId>
<version>1.0.1</version>
</dependency>
{{/hasOAuthMethods}}
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3-version}</version>
</dependency>
{{#joda}}
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${jodatime-version}</version>
</dependency>
{{/joda}}
{{#threetenbp}}
<dependency>
<groupId>org.threeten</groupId>
<artifactId>threetenbp</artifactId>
<version>${threetenbp-version}</version>
</dependency>
{{/threetenbp}}
{{#dynamicOperations}}
<dependency>
<groupId>io.swagger.parser.v3</groupId>
<artifactId>swagger-parser-v3</artifactId>
<version>2.0.28</version>
</dependency>
{{/dynamicOperations}}
{{#useBeanValidation}}
<!-- Bean Validation API support -->
<dependency>
<groupId>jakarta.validation</groupId>
<artifactId>jakarta.validation-api</artifactId>
<version>${beanvalidation-version}</version>
<scope>provided</scope>
</dependency>
{{/useBeanValidation}}
{{#performBeanValidation}}
<!-- Bean Validation Impl. used to perform BeanValidation -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.4.3.Final</version>
</dependency>
<dependency>
<groupId>jakarta.el</groupId>
<artifactId>jakarta.el-api</artifactId>
<version>${jakarta.el-version}</version>
</dependency>
{{/performBeanValidation}}
{{#parcelableModel}}
<!-- Needed for Parcelable support-->
<dependency>
<groupId>com.google.android</groupId>
<artifactId>android</artifactId>
<version>4.1.1.4</version>
<scope>provided</scope>
</dependency>
{{/parcelableModel}}
<dependency>
<groupId>jakarta.annotation</groupId>
<artifactId>jakarta.annotation-api</artifactId>
<version>${jakarta-annotation-version}</version>
<scope>provided</scope>
</dependency>
{{#openApiNullable}}
<dependency>
<groupId>org.openapitools</groupId>
<artifactId>jackson-databind-nullable</artifactId>
<version>${jackson-databind-nullable-version}</version>
</dependency>
{{/openApiNullable}}
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0</version>
</dependency>
<!-- test dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.12.4</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<java.version>1.8</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<gson-fire-version>1.8.5</gson-fire-version>
<swagger-core-version>1.6.3</swagger-core-version>
<okhttp-version>4.9.2</okhttp-version>
<gson-version>2.8.8</gson-version>
<commons-lang3-version>3.12.0</commons-lang3-version>
{{#openApiNullable}}
<jackson-databind-nullable-version>0.2.2</jackson-databind-nullable-version>
{{/openApiNullable}}
{{#joda}}
<jodatime-version>2.10.9</jodatime-version>
{{/joda}}
{{#threetenbp}}
<threetenbp-version>1.5.0</threetenbp-version>
{{/threetenbp}}
<jakarta-annotation-version>1.3.5</jakarta-annotation-version>
{{#performBeanValidation}}
<jakarta.el-version>3.0.3</jakarta.el-version>
{{/performBeanValidation}}
{{#useBeanValidation}}
<beanvalidation-version>2.0.2</beanvalidation-version>
{{/useBeanValidation}}
<junit-version>4.13.2</junit-version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spotless.version>2.17.3</spotless.version>
</properties>
</project>

View File

@@ -1303,6 +1303,7 @@ public class ApiClient {
/**
* Build HTTP call with the given options.
*
* @param baseUrl The base URL
* @param path The sub-path of the HTTP URL
* @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE"
* @param queryParams The query parameters
@@ -1325,6 +1326,7 @@ public class ApiClient {
/**
* Build an HTTP request with the given options.
*
* @param baseUrl The base URL
* @param path The sub-path of the HTTP URL
* @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE"
* @param queryParams The query parameters
@@ -1393,6 +1395,7 @@ public class ApiClient {
/**
* Build full URL by concatenating base path, the given sub path and query parameters.
*
* @param baseUrl The base URL
* @param path The sub path
* @param queryParams The query parameters
* @param collectionQueryParams The collection query parameters
@@ -1487,6 +1490,7 @@ public class ApiClient {
* @param payload HTTP request body
* @param method HTTP method
* @param uri URI
* @throws org.openapitools.client.ApiException If fails to update the parameters
*/
public void updateParamsForAuth(String[] authNames, List<Pair> queryParams, Map<String, String> headerParams,
Map<String, String> cookieParams, String payload, String method, URI uri) throws ApiException {

View File

@@ -51,6 +51,7 @@ import java.util.Map;
import java.io.InputStream;
{{/supportStreaming}}
{{/fullJavaUtil}}
import javax.ws.rs.core.GenericType;
{{#operations}}
public class {{classname}} {
@@ -119,7 +120,6 @@ public class {{classname}} {
{{/isDeprecated}}
public{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}private{{/vendorExtensions.x-group-parameters}} okhttp3.Call {{operationId}}Call({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { {{#servers}}"{{{url}}}"{{^-last}}, {{/-last}}{{/servers}} };
@@ -326,13 +326,32 @@ public class {{classname}} {
{{/isDeprecated}}
public{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}private{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-streaming}} InputStream {{operationId}}WithHttpInfo({{#allParams}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws ApiException {
okhttp3.Call localVarCall = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}null);
{{#returnType}}Type localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType();
return localVarApiClient.executeStream(localVarCall, localVarReturnType);{{/returnType}}
{{#returnType}}
try {
Type localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType();
return localVarApiClient.executeStream(localVarCall, localVarReturnType);
} catch (ApiException e) {
e.setErrorObject(localVarApiClient.getJSON().getGson().fromJson(e.getResponseBody(), new TypeToken<{{{errorObjectType}}}{{^errorObjectType}}{{{returnType}}}{{/errorObjectType}}>(){}.getType()));
e.setErrorObjectType(new GenericType<{{{errorObjectType}}}{{^errorObjectType}}{{{returnType}}}{{/errorObjectType}}>(){});
throw e;
}
{{/returnType}}
}
{{/vendorExtensions.x-streaming}}{{^vendorExtensions.x-streaming}} ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws ApiException {
okhttp3.Call localVarCall = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}null);
{{#returnType}}Type localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);{{/returnType}}{{^returnType}}return localVarApiClient.execute(localVarCall);{{/returnType}}
{{^returnType}}
return localVarApiClient.execute(localVarCall);
{{/returnType}}
{{#returnType}}
try {
Type localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
} catch (ApiException e) {
e.setErrorObject(localVarApiClient.getJSON().getGson().fromJson(e.getResponseBody(), new TypeToken<{{{errorObjectType}}}{{^errorObjectType}}{{{returnType}}}{{/errorObjectType}}>(){}.getType()));
e.setErrorObjectType(new GenericType<{{{errorObjectType}}}{{^errorObjectType}}{{{returnType}}}{{/errorObjectType}}>(){});
throw e;
}
{{/returnType}}
}
{{/vendorExtensions.x-streaming}}

View File

@@ -9,6 +9,8 @@ import java.util.Map.Entry;
import java.util.TreeMap;
{{/caseInsensitiveResponseHeaders}}
import javax.ws.rs.core.GenericType;
/**
* <p>ApiException class.</p>
*/
@@ -18,6 +20,8 @@ public class ApiException extends{{#useRuntimeException}} RuntimeException {{/us
private int code = 0;
private Map<String, List<String>> responseHeaders = null;
private String responseBody = null;
private {{{errorObjectType}}}{{^errorObjectType}}Object{{/errorObjectType}} errorObject = null;
private GenericType errorObjectType = null;
/**
* <p>Constructor for ApiException.</p>
@@ -156,4 +160,40 @@ public class ApiException extends{{#useRuntimeException}} RuntimeException {{/us
public String getResponseBody() {
return responseBody;
}
/**
* Get the error object type.
*
* @return Error object type
*/
public GenericType getErrorObjectType() {
return errorObjectType;
}
/**
* Set the error object type.
*
* @param errorObjectType object type
*/
public void setErrorObjectType(GenericType errorObjectType) {
this.errorObjectType = errorObjectType;
}
/**
* Get the error object.
*
* @return Error object
*/
public {{{errorObjectType}}}{{^errorObjectType}}Object{{/errorObjectType}} getErrorObject() {
return errorObject;
}
/**
* Get the error object.
*
* @param errorObject Error object
*/
public void setErrorObject({{{errorObjectType}}}{{^errorObjectType}}Object{{/errorObjectType}} errorObject) {
this.errorObject = errorObject;
}
}

View File

@@ -29,22 +29,31 @@ public class RetryingOAuth extends OAuth implements Interceptor {
private TokenRequestBuilder tokenRequestBuilder;
/**
* @param client An OkHttp client
* @param tokenRequestBuilder A token request builder
*/
public RetryingOAuth(OkHttpClient client, TokenRequestBuilder tokenRequestBuilder) {
this.oAuthClient = new OAuthClient(new OAuthOkHttpClient(client));
this.tokenRequestBuilder = tokenRequestBuilder;
}
/**
* @param tokenRequestBuilder A token request builder
*/
public RetryingOAuth(TokenRequestBuilder tokenRequestBuilder) {
this(new OkHttpClient(), tokenRequestBuilder);
}
/**
@param tokenUrl The token URL to be used for this OAuth2 flow.
Applicable to the following OAuth2 flows: "password", "clientCredentials" and "authorizationCode".
The value must be an absolute URL.
@param clientId The OAuth2 client ID for the "clientCredentials" flow.
@param clientSecret The OAuth2 client secret for the "clientCredentials" flow.
*/
* @param tokenUrl The token URL to be used for this OAuth2 flow.
* Applicable to the following OAuth2 flows: "password", "clientCredentials" and "authorizationCode".
* The value must be an absolute URL.
* @param clientId The OAuth2 client ID for the "clientCredentials" flow.
* @param flow OAuth flow.
* @param clientSecret The OAuth2 client secret for the "clientCredentials" flow.
* @param parameters A map of string.
*/
public RetryingOAuth(
String tokenUrl,
String clientId,
@@ -63,6 +72,11 @@ public class RetryingOAuth extends OAuth implements Interceptor {
}
}
/**
* Set the OAuth flow
*
* @param flow The OAuth flow.
*/
public void setFlow(OAuthFlow flow) {
switch(flow) {
case ACCESS_CODE:
@@ -148,8 +162,12 @@ public class RetryingOAuth extends OAuth implements Interceptor {
}
}
/*
/**
* Returns true if the access token has been updated
*
* @param requestAccessToken the request access token
* @return True if the update is successful
* @throws java.io.IOException If fail to update the access token
*/
public synchronized boolean updateAccessToken(String requestAccessToken) throws IOException {
if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) {
@@ -166,10 +184,21 @@ public class RetryingOAuth extends OAuth implements Interceptor {
return getAccessToken() == null || !getAccessToken().equals(requestAccessToken);
}
/**
* Gets the token request builder
*
* @return A token request builder
* @throws java.io.IOException If fail to update the access token
*/
public TokenRequestBuilder getTokenRequestBuilder() {
return tokenRequestBuilder;
}
/**
* Sets the token request builder
*
* @param tokenRequestBuilder Token request builder
*/
public void setTokenRequestBuilder(TokenRequestBuilder tokenRequestBuilder) {
this.tokenRequestBuilder = tokenRequestBuilder;
}

View File

@@ -364,6 +364,16 @@
<version>${jackson-databind-nullable-version}</version>
</dependency>
{{/openApiNullable}}
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0</version>
</dependency>
<!-- test dependencies -->
<dependency>
<groupId>junit</groupId>

View File

@@ -64,7 +64,7 @@ public class DefaultGeneratorTest {
List<File> files = generator.opts(clientOptInput).generate();
Assert.assertEquals(files.size(), 42);
Assert.assertEquals(files.size(), 43);
// Check expected generated files
// api sanity check

View File

@@ -291,7 +291,7 @@ public class JavaClientCodegenTest {
DefaultGenerator generator = new DefaultGenerator();
List<File> files = generator.opts(clientOptInput).generate();
Assert.assertEquals(files.size(), 38);
Assert.assertEquals(files.size(), 39);
TestUtils.ensureContainsFile(files, output, ".gitignore");
TestUtils.ensureContainsFile(files, output, ".openapi-generator-ignore");
TestUtils.ensureContainsFile(files, output, ".openapi-generator/FILES");
@@ -360,7 +360,7 @@ public class JavaClientCodegenTest {
DefaultGenerator generator = new DefaultGenerator();
List<File> files = generator.opts(clientOptInput).generate();
Assert.assertEquals(files.size(), 41);
Assert.assertEquals(files.size(), 42);
TestUtils.ensureContainsFile(files, output, ".gitignore");
TestUtils.ensureContainsFile(files, output, ".openapi-generator-ignore");
TestUtils.ensureContainsFile(files, output, ".openapi-generator/FILES");
@@ -1005,7 +1005,7 @@ public class JavaClientCodegenTest {
DefaultGenerator generator = new DefaultGenerator();
List<File> files = generator.opts(clientOptInput).generate();
Assert.assertEquals(files.size(), 47);
Assert.assertEquals(files.size(), 48);
TestUtils.ensureContainsFile(files, output, "src/main/java/org/openapitools/client/model/RealCommand.java");
TestUtils.ensureContainsFile(files, output, "src/main/java/org/openapitools/client/model/Command.java");

View File

@@ -1346,7 +1346,6 @@
<module>samples/openapi3/client/petstore/java/jersey2-java8</module>
<module>samples/client/others/java/okhttp-gson-streaming</module>
<module>samples/client/petstore/java/okhttp-gson</module>
<!--<module>samples/client/petstore/java/okhttp-gson-nextgen</module>-->
<module>samples/client/petstore/java/retrofit2</module>
<module>samples/client/petstore/java/retrofit2rx2</module>
<module>samples/client/petstore/java/retrofit2rx3</module>

View File

@@ -33,4 +33,5 @@ src/main/java/org/openapitools/client/auth/ApiKeyAuth.java
src/main/java/org/openapitools/client/auth/Authentication.java
src/main/java/org/openapitools/client/auth/HttpBasicAuth.java
src/main/java/org/openapitools/client/auth/HttpBearerAuth.java
src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java
src/main/java/org/openapitools/client/model/SomeObj.java

View File

@@ -301,6 +301,16 @@
<artifactId>jackson-databind-nullable</artifactId>
<version>${jackson-databind-nullable-version}</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0</version>
</dependency>
<!-- test dependencies -->
<dependency>
<groupId>junit</groupId>

View File

@@ -1091,6 +1091,7 @@ public class ApiClient {
/**
* Build HTTP call with the given options.
*
* @param baseUrl The base URL
* @param path The sub-path of the HTTP URL
* @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE"
* @param queryParams The query parameters
@@ -1113,6 +1114,7 @@ public class ApiClient {
/**
* Build an HTTP request with the given options.
*
* @param baseUrl The base URL
* @param path The sub-path of the HTTP URL
* @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE"
* @param queryParams The query parameters
@@ -1181,6 +1183,7 @@ public class ApiClient {
/**
* Build full URL by concatenating base path, the given sub path and query parameters.
*
* @param baseUrl The base URL
* @param path The sub path
* @param queryParams The query parameters
* @param collectionQueryParams The collection query parameters
@@ -1275,6 +1278,7 @@ public class ApiClient {
* @param payload HTTP request body
* @param method HTTP method
* @param uri URI
* @throws org.openapitools.client.ApiException If fails to update the parameters
*/
public void updateParamsForAuth(String[] authNames, List<Pair> queryParams, Map<String, String> headerParams,
Map<String, String> cookieParams, String payload, String method, URI uri) throws ApiException {

View File

@@ -16,6 +16,8 @@ package org.openapitools.client;
import java.util.Map;
import java.util.List;
import javax.ws.rs.core.GenericType;
/**
* <p>ApiException class.</p>
*/
@@ -25,6 +27,8 @@ public class ApiException extends Exception {
private int code = 0;
private Map<String, List<String>> responseHeaders = null;
private String responseBody = null;
private Object errorObject = null;
private GenericType errorObjectType = null;
/**
* <p>Constructor for ApiException.</p>
@@ -151,4 +155,40 @@ public class ApiException extends Exception {
public String getResponseBody() {
return responseBody;
}
/**
* Get the error object type.
*
* @return Error object type
*/
public GenericType getErrorObjectType() {
return errorObjectType;
}
/**
* Set the error object type.
*
* @param errorObjectType object type
*/
public void setErrorObjectType(GenericType errorObjectType) {
this.errorObjectType = errorObjectType;
}
/**
* Get the error object.
*
* @return Error object
*/
public Object getErrorObject() {
return errorObject;
}
/**
* Get the error object.
*
* @param errorObject Error object
*/
public void setErrorObject(Object errorObject) {
this.errorObject = errorObject;
}
}

View File

@@ -27,7 +27,6 @@ import org.threeten.bp.LocalDate;
import org.threeten.bp.OffsetDateTime;
import org.threeten.bp.format.DateTimeFormatter;
import org.openapitools.client.model.*;
import okio.ByteString;
import java.io.IOException;
@@ -41,14 +40,20 @@ import java.util.Locale;
import java.util.Map;
import java.util.HashMap;
/*
* A JSON utility class
*
* NOTE: in the future, this class may be converted to static, which may break
* backward-compatibility
*/
public class JSON {
private Gson gson;
private boolean isLenientOnJson = false;
private DateTypeAdapter dateTypeAdapter = new DateTypeAdapter();
private SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter();
private OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter();
private LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter();
private ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter();
private static Gson gson;
private static boolean isLenientOnJson = false;
private static DateTypeAdapter dateTypeAdapter = new DateTypeAdapter();
private static SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter();
private static OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter();
private static LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter();
private static ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter();
@SuppressWarnings("unchecked")
public static GsonBuilder createGson() {
@@ -81,13 +86,14 @@ public class JSON {
return clazz;
}
public JSON() {
{
gson = createGson()
.registerTypeAdapter(Date.class, dateTypeAdapter)
.registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter)
.registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter)
.registerTypeAdapter(LocalDate.class, localDateTypeAdapter)
.registerTypeAdapter(byte[].class, byteArrayAdapter)
.registerTypeAdapterFactory(new org.openapitools.client.model.SomeObj.CustomTypeAdapterFactory())
.create();
}
@@ -96,7 +102,7 @@ public class JSON {
*
* @return Gson
*/
public Gson getGson() {
public static Gson getGson() {
return gson;
}
@@ -104,23 +110,13 @@ public class JSON {
* Set Gson.
*
* @param gson Gson
* @return JSON
*/
public JSON setGson(Gson gson) {
this.gson = gson;
return this;
public static void setGson(Gson gson) {
JSON.gson = gson;
}
/**
* Configure the parser to be liberal in what it accepts.
*
* @param lenientOnJson Set it to true to ignore some syntax errors
* @return JSON
* @see <a href="https://www.javadoc.io/doc/com.google.code.gson/gson/2.8.5/com/google/gson/stream/JsonReader.html">https://www.javadoc.io/doc/com.google.code.gson/gson/2.8.5/com/google/gson/stream/JsonReader.html</a>
*/
public JSON setLenientOnJson(boolean lenientOnJson) {
public static void setLenientOnJson(boolean lenientOnJson) {
isLenientOnJson = lenientOnJson;
return this;
}
/**
@@ -129,7 +125,7 @@ public class JSON {
* @param obj Object
* @return String representation of the JSON
*/
public String serialize(Object obj) {
public static String serialize(Object obj) {
return gson.toJson(obj);
}
@@ -142,11 +138,11 @@ public class JSON {
* @return The deserialized Java object
*/
@SuppressWarnings("unchecked")
public <T> T deserialize(String body, Type returnType) {
public static <T> T deserialize(String body, Type returnType) {
try {
if (isLenientOnJson) {
JsonReader jsonReader = new JsonReader(new StringReader(body));
// see https://www.javadoc.io/doc/com.google.code.gson/gson/2.8.5/com/google/gson/stream/JsonReader.html
// see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean)
jsonReader.setLenient(true);
return gson.fromJson(jsonReader, returnType);
} else {
@@ -166,7 +162,7 @@ public class JSON {
/**
* Gson TypeAdapter for Byte Array type
*/
public class ByteArrayAdapter extends TypeAdapter<byte[]> {
public static class ByteArrayAdapter extends TypeAdapter<byte[]> {
@Override
public void write(JsonWriter out, byte[] value) throws IOException {
@@ -238,7 +234,7 @@ public class JSON {
/**
* Gson TypeAdapter for JSR310 LocalDate type
*/
public class LocalDateTypeAdapter extends TypeAdapter<LocalDate> {
public static class LocalDateTypeAdapter extends TypeAdapter<LocalDate> {
private DateTimeFormatter formatter;
@@ -276,14 +272,12 @@ public class JSON {
}
}
public JSON setOffsetDateTimeFormat(DateTimeFormatter dateFormat) {
public static void setOffsetDateTimeFormat(DateTimeFormatter dateFormat) {
offsetDateTimeTypeAdapter.setFormat(dateFormat);
return this;
}
public JSON setLocalDateFormat(DateTimeFormatter dateFormat) {
public static void setLocalDateFormat(DateTimeFormatter dateFormat) {
localDateTypeAdapter.setFormat(dateFormat);
return this;
}
/**
@@ -397,14 +391,11 @@ public class JSON {
}
}
public JSON setDateFormat(DateFormat dateFormat) {
public static void setDateFormat(DateFormat dateFormat) {
dateTypeAdapter.setFormat(dateFormat);
return this;
}
public JSON setSqlDateFormat(DateFormat dateFormat) {
public static void setSqlDateFormat(DateFormat dateFormat) {
sqlDateTypeAdapter.setFormat(dateFormat);
return this;
}
}

View File

@@ -35,6 +35,7 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.InputStream;
import javax.ws.rs.core.GenericType;
public class PingApi {
private ApiClient localVarApiClient;
@@ -87,7 +88,6 @@ public class PingApi {
*/
public okhttp3.Call postPingCall(SomeObj someObj, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -171,8 +171,14 @@ public class PingApi {
*/
public InputStream postPingWithHttpInfo(SomeObj someObj) throws ApiException {
okhttp3.Call localVarCall = postPingValidateBeforeCall(someObj, null);
Type localVarReturnType = new TypeToken<SomeObj>(){}.getType();
return localVarApiClient.executeStream(localVarCall, localVarReturnType);
try {
Type localVarReturnType = new TypeToken<SomeObj>(){}.getType();
return localVarApiClient.executeStream(localVarCall, localVarReturnType);
} catch (ApiException e) {
e.setErrorObject(localVarApiClient.getJSON().getGson().fromJson(e.getResponseBody(), new TypeToken<SomeObj>(){}.getType()));
e.setErrorObjectType(new GenericType<SomeObj>(){});
throw e;
}
}
/**

View File

@@ -0,0 +1,149 @@
/*
* ping some object
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 1.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.client.model;
import org.openapitools.client.ApiException;
import java.util.Objects;
import java.lang.reflect.Type;
import java.util.Map;
import javax.ws.rs.core.GenericType;
//import com.fasterxml.jackson.annotation.JsonValue;
/**
* Abstract class for oneOf,anyOf schemas defined in OpenAPI spec
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen")
public abstract class AbstractOpenApiSchema {
// store the actual instance of the schema/object
private Object instance;
// is nullable
private Boolean isNullable;
// schema type (e.g. oneOf, anyOf)
private final String schemaType;
public AbstractOpenApiSchema(String schemaType, Boolean isNullable) {
this.schemaType = schemaType;
this.isNullable = isNullable;
}
/**
* Get the list of oneOf/anyOf composed schemas allowed to be stored in this object
*
* @return an instance of the actual schema/object
*/
public abstract Map<String, GenericType> getSchemas();
/**
* Get the actual instance
*
* @return an instance of the actual schema/object
*/
//@JsonValue
public Object getActualInstance() {return instance;}
/**
* Set the actual instance
*
* @param instance the actual instance of the schema/object
*/
public void setActualInstance(Object instance) {this.instance = instance;}
/**
* Get the instant recursively when the schemas defined in oneOf/anyof happen to be oneOf/anyOf schema as well
*
* @return an instance of the actual schema/object
*/
public Object getActualInstanceRecursively() {
return getActualInstanceRecursively(this);
}
private Object getActualInstanceRecursively(AbstractOpenApiSchema object) {
if (object.getActualInstance() == null) {
return null;
} else if (object.getActualInstance() instanceof AbstractOpenApiSchema) {
return getActualInstanceRecursively((AbstractOpenApiSchema)object.getActualInstance());
} else {
return object.getActualInstance();
}
}
/**
* Get the schema type (e.g. anyOf, oneOf)
*
* @return the schema type
*/
public String getSchemaType() {
return schemaType;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ").append(getClass()).append(" {\n");
sb.append(" instance: ").append(toIndentedString(instance)).append("\n");
sb.append(" isNullable: ").append(toIndentedString(isNullable)).append("\n");
sb.append(" schemaType: ").append(toIndentedString(schemaType)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AbstractOpenApiSchema a = (AbstractOpenApiSchema) o;
return Objects.equals(this.instance, a.instance) &&
Objects.equals(this.isNullable, a.isNullable) &&
Objects.equals(this.schemaType, a.schemaType);
}
@Override
public int hashCode() {
return Objects.hash(instance, isNullable, schemaType);
}
/**
* Is nullable
*
* @return true if it's nullable
*/
public Boolean isNullable() {
if (Boolean.TRUE.equals(isNullable)) {
return Boolean.TRUE;
} else {
return Boolean.FALSE;
}
}
}

View File

@@ -24,6 +24,25 @@ import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* SomeObj
*/
@@ -257,5 +276,93 @@ public class SomeObj {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("$_type");
openapiFields.add("id");
openapiFields.add("name");
openapiFields.add("active");
openapiFields.add("type");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to SomeObj
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (SomeObj.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in SomeObj is not found in the empty JSON string", SomeObj.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!SomeObj.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `SomeObj` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!SomeObj.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'SomeObj' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<SomeObj> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(SomeObj.class));
return (TypeAdapter<T>) new TypeAdapter<SomeObj>() {
@Override
public void write(JsonWriter out, SomeObj value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public SomeObj read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of SomeObj given an JSON string
*
* @param jsonString JSON string
* @return An instance of SomeObj
* @throws IOException if the JSON string is invalid with respect to SomeObj
*/
public static SomeObj fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, SomeObj.class);
}
/**
* Convert an instance of SomeObj to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -94,6 +94,7 @@ src/main/java/org/openapitools/client/auth/OAuth.java
src/main/java/org/openapitools/client/auth/OAuthFlow.java
src/main/java/org/openapitools/client/auth/OAuthOkHttpClient.java
src/main/java/org/openapitools/client/auth/RetryingOAuth.java
src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java
src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java
src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java
src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java

View File

@@ -311,6 +311,16 @@
<artifactId>jackson-databind-nullable</artifactId>
<version>${jackson-databind-nullable-version}</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0</version>
</dependency>
<!-- test dependencies -->
<dependency>
<groupId>junit</groupId>

View File

@@ -1169,6 +1169,7 @@ public class ApiClient {
/**
* Build HTTP call with the given options.
*
* @param baseUrl The base URL
* @param path The sub-path of the HTTP URL
* @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE"
* @param queryParams The query parameters
@@ -1191,6 +1192,7 @@ public class ApiClient {
/**
* Build an HTTP request with the given options.
*
* @param baseUrl The base URL
* @param path The sub-path of the HTTP URL
* @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE"
* @param queryParams The query parameters
@@ -1259,6 +1261,7 @@ public class ApiClient {
/**
* Build full URL by concatenating base path, the given sub path and query parameters.
*
* @param baseUrl The base URL
* @param path The sub path
* @param queryParams The query parameters
* @param collectionQueryParams The collection query parameters
@@ -1353,6 +1356,7 @@ public class ApiClient {
* @param payload HTTP request body
* @param method HTTP method
* @param uri URI
* @throws org.openapitools.client.ApiException If fails to update the parameters
*/
public void updateParamsForAuth(String[] authNames, List<Pair> queryParams, Map<String, String> headerParams,
Map<String, String> cookieParams, String payload, String method, URI uri) throws ApiException {

View File

@@ -16,6 +16,8 @@ package org.openapitools.client;
import java.util.Map;
import java.util.List;
import javax.ws.rs.core.GenericType;
/**
* <p>ApiException class.</p>
*/
@@ -25,6 +27,8 @@ public class ApiException extends Exception {
private int code = 0;
private Map<String, List<String>> responseHeaders = null;
private String responseBody = null;
private Object errorObject = null;
private GenericType errorObjectType = null;
/**
* <p>Constructor for ApiException.</p>
@@ -151,4 +155,40 @@ public class ApiException extends Exception {
public String getResponseBody() {
return responseBody;
}
/**
* Get the error object type.
*
* @return Error object type
*/
public GenericType getErrorObjectType() {
return errorObjectType;
}
/**
* Set the error object type.
*
* @param errorObjectType object type
*/
public void setErrorObjectType(GenericType errorObjectType) {
this.errorObjectType = errorObjectType;
}
/**
* Get the error object.
*
* @return Error object
*/
public Object getErrorObject() {
return errorObject;
}
/**
* Get the error object.
*
* @param errorObject Error object
*/
public void setErrorObject(Object errorObject) {
this.errorObject = errorObject;
}
}

View File

@@ -27,7 +27,6 @@ import org.threeten.bp.LocalDate;
import org.threeten.bp.OffsetDateTime;
import org.threeten.bp.format.DateTimeFormatter;
import org.openapitools.client.model.*;
import okio.ByteString;
import java.io.IOException;
@@ -41,54 +40,60 @@ import java.util.Locale;
import java.util.Map;
import java.util.HashMap;
/*
* A JSON utility class
*
* NOTE: in the future, this class may be converted to static, which may break
* backward-compatibility
*/
public class JSON {
private Gson gson;
private boolean isLenientOnJson = false;
private DateTypeAdapter dateTypeAdapter = new DateTypeAdapter();
private SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter();
private OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter();
private LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter();
private ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter();
private static Gson gson;
private static boolean isLenientOnJson = false;
private static DateTypeAdapter dateTypeAdapter = new DateTypeAdapter();
private static SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter();
private static OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter();
private static LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter();
private static ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter();
@SuppressWarnings("unchecked")
public static GsonBuilder createGson() {
GsonFireBuilder fireBuilder = new GsonFireBuilder()
.registerTypeSelector(Animal.class, new TypeSelector<Animal>() {
.registerTypeSelector(org.openapitools.client.model.Animal.class, new TypeSelector<org.openapitools.client.model.Animal>() {
@Override
public Class<? extends Animal> getClassForElement(JsonElement readElement) {
public Class<? extends org.openapitools.client.model.Animal> getClassForElement(JsonElement readElement) {
Map<String, Class> classByDiscriminatorValue = new HashMap<String, Class>();
classByDiscriminatorValue.put("BigCat", BigCat.class);
classByDiscriminatorValue.put("Cat", Cat.class);
classByDiscriminatorValue.put("Dog", Dog.class);
classByDiscriminatorValue.put("Animal", Animal.class);
classByDiscriminatorValue.put("BigCat", org.openapitools.client.model.BigCat.class);
classByDiscriminatorValue.put("Cat", org.openapitools.client.model.Cat.class);
classByDiscriminatorValue.put("Dog", org.openapitools.client.model.Dog.class);
classByDiscriminatorValue.put("Animal", org.openapitools.client.model.Animal.class);
return getClassByDiscriminator(classByDiscriminatorValue,
getDiscriminatorValue(readElement, "className"));
}
})
.registerTypeSelector(BigCat.class, new TypeSelector<BigCat>() {
.registerTypeSelector(org.openapitools.client.model.BigCat.class, new TypeSelector<org.openapitools.client.model.BigCat>() {
@Override
public Class<? extends BigCat> getClassForElement(JsonElement readElement) {
public Class<? extends org.openapitools.client.model.BigCat> getClassForElement(JsonElement readElement) {
Map<String, Class> classByDiscriminatorValue = new HashMap<String, Class>();
classByDiscriminatorValue.put("BigCat", BigCat.class);
classByDiscriminatorValue.put("BigCat", org.openapitools.client.model.BigCat.class);
return getClassByDiscriminator(classByDiscriminatorValue,
getDiscriminatorValue(readElement, "className"));
}
})
.registerTypeSelector(Cat.class, new TypeSelector<Cat>() {
.registerTypeSelector(org.openapitools.client.model.Cat.class, new TypeSelector<org.openapitools.client.model.Cat>() {
@Override
public Class<? extends Cat> getClassForElement(JsonElement readElement) {
public Class<? extends org.openapitools.client.model.Cat> getClassForElement(JsonElement readElement) {
Map<String, Class> classByDiscriminatorValue = new HashMap<String, Class>();
classByDiscriminatorValue.put("BigCat", BigCat.class);
classByDiscriminatorValue.put("Cat", Cat.class);
classByDiscriminatorValue.put("BigCat", org.openapitools.client.model.BigCat.class);
classByDiscriminatorValue.put("Cat", org.openapitools.client.model.Cat.class);
return getClassByDiscriminator(classByDiscriminatorValue,
getDiscriminatorValue(readElement, "className"));
}
})
.registerTypeSelector(Dog.class, new TypeSelector<Dog>() {
.registerTypeSelector(org.openapitools.client.model.Dog.class, new TypeSelector<org.openapitools.client.model.Dog>() {
@Override
public Class<? extends Dog> getClassForElement(JsonElement readElement) {
public Class<? extends org.openapitools.client.model.Dog> getClassForElement(JsonElement readElement) {
Map<String, Class> classByDiscriminatorValue = new HashMap<String, Class>();
classByDiscriminatorValue.put("Dog", Dog.class);
classByDiscriminatorValue.put("Dog", org.openapitools.client.model.Dog.class);
return getClassByDiscriminator(classByDiscriminatorValue,
getDiscriminatorValue(readElement, "className"));
}
@@ -121,13 +126,57 @@ public class JSON {
return clazz;
}
public JSON() {
{
gson = createGson()
.registerTypeAdapter(Date.class, dateTypeAdapter)
.registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter)
.registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter)
.registerTypeAdapter(LocalDate.class, localDateTypeAdapter)
.registerTypeAdapter(byte[].class, byteArrayAdapter)
.registerTypeAdapterFactory(new org.openapitools.client.model.AdditionalPropertiesAnyType.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.AdditionalPropertiesArray.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.AdditionalPropertiesBoolean.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.AdditionalPropertiesClass.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.AdditionalPropertiesInteger.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.AdditionalPropertiesNumber.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.AdditionalPropertiesObject.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.AdditionalPropertiesString.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.ArrayOfArrayOfNumberOnly.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.ArrayOfNumberOnly.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.ArrayTest.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.BigCat.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.BigCatAllOf.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.Capitalization.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.CatAllOf.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.Category.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.ClassModel.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.Client.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.Dog.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.DogAllOf.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.EnumArrays.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.EnumTest.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.FileSchemaTestClass.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.FormatTest.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.HasOnlyReadOnly.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.MapTest.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.MixedPropertiesAndAdditionalPropertiesClass.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.Model200Response.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.ModelApiResponse.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.ModelFile.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.ModelList.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.ModelReturn.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.Name.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.NumberOnly.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.Order.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.OuterComposite.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.Pet.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.ReadOnlyFirst.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.SpecialModelName.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.Tag.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.TypeHolderDefault.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.TypeHolderExample.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.User.CustomTypeAdapterFactory())
.registerTypeAdapterFactory(new org.openapitools.client.model.XmlItem.CustomTypeAdapterFactory())
.create();
}
@@ -136,7 +185,7 @@ public class JSON {
*
* @return Gson
*/
public Gson getGson() {
public static Gson getGson() {
return gson;
}
@@ -144,23 +193,13 @@ public class JSON {
* Set Gson.
*
* @param gson Gson
* @return JSON
*/
public JSON setGson(Gson gson) {
this.gson = gson;
return this;
public static void setGson(Gson gson) {
JSON.gson = gson;
}
/**
* Configure the parser to be liberal in what it accepts.
*
* @param lenientOnJson Set it to true to ignore some syntax errors
* @return JSON
* @see <a href="https://www.javadoc.io/doc/com.google.code.gson/gson/2.8.5/com/google/gson/stream/JsonReader.html">https://www.javadoc.io/doc/com.google.code.gson/gson/2.8.5/com/google/gson/stream/JsonReader.html</a>
*/
public JSON setLenientOnJson(boolean lenientOnJson) {
public static void setLenientOnJson(boolean lenientOnJson) {
isLenientOnJson = lenientOnJson;
return this;
}
/**
@@ -169,7 +208,7 @@ public class JSON {
* @param obj Object
* @return String representation of the JSON
*/
public String serialize(Object obj) {
public static String serialize(Object obj) {
return gson.toJson(obj);
}
@@ -182,11 +221,11 @@ public class JSON {
* @return The deserialized Java object
*/
@SuppressWarnings("unchecked")
public <T> T deserialize(String body, Type returnType) {
public static <T> T deserialize(String body, Type returnType) {
try {
if (isLenientOnJson) {
JsonReader jsonReader = new JsonReader(new StringReader(body));
// see https://www.javadoc.io/doc/com.google.code.gson/gson/2.8.5/com/google/gson/stream/JsonReader.html
// see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean)
jsonReader.setLenient(true);
return gson.fromJson(jsonReader, returnType);
} else {
@@ -206,7 +245,7 @@ public class JSON {
/**
* Gson TypeAdapter for Byte Array type
*/
public class ByteArrayAdapter extends TypeAdapter<byte[]> {
public static class ByteArrayAdapter extends TypeAdapter<byte[]> {
@Override
public void write(JsonWriter out, byte[] value) throws IOException {
@@ -278,7 +317,7 @@ public class JSON {
/**
* Gson TypeAdapter for JSR310 LocalDate type
*/
public class LocalDateTypeAdapter extends TypeAdapter<LocalDate> {
public static class LocalDateTypeAdapter extends TypeAdapter<LocalDate> {
private DateTimeFormatter formatter;
@@ -316,14 +355,12 @@ public class JSON {
}
}
public JSON setOffsetDateTimeFormat(DateTimeFormatter dateFormat) {
public static void setOffsetDateTimeFormat(DateTimeFormatter dateFormat) {
offsetDateTimeTypeAdapter.setFormat(dateFormat);
return this;
}
public JSON setLocalDateFormat(DateTimeFormatter dateFormat) {
public static void setLocalDateFormat(DateTimeFormatter dateFormat) {
localDateTypeAdapter.setFormat(dateFormat);
return this;
}
/**
@@ -437,14 +474,11 @@ public class JSON {
}
}
public JSON setDateFormat(DateFormat dateFormat) {
public static void setDateFormat(DateFormat dateFormat) {
dateTypeAdapter.setFormat(dateFormat);
return this;
}
public JSON setSqlDateFormat(DateFormat dateFormat) {
public static void setSqlDateFormat(DateFormat dateFormat) {
sqlDateTypeAdapter.setFormat(dateFormat);
return this;
}
}

View File

@@ -37,6 +37,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.core.GenericType;
public class AnotherFakeApi {
private ApiClient localVarApiClient;
@@ -89,7 +90,6 @@ public class AnotherFakeApi {
*/
public okhttp3.Call call123testSpecialTagsCall(Client body, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -186,8 +186,14 @@ public class AnotherFakeApi {
*/
public ApiResponse<Client> call123testSpecialTagsWithHttpInfo(Client body) throws ApiException {
okhttp3.Call localVarCall = call123testSpecialTagsValidateBeforeCall(body, null);
Type localVarReturnType = new TypeToken<Client>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
try {
Type localVarReturnType = new TypeToken<Client>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
} catch (ApiException e) {
e.setErrorObject(localVarApiClient.getJSON().getGson().fromJson(e.getResponseBody(), new TypeToken<Client>(){}.getType()));
e.setErrorObjectType(new GenericType<Client>(){});
throw e;
}
}
/**

View File

@@ -45,6 +45,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.core.GenericType;
public class FakeApi {
private ApiClient localVarApiClient;
@@ -97,7 +98,6 @@ public class FakeApi {
*/
public okhttp3.Call createXmlItemCall(XmlItem xmlItem, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -228,7 +228,6 @@ public class FakeApi {
*/
public okhttp3.Call fakeOuterBooleanSerializeCall(Boolean body, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -320,8 +319,14 @@ public class FakeApi {
*/
public ApiResponse<Boolean> fakeOuterBooleanSerializeWithHttpInfo(Boolean body) throws ApiException {
okhttp3.Call localVarCall = fakeOuterBooleanSerializeValidateBeforeCall(body, null);
Type localVarReturnType = new TypeToken<Boolean>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
try {
Type localVarReturnType = new TypeToken<Boolean>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
} catch (ApiException e) {
e.setErrorObject(localVarApiClient.getJSON().getGson().fromJson(e.getResponseBody(), new TypeToken<Boolean>(){}.getType()));
e.setErrorObjectType(new GenericType<Boolean>(){});
throw e;
}
}
/**
@@ -358,7 +363,6 @@ public class FakeApi {
*/
public okhttp3.Call fakeOuterCompositeSerializeCall(OuterComposite body, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -450,8 +454,14 @@ public class FakeApi {
*/
public ApiResponse<OuterComposite> fakeOuterCompositeSerializeWithHttpInfo(OuterComposite body) throws ApiException {
okhttp3.Call localVarCall = fakeOuterCompositeSerializeValidateBeforeCall(body, null);
Type localVarReturnType = new TypeToken<OuterComposite>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
try {
Type localVarReturnType = new TypeToken<OuterComposite>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
} catch (ApiException e) {
e.setErrorObject(localVarApiClient.getJSON().getGson().fromJson(e.getResponseBody(), new TypeToken<OuterComposite>(){}.getType()));
e.setErrorObjectType(new GenericType<OuterComposite>(){});
throw e;
}
}
/**
@@ -488,7 +498,6 @@ public class FakeApi {
*/
public okhttp3.Call fakeOuterNumberSerializeCall(BigDecimal body, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -580,8 +589,14 @@ public class FakeApi {
*/
public ApiResponse<BigDecimal> fakeOuterNumberSerializeWithHttpInfo(BigDecimal body) throws ApiException {
okhttp3.Call localVarCall = fakeOuterNumberSerializeValidateBeforeCall(body, null);
Type localVarReturnType = new TypeToken<BigDecimal>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
try {
Type localVarReturnType = new TypeToken<BigDecimal>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
} catch (ApiException e) {
e.setErrorObject(localVarApiClient.getJSON().getGson().fromJson(e.getResponseBody(), new TypeToken<BigDecimal>(){}.getType()));
e.setErrorObjectType(new GenericType<BigDecimal>(){});
throw e;
}
}
/**
@@ -618,7 +633,6 @@ public class FakeApi {
*/
public okhttp3.Call fakeOuterStringSerializeCall(String body, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -710,8 +724,14 @@ public class FakeApi {
*/
public ApiResponse<String> fakeOuterStringSerializeWithHttpInfo(String body) throws ApiException {
okhttp3.Call localVarCall = fakeOuterStringSerializeValidateBeforeCall(body, null);
Type localVarReturnType = new TypeToken<String>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
try {
Type localVarReturnType = new TypeToken<String>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
} catch (ApiException e) {
e.setErrorObject(localVarApiClient.getJSON().getGson().fromJson(e.getResponseBody(), new TypeToken<String>(){}.getType()));
e.setErrorObjectType(new GenericType<String>(){});
throw e;
}
}
/**
@@ -748,7 +768,6 @@ public class FakeApi {
*/
public okhttp3.Call testBodyWithFileSchemaCall(FileSchemaTestClass body, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -880,7 +899,6 @@ public class FakeApi {
*/
public okhttp3.Call testBodyWithQueryParamsCall(String query, User body, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -1020,7 +1038,6 @@ public class FakeApi {
*/
public okhttp3.Call testClientModelCall(Client body, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -1117,8 +1134,14 @@ public class FakeApi {
*/
public ApiResponse<Client> testClientModelWithHttpInfo(Client body) throws ApiException {
okhttp3.Call localVarCall = testClientModelValidateBeforeCall(body, null);
Type localVarReturnType = new TypeToken<Client>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
try {
Type localVarReturnType = new TypeToken<Client>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
} catch (ApiException e) {
e.setErrorObject(localVarApiClient.getJSON().getGson().fromJson(e.getResponseBody(), new TypeToken<Client>(){}.getType()));
e.setErrorObjectType(new GenericType<Client>(){});
throw e;
}
}
/**
@@ -1169,7 +1192,6 @@ public class FakeApi {
*/
public okhttp3.Call testEndpointParametersCall(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, File binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -1421,7 +1443,6 @@ public class FakeApi {
*/
public okhttp3.Call testEnumParametersCall(List<String> enumHeaderStringArray, String enumHeaderString, List<String> enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, List<String> enumFormStringArray, String enumFormString, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -1573,7 +1594,6 @@ public class FakeApi {
}
private okhttp3.Call testGroupParametersCall(Integer requiredStringGroup, Boolean requiredBooleanGroup, Long requiredInt64Group, Integer stringGroup, Boolean booleanGroup, Long int64Group, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -1800,7 +1820,6 @@ public class FakeApi {
*/
public okhttp3.Call testInlineAdditionalPropertiesCall(Map<String, String> param, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -1932,7 +1951,6 @@ public class FakeApi {
*/
public okhttp3.Call testJsonFormDataCall(String param, String param2, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -2083,7 +2101,6 @@ public class FakeApi {
*/
public okhttp3.Call testQueryParameterCollectionFormatCall(List<String> pipe, List<String> ioutil, List<String> http, List<String> url, List<String> context, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };

View File

@@ -37,6 +37,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.core.GenericType;
public class FakeClassnameTags123Api {
private ApiClient localVarApiClient;
@@ -89,7 +90,6 @@ public class FakeClassnameTags123Api {
*/
public okhttp3.Call testClassnameCall(Client body, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -186,8 +186,14 @@ public class FakeClassnameTags123Api {
*/
public ApiResponse<Client> testClassnameWithHttpInfo(Client body) throws ApiException {
okhttp3.Call localVarCall = testClassnameValidateBeforeCall(body, null);
Type localVarReturnType = new TypeToken<Client>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
try {
Type localVarReturnType = new TypeToken<Client>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
} catch (ApiException e) {
e.setErrorObject(localVarApiClient.getJSON().getGson().fromJson(e.getResponseBody(), new TypeToken<Client>(){}.getType()));
e.setErrorObjectType(new GenericType<Client>(){});
throw e;
}
}
/**

View File

@@ -40,6 +40,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.core.GenericType;
public class PetApi {
private ApiClient localVarApiClient;
@@ -93,7 +94,6 @@ public class PetApi {
*/
public okhttp3.Call addPetCall(Pet body, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -229,7 +229,6 @@ public class PetApi {
*/
public okhttp3.Call deletePetCall(Long petId, String apiKey, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -369,7 +368,6 @@ public class PetApi {
*/
public okhttp3.Call findPetsByStatusCall(List<String> status, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -469,8 +467,14 @@ public class PetApi {
*/
public ApiResponse<List<Pet>> findPetsByStatusWithHttpInfo(List<String> status) throws ApiException {
okhttp3.Call localVarCall = findPetsByStatusValidateBeforeCall(status, null);
Type localVarReturnType = new TypeToken<List<Pet>>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
try {
Type localVarReturnType = new TypeToken<List<Pet>>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
} catch (ApiException e) {
e.setErrorObject(localVarApiClient.getJSON().getGson().fromJson(e.getResponseBody(), new TypeToken<List<Pet>>(){}.getType()));
e.setErrorObjectType(new GenericType<List<Pet>>(){});
throw e;
}
}
/**
@@ -511,7 +515,6 @@ public class PetApi {
@Deprecated
public okhttp3.Call findPetsByTagsCall(Set<String> tags, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -616,8 +619,14 @@ public class PetApi {
@Deprecated
public ApiResponse<Set<Pet>> findPetsByTagsWithHttpInfo(Set<String> tags) throws ApiException {
okhttp3.Call localVarCall = findPetsByTagsValidateBeforeCall(tags, null);
Type localVarReturnType = new TypeToken<Set<Pet>>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
try {
Type localVarReturnType = new TypeToken<Set<Pet>>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
} catch (ApiException e) {
e.setErrorObject(localVarApiClient.getJSON().getGson().fromJson(e.getResponseBody(), new TypeToken<Set<Pet>>(){}.getType()));
e.setErrorObjectType(new GenericType<Set<Pet>>(){});
throw e;
}
}
/**
@@ -659,7 +668,6 @@ public class PetApi {
*/
public okhttp3.Call getPetByIdCall(Long petId, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -761,8 +769,14 @@ public class PetApi {
*/
public ApiResponse<Pet> getPetByIdWithHttpInfo(Long petId) throws ApiException {
okhttp3.Call localVarCall = getPetByIdValidateBeforeCall(petId, null);
Type localVarReturnType = new TypeToken<Pet>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
try {
Type localVarReturnType = new TypeToken<Pet>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
} catch (ApiException e) {
e.setErrorObject(localVarApiClient.getJSON().getGson().fromJson(e.getResponseBody(), new TypeToken<Pet>(){}.getType()));
e.setErrorObjectType(new GenericType<Pet>(){});
throw e;
}
}
/**
@@ -804,7 +818,6 @@ public class PetApi {
*/
public okhttp3.Call updatePetCall(Pet body, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -946,7 +959,6 @@ public class PetApi {
*/
public okhttp3.Call updatePetWithFormCall(Long petId, String name, String status, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -1094,7 +1106,6 @@ public class PetApi {
*/
public okhttp3.Call uploadFileCall(Long petId, String additionalMetadata, File _file, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -1204,8 +1215,14 @@ public class PetApi {
*/
public ApiResponse<ModelApiResponse> uploadFileWithHttpInfo(Long petId, String additionalMetadata, File _file) throws ApiException {
okhttp3.Call localVarCall = uploadFileValidateBeforeCall(petId, additionalMetadata, _file, null);
Type localVarReturnType = new TypeToken<ModelApiResponse>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
try {
Type localVarReturnType = new TypeToken<ModelApiResponse>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
} catch (ApiException e) {
e.setErrorObject(localVarApiClient.getJSON().getGson().fromJson(e.getResponseBody(), new TypeToken<ModelApiResponse>(){}.getType()));
e.setErrorObjectType(new GenericType<ModelApiResponse>(){});
throw e;
}
}
/**
@@ -1246,7 +1263,6 @@ public class PetApi {
*/
public okhttp3.Call uploadFileWithRequiredFileCall(Long petId, File requiredFile, String additionalMetadata, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -1361,8 +1377,14 @@ public class PetApi {
*/
public ApiResponse<ModelApiResponse> uploadFileWithRequiredFileWithHttpInfo(Long petId, File requiredFile, String additionalMetadata) throws ApiException {
okhttp3.Call localVarCall = uploadFileWithRequiredFileValidateBeforeCall(petId, requiredFile, additionalMetadata, null);
Type localVarReturnType = new TypeToken<ModelApiResponse>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
try {
Type localVarReturnType = new TypeToken<ModelApiResponse>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
} catch (ApiException e) {
e.setErrorObject(localVarApiClient.getJSON().getGson().fromJson(e.getResponseBody(), new TypeToken<ModelApiResponse>(){}.getType()));
e.setErrorObjectType(new GenericType<ModelApiResponse>(){});
throw e;
}
}
/**

View File

@@ -37,6 +37,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.core.GenericType;
public class StoreApi {
private ApiClient localVarApiClient;
@@ -90,7 +91,6 @@ public class StoreApi {
*/
public okhttp3.Call deleteOrderCall(String orderId, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -224,7 +224,6 @@ public class StoreApi {
*/
public okhttp3.Call getInventoryCall(final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -314,8 +313,14 @@ public class StoreApi {
*/
public ApiResponse<Map<String, Integer>> getInventoryWithHttpInfo() throws ApiException {
okhttp3.Call localVarCall = getInventoryValidateBeforeCall(null);
Type localVarReturnType = new TypeToken<Map<String, Integer>>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
try {
Type localVarReturnType = new TypeToken<Map<String, Integer>>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
} catch (ApiException e) {
e.setErrorObject(localVarApiClient.getJSON().getGson().fromJson(e.getResponseBody(), new TypeToken<Map<String, Integer>>(){}.getType()));
e.setErrorObjectType(new GenericType<Map<String, Integer>>(){});
throw e;
}
}
/**
@@ -353,7 +358,6 @@ public class StoreApi {
*/
public okhttp3.Call getOrderByIdCall(Long orderId, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -455,8 +459,14 @@ public class StoreApi {
*/
public ApiResponse<Order> getOrderByIdWithHttpInfo(Long orderId) throws ApiException {
okhttp3.Call localVarCall = getOrderByIdValidateBeforeCall(orderId, null);
Type localVarReturnType = new TypeToken<Order>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
try {
Type localVarReturnType = new TypeToken<Order>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
} catch (ApiException e) {
e.setErrorObject(localVarApiClient.getJSON().getGson().fromJson(e.getResponseBody(), new TypeToken<Order>(){}.getType()));
e.setErrorObjectType(new GenericType<Order>(){});
throw e;
}
}
/**
@@ -496,7 +506,6 @@ public class StoreApi {
*/
public okhttp3.Call placeOrderCall(Order body, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -595,8 +604,14 @@ public class StoreApi {
*/
public ApiResponse<Order> placeOrderWithHttpInfo(Order body) throws ApiException {
okhttp3.Call localVarCall = placeOrderValidateBeforeCall(body, null);
Type localVarReturnType = new TypeToken<Order>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
try {
Type localVarReturnType = new TypeToken<Order>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
} catch (ApiException e) {
e.setErrorObject(localVarApiClient.getJSON().getGson().fromJson(e.getResponseBody(), new TypeToken<Order>(){}.getType()));
e.setErrorObjectType(new GenericType<Order>(){});
throw e;
}
}
/**

View File

@@ -38,6 +38,7 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.core.GenericType;
public class UserApi {
private ApiClient localVarApiClient;
@@ -90,7 +91,6 @@ public class UserApi {
*/
public okhttp3.Call createUserCall(User body, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -221,7 +221,6 @@ public class UserApi {
*/
public okhttp3.Call createUsersWithArrayInputCall(List<User> body, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -352,7 +351,6 @@ public class UserApi {
*/
public okhttp3.Call createUsersWithListInputCall(List<User> body, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -484,7 +482,6 @@ public class UserApi {
*/
public okhttp3.Call deleteUserCall(String username, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -621,7 +618,6 @@ public class UserApi {
*/
public okhttp3.Call getUserByNameCall(String username, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -723,8 +719,14 @@ public class UserApi {
*/
public ApiResponse<User> getUserByNameWithHttpInfo(String username) throws ApiException {
okhttp3.Call localVarCall = getUserByNameValidateBeforeCall(username, null);
Type localVarReturnType = new TypeToken<User>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
try {
Type localVarReturnType = new TypeToken<User>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
} catch (ApiException e) {
e.setErrorObject(localVarApiClient.getJSON().getGson().fromJson(e.getResponseBody(), new TypeToken<User>(){}.getType()));
e.setErrorObjectType(new GenericType<User>(){});
throw e;
}
}
/**
@@ -765,7 +767,6 @@ public class UserApi {
*/
public okhttp3.Call loginUserCall(String username, String password, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -873,8 +874,14 @@ public class UserApi {
*/
public ApiResponse<String> loginUserWithHttpInfo(String username, String password) throws ApiException {
okhttp3.Call localVarCall = loginUserValidateBeforeCall(username, password, null);
Type localVarReturnType = new TypeToken<String>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
try {
Type localVarReturnType = new TypeToken<String>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);
} catch (ApiException e) {
e.setErrorObject(localVarApiClient.getJSON().getGson().fromJson(e.getResponseBody(), new TypeToken<String>(){}.getType()));
e.setErrorObjectType(new GenericType<String>(){});
throw e;
}
}
/**
@@ -912,7 +919,6 @@ public class UserApi {
*/
public okhttp3.Call logoutUserCall(final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };
@@ -1037,7 +1043,6 @@ public class UserApi {
*/
public okhttp3.Call updateUserCall(String username, User body, final ApiCallback _callback) throws ApiException {
String basePath = null;
// Operation Servers
String[] localBasePaths = new String[] { };

View File

@@ -28,22 +28,31 @@ public class RetryingOAuth extends OAuth implements Interceptor {
private TokenRequestBuilder tokenRequestBuilder;
/**
* @param client An OkHttp client
* @param tokenRequestBuilder A token request builder
*/
public RetryingOAuth(OkHttpClient client, TokenRequestBuilder tokenRequestBuilder) {
this.oAuthClient = new OAuthClient(new OAuthOkHttpClient(client));
this.tokenRequestBuilder = tokenRequestBuilder;
}
/**
* @param tokenRequestBuilder A token request builder
*/
public RetryingOAuth(TokenRequestBuilder tokenRequestBuilder) {
this(new OkHttpClient(), tokenRequestBuilder);
}
/**
@param tokenUrl The token URL to be used for this OAuth2 flow.
Applicable to the following OAuth2 flows: "password", "clientCredentials" and "authorizationCode".
The value must be an absolute URL.
@param clientId The OAuth2 client ID for the "clientCredentials" flow.
@param clientSecret The OAuth2 client secret for the "clientCredentials" flow.
*/
* @param tokenUrl The token URL to be used for this OAuth2 flow.
* Applicable to the following OAuth2 flows: "password", "clientCredentials" and "authorizationCode".
* The value must be an absolute URL.
* @param clientId The OAuth2 client ID for the "clientCredentials" flow.
* @param flow OAuth flow.
* @param clientSecret The OAuth2 client secret for the "clientCredentials" flow.
* @param parameters A map of string.
*/
public RetryingOAuth(
String tokenUrl,
String clientId,
@@ -62,6 +71,11 @@ public class RetryingOAuth extends OAuth implements Interceptor {
}
}
/**
* Set the OAuth flow
*
* @param flow The OAuth flow.
*/
public void setFlow(OAuthFlow flow) {
switch(flow) {
case ACCESS_CODE:
@@ -147,8 +161,12 @@ public class RetryingOAuth extends OAuth implements Interceptor {
}
}
/*
/**
* Returns true if the access token has been updated
*
* @param requestAccessToken the request access token
* @return True if the update is successful
* @throws java.io.IOException If fail to update the access token
*/
public synchronized boolean updateAccessToken(String requestAccessToken) throws IOException {
if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) {
@@ -165,10 +183,21 @@ public class RetryingOAuth extends OAuth implements Interceptor {
return getAccessToken() == null || !getAccessToken().equals(requestAccessToken);
}
/**
* Gets the token request builder
*
* @return A token request builder
* @throws java.io.IOException If fail to update the access token
*/
public TokenRequestBuilder getTokenRequestBuilder() {
return tokenRequestBuilder;
}
/**
* Sets the token request builder
*
* @param tokenRequestBuilder Token request builder
*/
public void setTokenRequestBuilder(TokenRequestBuilder tokenRequestBuilder) {
this.tokenRequestBuilder = tokenRequestBuilder;
}

View File

@@ -26,6 +26,25 @@ import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* AdditionalPropertiesAnyType
*/
@@ -100,5 +119,89 @@ public class AdditionalPropertiesAnyType extends HashMap<String, Object> {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("name");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to AdditionalPropertiesAnyType
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (AdditionalPropertiesAnyType.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesAnyType is not found in the empty JSON string", AdditionalPropertiesAnyType.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!AdditionalPropertiesAnyType.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesAnyType` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!AdditionalPropertiesAnyType.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'AdditionalPropertiesAnyType' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<AdditionalPropertiesAnyType> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(AdditionalPropertiesAnyType.class));
return (TypeAdapter<T>) new TypeAdapter<AdditionalPropertiesAnyType>() {
@Override
public void write(JsonWriter out, AdditionalPropertiesAnyType value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public AdditionalPropertiesAnyType read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of AdditionalPropertiesAnyType given an JSON string
*
* @param jsonString JSON string
* @return An instance of AdditionalPropertiesAnyType
* @throws IOException if the JSON string is invalid with respect to AdditionalPropertiesAnyType
*/
public static AdditionalPropertiesAnyType fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, AdditionalPropertiesAnyType.class);
}
/**
* Convert an instance of AdditionalPropertiesAnyType to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -27,6 +27,25 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* AdditionalPropertiesArray
*/
@@ -101,5 +120,89 @@ public class AdditionalPropertiesArray extends HashMap<String, List> {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("name");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to AdditionalPropertiesArray
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (AdditionalPropertiesArray.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesArray is not found in the empty JSON string", AdditionalPropertiesArray.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!AdditionalPropertiesArray.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesArray` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!AdditionalPropertiesArray.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'AdditionalPropertiesArray' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<AdditionalPropertiesArray> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(AdditionalPropertiesArray.class));
return (TypeAdapter<T>) new TypeAdapter<AdditionalPropertiesArray>() {
@Override
public void write(JsonWriter out, AdditionalPropertiesArray value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public AdditionalPropertiesArray read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of AdditionalPropertiesArray given an JSON string
*
* @param jsonString JSON string
* @return An instance of AdditionalPropertiesArray
* @throws IOException if the JSON string is invalid with respect to AdditionalPropertiesArray
*/
public static AdditionalPropertiesArray fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, AdditionalPropertiesArray.class);
}
/**
* Convert an instance of AdditionalPropertiesArray to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -26,6 +26,25 @@ import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* AdditionalPropertiesBoolean
*/
@@ -100,5 +119,89 @@ public class AdditionalPropertiesBoolean extends HashMap<String, Boolean> {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("name");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to AdditionalPropertiesBoolean
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (AdditionalPropertiesBoolean.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesBoolean is not found in the empty JSON string", AdditionalPropertiesBoolean.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!AdditionalPropertiesBoolean.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesBoolean` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!AdditionalPropertiesBoolean.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'AdditionalPropertiesBoolean' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<AdditionalPropertiesBoolean> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(AdditionalPropertiesBoolean.class));
return (TypeAdapter<T>) new TypeAdapter<AdditionalPropertiesBoolean>() {
@Override
public void write(JsonWriter out, AdditionalPropertiesBoolean value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public AdditionalPropertiesBoolean read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of AdditionalPropertiesBoolean given an JSON string
*
* @param jsonString JSON string
* @return An instance of AdditionalPropertiesBoolean
* @throws IOException if the JSON string is invalid with respect to AdditionalPropertiesBoolean
*/
public static AdditionalPropertiesBoolean fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, AdditionalPropertiesBoolean.class);
}
/**
* Convert an instance of AdditionalPropertiesBoolean to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -28,6 +28,25 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* AdditionalPropertiesClass
*/
@@ -454,5 +473,99 @@ public class AdditionalPropertiesClass {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("map_string");
openapiFields.add("map_number");
openapiFields.add("map_integer");
openapiFields.add("map_boolean");
openapiFields.add("map_array_integer");
openapiFields.add("map_array_anytype");
openapiFields.add("map_map_string");
openapiFields.add("map_map_anytype");
openapiFields.add("anytype_1");
openapiFields.add("anytype_2");
openapiFields.add("anytype_3");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to AdditionalPropertiesClass
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (AdditionalPropertiesClass.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesClass is not found in the empty JSON string", AdditionalPropertiesClass.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!AdditionalPropertiesClass.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesClass` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!AdditionalPropertiesClass.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'AdditionalPropertiesClass' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<AdditionalPropertiesClass> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(AdditionalPropertiesClass.class));
return (TypeAdapter<T>) new TypeAdapter<AdditionalPropertiesClass>() {
@Override
public void write(JsonWriter out, AdditionalPropertiesClass value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public AdditionalPropertiesClass read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of AdditionalPropertiesClass given an JSON string
*
* @param jsonString JSON string
* @return An instance of AdditionalPropertiesClass
* @throws IOException if the JSON string is invalid with respect to AdditionalPropertiesClass
*/
public static AdditionalPropertiesClass fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, AdditionalPropertiesClass.class);
}
/**
* Convert an instance of AdditionalPropertiesClass to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -26,6 +26,25 @@ import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* AdditionalPropertiesInteger
*/
@@ -100,5 +119,89 @@ public class AdditionalPropertiesInteger extends HashMap<String, Integer> {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("name");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to AdditionalPropertiesInteger
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (AdditionalPropertiesInteger.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesInteger is not found in the empty JSON string", AdditionalPropertiesInteger.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!AdditionalPropertiesInteger.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesInteger` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!AdditionalPropertiesInteger.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'AdditionalPropertiesInteger' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<AdditionalPropertiesInteger> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(AdditionalPropertiesInteger.class));
return (TypeAdapter<T>) new TypeAdapter<AdditionalPropertiesInteger>() {
@Override
public void write(JsonWriter out, AdditionalPropertiesInteger value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public AdditionalPropertiesInteger read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of AdditionalPropertiesInteger given an JSON string
*
* @param jsonString JSON string
* @return An instance of AdditionalPropertiesInteger
* @throws IOException if the JSON string is invalid with respect to AdditionalPropertiesInteger
*/
public static AdditionalPropertiesInteger fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, AdditionalPropertiesInteger.class);
}
/**
* Convert an instance of AdditionalPropertiesInteger to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -27,6 +27,25 @@ import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* AdditionalPropertiesNumber
*/
@@ -101,5 +120,89 @@ public class AdditionalPropertiesNumber extends HashMap<String, BigDecimal> {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("name");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to AdditionalPropertiesNumber
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (AdditionalPropertiesNumber.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesNumber is not found in the empty JSON string", AdditionalPropertiesNumber.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!AdditionalPropertiesNumber.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesNumber` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!AdditionalPropertiesNumber.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'AdditionalPropertiesNumber' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<AdditionalPropertiesNumber> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(AdditionalPropertiesNumber.class));
return (TypeAdapter<T>) new TypeAdapter<AdditionalPropertiesNumber>() {
@Override
public void write(JsonWriter out, AdditionalPropertiesNumber value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public AdditionalPropertiesNumber read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of AdditionalPropertiesNumber given an JSON string
*
* @param jsonString JSON string
* @return An instance of AdditionalPropertiesNumber
* @throws IOException if the JSON string is invalid with respect to AdditionalPropertiesNumber
*/
public static AdditionalPropertiesNumber fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, AdditionalPropertiesNumber.class);
}
/**
* Convert an instance of AdditionalPropertiesNumber to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -26,6 +26,25 @@ import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* AdditionalPropertiesObject
*/
@@ -100,5 +119,89 @@ public class AdditionalPropertiesObject extends HashMap<String, Map> {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("name");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to AdditionalPropertiesObject
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (AdditionalPropertiesObject.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesObject is not found in the empty JSON string", AdditionalPropertiesObject.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!AdditionalPropertiesObject.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesObject` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!AdditionalPropertiesObject.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'AdditionalPropertiesObject' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<AdditionalPropertiesObject> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(AdditionalPropertiesObject.class));
return (TypeAdapter<T>) new TypeAdapter<AdditionalPropertiesObject>() {
@Override
public void write(JsonWriter out, AdditionalPropertiesObject value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public AdditionalPropertiesObject read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of AdditionalPropertiesObject given an JSON string
*
* @param jsonString JSON string
* @return An instance of AdditionalPropertiesObject
* @throws IOException if the JSON string is invalid with respect to AdditionalPropertiesObject
*/
public static AdditionalPropertiesObject fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, AdditionalPropertiesObject.class);
}
/**
* Convert an instance of AdditionalPropertiesObject to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -26,6 +26,25 @@ import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* AdditionalPropertiesString
*/
@@ -100,5 +119,89 @@ public class AdditionalPropertiesString extends HashMap<String, String> {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("name");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to AdditionalPropertiesString
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (AdditionalPropertiesString.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in AdditionalPropertiesString is not found in the empty JSON string", AdditionalPropertiesString.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!AdditionalPropertiesString.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `AdditionalPropertiesString` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!AdditionalPropertiesString.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'AdditionalPropertiesString' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<AdditionalPropertiesString> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(AdditionalPropertiesString.class));
return (TypeAdapter<T>) new TypeAdapter<AdditionalPropertiesString>() {
@Override
public void write(JsonWriter out, AdditionalPropertiesString value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public AdditionalPropertiesString read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of AdditionalPropertiesString given an JSON string
*
* @param jsonString JSON string
* @return An instance of AdditionalPropertiesString
* @throws IOException if the JSON string is invalid with respect to AdditionalPropertiesString
*/
public static AdditionalPropertiesString fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, AdditionalPropertiesString.class);
}
/**
* Convert an instance of AdditionalPropertiesString to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -27,6 +27,25 @@ import org.openapitools.client.model.BigCat;
import org.openapitools.client.model.Cat;
import org.openapitools.client.model.Dog;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* Animal
*/
@@ -129,5 +148,71 @@ public class Animal {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("className");
openapiFields.add("color");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
openapiRequiredFields.add("className");
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Animal
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (Animal.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in Animal is not found in the empty JSON string", Animal.openapiRequiredFields.toString()));
}
}
String discriminatorValue = jsonObj.get("className").getAsString();
switch (discriminatorValue) {
case "BigCat":
BigCat.validateJsonObject(jsonObj);
break;
case "Cat":
Cat.validateJsonObject(jsonObj);
break;
case "Dog":
Dog.validateJsonObject(jsonObj);
break;
default:
throw new IllegalArgumentException(String.format("The value of the `className` field `%s` does not match any key defined in the discriminator's mapping.", discriminatorValue));
}
}
/**
* Create an instance of Animal given an JSON string
*
* @param jsonString JSON string
* @return An instance of Animal
* @throws IOException if the JSON string is invalid with respect to Animal
*/
public static Animal fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, Animal.class);
}
/**
* Convert an instance of Animal to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -27,6 +27,25 @@ import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* ArrayOfArrayOfNumberOnly
*/
@@ -107,5 +126,89 @@ public class ArrayOfArrayOfNumberOnly {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("ArrayArrayNumber");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to ArrayOfArrayOfNumberOnly
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (ArrayOfArrayOfNumberOnly.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in ArrayOfArrayOfNumberOnly is not found in the empty JSON string", ArrayOfArrayOfNumberOnly.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!ArrayOfArrayOfNumberOnly.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `ArrayOfArrayOfNumberOnly` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!ArrayOfArrayOfNumberOnly.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'ArrayOfArrayOfNumberOnly' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<ArrayOfArrayOfNumberOnly> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(ArrayOfArrayOfNumberOnly.class));
return (TypeAdapter<T>) new TypeAdapter<ArrayOfArrayOfNumberOnly>() {
@Override
public void write(JsonWriter out, ArrayOfArrayOfNumberOnly value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public ArrayOfArrayOfNumberOnly read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of ArrayOfArrayOfNumberOnly given an JSON string
*
* @param jsonString JSON string
* @return An instance of ArrayOfArrayOfNumberOnly
* @throws IOException if the JSON string is invalid with respect to ArrayOfArrayOfNumberOnly
*/
public static ArrayOfArrayOfNumberOnly fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, ArrayOfArrayOfNumberOnly.class);
}
/**
* Convert an instance of ArrayOfArrayOfNumberOnly to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -27,6 +27,25 @@ import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* ArrayOfNumberOnly
*/
@@ -107,5 +126,89 @@ public class ArrayOfNumberOnly {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("ArrayNumber");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to ArrayOfNumberOnly
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (ArrayOfNumberOnly.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in ArrayOfNumberOnly is not found in the empty JSON string", ArrayOfNumberOnly.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!ArrayOfNumberOnly.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `ArrayOfNumberOnly` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!ArrayOfNumberOnly.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'ArrayOfNumberOnly' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<ArrayOfNumberOnly> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(ArrayOfNumberOnly.class));
return (TypeAdapter<T>) new TypeAdapter<ArrayOfNumberOnly>() {
@Override
public void write(JsonWriter out, ArrayOfNumberOnly value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public ArrayOfNumberOnly read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of ArrayOfNumberOnly given an JSON string
*
* @param jsonString JSON string
* @return An instance of ArrayOfNumberOnly
* @throws IOException if the JSON string is invalid with respect to ArrayOfNumberOnly
*/
public static ArrayOfNumberOnly fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, ArrayOfNumberOnly.class);
}
/**
* Convert an instance of ArrayOfNumberOnly to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -27,6 +27,25 @@ import java.util.ArrayList;
import java.util.List;
import org.openapitools.client.model.ReadOnlyFirst;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* ArrayTest
*/
@@ -181,5 +200,91 @@ public class ArrayTest {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("array_of_string");
openapiFields.add("array_array_of_integer");
openapiFields.add("array_array_of_model");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to ArrayTest
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (ArrayTest.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in ArrayTest is not found in the empty JSON string", ArrayTest.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!ArrayTest.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `ArrayTest` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!ArrayTest.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'ArrayTest' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<ArrayTest> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(ArrayTest.class));
return (TypeAdapter<T>) new TypeAdapter<ArrayTest>() {
@Override
public void write(JsonWriter out, ArrayTest value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public ArrayTest read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of ArrayTest given an JSON string
*
* @param jsonString JSON string
* @return An instance of ArrayTest
* @throws IOException if the JSON string is invalid with respect to ArrayTest
*/
public static ArrayTest fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, ArrayTest.class);
}
/**
* Convert an instance of ArrayTest to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -26,6 +26,25 @@ import java.io.IOException;
import org.openapitools.client.model.BigCatAllOf;
import org.openapitools.client.model.Cat;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* BigCat
*/
@@ -152,5 +171,100 @@ public class BigCat extends Cat {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("className");
openapiFields.add("color");
openapiFields.add("declawed");
openapiFields.add("kind");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
openapiRequiredFields.add("className");
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to BigCat
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (BigCat.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in BigCat is not found in the empty JSON string", BigCat.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!BigCat.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `BigCat` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : BigCat.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!BigCat.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'BigCat' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<BigCat> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(BigCat.class));
return (TypeAdapter<T>) new TypeAdapter<BigCat>() {
@Override
public void write(JsonWriter out, BigCat value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public BigCat read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of BigCat given an JSON string
*
* @param jsonString JSON string
* @return An instance of BigCat
* @throws IOException if the JSON string is invalid with respect to BigCat
*/
public static BigCat fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, BigCat.class);
}
/**
* Convert an instance of BigCat to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -24,6 +24,25 @@ import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* BigCatAllOf
*/
@@ -147,5 +166,89 @@ public class BigCatAllOf {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("kind");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to BigCatAllOf
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (BigCatAllOf.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in BigCatAllOf is not found in the empty JSON string", BigCatAllOf.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!BigCatAllOf.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `BigCatAllOf` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!BigCatAllOf.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'BigCatAllOf' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<BigCatAllOf> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(BigCatAllOf.class));
return (TypeAdapter<T>) new TypeAdapter<BigCatAllOf>() {
@Override
public void write(JsonWriter out, BigCatAllOf value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public BigCatAllOf read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of BigCatAllOf given an JSON string
*
* @param jsonString JSON string
* @return An instance of BigCatAllOf
* @throws IOException if the JSON string is invalid with respect to BigCatAllOf
*/
public static BigCatAllOf fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, BigCatAllOf.class);
}
/**
* Convert an instance of BigCatAllOf to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -24,6 +24,25 @@ import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* Capitalization
*/
@@ -241,5 +260,94 @@ public class Capitalization {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("smallCamel");
openapiFields.add("CapitalCamel");
openapiFields.add("small_Snake");
openapiFields.add("Capital_Snake");
openapiFields.add("SCA_ETH_Flow_Points");
openapiFields.add("ATT_NAME");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Capitalization
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (Capitalization.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in Capitalization is not found in the empty JSON string", Capitalization.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!Capitalization.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Capitalization` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!Capitalization.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'Capitalization' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Capitalization> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(Capitalization.class));
return (TypeAdapter<T>) new TypeAdapter<Capitalization>() {
@Override
public void write(JsonWriter out, Capitalization value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public Capitalization read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of Capitalization given an JSON string
*
* @param jsonString JSON string
* @return An instance of Capitalization
* @throws IOException if the JSON string is invalid with respect to Capitalization
*/
public static Capitalization fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, Capitalization.class);
}
/**
* Convert an instance of Capitalization to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -27,6 +27,25 @@ import org.openapitools.client.model.Animal;
import org.openapitools.client.model.BigCat;
import org.openapitools.client.model.CatAllOf;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* Cat
*/
@@ -102,5 +121,66 @@ public class Cat extends Animal {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("className");
openapiFields.add("color");
openapiFields.add("declawed");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
openapiRequiredFields.add("className");
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Cat
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (Cat.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in Cat is not found in the empty JSON string", Cat.openapiRequiredFields.toString()));
}
}
String discriminatorValue = jsonObj.get("className").getAsString();
switch (discriminatorValue) {
case "BigCat":
BigCat.validateJsonObject(jsonObj);
break;
default:
throw new IllegalArgumentException(String.format("The value of the `className` field `%s` does not match any key defined in the discriminator's mapping.", discriminatorValue));
}
}
/**
* Create an instance of Cat given an JSON string
*
* @param jsonString JSON string
* @return An instance of Cat
* @throws IOException if the JSON string is invalid with respect to Cat
*/
public static Cat fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, Cat.class);
}
/**
* Convert an instance of Cat to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -24,6 +24,25 @@ import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* CatAllOf
*/
@@ -96,5 +115,89 @@ public class CatAllOf {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("declawed");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to CatAllOf
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (CatAllOf.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in CatAllOf is not found in the empty JSON string", CatAllOf.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!CatAllOf.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `CatAllOf` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!CatAllOf.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'CatAllOf' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<CatAllOf> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(CatAllOf.class));
return (TypeAdapter<T>) new TypeAdapter<CatAllOf>() {
@Override
public void write(JsonWriter out, CatAllOf value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public CatAllOf read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of CatAllOf given an JSON string
*
* @param jsonString JSON string
* @return An instance of CatAllOf
* @throws IOException if the JSON string is invalid with respect to CatAllOf
*/
public static CatAllOf fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, CatAllOf.class);
}
/**
* Convert an instance of CatAllOf to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -24,6 +24,25 @@ import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* Category
*/
@@ -125,5 +144,98 @@ public class Category {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("id");
openapiFields.add("name");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
openapiRequiredFields.add("name");
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Category
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (Category.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in Category is not found in the empty JSON string", Category.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!Category.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Category` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : Category.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!Category.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'Category' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Category> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(Category.class));
return (TypeAdapter<T>) new TypeAdapter<Category>() {
@Override
public void write(JsonWriter out, Category value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public Category read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of Category given an JSON string
*
* @param jsonString JSON string
* @return An instance of Category
* @throws IOException if the JSON string is invalid with respect to Category
*/
public static Category fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, Category.class);
}
/**
* Convert an instance of Category to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -24,6 +24,25 @@ import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* Model for testing model with \&quot;_class\&quot; property
*/
@@ -97,5 +116,89 @@ public class ClassModel {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("_class");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to ClassModel
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (ClassModel.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in ClassModel is not found in the empty JSON string", ClassModel.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!ClassModel.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `ClassModel` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!ClassModel.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'ClassModel' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<ClassModel> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(ClassModel.class));
return (TypeAdapter<T>) new TypeAdapter<ClassModel>() {
@Override
public void write(JsonWriter out, ClassModel value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public ClassModel read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of ClassModel given an JSON string
*
* @param jsonString JSON string
* @return An instance of ClassModel
* @throws IOException if the JSON string is invalid with respect to ClassModel
*/
public static ClassModel fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, ClassModel.class);
}
/**
* Convert an instance of ClassModel to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -24,6 +24,25 @@ import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* Client
*/
@@ -96,5 +115,89 @@ public class Client {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("client");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Client
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (Client.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in Client is not found in the empty JSON string", Client.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!Client.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Client` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!Client.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'Client' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Client> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(Client.class));
return (TypeAdapter<T>) new TypeAdapter<Client>() {
@Override
public void write(JsonWriter out, Client value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public Client read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of Client given an JSON string
*
* @param jsonString JSON string
* @return An instance of Client
* @throws IOException if the JSON string is invalid with respect to Client
*/
public static Client fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, Client.class);
}
/**
* Convert an instance of Client to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -26,6 +26,25 @@ import java.io.IOException;
import org.openapitools.client.model.Animal;
import org.openapitools.client.model.DogAllOf;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* Dog
*/
@@ -101,5 +120,99 @@ public class Dog extends Animal {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("className");
openapiFields.add("color");
openapiFields.add("breed");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
openapiRequiredFields.add("className");
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Dog
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (Dog.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in Dog is not found in the empty JSON string", Dog.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!Dog.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Dog` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : Dog.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!Dog.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'Dog' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Dog> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(Dog.class));
return (TypeAdapter<T>) new TypeAdapter<Dog>() {
@Override
public void write(JsonWriter out, Dog value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public Dog read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of Dog given an JSON string
*
* @param jsonString JSON string
* @return An instance of Dog
* @throws IOException if the JSON string is invalid with respect to Dog
*/
public static Dog fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, Dog.class);
}
/**
* Convert an instance of Dog to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -24,6 +24,25 @@ import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* DogAllOf
*/
@@ -96,5 +115,89 @@ public class DogAllOf {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("breed");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to DogAllOf
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (DogAllOf.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in DogAllOf is not found in the empty JSON string", DogAllOf.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!DogAllOf.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `DogAllOf` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!DogAllOf.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'DogAllOf' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<DogAllOf> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(DogAllOf.class));
return (TypeAdapter<T>) new TypeAdapter<DogAllOf>() {
@Override
public void write(JsonWriter out, DogAllOf value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public DogAllOf read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of DogAllOf given an JSON string
*
* @param jsonString JSON string
* @return An instance of DogAllOf
* @throws IOException if the JSON string is invalid with respect to DogAllOf
*/
public static DogAllOf fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, DogAllOf.class);
}
/**
* Convert an instance of DogAllOf to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -26,6 +26,25 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* EnumArrays
*/
@@ -229,5 +248,90 @@ public class EnumArrays {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("just_symbol");
openapiFields.add("array_enum");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to EnumArrays
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (EnumArrays.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in EnumArrays is not found in the empty JSON string", EnumArrays.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!EnumArrays.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `EnumArrays` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!EnumArrays.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'EnumArrays' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<EnumArrays> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(EnumArrays.class));
return (TypeAdapter<T>) new TypeAdapter<EnumArrays>() {
@Override
public void write(JsonWriter out, EnumArrays value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public EnumArrays read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of EnumArrays given an JSON string
*
* @param jsonString JSON string
* @return An instance of EnumArrays
* @throws IOException if the JSON string is invalid with respect to EnumArrays
*/
public static EnumArrays fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, EnumArrays.class);
}
/**
* Convert an instance of EnumArrays to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -25,6 +25,25 @@ import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import org.openapitools.client.model.OuterEnum;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* EnumTest
*/
@@ -405,5 +424,101 @@ public class EnumTest {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("enum_string");
openapiFields.add("enum_string_required");
openapiFields.add("enum_integer");
openapiFields.add("enum_number");
openapiFields.add("outerEnum");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
openapiRequiredFields.add("enum_string_required");
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to EnumTest
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (EnumTest.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in EnumTest is not found in the empty JSON string", EnumTest.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!EnumTest.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `EnumTest` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : EnumTest.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!EnumTest.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'EnumTest' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<EnumTest> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(EnumTest.class));
return (TypeAdapter<T>) new TypeAdapter<EnumTest>() {
@Override
public void write(JsonWriter out, EnumTest value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public EnumTest read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of EnumTest given an JSON string
*
* @param jsonString JSON string
* @return An instance of EnumTest
* @throws IOException if the JSON string is invalid with respect to EnumTest
*/
public static EnumTest fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, EnumTest.class);
}
/**
* Convert an instance of EnumTest to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -27,6 +27,25 @@ import java.util.ArrayList;
import java.util.List;
import org.openapitools.client.model.ModelFile;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* FileSchemaTestClass
*/
@@ -136,5 +155,101 @@ public class FileSchemaTestClass {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("file");
openapiFields.add("files");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to FileSchemaTestClass
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (FileSchemaTestClass.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in FileSchemaTestClass is not found in the empty JSON string", FileSchemaTestClass.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!FileSchemaTestClass.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `FileSchemaTestClass` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
// validate the optional field `file`
if (jsonObj.getAsJsonObject("file") != null) {
ModelFile.validateJsonObject(jsonObj.getAsJsonObject("file"));
}
JsonArray jsonArrayfiles = jsonObj.getAsJsonArray("files");
// validate the optional field `files` (array)
if (jsonArrayfiles != null) {
for (int i = 0; i < jsonArrayfiles.size(); i++) {
ModelFile.validateJsonObject(jsonArrayfiles.get(i).getAsJsonObject());
};
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!FileSchemaTestClass.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'FileSchemaTestClass' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<FileSchemaTestClass> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(FileSchemaTestClass.class));
return (TypeAdapter<T>) new TypeAdapter<FileSchemaTestClass>() {
@Override
public void write(JsonWriter out, FileSchemaTestClass value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public FileSchemaTestClass read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of FileSchemaTestClass given an JSON string
*
* @param jsonString JSON string
* @return An instance of FileSchemaTestClass
* @throws IOException if the JSON string is invalid with respect to FileSchemaTestClass
*/
public static FileSchemaTestClass fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, FileSchemaTestClass.class);
}
/**
* Convert an instance of FileSchemaTestClass to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -29,6 +29,25 @@ import java.util.UUID;
import org.threeten.bp.LocalDate;
import org.threeten.bp.OffsetDateTime;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* FormatTest
*/
@@ -488,5 +507,113 @@ public class FormatTest {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("integer");
openapiFields.add("int32");
openapiFields.add("int64");
openapiFields.add("number");
openapiFields.add("float");
openapiFields.add("double");
openapiFields.add("string");
openapiFields.add("byte");
openapiFields.add("binary");
openapiFields.add("date");
openapiFields.add("dateTime");
openapiFields.add("uuid");
openapiFields.add("password");
openapiFields.add("BigDecimal");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
openapiRequiredFields.add("number");
openapiRequiredFields.add("byte");
openapiRequiredFields.add("date");
openapiRequiredFields.add("password");
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to FormatTest
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (FormatTest.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in FormatTest is not found in the empty JSON string", FormatTest.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!FormatTest.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `FormatTest` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : FormatTest.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!FormatTest.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'FormatTest' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<FormatTest> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(FormatTest.class));
return (TypeAdapter<T>) new TypeAdapter<FormatTest>() {
@Override
public void write(JsonWriter out, FormatTest value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public FormatTest read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of FormatTest given an JSON string
*
* @param jsonString JSON string
* @return An instance of FormatTest
* @throws IOException if the JSON string is invalid with respect to FormatTest
*/
public static FormatTest fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, FormatTest.class);
}
/**
* Convert an instance of FormatTest to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -24,6 +24,25 @@ import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* HasOnlyReadOnly
*/
@@ -117,5 +136,90 @@ public class HasOnlyReadOnly {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("bar");
openapiFields.add("foo");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to HasOnlyReadOnly
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (HasOnlyReadOnly.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in HasOnlyReadOnly is not found in the empty JSON string", HasOnlyReadOnly.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!HasOnlyReadOnly.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `HasOnlyReadOnly` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!HasOnlyReadOnly.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'HasOnlyReadOnly' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<HasOnlyReadOnly> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(HasOnlyReadOnly.class));
return (TypeAdapter<T>) new TypeAdapter<HasOnlyReadOnly>() {
@Override
public void write(JsonWriter out, HasOnlyReadOnly value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public HasOnlyReadOnly read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of HasOnlyReadOnly given an JSON string
*
* @param jsonString JSON string
* @return An instance of HasOnlyReadOnly
* @throws IOException if the JSON string is invalid with respect to HasOnlyReadOnly
*/
public static HasOnlyReadOnly fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, HasOnlyReadOnly.class);
}
/**
* Convert an instance of HasOnlyReadOnly to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -27,6 +27,25 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* MapTest
*/
@@ -265,5 +284,92 @@ public class MapTest {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("map_map_of_string");
openapiFields.add("map_of_enum_string");
openapiFields.add("direct_map");
openapiFields.add("indirect_map");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to MapTest
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (MapTest.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in MapTest is not found in the empty JSON string", MapTest.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!MapTest.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `MapTest` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!MapTest.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'MapTest' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<MapTest> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(MapTest.class));
return (TypeAdapter<T>) new TypeAdapter<MapTest>() {
@Override
public void write(JsonWriter out, MapTest value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public MapTest read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of MapTest given an JSON string
*
* @param jsonString JSON string
* @return An instance of MapTest
* @throws IOException if the JSON string is invalid with respect to MapTest
*/
public static MapTest fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, MapTest.class);
}
/**
* Convert an instance of MapTest to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -30,6 +30,25 @@ import java.util.UUID;
import org.openapitools.client.model.Animal;
import org.threeten.bp.OffsetDateTime;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* MixedPropertiesAndAdditionalPropertiesClass
*/
@@ -168,5 +187,91 @@ public class MixedPropertiesAndAdditionalPropertiesClass {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("uuid");
openapiFields.add("dateTime");
openapiFields.add("map");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to MixedPropertiesAndAdditionalPropertiesClass
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (MixedPropertiesAndAdditionalPropertiesClass.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in MixedPropertiesAndAdditionalPropertiesClass is not found in the empty JSON string", MixedPropertiesAndAdditionalPropertiesClass.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!MixedPropertiesAndAdditionalPropertiesClass.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `MixedPropertiesAndAdditionalPropertiesClass` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!MixedPropertiesAndAdditionalPropertiesClass.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'MixedPropertiesAndAdditionalPropertiesClass' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<MixedPropertiesAndAdditionalPropertiesClass> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(MixedPropertiesAndAdditionalPropertiesClass.class));
return (TypeAdapter<T>) new TypeAdapter<MixedPropertiesAndAdditionalPropertiesClass>() {
@Override
public void write(JsonWriter out, MixedPropertiesAndAdditionalPropertiesClass value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public MixedPropertiesAndAdditionalPropertiesClass read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of MixedPropertiesAndAdditionalPropertiesClass given an JSON string
*
* @param jsonString JSON string
* @return An instance of MixedPropertiesAndAdditionalPropertiesClass
* @throws IOException if the JSON string is invalid with respect to MixedPropertiesAndAdditionalPropertiesClass
*/
public static MixedPropertiesAndAdditionalPropertiesClass fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, MixedPropertiesAndAdditionalPropertiesClass.class);
}
/**
* Convert an instance of MixedPropertiesAndAdditionalPropertiesClass to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -24,6 +24,25 @@ import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* Model for testing model name starting with number
*/
@@ -126,5 +145,90 @@ public class Model200Response {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("name");
openapiFields.add("class");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Model200Response
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (Model200Response.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in Model200Response is not found in the empty JSON string", Model200Response.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!Model200Response.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Model200Response` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!Model200Response.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'Model200Response' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Model200Response> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(Model200Response.class));
return (TypeAdapter<T>) new TypeAdapter<Model200Response>() {
@Override
public void write(JsonWriter out, Model200Response value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public Model200Response read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of Model200Response given an JSON string
*
* @param jsonString JSON string
* @return An instance of Model200Response
* @throws IOException if the JSON string is invalid with respect to Model200Response
*/
public static Model200Response fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, Model200Response.class);
}
/**
* Convert an instance of Model200Response to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -24,6 +24,25 @@ import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* ModelApiResponse
*/
@@ -154,5 +173,91 @@ public class ModelApiResponse {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("code");
openapiFields.add("type");
openapiFields.add("message");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to ModelApiResponse
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (ModelApiResponse.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in ModelApiResponse is not found in the empty JSON string", ModelApiResponse.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!ModelApiResponse.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `ModelApiResponse` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!ModelApiResponse.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'ModelApiResponse' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<ModelApiResponse> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(ModelApiResponse.class));
return (TypeAdapter<T>) new TypeAdapter<ModelApiResponse>() {
@Override
public void write(JsonWriter out, ModelApiResponse value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public ModelApiResponse read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of ModelApiResponse given an JSON string
*
* @param jsonString JSON string
* @return An instance of ModelApiResponse
* @throws IOException if the JSON string is invalid with respect to ModelApiResponse
*/
public static ModelApiResponse fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, ModelApiResponse.class);
}
/**
* Convert an instance of ModelApiResponse to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -24,6 +24,25 @@ import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* Must be named &#x60;File&#x60; for test.
*/
@@ -97,5 +116,89 @@ public class ModelFile {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("sourceURI");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to ModelFile
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (ModelFile.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in ModelFile is not found in the empty JSON string", ModelFile.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!ModelFile.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `ModelFile` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!ModelFile.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'ModelFile' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<ModelFile> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(ModelFile.class));
return (TypeAdapter<T>) new TypeAdapter<ModelFile>() {
@Override
public void write(JsonWriter out, ModelFile value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public ModelFile read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of ModelFile given an JSON string
*
* @param jsonString JSON string
* @return An instance of ModelFile
* @throws IOException if the JSON string is invalid with respect to ModelFile
*/
public static ModelFile fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, ModelFile.class);
}
/**
* Convert an instance of ModelFile to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -24,6 +24,25 @@ import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* ModelList
*/
@@ -96,5 +115,89 @@ public class ModelList {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("123-list");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to ModelList
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (ModelList.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in ModelList is not found in the empty JSON string", ModelList.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!ModelList.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `ModelList` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!ModelList.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'ModelList' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<ModelList> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(ModelList.class));
return (TypeAdapter<T>) new TypeAdapter<ModelList>() {
@Override
public void write(JsonWriter out, ModelList value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public ModelList read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of ModelList given an JSON string
*
* @param jsonString JSON string
* @return An instance of ModelList
* @throws IOException if the JSON string is invalid with respect to ModelList
*/
public static ModelList fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, ModelList.class);
}
/**
* Convert an instance of ModelList to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -24,6 +24,25 @@ import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* Model for testing reserved words
*/
@@ -97,5 +116,89 @@ public class ModelReturn {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("return");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to ModelReturn
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (ModelReturn.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in ModelReturn is not found in the empty JSON string", ModelReturn.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!ModelReturn.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `ModelReturn` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!ModelReturn.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'ModelReturn' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<ModelReturn> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(ModelReturn.class));
return (TypeAdapter<T>) new TypeAdapter<ModelReturn>() {
@Override
public void write(JsonWriter out, ModelReturn value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public ModelReturn read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of ModelReturn given an JSON string
*
* @param jsonString JSON string
* @return An instance of ModelReturn
* @throws IOException if the JSON string is invalid with respect to ModelReturn
*/
public static ModelReturn fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, ModelReturn.class);
}
/**
* Convert an instance of ModelReturn to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -24,6 +24,25 @@ import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* Model for testing model name same as property name
*/
@@ -176,5 +195,100 @@ public class Name {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("name");
openapiFields.add("snake_case");
openapiFields.add("property");
openapiFields.add("123Number");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
openapiRequiredFields.add("name");
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Name
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (Name.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in Name is not found in the empty JSON string", Name.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!Name.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Name` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : Name.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!Name.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'Name' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Name> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(Name.class));
return (TypeAdapter<T>) new TypeAdapter<Name>() {
@Override
public void write(JsonWriter out, Name value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public Name read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of Name given an JSON string
*
* @param jsonString JSON string
* @return An instance of Name
* @throws IOException if the JSON string is invalid with respect to Name
*/
public static Name fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, Name.class);
}
/**
* Convert an instance of Name to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -25,6 +25,25 @@ import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.math.BigDecimal;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* NumberOnly
*/
@@ -97,5 +116,89 @@ public class NumberOnly {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("JustNumber");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to NumberOnly
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (NumberOnly.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in NumberOnly is not found in the empty JSON string", NumberOnly.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!NumberOnly.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `NumberOnly` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!NumberOnly.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'NumberOnly' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<NumberOnly> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(NumberOnly.class));
return (TypeAdapter<T>) new TypeAdapter<NumberOnly>() {
@Override
public void write(JsonWriter out, NumberOnly value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public NumberOnly read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of NumberOnly given an JSON string
*
* @param jsonString JSON string
* @return An instance of NumberOnly
* @throws IOException if the JSON string is invalid with respect to NumberOnly
*/
public static NumberOnly fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, NumberOnly.class);
}
/**
* Convert an instance of NumberOnly to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -25,6 +25,25 @@ import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import org.threeten.bp.OffsetDateTime;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* Order
*/
@@ -291,5 +310,94 @@ public class Order {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("id");
openapiFields.add("petId");
openapiFields.add("quantity");
openapiFields.add("shipDate");
openapiFields.add("status");
openapiFields.add("complete");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Order
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (Order.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in Order is not found in the empty JSON string", Order.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!Order.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Order` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!Order.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'Order' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Order> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(Order.class));
return (TypeAdapter<T>) new TypeAdapter<Order>() {
@Override
public void write(JsonWriter out, Order value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public Order read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of Order given an JSON string
*
* @param jsonString JSON string
* @return An instance of Order
* @throws IOException if the JSON string is invalid with respect to Order
*/
public static Order fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, Order.class);
}
/**
* Convert an instance of Order to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -25,6 +25,25 @@ import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.math.BigDecimal;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* OuterComposite
*/
@@ -155,5 +174,91 @@ public class OuterComposite {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("my_number");
openapiFields.add("my_string");
openapiFields.add("my_boolean");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to OuterComposite
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (OuterComposite.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in OuterComposite is not found in the empty JSON string", OuterComposite.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!OuterComposite.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `OuterComposite` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!OuterComposite.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'OuterComposite' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<OuterComposite> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(OuterComposite.class));
return (TypeAdapter<T>) new TypeAdapter<OuterComposite>() {
@Override
public void write(JsonWriter out, OuterComposite value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public OuterComposite read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of OuterComposite given an JSON string
*
* @param jsonString JSON string
* @return An instance of OuterComposite
* @throws IOException if the JSON string is invalid with respect to OuterComposite
*/
public static OuterComposite fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, OuterComposite.class);
}
/**
* Convert an instance of OuterComposite to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -30,6 +30,25 @@ import java.util.Set;
import org.openapitools.client.model.Category;
import org.openapitools.client.model.Tag;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* Pet
*/
@@ -309,5 +328,114 @@ public class Pet {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("id");
openapiFields.add("category");
openapiFields.add("name");
openapiFields.add("photoUrls");
openapiFields.add("tags");
openapiFields.add("status");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
openapiRequiredFields.add("name");
openapiRequiredFields.add("photoUrls");
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to Pet
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (Pet.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in Pet is not found in the empty JSON string", Pet.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!Pet.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `Pet` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
// check to make sure all required properties/fields are present in the JSON string
for (String requiredField : Pet.openapiRequiredFields) {
if (jsonObj.get(requiredField) == null) {
throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonObj.toString()));
}
}
// validate the optional field `category`
if (jsonObj.getAsJsonObject("category") != null) {
Category.validateJsonObject(jsonObj.getAsJsonObject("category"));
}
JsonArray jsonArraytags = jsonObj.getAsJsonArray("tags");
// validate the optional field `tags` (array)
if (jsonArraytags != null) {
for (int i = 0; i < jsonArraytags.size(); i++) {
Tag.validateJsonObject(jsonArraytags.get(i).getAsJsonObject());
};
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!Pet.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'Pet' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<Pet> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(Pet.class));
return (TypeAdapter<T>) new TypeAdapter<Pet>() {
@Override
public void write(JsonWriter out, Pet value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public Pet read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of Pet given an JSON string
*
* @param jsonString JSON string
* @return An instance of Pet
* @throws IOException if the JSON string is invalid with respect to Pet
*/
public static Pet fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, Pet.class);
}
/**
* Convert an instance of Pet to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

View File

@@ -24,6 +24,25 @@ import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.openapitools.client.JSON;
/**
* ReadOnlyFirst
*/
@@ -124,5 +143,90 @@ public class ReadOnlyFirst {
return o.toString().replace("\n", "\n ");
}
public static HashSet<String> openapiFields;
public static HashSet<String> openapiRequiredFields;
static {
// a set of all properties/fields (JSON key names)
openapiFields = new HashSet<String>();
openapiFields.add("bar");
openapiFields.add("baz");
// a set of required properties/fields (JSON key names)
openapiRequiredFields = new HashSet<String>();
}
/**
* Validates the JSON Object and throws an exception if issues found
*
* @param jsonObj JSON Object
* @throws IOException if the JSON Object is invalid with respect to ReadOnlyFirst
*/
public static void validateJsonObject(JsonObject jsonObj) throws IOException {
if (jsonObj == null) {
if (ReadOnlyFirst.openapiRequiredFields.isEmpty()) {
return;
} else { // has reuqired fields
throw new IllegalArgumentException(String.format("The required field(s) %s in ReadOnlyFirst is not found in the empty JSON string", ReadOnlyFirst.openapiRequiredFields.toString()));
}
}
Set<Entry<String, JsonElement>> entries = jsonObj.entrySet();
// check to see if the JSON string contains additional fields
for (Entry<String, JsonElement> entry : entries) {
if (!ReadOnlyFirst.openapiFields.contains(entry.getKey())) {
throw new IllegalArgumentException(String.format("The field `%s` in the JSON string is not defined in the `ReadOnlyFirst` properties. JSON: %s", entry.getKey(), jsonObj.toString()));
}
}
}
public static class CustomTypeAdapterFactory implements TypeAdapterFactory {
@SuppressWarnings("unchecked")
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
if (!ReadOnlyFirst.class.isAssignableFrom(type.getRawType())) {
return null; // this class only serializes 'ReadOnlyFirst' and its subtypes
}
final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
final TypeAdapter<ReadOnlyFirst> thisAdapter
= gson.getDelegateAdapter(this, TypeToken.get(ReadOnlyFirst.class));
return (TypeAdapter<T>) new TypeAdapter<ReadOnlyFirst>() {
@Override
public void write(JsonWriter out, ReadOnlyFirst value) throws IOException {
JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject();
elementAdapter.write(out, obj);
}
@Override
public ReadOnlyFirst read(JsonReader in) throws IOException {
JsonObject jsonObj = elementAdapter.read(in).getAsJsonObject();
validateJsonObject(jsonObj);
return thisAdapter.fromJsonTree(jsonObj);
}
}.nullSafe();
}
}
/**
* Create an instance of ReadOnlyFirst given an JSON string
*
* @param jsonString JSON string
* @return An instance of ReadOnlyFirst
* @throws IOException if the JSON string is invalid with respect to ReadOnlyFirst
*/
public static ReadOnlyFirst fromJson(String jsonString) throws IOException {
return JSON.getGson().fromJson(jsonString, ReadOnlyFirst.class);
}
/**
* Convert an instance of ReadOnlyFirst to an JSON string
*
* @return JSON string
*/
public String toJson() {
return JSON.getGson().toJson(this);
}
}

Some files were not shown because too many files have changed in this diff Show More