* BAEL-3304 - Add openapi generator client

* BAEL-3304 - Add openapi generator client

* BAEL-3304 - Add openapi generator client to root module

* Remove .gitignore
This commit is contained in:
Mark Thomas 2020-03-22 14:06:39 -05:00 committed by GitHub
parent 504348e3ad
commit 538f07945a
52 changed files with 6996 additions and 0 deletions

View File

@ -15,6 +15,7 @@
<modules>
<module>spring-swagger-codegen-api-client</module>
<module>spring-openapi-generator-api-client</module>
<module>spring-swagger-codegen-app</module>
</modules>

View File

@ -0,0 +1,23 @@
# OpenAPI Generator Ignore
# Generated by openapi-generator https://github.com/openapitools/openapi-generator
# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.
# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
#ApiClient.cs
# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md

View File

@ -0,0 +1,22 @@
#
# Generated by OpenAPI Generator: https://openapi-generator.tech
#
# Ref: https://docs.travis-ci.com/user/languages/java/
#
language: java
jdk:
- openjdk12
- openjdk11
- openjdk10
- openjdk9
- openjdk8
before_install:
# ensure gradlew has proper permission
- chmod a+x ./gradlew
script:
# test using maven
#- mvn test
# test using gradle
- gradle test
# test using sbt
# - sbt test

View File

@ -0,0 +1,174 @@
# spring-openapi-generator-api-client
Swagger Petstore
- API version: 1.0.3
- Build date: 2020-03-15T06:14:01.568992-05:00[America/Chicago]
This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*Automatically generated by the [OpenAPI Generator](https://openapi-generator.tech)*
## Requirements
Building the API client library requires:
1. Java 1.8+
2. Maven/Gradle
## 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>com.baeldung</groupId>
<artifactId>spring-openapi-generator-api-client</artifactId>
<version>0.0.1-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
```
### Gradle users
Add this dependency to your project's build file:
```groovy
compile "com.baeldung:spring-openapi-generator-api-client:0.0.1-SNAPSHOT"
```
### Others
At first generate the JAR by executing:
```shell
mvn clean package
```
Then manually install the following JARs:
- `target/spring-openapi-generator-api-client-0.0.1-SNAPSHOT.jar`
- `target/lib/*.jar`
## Getting Started
Please follow the [installation](#installation) instruction and execute the following Java code:
```java
import com.baeldung.petstore.client.invoker.*;
import com.baeldung.petstore.client.invoker.auth.*;
import com.baeldung.petstore.client.model.*;
import com.baeldung.petstore.client.api.PetApi;
public class PetApiExample {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("https://petstore.swagger.io/v2");
// Configure OAuth2 access token for authorization: petstore_auth
OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth");
petstore_auth.setAccessToken("YOUR ACCESS TOKEN");
PetApi apiInstance = new PetApi(defaultClient);
Pet body = new Pet(); // Pet | Pet object that needs to be added to the store
try {
apiInstance.addPet(body);
} catch (ApiException e) {
System.err.println("Exception when calling PetApi#addPet");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
## Documentation for API Endpoints
All URIs are relative to *https://petstore.swagger.io/v2*
Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
*PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store
*PetApi* | [**deletePet**](docs/PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet
*PetApi* | [**findPetsByStatus**](docs/PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status
*PetApi* | [**findPetsByTags**](docs/PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags
*PetApi* | [**getPetById**](docs/PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID
*PetApi* | [**updatePet**](docs/PetApi.md#updatePet) | **PUT** /pet | Update an existing pet
*PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data
*PetApi* | [**uploadFile**](docs/PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image
*StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID
*StoreApi* | [**getInventory**](docs/StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status
*StoreApi* | [**getOrderById**](docs/StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID
*StoreApi* | [**placeOrder**](docs/StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet
*UserApi* | [**createUser**](docs/UserApi.md#createUser) | **POST** /user | Create user
*UserApi* | [**createUsersWithArrayInput**](docs/UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array
*UserApi* | [**createUsersWithListInput**](docs/UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array
*UserApi* | [**deleteUser**](docs/UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user
*UserApi* | [**getUserByName**](docs/UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name
*UserApi* | [**loginUser**](docs/UserApi.md#loginUser) | **GET** /user/login | Logs user into the system
*UserApi* | [**logoutUser**](docs/UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session
*UserApi* | [**updateUser**](docs/UserApi.md#updateUser) | **PUT** /user/{username} | Updated user
## Documentation for Models
- [Category](docs/Category.md)
- [ModelApiResponse](docs/ModelApiResponse.md)
- [Order](docs/Order.md)
- [Pet](docs/Pet.md)
- [Tag](docs/Tag.md)
- [User](docs/User.md)
## Documentation for Authorization
Authentication schemes defined for the API:
### api_key
- **Type**: API key
- **API key parameter name**: api_key
- **Location**: HTTP header
### petstore_auth
- **Type**: OAuth
- **Flow**: implicit
- **Authorization URL**: https://petstore.swagger.io/oauth/authorize
- **Scopes**:
- read:pets: read your pets
- write:pets: modify pets in your account
## Recommendation
It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues.
## Author
apiteam@swagger.io

View File

@ -0,0 +1,120 @@
apply plugin: 'idea'
apply plugin: 'eclipse'
group = 'com.baeldung'
version = '0.0.1-SNAPSHOT'
buildscript {
repositories {
maven { url "https://repo1.maven.org/maven2" }
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.5.+'
classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3'
}
}
repositories {
jcenter()
}
if(hasProperty('target') && target == 'android') {
apply plugin: 'com.android.library'
apply plugin: 'com.github.dcendents.android-maven'
android {
compileSdkVersion 23
buildToolsVersion '23.0.2'
defaultConfig {
minSdkVersion 14
targetSdkVersion 22
}
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 'javax.annotation:jsr250-api:1.0'
}
}
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'
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
install {
repositories.mavenInstaller {
pom.artifactId = 'spring-openapi-generator-api-client'
}
}
task execute(type:JavaExec) {
main = System.getProperty('mainClass')
classpath = sourceSets.main.runtimeClasspath
}
}
ext {
swagger_annotations_version = "1.5.22"
jackson_version = "2.10.1"
jackson_databind_version = "2.10.1"
jackson_databind_nullable_version = "0.2.1"
spring_web_version = "4.3.9.RELEASE"
jodatime_version = "2.9.9"
junit_version = "4.13"
jackson_threeten_version = "2.9.10"
}
dependencies {
compile "io.swagger:swagger-annotations:$swagger_annotations_version"
compile "com.google.code.findbugs:jsr305:3.0.2"
compile "org.springframework:spring-web:$spring_web_version"
compile "com.fasterxml.jackson.core:jackson-core:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version"
compile "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version"
compile "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:$jackson_version"
compile "org.openapitools:jackson-databind-nullable:$jackson_databind_nullable_version"
compile "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version"
compile "com.github.joschi.jackson:jackson-datatype-threetenbp:$jackson_threeten_version"
testCompile "junit:junit:$junit_version"
}

View File

@ -0,0 +1,13 @@
# Category
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **Long** | | [optional]
**name** | **String** | | [optional]

View File

@ -0,0 +1,14 @@
# ModelApiResponse
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**code** | **Integer** | | [optional]
**type** | **String** | | [optional]
**message** | **String** | | [optional]

View File

@ -0,0 +1,27 @@
# Order
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **Long** | | [optional]
**petId** | **Long** | | [optional]
**quantity** | **Integer** | | [optional]
**shipDate** | [**OffsetDateTime**](OffsetDateTime.md) | | [optional]
**status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional]
**complete** | **Boolean** | | [optional]
## Enum: StatusEnum
Name | Value
---- | -----
PLACED | &quot;placed&quot;
APPROVED | &quot;approved&quot;
DELIVERED | &quot;delivered&quot;

View File

@ -0,0 +1,27 @@
# Pet
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **Long** | | [optional]
**category** | [**Category**](Category.md) | | [optional]
**name** | **String** | |
**photoUrls** | **List&lt;String&gt;** | |
**tags** | [**List&lt;Tag&gt;**](Tag.md) | | [optional]
**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional]
## Enum: StatusEnum
Name | Value
---- | -----
AVAILABLE | &quot;available&quot;
PENDING | &quot;pending&quot;
SOLD | &quot;sold&quot;

View File

@ -0,0 +1,581 @@
# PetApi
All URIs are relative to *https://petstore.swagger.io/v2*
Method | HTTP request | Description
------------- | ------------- | -------------
[**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store
[**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet
[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status
[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags
[**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID
[**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet
[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data
[**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image
## addPet
> addPet(body)
Add a new pet to the store
### Example
```java
// Import classes:
import com.baeldung.petstore.client.invoker.ApiClient;
import com.baeldung.petstore.client.invoker.ApiException;
import com.baeldung.petstore.client.invoker.Configuration;
import com.baeldung.petstore.client.invoker.auth.*;
import com.baeldung.petstore.client.invoker.models.*;
import com.baeldung.petstore.client.api.PetApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("https://petstore.swagger.io/v2");
// Configure OAuth2 access token for authorization: petstore_auth
OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth");
petstore_auth.setAccessToken("YOUR ACCESS TOKEN");
PetApi apiInstance = new PetApi(defaultClient);
Pet body = new Pet(); // Pet | Pet object that needs to be added to the store
try {
apiInstance.addPet(body);
} catch (ApiException e) {
System.err.println("Exception when calling PetApi#addPet");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store |
### Return type
null (empty response body)
### Authorization
[petstore_auth](../README.md#petstore_auth)
### HTTP request headers
- **Content-Type**: application/json, application/xml
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **405** | Invalid input | - |
## deletePet
> deletePet(petId, apiKey)
Deletes a pet
### Example
```java
// Import classes:
import com.baeldung.petstore.client.invoker.ApiClient;
import com.baeldung.petstore.client.invoker.ApiException;
import com.baeldung.petstore.client.invoker.Configuration;
import com.baeldung.petstore.client.invoker.auth.*;
import com.baeldung.petstore.client.invoker.models.*;
import com.baeldung.petstore.client.api.PetApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("https://petstore.swagger.io/v2");
// Configure OAuth2 access token for authorization: petstore_auth
OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth");
petstore_auth.setAccessToken("YOUR ACCESS TOKEN");
PetApi apiInstance = new PetApi(defaultClient);
Long petId = 56L; // Long | Pet id to delete
String apiKey = "apiKey_example"; // String |
try {
apiInstance.deletePet(petId, apiKey);
} catch (ApiException e) {
System.err.println("Exception when calling PetApi#deletePet");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**petId** | **Long**| Pet id to delete |
**apiKey** | **String**| | [optional]
### Return type
null (empty response body)
### Authorization
[petstore_auth](../README.md#petstore_auth)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **400** | Invalid ID supplied | - |
| **404** | Pet not found | - |
## findPetsByStatus
> List&lt;Pet&gt; findPetsByStatus(status)
Finds Pets by status
Multiple status values can be provided with comma separated strings
### Example
```java
// Import classes:
import com.baeldung.petstore.client.invoker.ApiClient;
import com.baeldung.petstore.client.invoker.ApiException;
import com.baeldung.petstore.client.invoker.Configuration;
import com.baeldung.petstore.client.invoker.auth.*;
import com.baeldung.petstore.client.invoker.models.*;
import com.baeldung.petstore.client.api.PetApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("https://petstore.swagger.io/v2");
// Configure OAuth2 access token for authorization: petstore_auth
OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth");
petstore_auth.setAccessToken("YOUR ACCESS TOKEN");
PetApi apiInstance = new PetApi(defaultClient);
List<String> status = Arrays.asList("available"); // List<String> | Status values that need to be considered for filter
try {
List<Pet> result = apiInstance.findPetsByStatus(status);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PetApi#findPetsByStatus");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**status** | [**List&lt;String&gt;**](String.md)| Status values that need to be considered for filter | [enum: available, pending, sold]
### Return type
[**List&lt;Pet&gt;**](Pet.md)
### Authorization
[petstore_auth](../README.md#petstore_auth)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json, application/xml
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid status value | - |
## findPetsByTags
> List&lt;Pet&gt; findPetsByTags(tags)
Finds Pets by tags
Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
### Example
```java
// Import classes:
import com.baeldung.petstore.client.invoker.ApiClient;
import com.baeldung.petstore.client.invoker.ApiException;
import com.baeldung.petstore.client.invoker.Configuration;
import com.baeldung.petstore.client.invoker.auth.*;
import com.baeldung.petstore.client.invoker.models.*;
import com.baeldung.petstore.client.api.PetApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("https://petstore.swagger.io/v2");
// Configure OAuth2 access token for authorization: petstore_auth
OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth");
petstore_auth.setAccessToken("YOUR ACCESS TOKEN");
PetApi apiInstance = new PetApi(defaultClient);
List<String> tags = Arrays.asList(); // List<String> | Tags to filter by
try {
List<Pet> result = apiInstance.findPetsByTags(tags);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PetApi#findPetsByTags");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**tags** | [**List&lt;String&gt;**](String.md)| Tags to filter by |
### Return type
[**List&lt;Pet&gt;**](Pet.md)
### Authorization
[petstore_auth](../README.md#petstore_auth)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json, application/xml
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid tag value | - |
## getPetById
> Pet getPetById(petId)
Find pet by ID
Returns a single pet
### Example
```java
// Import classes:
import com.baeldung.petstore.client.invoker.ApiClient;
import com.baeldung.petstore.client.invoker.ApiException;
import com.baeldung.petstore.client.invoker.Configuration;
import com.baeldung.petstore.client.invoker.auth.*;
import com.baeldung.petstore.client.invoker.models.*;
import com.baeldung.petstore.client.api.PetApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("https://petstore.swagger.io/v2");
// Configure API key authorization: api_key
ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key");
api_key.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//api_key.setApiKeyPrefix("Token");
PetApi apiInstance = new PetApi(defaultClient);
Long petId = 56L; // Long | ID of pet to return
try {
Pet result = apiInstance.getPetById(petId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PetApi#getPetById");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**petId** | **Long**| ID of pet to return |
### Return type
[**Pet**](Pet.md)
### Authorization
[api_key](../README.md#api_key)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json, application/xml
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid ID supplied | - |
| **404** | Pet not found | - |
## updatePet
> updatePet(body)
Update an existing pet
### Example
```java
// Import classes:
import com.baeldung.petstore.client.invoker.ApiClient;
import com.baeldung.petstore.client.invoker.ApiException;
import com.baeldung.petstore.client.invoker.Configuration;
import com.baeldung.petstore.client.invoker.auth.*;
import com.baeldung.petstore.client.invoker.models.*;
import com.baeldung.petstore.client.api.PetApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("https://petstore.swagger.io/v2");
// Configure OAuth2 access token for authorization: petstore_auth
OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth");
petstore_auth.setAccessToken("YOUR ACCESS TOKEN");
PetApi apiInstance = new PetApi(defaultClient);
Pet body = new Pet(); // Pet | Pet object that needs to be added to the store
try {
apiInstance.updatePet(body);
} catch (ApiException e) {
System.err.println("Exception when calling PetApi#updatePet");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store |
### Return type
null (empty response body)
### Authorization
[petstore_auth](../README.md#petstore_auth)
### HTTP request headers
- **Content-Type**: application/json, application/xml
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **400** | Invalid ID supplied | - |
| **404** | Pet not found | - |
| **405** | Validation exception | - |
## updatePetWithForm
> updatePetWithForm(petId, name, status)
Updates a pet in the store with form data
### Example
```java
// Import classes:
import com.baeldung.petstore.client.invoker.ApiClient;
import com.baeldung.petstore.client.invoker.ApiException;
import com.baeldung.petstore.client.invoker.Configuration;
import com.baeldung.petstore.client.invoker.auth.*;
import com.baeldung.petstore.client.invoker.models.*;
import com.baeldung.petstore.client.api.PetApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("https://petstore.swagger.io/v2");
// Configure OAuth2 access token for authorization: petstore_auth
OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth");
petstore_auth.setAccessToken("YOUR ACCESS TOKEN");
PetApi apiInstance = new PetApi(defaultClient);
Long petId = 56L; // Long | ID of pet that needs to be updated
String name = "name_example"; // String | Updated name of the pet
String status = "status_example"; // String | Updated status of the pet
try {
apiInstance.updatePetWithForm(petId, name, status);
} catch (ApiException e) {
System.err.println("Exception when calling PetApi#updatePetWithForm");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**petId** | **Long**| ID of pet that needs to be updated |
**name** | **String**| Updated name of the pet | [optional]
**status** | **String**| Updated status of the pet | [optional]
### Return type
null (empty response body)
### Authorization
[petstore_auth](../README.md#petstore_auth)
### HTTP request headers
- **Content-Type**: application/x-www-form-urlencoded
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **405** | Invalid input | - |
## uploadFile
> ModelApiResponse uploadFile(petId, additionalMetadata, file)
uploads an image
### Example
```java
// Import classes:
import com.baeldung.petstore.client.invoker.ApiClient;
import com.baeldung.petstore.client.invoker.ApiException;
import com.baeldung.petstore.client.invoker.Configuration;
import com.baeldung.petstore.client.invoker.auth.*;
import com.baeldung.petstore.client.invoker.models.*;
import com.baeldung.petstore.client.api.PetApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("https://petstore.swagger.io/v2");
// Configure OAuth2 access token for authorization: petstore_auth
OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth");
petstore_auth.setAccessToken("YOUR ACCESS TOKEN");
PetApi apiInstance = new PetApi(defaultClient);
Long petId = 56L; // Long | ID of pet to update
String additionalMetadata = "additionalMetadata_example"; // String | Additional data to pass to server
File file = new File("/path/to/file"); // File | file to upload
try {
ModelApiResponse result = apiInstance.uploadFile(petId, additionalMetadata, file);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling PetApi#uploadFile");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**petId** | **Long**| ID of pet to update |
**additionalMetadata** | **String**| Additional data to pass to server | [optional]
**file** | **File**| file to upload | [optional]
### Return type
[**ModelApiResponse**](ModelApiResponse.md)
### Authorization
[petstore_auth](../README.md#petstore_auth)
### HTTP request headers
- **Content-Type**: multipart/form-data
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |

View File

@ -0,0 +1,276 @@
# StoreApi
All URIs are relative to *https://petstore.swagger.io/v2*
Method | HTTP request | Description
------------- | ------------- | -------------
[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID
[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status
[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID
[**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet
## deleteOrder
> deleteOrder(orderId)
Delete purchase order by ID
For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors
### Example
```java
// Import classes:
import com.baeldung.petstore.client.invoker.ApiClient;
import com.baeldung.petstore.client.invoker.ApiException;
import com.baeldung.petstore.client.invoker.Configuration;
import com.baeldung.petstore.client.invoker.models.*;
import com.baeldung.petstore.client.api.StoreApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("https://petstore.swagger.io/v2");
StoreApi apiInstance = new StoreApi(defaultClient);
Long orderId = 56L; // Long | ID of the order that needs to be deleted
try {
apiInstance.deleteOrder(orderId);
} catch (ApiException e) {
System.err.println("Exception when calling StoreApi#deleteOrder");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**orderId** | **Long**| ID of the order that needs to be deleted |
### Return type
null (empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **400** | Invalid ID supplied | - |
| **404** | Order not found | - |
## getInventory
> Map&lt;String, Integer&gt; getInventory()
Returns pet inventories by status
Returns a map of status codes to quantities
### Example
```java
// Import classes:
import com.baeldung.petstore.client.invoker.ApiClient;
import com.baeldung.petstore.client.invoker.ApiException;
import com.baeldung.petstore.client.invoker.Configuration;
import com.baeldung.petstore.client.invoker.auth.*;
import com.baeldung.petstore.client.invoker.models.*;
import com.baeldung.petstore.client.api.StoreApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("https://petstore.swagger.io/v2");
// Configure API key authorization: api_key
ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key");
api_key.setApiKey("YOUR API KEY");
// Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null)
//api_key.setApiKeyPrefix("Token");
StoreApi apiInstance = new StoreApi(defaultClient);
try {
Map<String, Integer> result = apiInstance.getInventory();
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling StoreApi#getInventory");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
This endpoint does not need any parameter.
### Return type
**Map&lt;String, Integer&gt;**
### Authorization
[api_key](../README.md#api_key)
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
## getOrderById
> Order getOrderById(orderId)
Find purchase order by ID
For valid response try integer IDs with value &gt;&#x3D; 1 and &lt;&#x3D; 10. Other values will generated exceptions
### Example
```java
// Import classes:
import com.baeldung.petstore.client.invoker.ApiClient;
import com.baeldung.petstore.client.invoker.ApiException;
import com.baeldung.petstore.client.invoker.Configuration;
import com.baeldung.petstore.client.invoker.models.*;
import com.baeldung.petstore.client.api.StoreApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("https://petstore.swagger.io/v2");
StoreApi apiInstance = new StoreApi(defaultClient);
Long orderId = 56L; // Long | ID of pet that needs to be fetched
try {
Order result = apiInstance.getOrderById(orderId);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling StoreApi#getOrderById");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**orderId** | **Long**| ID of pet that needs to be fetched |
### Return type
[**Order**](Order.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json, application/xml
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid ID supplied | - |
| **404** | Order not found | - |
## placeOrder
> Order placeOrder(body)
Place an order for a pet
### Example
```java
// Import classes:
import com.baeldung.petstore.client.invoker.ApiClient;
import com.baeldung.petstore.client.invoker.ApiException;
import com.baeldung.petstore.client.invoker.Configuration;
import com.baeldung.petstore.client.invoker.models.*;
import com.baeldung.petstore.client.api.StoreApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("https://petstore.swagger.io/v2");
StoreApi apiInstance = new StoreApi(defaultClient);
Order body = new Order(); // Order | order placed for purchasing the pet
try {
Order result = apiInstance.placeOrder(body);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling StoreApi#placeOrder");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**Order**](Order.md)| order placed for purchasing the pet |
### Return type
[**Order**](Order.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: application/json, application/xml
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid Order | - |

View File

@ -0,0 +1,13 @@
# Tag
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **Long** | | [optional]
**name** | **String** | | [optional]

View File

@ -0,0 +1,19 @@
# User
## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **Long** | | [optional]
**username** | **String** | | [optional]
**firstName** | **String** | | [optional]
**lastName** | **String** | | [optional]
**email** | **String** | | [optional]
**password** | **String** | | [optional]
**phone** | **String** | | [optional]
**userStatus** | **Integer** | User Status | [optional]

View File

@ -0,0 +1,525 @@
# UserApi
All URIs are relative to *https://petstore.swagger.io/v2*
Method | HTTP request | Description
------------- | ------------- | -------------
[**createUser**](UserApi.md#createUser) | **POST** /user | Create user
[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array
[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array
[**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user
[**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name
[**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system
[**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session
[**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user
## createUser
> createUser(body)
Create user
This can only be done by the logged in user.
### Example
```java
// Import classes:
import com.baeldung.petstore.client.invoker.ApiClient;
import com.baeldung.petstore.client.invoker.ApiException;
import com.baeldung.petstore.client.invoker.Configuration;
import com.baeldung.petstore.client.invoker.models.*;
import com.baeldung.petstore.client.api.UserApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("https://petstore.swagger.io/v2");
UserApi apiInstance = new UserApi(defaultClient);
User body = new User(); // User | Created user object
try {
apiInstance.createUser(body);
} catch (ApiException e) {
System.err.println("Exception when calling UserApi#createUser");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**User**](User.md)| Created user object |
### Return type
null (empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **0** | successful operation | - |
## createUsersWithArrayInput
> createUsersWithArrayInput(body)
Creates list of users with given input array
### Example
```java
// Import classes:
import com.baeldung.petstore.client.invoker.ApiClient;
import com.baeldung.petstore.client.invoker.ApiException;
import com.baeldung.petstore.client.invoker.Configuration;
import com.baeldung.petstore.client.invoker.models.*;
import com.baeldung.petstore.client.api.UserApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("https://petstore.swagger.io/v2");
UserApi apiInstance = new UserApi(defaultClient);
List<User> body = Arrays.asList(); // List<User> | List of user object
try {
apiInstance.createUsersWithArrayInput(body);
} catch (ApiException e) {
System.err.println("Exception when calling UserApi#createUsersWithArrayInput");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**List&lt;User&gt;**](User.md)| List of user object |
### Return type
null (empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **0** | successful operation | - |
## createUsersWithListInput
> createUsersWithListInput(body)
Creates list of users with given input array
### Example
```java
// Import classes:
import com.baeldung.petstore.client.invoker.ApiClient;
import com.baeldung.petstore.client.invoker.ApiException;
import com.baeldung.petstore.client.invoker.Configuration;
import com.baeldung.petstore.client.invoker.models.*;
import com.baeldung.petstore.client.api.UserApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("https://petstore.swagger.io/v2");
UserApi apiInstance = new UserApi(defaultClient);
List<User> body = Arrays.asList(); // List<User> | List of user object
try {
apiInstance.createUsersWithListInput(body);
} catch (ApiException e) {
System.err.println("Exception when calling UserApi#createUsersWithListInput");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**body** | [**List&lt;User&gt;**](User.md)| List of user object |
### Return type
null (empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **0** | successful operation | - |
## deleteUser
> deleteUser(username)
Delete user
This can only be done by the logged in user.
### Example
```java
// Import classes:
import com.baeldung.petstore.client.invoker.ApiClient;
import com.baeldung.petstore.client.invoker.ApiException;
import com.baeldung.petstore.client.invoker.Configuration;
import com.baeldung.petstore.client.invoker.models.*;
import com.baeldung.petstore.client.api.UserApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("https://petstore.swagger.io/v2");
UserApi apiInstance = new UserApi(defaultClient);
String username = "username_example"; // String | The name that needs to be deleted
try {
apiInstance.deleteUser(username);
} catch (ApiException e) {
System.err.println("Exception when calling UserApi#deleteUser");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**username** | **String**| The name that needs to be deleted |
### Return type
null (empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **400** | Invalid username supplied | - |
| **404** | User not found | - |
## getUserByName
> User getUserByName(username)
Get user by user name
### Example
```java
// Import classes:
import com.baeldung.petstore.client.invoker.ApiClient;
import com.baeldung.petstore.client.invoker.ApiException;
import com.baeldung.petstore.client.invoker.Configuration;
import com.baeldung.petstore.client.invoker.models.*;
import com.baeldung.petstore.client.api.UserApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("https://petstore.swagger.io/v2");
UserApi apiInstance = new UserApi(defaultClient);
String username = "username_example"; // String | The name that needs to be fetched. Use user1 for testing.
try {
User result = apiInstance.getUserByName(username);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling UserApi#getUserByName");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**username** | **String**| The name that needs to be fetched. Use user1 for testing. |
### Return type
[**User**](User.md)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json, application/xml
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | - |
| **400** | Invalid username supplied | - |
| **404** | User not found | - |
## loginUser
> String loginUser(username, password)
Logs user into the system
### Example
```java
// Import classes:
import com.baeldung.petstore.client.invoker.ApiClient;
import com.baeldung.petstore.client.invoker.ApiException;
import com.baeldung.petstore.client.invoker.Configuration;
import com.baeldung.petstore.client.invoker.models.*;
import com.baeldung.petstore.client.api.UserApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("https://petstore.swagger.io/v2");
UserApi apiInstance = new UserApi(defaultClient);
String username = "username_example"; // String | The user name for login
String password = "password_example"; // String | The password for login in clear text
try {
String result = apiInstance.loginUser(username, password);
System.out.println(result);
} catch (ApiException e) {
System.err.println("Exception when calling UserApi#loginUser");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**username** | **String**| The user name for login |
**password** | **String**| The password for login in clear text |
### Return type
**String**
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: application/json, application/xml
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **200** | successful operation | * X-Rate-Limit - calls per hour allowed by the user <br> * X-Expires-After - date in UTC when token expires <br> |
| **400** | Invalid username/password supplied | - |
## logoutUser
> logoutUser()
Logs out current logged in user session
### Example
```java
// Import classes:
import com.baeldung.petstore.client.invoker.ApiClient;
import com.baeldung.petstore.client.invoker.ApiException;
import com.baeldung.petstore.client.invoker.Configuration;
import com.baeldung.petstore.client.invoker.models.*;
import com.baeldung.petstore.client.api.UserApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("https://petstore.swagger.io/v2");
UserApi apiInstance = new UserApi(defaultClient);
try {
apiInstance.logoutUser();
} catch (ApiException e) {
System.err.println("Exception when calling UserApi#logoutUser");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
This endpoint does not need any parameter.
### Return type
null (empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: Not defined
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **0** | successful operation | - |
## updateUser
> updateUser(username, body)
Updated user
This can only be done by the logged in user.
### Example
```java
// Import classes:
import com.baeldung.petstore.client.invoker.ApiClient;
import com.baeldung.petstore.client.invoker.ApiException;
import com.baeldung.petstore.client.invoker.Configuration;
import com.baeldung.petstore.client.invoker.models.*;
import com.baeldung.petstore.client.api.UserApi;
public class Example {
public static void main(String[] args) {
ApiClient defaultClient = Configuration.getDefaultApiClient();
defaultClient.setBasePath("https://petstore.swagger.io/v2");
UserApi apiInstance = new UserApi(defaultClient);
String username = "username_example"; // String | name that need to be updated
User body = new User(); // User | Updated user object
try {
apiInstance.updateUser(username, body);
} catch (ApiException e) {
System.err.println("Exception when calling UserApi#updateUser");
System.err.println("Status code: " + e.getCode());
System.err.println("Reason: " + e.getResponseBody());
System.err.println("Response headers: " + e.getResponseHeaders());
e.printStackTrace();
}
}
}
```
### Parameters
Name | Type | Description | Notes
------------- | ------------- | ------------- | -------------
**username** | **String**| name that need to be updated |
**body** | [**User**](User.md)| Updated user object |
### Return type
null (empty response body)
### Authorization
No authorization required
### HTTP request headers
- **Content-Type**: application/json
- **Accept**: Not defined
### HTTP response details
| Status code | Description | Response headers |
|-------------|-------------|------------------|
| **400** | Invalid user supplied | - |
| **404** | User not found | - |

View File

@ -0,0 +1,58 @@
#!/bin/sh
# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/
#
# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com"
git_user_id=$1
git_repo_id=$2
release_note=$3
git_host=$4
if [ "$git_host" = "" ]; then
git_host="github.com"
echo "[INFO] No command line input provided. Set \$git_host to $git_host"
fi
if [ "$git_user_id" = "" ]; then
git_user_id="GIT_USER_ID"
echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id"
fi
if [ "$git_repo_id" = "" ]; then
git_repo_id="GIT_REPO_ID"
echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id"
fi
if [ "$release_note" = "" ]; then
release_note="Minor update"
echo "[INFO] No command line input provided. Set \$release_note to $release_note"
fi
# Initialize the local directory as a Git repository
git init
# Adds the files in the local repository and stages them for commit.
git add .
# Commits the tracked changes and prepares them to be pushed to a remote repository.
git commit -m "$release_note"
# Sets the new remote
git_remote=`git remote`
if [ "$git_remote" = "" ]; then # git remote not defined
if [ "$GIT_TOKEN" = "" ]; then
echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment."
git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git
else
git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git
fi
fi
git pull origin master
# Pushes (Forces) the changes in the local repository up to the remote repository
echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git"
git push origin master 2>&1 | grep -v 'To https'

View File

@ -0,0 +1,2 @@
# Uncomment to build for Android
#target = android

View File

@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.0.1-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

View File

@ -0,0 +1,183 @@
#!/usr/bin/env sh
#
# Copyright 2015 the original author or authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##############################################################################
##
## Gradle start up script for UN*X
##
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
PRG="$0"
# Need this for relative symlinks.
while [ -h "$PRG" ] ; do
ls=`ls -ld "$PRG"`
link=`expr "$ls" : '.*-> \(.*\)$'`
if expr "$link" : '/.*' > /dev/null; then
PRG="$link"
else
PRG=`dirname "$PRG"`"/$link"
fi
done
SAVED="`pwd`"
cd "`dirname \"$PRG\"`/" >/dev/null
APP_HOME="`pwd -P`"
cd "$SAVED" >/dev/null
APP_NAME="Gradle"
APP_BASE_NAME=`basename "$0"`
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD="maximum"
warn () {
echo "$*"
}
die () {
echo
echo "$*"
echo
exit 1
}
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "`uname`" in
CYGWIN* )
cygwin=true
;;
Darwin* )
darwin=true
;;
MINGW* )
msys=true
;;
NONSTOP* )
nonstop=true
;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD="$JAVA_HOME/jre/sh/java"
else
JAVACMD="$JAVA_HOME/bin/java"
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD="java"
which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
# Increase the maximum file descriptors if we can.
if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
MAX_FD_LIMIT=`ulimit -H -n`
if [ $? -eq 0 ] ; then
if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
MAX_FD="$MAX_FD_LIMIT"
fi
ulimit -n $MAX_FD
if [ $? -ne 0 ] ; then
warn "Could not set maximum file descriptor limit: $MAX_FD"
fi
else
warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
fi
fi
# For Darwin, add options to specify how the application appears in the dock
if $darwin; then
GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
fi
# For Cygwin or MSYS, switch paths to Windows format before running java
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
JAVACMD=`cygpath --unix "$JAVACMD"`
# We build the pattern for arguments to be converted via cygpath
ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
SEP=""
for dir in $ROOTDIRSRAW ; do
ROOTDIRS="$ROOTDIRS$SEP$dir"
SEP="|"
done
OURCYGPATTERN="(^($ROOTDIRS))"
# Add a user-defined pattern to the cygpath arguments
if [ "$GRADLE_CYGPATTERN" != "" ] ; then
OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
fi
# Now convert the arguments - kludge to limit ourselves to /bin/sh
i=0
for arg in "$@" ; do
CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
else
eval `echo args$i`="\"$arg\""
fi
i=`expr $i + 1`
done
case $i in
0) set -- ;;
1) set -- "$args0" ;;
2) set -- "$args0" "$args1" ;;
3) set -- "$args0" "$args1" "$args2" ;;
4) set -- "$args0" "$args1" "$args2" "$args3" ;;
5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
esac
fi
# Escape application args
save () {
for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
echo " "
}
APP_ARGS=`save "$@"`
# Collect all arguments for the java command, following the shell quoting and substitution rules
eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
exec "$JAVACMD" "$@"

View File

@ -0,0 +1,100 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@if "%DEBUG%" == "" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%" == "" set DIRNAME=.
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if "%ERRORLEVEL%" == "0" goto init
echo.
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto init
echo.
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
echo.
echo Please set the JAVA_HOME variable in your environment to match the
echo location of your Java installation.
goto fail
:init
@rem Get command-line arguments, handling Windows variants
if not "%OS%" == "Windows_NT" goto win9xME_args
:win9xME_args
@rem Slurp the command line arguments.
set CMD_LINE_ARGS=
set _SKIP=2
:win9xME_args_slurp
if "x%~1" == "x" goto execute
set CMD_LINE_ARGS=%*
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
:end
@rem End local scope for the variables with windows NT shell
if "%ERRORLEVEL%"=="0" goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
exit /b 1
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@ -0,0 +1,274 @@
<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>com.baeldung</groupId>
<artifactId>spring-openapi-generator-api-client</artifactId>
<packaging>jar</packaging>
<name>spring-openapi-generator-api-client</name>
<version>0.0.1-SNAPSHOT</version>
<url>https://github.com/openapitools/openapi-generator</url>
<description>OpenAPI Java</description>
<scm>
<connection>scm:git:git@github.com:openapitools/openapi-generator.git</connection>
<developerConnection>scm:git:git@github.com:openapitools/openapi-generator.git</developerConnection>
<url>https://github.com/openapitools/openapi-generator</url>
</scm>
<licenses>
<license>
<name>Unlicense</name>
<url>http://www.apache.org/licenses/LICENSE-2.0.html</url>
<distribution>repo</distribution>
</license>
</licenses>
<developers>
<developer>
<name>OpenAPI-Generator Contributors</name>
<email>team@openapitools.org</email>
<organization>OpenAPITools.org</organization>
<organizationUrl>http://openapitools.org</organizationUrl>
</developer>
</developers>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.0.0-M1</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>2.12</version>
<configuration>
<systemProperties>
<property>
<name>loggerPath</name>
<value>conf/log4j.properties</value>
</property>
</systemProperties>
<argLine>-Xms512m -Xmx1500m</argLine>
<parallel>methods</parallel>
<forkMode>pertest</forkMode>
</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>2.2</version>
<executions>
<execution>
<goals>
<goal>jar</goal>
<goal>test-jar</goal>
</goals>
</execution>
</executions>
<configuration>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>1.10</version>
<executions>
<execution>
<id>add_sources</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>src/main/java</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-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.10.4</version>
<executions>
<execution>
<id>attach-javadocs</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.2.1</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar-no-fork</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>sign-artifacts</id>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-gpg-plugin</artifactId>
<version>1.5</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-annotations-version}</version>
</dependency>
<!-- @Nullable annotation -->
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.2</version>
</dependency>
<!-- HTTP client: Spring RestTemplate -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring-web-version}</version>
</dependency>
<!-- JSON processing: jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-databind-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>org.openapitools</groupId>
<artifactId>jackson-databind-nullable</artifactId>
<version>${jackson-databind-nullable-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.github.joschi.jackson</groupId>
<artifactId>jackson-datatype-threetenbp</artifactId>
<version>${jackson-threetenbp-version}</version>
</dependency>
<!-- test dependencies -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<swagger-annotations-version>1.5.22</swagger-annotations-version>
<spring-web-version>4.3.9.RELEASE</spring-web-version>
<jackson-version>2.10.1</jackson-version>
<jackson-databind-version>2.10.1</jackson-databind-version>
<jackson-databind-nullable-version>0.2.1</jackson-databind-nullable-version>
<jackson-threetenbp-version>2.9.10</jackson-threetenbp-version>
<maven-plugin-version>1.0.0</maven-plugin-version>
<junit-version>4.13</junit-version>
</properties>
</project>

View File

@ -0,0 +1 @@
rootProject.name = "spring-openapi-generator-api-client"

View File

@ -0,0 +1,3 @@
<manifest package="com.baeldung.petstore.client.invoker" xmlns:android="http://schemas.android.com/apk/res/android">
<application />
</manifest>

View File

@ -0,0 +1,477 @@
package com.baeldung.petstore.client.api;
import com.baeldung.petstore.client.invoker.ApiClient;
import com.baeldung.petstore.client.model.ModelApiResponse;
import com.baeldung.petstore.client.model.Pet;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestClientException;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]")
@Component("com.baeldung.petstore.client.api.PetApi")
public class PetApi {
private ApiClient apiClient;
public PetApi() {
this(new ApiClient());
}
@Autowired
public PetApi(ApiClient apiClient) {
this.apiClient = apiClient;
}
public ApiClient getApiClient() {
return apiClient;
}
public void setApiClient(ApiClient apiClient) {
this.apiClient = apiClient;
}
/**
* Add a new pet to the store
*
* <p><b>405</b> - Invalid input
* @param body Pet object that needs to be added to the store (required)
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public void addPet(Pet body) throws RestClientException {
addPetWithHttpInfo(body);
}
/**
* Add a new pet to the store
*
* <p><b>405</b> - Invalid input
* @param body Pet object that needs to be added to the store (required)
* @return ResponseEntity&lt;Void&gt;
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public ResponseEntity<Void> addPetWithHttpInfo(Pet body) throws RestClientException {
Object postBody = body;
// verify the required parameter 'body' is set
if (body == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling addPet");
}
String path = apiClient.expandPath("/pet", Collections.<String, Object>emptyMap());
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
final MultiValueMap formParams = new LinkedMultiValueMap();
final String[] accepts = { };
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json", "application/xml"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { "petstore_auth" };
ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Deletes a pet
*
* <p><b>400</b> - Invalid ID supplied
* <p><b>404</b> - Pet not found
* @param petId Pet id to delete (required)
* @param apiKey (optional)
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public void deletePet(Long petId, String apiKey) throws RestClientException {
deletePetWithHttpInfo(petId, apiKey);
}
/**
* Deletes a pet
*
* <p><b>400</b> - Invalid ID supplied
* <p><b>404</b> - Pet not found
* @param petId Pet id to delete (required)
* @param apiKey (optional)
* @return ResponseEntity&lt;Void&gt;
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public ResponseEntity<Void> deletePetWithHttpInfo(Long petId, String apiKey) throws RestClientException {
Object postBody = null;
// verify the required parameter 'petId' is set
if (petId == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'petId' when calling deletePet");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("petId", petId);
String path = apiClient.expandPath("/pet/{petId}", uriVariables);
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
final MultiValueMap formParams = new LinkedMultiValueMap();
if (apiKey != null)
headerParams.add("api_key", apiClient.parameterToString(apiKey));
final String[] accepts = { };
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = { };
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { "petstore_auth" };
ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Finds Pets by status
* Multiple status values can be provided with comma separated strings
* <p><b>200</b> - successful operation
* <p><b>400</b> - Invalid status value
* @param status Status values that need to be considered for filter (required)
* @return List&lt;Pet&gt;
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public List<Pet> findPetsByStatus(List<String> status) throws RestClientException {
return findPetsByStatusWithHttpInfo(status).getBody();
}
/**
* Finds Pets by status
* Multiple status values can be provided with comma separated strings
* <p><b>200</b> - successful operation
* <p><b>400</b> - Invalid status value
* @param status Status values that need to be considered for filter (required)
* @return ResponseEntity&lt;List&lt;Pet&gt;&gt;
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public ResponseEntity<List<Pet>> findPetsByStatusWithHttpInfo(List<String> status) throws RestClientException {
Object postBody = null;
// verify the required parameter 'status' is set
if (status == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'status' when calling findPetsByStatus");
}
String path = apiClient.expandPath("/pet/findByStatus", Collections.<String, Object>emptyMap());
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
final MultiValueMap formParams = new LinkedMultiValueMap();
queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "status", status));
final String[] accepts = {
"application/json", "application/xml"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = { };
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { "petstore_auth" };
ParameterizedTypeReference<List<Pet>> returnType = new ParameterizedTypeReference<List<Pet>>() {};
return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Finds Pets by tags
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
* <p><b>200</b> - successful operation
* <p><b>400</b> - Invalid tag value
* @param tags Tags to filter by (required)
* @return List&lt;Pet&gt;
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
@Deprecated
public List<Pet> findPetsByTags(List<String> tags) throws RestClientException {
return findPetsByTagsWithHttpInfo(tags).getBody();
}
/**
* Finds Pets by tags
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
* <p><b>200</b> - successful operation
* <p><b>400</b> - Invalid tag value
* @param tags Tags to filter by (required)
* @return ResponseEntity&lt;List&lt;Pet&gt;&gt;
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
@Deprecated
public ResponseEntity<List<Pet>> findPetsByTagsWithHttpInfo(List<String> tags) throws RestClientException {
Object postBody = null;
// verify the required parameter 'tags' is set
if (tags == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'tags' when calling findPetsByTags");
}
String path = apiClient.expandPath("/pet/findByTags", Collections.<String, Object>emptyMap());
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
final MultiValueMap formParams = new LinkedMultiValueMap();
queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "tags", tags));
final String[] accepts = {
"application/json", "application/xml"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = { };
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { "petstore_auth" };
ParameterizedTypeReference<List<Pet>> returnType = new ParameterizedTypeReference<List<Pet>>() {};
return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Find pet by ID
* Returns a single pet
* <p><b>200</b> - successful operation
* <p><b>400</b> - Invalid ID supplied
* <p><b>404</b> - Pet not found
* @param petId ID of pet to return (required)
* @return Pet
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public Pet getPetById(Long petId) throws RestClientException {
return getPetByIdWithHttpInfo(petId).getBody();
}
/**
* Find pet by ID
* Returns a single pet
* <p><b>200</b> - successful operation
* <p><b>400</b> - Invalid ID supplied
* <p><b>404</b> - Pet not found
* @param petId ID of pet to return (required)
* @return ResponseEntity&lt;Pet&gt;
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public ResponseEntity<Pet> getPetByIdWithHttpInfo(Long petId) throws RestClientException {
Object postBody = null;
// verify the required parameter 'petId' is set
if (petId == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'petId' when calling getPetById");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("petId", petId);
String path = apiClient.expandPath("/pet/{petId}", uriVariables);
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
final MultiValueMap formParams = new LinkedMultiValueMap();
final String[] accepts = {
"application/json", "application/xml"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = { };
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { "api_key" };
ParameterizedTypeReference<Pet> returnType = new ParameterizedTypeReference<Pet>() {};
return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Update an existing pet
*
* <p><b>400</b> - Invalid ID supplied
* <p><b>404</b> - Pet not found
* <p><b>405</b> - Validation exception
* @param body Pet object that needs to be added to the store (required)
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public void updatePet(Pet body) throws RestClientException {
updatePetWithHttpInfo(body);
}
/**
* Update an existing pet
*
* <p><b>400</b> - Invalid ID supplied
* <p><b>404</b> - Pet not found
* <p><b>405</b> - Validation exception
* @param body Pet object that needs to be added to the store (required)
* @return ResponseEntity&lt;Void&gt;
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public ResponseEntity<Void> updatePetWithHttpInfo(Pet body) throws RestClientException {
Object postBody = body;
// verify the required parameter 'body' is set
if (body == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling updatePet");
}
String path = apiClient.expandPath("/pet", Collections.<String, Object>emptyMap());
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
final MultiValueMap formParams = new LinkedMultiValueMap();
final String[] accepts = { };
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json", "application/xml"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { "petstore_auth" };
ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Updates a pet in the store with form data
*
* <p><b>405</b> - Invalid input
* @param petId ID of pet that needs to be updated (required)
* @param name Updated name of the pet (optional)
* @param status Updated status of the pet (optional)
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public void updatePetWithForm(Long petId, String name, String status) throws RestClientException {
updatePetWithFormWithHttpInfo(petId, name, status);
}
/**
* Updates a pet in the store with form data
*
* <p><b>405</b> - Invalid input
* @param petId ID of pet that needs to be updated (required)
* @param name Updated name of the pet (optional)
* @param status Updated status of the pet (optional)
* @return ResponseEntity&lt;Void&gt;
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public ResponseEntity<Void> updatePetWithFormWithHttpInfo(Long petId, String name, String status) throws RestClientException {
Object postBody = null;
// verify the required parameter 'petId' is set
if (petId == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'petId' when calling updatePetWithForm");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("petId", petId);
String path = apiClient.expandPath("/pet/{petId}", uriVariables);
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
final MultiValueMap formParams = new LinkedMultiValueMap();
if (name != null)
formParams.add("name", name);
if (status != null)
formParams.add("status", status);
final String[] accepts = { };
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/x-www-form-urlencoded"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { "petstore_auth" };
ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
/**
* uploads an image
*
* <p><b>200</b> - successful operation
* @param petId ID of pet to update (required)
* @param additionalMetadata Additional data to pass to server (optional)
* @param file file to upload (optional)
* @return ModelApiResponse
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws RestClientException {
return uploadFileWithHttpInfo(petId, additionalMetadata, file).getBody();
}
/**
* uploads an image
*
* <p><b>200</b> - successful operation
* @param petId ID of pet to update (required)
* @param additionalMetadata Additional data to pass to server (optional)
* @param file file to upload (optional)
* @return ResponseEntity&lt;ModelApiResponse&gt;
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public ResponseEntity<ModelApiResponse> uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file) throws RestClientException {
Object postBody = null;
// verify the required parameter 'petId' is set
if (petId == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'petId' when calling uploadFile");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("petId", petId);
String path = apiClient.expandPath("/pet/{petId}/uploadImage", uriVariables);
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
final MultiValueMap formParams = new LinkedMultiValueMap();
if (additionalMetadata != null)
formParams.add("additionalMetadata", additionalMetadata);
if (file != null)
formParams.add("file", new FileSystemResource(file));
final String[] accepts = {
"application/json"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"multipart/form-data"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { "petstore_auth" };
ParameterizedTypeReference<ModelApiResponse> returnType = new ParameterizedTypeReference<ModelApiResponse>() {};
return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
}

View File

@ -0,0 +1,240 @@
package com.baeldung.petstore.client.api;
import com.baeldung.petstore.client.invoker.ApiClient;
import com.baeldung.petstore.client.model.Order;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestClientException;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]")
@Component("com.baeldung.petstore.client.api.StoreApi")
public class StoreApi {
private ApiClient apiClient;
public StoreApi() {
this(new ApiClient());
}
@Autowired
public StoreApi(ApiClient apiClient) {
this.apiClient = apiClient;
}
public ApiClient getApiClient() {
return apiClient;
}
public void setApiClient(ApiClient apiClient) {
this.apiClient = apiClient;
}
/**
* Delete purchase order by ID
* For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors
* <p><b>400</b> - Invalid ID supplied
* <p><b>404</b> - Order not found
* @param orderId ID of the order that needs to be deleted (required)
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public void deleteOrder(Long orderId) throws RestClientException {
deleteOrderWithHttpInfo(orderId);
}
/**
* Delete purchase order by ID
* For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors
* <p><b>400</b> - Invalid ID supplied
* <p><b>404</b> - Order not found
* @param orderId ID of the order that needs to be deleted (required)
* @return ResponseEntity&lt;Void&gt;
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public ResponseEntity<Void> deleteOrderWithHttpInfo(Long orderId) throws RestClientException {
Object postBody = null;
// verify the required parameter 'orderId' is set
if (orderId == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'orderId' when calling deleteOrder");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("orderId", orderId);
String path = apiClient.expandPath("/store/order/{orderId}", uriVariables);
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
final MultiValueMap formParams = new LinkedMultiValueMap();
final String[] accepts = { };
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = { };
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
* <p><b>200</b> - successful operation
* @return Map&lt;String, Integer&gt;
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public Map<String, Integer> getInventory() throws RestClientException {
return getInventoryWithHttpInfo().getBody();
}
/**
* Returns pet inventories by status
* Returns a map of status codes to quantities
* <p><b>200</b> - successful operation
* @return ResponseEntity&lt;Map&lt;String, Integer&gt;&gt;
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public ResponseEntity<Map<String, Integer>> getInventoryWithHttpInfo() throws RestClientException {
Object postBody = null;
String path = apiClient.expandPath("/store/inventory", Collections.<String, Object>emptyMap());
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
final MultiValueMap formParams = new LinkedMultiValueMap();
final String[] accepts = {
"application/json"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = { };
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { "api_key" };
ParameterizedTypeReference<Map<String, Integer>> returnType = new ParameterizedTypeReference<Map<String, Integer>>() {};
return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Find purchase order by ID
* For valid response try integer IDs with value &gt;&#x3D; 1 and &lt;&#x3D; 10. Other values will generated exceptions
* <p><b>200</b> - successful operation
* <p><b>400</b> - Invalid ID supplied
* <p><b>404</b> - Order not found
* @param orderId ID of pet that needs to be fetched (required)
* @return Order
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public Order getOrderById(Long orderId) throws RestClientException {
return getOrderByIdWithHttpInfo(orderId).getBody();
}
/**
* Find purchase order by ID
* For valid response try integer IDs with value &gt;&#x3D; 1 and &lt;&#x3D; 10. Other values will generated exceptions
* <p><b>200</b> - successful operation
* <p><b>400</b> - Invalid ID supplied
* <p><b>404</b> - Order not found
* @param orderId ID of pet that needs to be fetched (required)
* @return ResponseEntity&lt;Order&gt;
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public ResponseEntity<Order> getOrderByIdWithHttpInfo(Long orderId) throws RestClientException {
Object postBody = null;
// verify the required parameter 'orderId' is set
if (orderId == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'orderId' when calling getOrderById");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("orderId", orderId);
String path = apiClient.expandPath("/store/order/{orderId}", uriVariables);
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
final MultiValueMap formParams = new LinkedMultiValueMap();
final String[] accepts = {
"application/json", "application/xml"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = { };
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<Order> returnType = new ParameterizedTypeReference<Order>() {};
return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Place an order for a pet
*
* <p><b>200</b> - successful operation
* <p><b>400</b> - Invalid Order
* @param body order placed for purchasing the pet (required)
* @return Order
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public Order placeOrder(Order body) throws RestClientException {
return placeOrderWithHttpInfo(body).getBody();
}
/**
* Place an order for a pet
*
* <p><b>200</b> - successful operation
* <p><b>400</b> - Invalid Order
* @param body order placed for purchasing the pet (required)
* @return ResponseEntity&lt;Order&gt;
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public ResponseEntity<Order> placeOrderWithHttpInfo(Order body) throws RestClientException {
Object postBody = body;
// verify the required parameter 'body' is set
if (body == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling placeOrder");
}
String path = apiClient.expandPath("/store/order", Collections.<String, Object>emptyMap());
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
final MultiValueMap formParams = new LinkedMultiValueMap();
final String[] accepts = {
"application/json", "application/xml"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<Order> returnType = new ParameterizedTypeReference<Order>() {};
return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
}

View File

@ -0,0 +1,441 @@
package com.baeldung.petstore.client.api;
import com.baeldung.petstore.client.invoker.ApiClient;
import com.baeldung.petstore.client.model.User;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestClientException;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]")
@Component("com.baeldung.petstore.client.api.UserApi")
public class UserApi {
private ApiClient apiClient;
public UserApi() {
this(new ApiClient());
}
@Autowired
public UserApi(ApiClient apiClient) {
this.apiClient = apiClient;
}
public ApiClient getApiClient() {
return apiClient;
}
public void setApiClient(ApiClient apiClient) {
this.apiClient = apiClient;
}
/**
* Create user
* This can only be done by the logged in user.
* <p><b>0</b> - successful operation
* @param body Created user object (required)
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public void createUser(User body) throws RestClientException {
createUserWithHttpInfo(body);
}
/**
* Create user
* This can only be done by the logged in user.
* <p><b>0</b> - successful operation
* @param body Created user object (required)
* @return ResponseEntity&lt;Void&gt;
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public ResponseEntity<Void> createUserWithHttpInfo(User body) throws RestClientException {
Object postBody = body;
// verify the required parameter 'body' is set
if (body == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling createUser");
}
String path = apiClient.expandPath("/user", Collections.<String, Object>emptyMap());
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
final MultiValueMap formParams = new LinkedMultiValueMap();
final String[] accepts = { };
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Creates list of users with given input array
*
* <p><b>0</b> - successful operation
* @param body List of user object (required)
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public void createUsersWithArrayInput(List<User> body) throws RestClientException {
createUsersWithArrayInputWithHttpInfo(body);
}
/**
* Creates list of users with given input array
*
* <p><b>0</b> - successful operation
* @param body List of user object (required)
* @return ResponseEntity&lt;Void&gt;
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public ResponseEntity<Void> createUsersWithArrayInputWithHttpInfo(List<User> body) throws RestClientException {
Object postBody = body;
// verify the required parameter 'body' is set
if (body == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling createUsersWithArrayInput");
}
String path = apiClient.expandPath("/user/createWithArray", Collections.<String, Object>emptyMap());
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
final MultiValueMap formParams = new LinkedMultiValueMap();
final String[] accepts = { };
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Creates list of users with given input array
*
* <p><b>0</b> - successful operation
* @param body List of user object (required)
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public void createUsersWithListInput(List<User> body) throws RestClientException {
createUsersWithListInputWithHttpInfo(body);
}
/**
* Creates list of users with given input array
*
* <p><b>0</b> - successful operation
* @param body List of user object (required)
* @return ResponseEntity&lt;Void&gt;
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public ResponseEntity<Void> createUsersWithListInputWithHttpInfo(List<User> body) throws RestClientException {
Object postBody = body;
// verify the required parameter 'body' is set
if (body == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling createUsersWithListInput");
}
String path = apiClient.expandPath("/user/createWithList", Collections.<String, Object>emptyMap());
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
final MultiValueMap formParams = new LinkedMultiValueMap();
final String[] accepts = { };
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
return apiClient.invokeAPI(path, HttpMethod.POST, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Delete user
* This can only be done by the logged in user.
* <p><b>400</b> - Invalid username supplied
* <p><b>404</b> - User not found
* @param username The name that needs to be deleted (required)
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public void deleteUser(String username) throws RestClientException {
deleteUserWithHttpInfo(username);
}
/**
* Delete user
* This can only be done by the logged in user.
* <p><b>400</b> - Invalid username supplied
* <p><b>404</b> - User not found
* @param username The name that needs to be deleted (required)
* @return ResponseEntity&lt;Void&gt;
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public ResponseEntity<Void> deleteUserWithHttpInfo(String username) throws RestClientException {
Object postBody = null;
// verify the required parameter 'username' is set
if (username == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling deleteUser");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("username", username);
String path = apiClient.expandPath("/user/{username}", uriVariables);
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
final MultiValueMap formParams = new LinkedMultiValueMap();
final String[] accepts = { };
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = { };
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
return apiClient.invokeAPI(path, HttpMethod.DELETE, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Get user by user name
*
* <p><b>200</b> - successful operation
* <p><b>400</b> - Invalid username supplied
* <p><b>404</b> - User not found
* @param username The name that needs to be fetched. Use user1 for testing. (required)
* @return User
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public User getUserByName(String username) throws RestClientException {
return getUserByNameWithHttpInfo(username).getBody();
}
/**
* Get user by user name
*
* <p><b>200</b> - successful operation
* <p><b>400</b> - Invalid username supplied
* <p><b>404</b> - User not found
* @param username The name that needs to be fetched. Use user1 for testing. (required)
* @return ResponseEntity&lt;User&gt;
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public ResponseEntity<User> getUserByNameWithHttpInfo(String username) throws RestClientException {
Object postBody = null;
// verify the required parameter 'username' is set
if (username == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling getUserByName");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("username", username);
String path = apiClient.expandPath("/user/{username}", uriVariables);
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
final MultiValueMap formParams = new LinkedMultiValueMap();
final String[] accepts = {
"application/json", "application/xml"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = { };
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<User> returnType = new ParameterizedTypeReference<User>() {};
return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Logs user into the system
*
* <p><b>200</b> - successful operation
* <p><b>400</b> - Invalid username/password supplied
* @param username The user name for login (required)
* @param password The password for login in clear text (required)
* @return String
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public String loginUser(String username, String password) throws RestClientException {
return loginUserWithHttpInfo(username, password).getBody();
}
/**
* Logs user into the system
*
* <p><b>200</b> - successful operation
* <p><b>400</b> - Invalid username/password supplied
* @param username The user name for login (required)
* @param password The password for login in clear text (required)
* @return ResponseEntity&lt;String&gt;
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public ResponseEntity<String> loginUserWithHttpInfo(String username, String password) throws RestClientException {
Object postBody = null;
// verify the required parameter 'username' is set
if (username == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling loginUser");
}
// verify the required parameter 'password' is set
if (password == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'password' when calling loginUser");
}
String path = apiClient.expandPath("/user/login", Collections.<String, Object>emptyMap());
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
final MultiValueMap formParams = new LinkedMultiValueMap();
queryParams.putAll(apiClient.parameterToMultiValueMap(null, "username", username));
queryParams.putAll(apiClient.parameterToMultiValueMap(null, "password", password));
final String[] accepts = {
"application/json", "application/xml"
};
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = { };
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<String> returnType = new ParameterizedTypeReference<String>() {};
return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Logs out current logged in user session
*
* <p><b>0</b> - successful operation
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public void logoutUser() throws RestClientException {
logoutUserWithHttpInfo();
}
/**
* Logs out current logged in user session
*
* <p><b>0</b> - successful operation
* @return ResponseEntity&lt;Void&gt;
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public ResponseEntity<Void> logoutUserWithHttpInfo() throws RestClientException {
Object postBody = null;
String path = apiClient.expandPath("/user/logout", Collections.<String, Object>emptyMap());
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
final MultiValueMap formParams = new LinkedMultiValueMap();
final String[] accepts = { };
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = { };
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
return apiClient.invokeAPI(path, HttpMethod.GET, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
/**
* Updated user
* This can only be done by the logged in user.
* <p><b>400</b> - Invalid user supplied
* <p><b>404</b> - User not found
* @param username name that need to be updated (required)
* @param body Updated user object (required)
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public void updateUser(String username, User body) throws RestClientException {
updateUserWithHttpInfo(username, body);
}
/**
* Updated user
* This can only be done by the logged in user.
* <p><b>400</b> - Invalid user supplied
* <p><b>404</b> - User not found
* @param username name that need to be updated (required)
* @param body Updated user object (required)
* @return ResponseEntity&lt;Void&gt;
* @throws RestClientException if an error occurs while attempting to invoke the API
*/
public ResponseEntity<Void> updateUserWithHttpInfo(String username, User body) throws RestClientException {
Object postBody = body;
// verify the required parameter 'username' is set
if (username == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'username' when calling updateUser");
}
// verify the required parameter 'body' is set
if (body == null) {
throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'body' when calling updateUser");
}
// create path and map variables
final Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("username", username);
String path = apiClient.expandPath("/user/{username}", uriVariables);
final MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<String, String>();
final HttpHeaders headerParams = new HttpHeaders();
final MultiValueMap<String, String> cookieParams = new LinkedMultiValueMap<String, String>();
final MultiValueMap formParams = new LinkedMultiValueMap();
final String[] accepts = { };
final List<MediaType> accept = apiClient.selectHeaderAccept(accepts);
final String[] contentTypes = {
"application/json"
};
final MediaType contentType = apiClient.selectHeaderContentType(contentTypes);
String[] authNames = new String[] { };
ParameterizedTypeReference<Void> returnType = new ParameterizedTypeReference<Void>() {};
return apiClient.invokeAPI(path, HttpMethod.PUT, queryParams, postBody, headerParams, cookieParams, formParams, accept, contentType, authNames, returnType);
}
}

View File

@ -0,0 +1,750 @@
package com.baeldung.petstore.client.invoker;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.threetenbp.ThreeTenModule;
import com.baeldung.petstore.client.invoker.auth.ApiKeyAuth;
import com.baeldung.petstore.client.invoker.auth.Authentication;
import com.baeldung.petstore.client.invoker.auth.HttpBasicAuth;
import com.baeldung.petstore.client.invoker.auth.HttpBearerAuth;
import com.baeldung.petstore.client.invoker.auth.OAuth;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TimeZone;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openapitools.jackson.nullable.JsonNullableModule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpRequest;
import org.springframework.http.InvalidMediaTypeException;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.http.RequestEntity.BodyBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.AbstractJackson2HttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import org.threeten.bp.*;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]")
@Component("com.baeldung.petstore.client.invoker.ApiClient")
public class ApiClient {
public enum CollectionFormat {
CSV(","), TSV("\t"), SSV(" "), PIPES("|"), MULTI(null);
private final String separator;
private CollectionFormat(String separator) {
this.separator = separator;
}
private String collectionToString(Collection<?> collection) {
return StringUtils.collectionToDelimitedString(collection, separator);
}
}
private boolean debugging = false;
private HttpHeaders defaultHeaders = new HttpHeaders();
private MultiValueMap<String, String> defaultCookies = new LinkedMultiValueMap<String, String>();
private String basePath = "https://petstore.swagger.io/v2";
private RestTemplate restTemplate;
private Map<String, Authentication> authentications;
private DateFormat dateFormat;
public ApiClient() {
this.restTemplate = buildRestTemplate();
init();
}
@Autowired
public ApiClient(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
init();
}
protected void init() {
// Use RFC3339 format for date and datetime.
// See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14
this.dateFormat = new RFC3339DateFormat();
// Use UTC as the default time zone.
this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
// Set default User-Agent.
setUserAgent("Java-SDK");
// Setup authentications (key: authentication name, value: authentication).
authentications = new HashMap<String, Authentication>();
authentications.put("api_key", new ApiKeyAuth("header", "api_key"));
authentications.put("petstore_auth", new OAuth());
// Prevent the authentications from being modified.
authentications = Collections.unmodifiableMap(authentications);
}
/**
* Get the current base path
* @return String the base path
*/
public String getBasePath() {
return basePath;
}
/**
* Set the base path, which should include the host
* @param basePath the base path
* @return ApiClient this client
*/
public ApiClient setBasePath(String basePath) {
this.basePath = basePath;
return this;
}
/**
* Get authentications (key: authentication name, value: authentication).
* @return Map the currently configured authentication types
*/
public Map<String, Authentication> getAuthentications() {
return authentications;
}
/**
* Get authentication for the given name.
*
* @param authName The authentication name
* @return The authentication, null if not found
*/
public Authentication getAuthentication(String authName) {
return authentications.get(authName);
}
/**
* Helper method to set token for HTTP bearer authentication.
* @param bearerToken the token
*/
public void setBearerToken(String bearerToken) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBearerAuth) {
((HttpBearerAuth) auth).setBearerToken(bearerToken);
return;
}
}
throw new RuntimeException("No Bearer authentication configured!");
}
/**
* Helper method to set username for the first HTTP basic authentication.
* @param username the username
*/
public void setUsername(String username) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setUsername(username);
return;
}
}
throw new RuntimeException("No HTTP basic authentication configured!");
}
/**
* Helper method to set password for the first HTTP basic authentication.
* @param password the password
*/
public void setPassword(String password) {
for (Authentication auth : authentications.values()) {
if (auth instanceof HttpBasicAuth) {
((HttpBasicAuth) auth).setPassword(password);
return;
}
}
throw new RuntimeException("No HTTP basic authentication configured!");
}
/**
* Helper method to set API key value for the first API key authentication.
* @param apiKey the API key
*/
public void setApiKey(String apiKey) {
for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKey(apiKey);
return;
}
}
throw new RuntimeException("No API key authentication configured!");
}
/**
* Helper method to set API key prefix for the first API key authentication.
* @param apiKeyPrefix the API key prefix
*/
public void setApiKeyPrefix(String apiKeyPrefix) {
for (Authentication auth : authentications.values()) {
if (auth instanceof ApiKeyAuth) {
((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix);
return;
}
}
throw new RuntimeException("No API key authentication configured!");
}
/**
* Helper method to set access token for the first OAuth2 authentication.
* @param accessToken the access token
*/
public void setAccessToken(String accessToken) {
for (Authentication auth : authentications.values()) {
if (auth instanceof OAuth) {
((OAuth) auth).setAccessToken(accessToken);
return;
}
}
throw new RuntimeException("No OAuth2 authentication configured!");
}
/**
* Set the User-Agent header's value (by adding to the default header map).
* @param userAgent the user agent string
* @return ApiClient this client
*/
public ApiClient setUserAgent(String userAgent) {
addDefaultHeader("User-Agent", userAgent);
return this;
}
/**
* Add a default header.
*
* @param name The header's name
* @param value The header's value
* @return ApiClient this client
*/
public ApiClient addDefaultHeader(String name, String value) {
if (defaultHeaders.containsKey(name)) {
defaultHeaders.remove(name);
}
defaultHeaders.add(name, value);
return this;
}
/**
* Add a default cookie.
*
* @param name The cookie's name
* @param value The cookie's value
* @return ApiClient this client
*/
public ApiClient addDefaultCookie(String name, String value) {
if (defaultCookies.containsKey(name)) {
defaultCookies.remove(name);
}
defaultCookies.add(name, value);
return this;
}
public void setDebugging(boolean debugging) {
List<ClientHttpRequestInterceptor> currentInterceptors = this.restTemplate.getInterceptors();
if(debugging) {
if (currentInterceptors == null) {
currentInterceptors = new ArrayList<ClientHttpRequestInterceptor>();
}
ClientHttpRequestInterceptor interceptor = new ApiClientHttpRequestInterceptor();
currentInterceptors.add(interceptor);
this.restTemplate.setInterceptors(currentInterceptors);
} else {
if (currentInterceptors != null && !currentInterceptors.isEmpty()) {
Iterator<ClientHttpRequestInterceptor> iter = currentInterceptors.iterator();
while (iter.hasNext()) {
ClientHttpRequestInterceptor interceptor = iter.next();
if (interceptor instanceof ApiClientHttpRequestInterceptor) {
iter.remove();
}
}
this.restTemplate.setInterceptors(currentInterceptors);
}
}
this.debugging = debugging;
}
/**
* Check that whether debugging is enabled for this API client.
* @return boolean true if this client is enabled for debugging, false otherwise
*/
public boolean isDebugging() {
return debugging;
}
/**
* Get the date format used to parse/format date parameters.
* @return DateFormat format
*/
public DateFormat getDateFormat() {
return dateFormat;
}
/**
* Set the date format used to parse/format date parameters.
* @param dateFormat Date format
* @return API client
*/
public ApiClient setDateFormat(DateFormat dateFormat) {
this.dateFormat = dateFormat;
for(HttpMessageConverter converter:restTemplate.getMessageConverters()){
if(converter instanceof AbstractJackson2HttpMessageConverter){
ObjectMapper mapper = ((AbstractJackson2HttpMessageConverter)converter).getObjectMapper();
mapper.setDateFormat(dateFormat);
}
}
return this;
}
/**
* Parse the given string into Date object.
* @param str the string to parse
* @return the Date parsed from the string
*/
public Date parseDate(String str) {
try {
return dateFormat.parse(str);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
/**
* Format the given Date object into string.
* @param date the date to format
* @return the formatted date as string
*/
public String formatDate(Date date) {
return dateFormat.format(date);
}
/**
* Format the given parameter object into string.
* @param param the object to convert
* @return String the parameter represented as a String
*/
public String parameterToString(Object param) {
if (param == null) {
return "";
} else if (param instanceof Date) {
return formatDate( (Date) param);
} else if (param instanceof Collection) {
StringBuilder b = new StringBuilder();
for(Object o : (Collection<?>) param) {
if(b.length() > 0) {
b.append(",");
}
b.append(String.valueOf(o));
}
return b.toString();
} else {
return String.valueOf(param);
}
}
/**
* Formats the specified collection path parameter to a string value.
*
* @param collectionFormat The collection format of the parameter.
* @param values The values of the parameter.
* @return String representation of the parameter
*/
public String collectionPathParameterToString(CollectionFormat collectionFormat, Collection<?> values) {
// create the value based on the collection format
if (CollectionFormat.MULTI.equals(collectionFormat)) {
// not valid for path params
return parameterToString(values);
}
// collectionFormat is assumed to be "csv" by default
if(collectionFormat == null) {
collectionFormat = CollectionFormat.CSV;
}
return collectionFormat.collectionToString(values);
}
/**
* Converts a parameter to a {@link MultiValueMap} for use in REST requests
* @param collectionFormat The format to convert to
* @param name The name of the parameter
* @param value The parameter's value
* @return a Map containing the String value(s) of the input parameter
*/
public MultiValueMap<String, String> parameterToMultiValueMap(CollectionFormat collectionFormat, String name, Object value) {
final MultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>();
if (name == null || name.isEmpty() || value == null) {
return params;
}
if(collectionFormat == null) {
collectionFormat = CollectionFormat.CSV;
}
Collection<?> valueCollection = null;
if (value instanceof Collection) {
valueCollection = (Collection<?>) value;
} else {
params.add(name, parameterToString(value));
return params;
}
if (valueCollection.isEmpty()){
return params;
}
if (collectionFormat.equals(CollectionFormat.MULTI)) {
for (Object item : valueCollection) {
params.add(name, parameterToString(item));
}
return params;
}
List<String> values = new ArrayList<String>();
for(Object o : valueCollection) {
values.add(parameterToString(o));
}
params.add(name, collectionFormat.collectionToString(values));
return params;
}
/**
* Check if the given {@code String} is a JSON MIME.
* @param mediaType the input MediaType
* @return boolean true if the MediaType represents JSON, false otherwise
*/
public boolean isJsonMime(String mediaType) {
// "* / *" is default to JSON
if ("*/*".equals(mediaType)) {
return true;
}
try {
return isJsonMime(MediaType.parseMediaType(mediaType));
} catch (InvalidMediaTypeException e) {
}
return false;
}
/**
* Check if the given MIME is a JSON MIME.
* JSON MIME examples:
* application/json
* application/json; charset=UTF8
* APPLICATION/JSON
* @param mediaType the input MediaType
* @return boolean true if the MediaType represents JSON, false otherwise
*/
public boolean isJsonMime(MediaType mediaType) {
return mediaType != null && (MediaType.APPLICATION_JSON.isCompatibleWith(mediaType) || mediaType.getSubtype().matches("^.*\\+json[;]?\\s*$"));
}
/**
* Select the Accept header's value from the given accepts array:
* if JSON exists in the given array, use it;
* otherwise use all of them (joining into a string)
*
* @param accepts The accepts array to select from
* @return List The list of MediaTypes to use for the Accept header
*/
public List<MediaType> selectHeaderAccept(String[] accepts) {
if (accepts.length == 0) {
return null;
}
for (String accept : accepts) {
MediaType mediaType = MediaType.parseMediaType(accept);
if (isJsonMime(mediaType)) {
return Collections.singletonList(mediaType);
}
}
return MediaType.parseMediaTypes(StringUtils.arrayToCommaDelimitedString(accepts));
}
/**
* Select the Content-Type header's value from the given array:
* if JSON exists in the given array, use it;
* otherwise use the first one of the array.
*
* @param contentTypes The Content-Type array to select from
* @return MediaType The Content-Type header to use. If the given array is empty, JSON will be used.
*/
public MediaType selectHeaderContentType(String[] contentTypes) {
if (contentTypes.length == 0) {
return MediaType.APPLICATION_JSON;
}
for (String contentType : contentTypes) {
MediaType mediaType = MediaType.parseMediaType(contentType);
if (isJsonMime(mediaType)) {
return mediaType;
}
}
return MediaType.parseMediaType(contentTypes[0]);
}
/**
* Select the body to use for the request
* @param obj the body object
* @param formParams the form parameters
* @param contentType the content type of the request
* @return Object the selected body
*/
protected Object selectBody(Object obj, MultiValueMap<String, Object> formParams, MediaType contentType) {
boolean isForm = MediaType.MULTIPART_FORM_DATA.isCompatibleWith(contentType) || MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(contentType);
return isForm ? formParams : obj;
}
/**
* Expand path template with variables
* @param pathTemplate path template with placeholders
* @param variables variables to replace
* @return path with placeholders replaced by variables
*/
public String expandPath(String pathTemplate, Map<String, Object> variables) {
return restTemplate.getUriTemplateHandler().expand(pathTemplate, variables).toString();
}
/**
* Invoke API by sending HTTP request with the given options.
*
* @param <T> the return type to use
* @param path The sub-path of the HTTP URL
* @param method The request method
* @param queryParams The query parameters
* @param body The request body object
* @param headerParams The header parameters
* @param cookieParams The cookie parameters
* @param formParams The form parameters
* @param accept The request's Accept header
* @param contentType The request's Content-Type header
* @param authNames The authentications to apply
* @param returnType The return type into which to deserialize the response
* @return ResponseEntity&lt;T&gt; The response of the chosen type
*/
public <T> ResponseEntity<T> invokeAPI(String path, HttpMethod method, MultiValueMap<String, String> queryParams, Object body, HttpHeaders headerParams, MultiValueMap<String, String> cookieParams, MultiValueMap<String, Object> formParams, List<MediaType> accept, MediaType contentType, String[] authNames, ParameterizedTypeReference<T> returnType) throws RestClientException {
updateParamsForAuth(authNames, queryParams, headerParams, cookieParams);
final UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(basePath).path(path);
if (queryParams != null) {
//encode the query parameters in case they contain unsafe characters
for (List<String> values : queryParams.values()) {
if (values != null) {
for (int i = 0; i < values.size(); i++) {
try {
values.set(i, URLEncoder.encode(values.get(i), "utf8"));
} catch (UnsupportedEncodingException e) {
}
}
}
}
builder.queryParams(queryParams);
}
URI uri;
try {
uri = new URI(builder.build().toUriString());
} catch(URISyntaxException ex) {
throw new RestClientException("Could not build URL: " + builder.toUriString(), ex);
}
final BodyBuilder requestBuilder = RequestEntity.method(method, uri);
if(accept != null) {
requestBuilder.accept(accept.toArray(new MediaType[accept.size()]));
}
if(contentType != null) {
requestBuilder.contentType(contentType);
}
addHeadersToRequest(headerParams, requestBuilder);
addHeadersToRequest(defaultHeaders, requestBuilder);
addCookiesToRequest(cookieParams, requestBuilder);
addCookiesToRequest(defaultCookies, requestBuilder);
RequestEntity<Object> requestEntity = requestBuilder.body(selectBody(body, formParams, contentType));
ResponseEntity<T> responseEntity = restTemplate.exchange(requestEntity, returnType);
if (responseEntity.getStatusCode().is2xxSuccessful()) {
return responseEntity;
} else {
// The error handler built into the RestTemplate should handle 400 and 500 series errors.
throw new RestClientException("API returned " + responseEntity.getStatusCode() + " and it wasn't handled by the RestTemplate error handler");
}
}
/**
* Add headers to the request that is being built
* @param headers The headers to add
* @param requestBuilder The current request
*/
protected void addHeadersToRequest(HttpHeaders headers, BodyBuilder requestBuilder) {
for (Entry<String, List<String>> entry : headers.entrySet()) {
List<String> values = entry.getValue();
for(String value : values) {
if (value != null) {
requestBuilder.header(entry.getKey(), value);
}
}
}
}
/**
* Add cookies to the request that is being built
* @param cookies The cookies to add
* @param requestBuilder The current request
*/
protected void addCookiesToRequest(MultiValueMap<String, String> cookies, BodyBuilder requestBuilder) {
if (!cookies.isEmpty()) {
requestBuilder.header("Cookie", buildCookieHeader(cookies));
}
}
/**
* Build cookie header. Keeps a single value per cookie (as per <a href="https://tools.ietf.org/html/rfc6265#section-5.3">
* RFC6265 section 5.3</a>).
*
* @param cookies map all cookies
* @return header string for cookies.
*/
private String buildCookieHeader(MultiValueMap<String, String> cookies) {
final StringBuilder cookieValue = new StringBuilder();
String delimiter = "";
for (final Map.Entry<String, List<String>> entry : cookies.entrySet()) {
final String value = entry.getValue().get(entry.getValue().size() - 1);
cookieValue.append(String.format("%s%s=%s", delimiter, entry.getKey(), value));
delimiter = "; ";
}
return cookieValue.toString();
}
/**
* Build the RestTemplate used to make HTTP requests.
* @return RestTemplate
*/
protected RestTemplate buildRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
for(HttpMessageConverter converter:restTemplate.getMessageConverters()){
if(converter instanceof AbstractJackson2HttpMessageConverter){
ObjectMapper mapper = ((AbstractJackson2HttpMessageConverter)converter).getObjectMapper();
ThreeTenModule module = new ThreeTenModule();
module.addDeserializer(Instant.class, CustomInstantDeserializer.INSTANT);
module.addDeserializer(OffsetDateTime.class, CustomInstantDeserializer.OFFSET_DATE_TIME);
module.addDeserializer(ZonedDateTime.class, CustomInstantDeserializer.ZONED_DATE_TIME);
mapper.registerModule(module);
mapper.registerModule(new JsonNullableModule());
}
}
// This allows us to read the response more than once - Necessary for debugging.
restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(restTemplate.getRequestFactory()));
return restTemplate;
}
/**
* Update query and header parameters based on authentication settings.
*
* @param authNames The authentications to apply
* @param queryParams The query parameters
* @param headerParams The header parameters
*/
private void updateParamsForAuth(String[] authNames, MultiValueMap<String, String> queryParams, HttpHeaders headerParams, MultiValueMap<String, String> cookieParams) {
for (String authName : authNames) {
Authentication auth = authentications.get(authName);
if (auth == null) {
throw new RestClientException("Authentication undefined: " + authName);
}
auth.applyToParams(queryParams, headerParams, cookieParams);
}
}
private class ApiClientHttpRequestInterceptor implements ClientHttpRequestInterceptor {
private final Log log = LogFactory.getLog(ApiClientHttpRequestInterceptor.class);
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
logRequest(request, body);
ClientHttpResponse response = execution.execute(request, body);
logResponse(response);
return response;
}
private void logRequest(HttpRequest request, byte[] body) throws UnsupportedEncodingException {
log.info("URI: " + request.getURI());
log.info("HTTP Method: " + request.getMethod());
log.info("HTTP Headers: " + headersToString(request.getHeaders()));
log.info("Request Body: " + new String(body, StandardCharsets.UTF_8));
}
private void logResponse(ClientHttpResponse response) throws IOException {
log.info("HTTP Status Code: " + response.getRawStatusCode());
log.info("Status Text: " + response.getStatusText());
log.info("HTTP Headers: " + headersToString(response.getHeaders()));
log.info("Response Body: " + bodyToString(response.getBody()));
}
private String headersToString(HttpHeaders headers) {
StringBuilder builder = new StringBuilder();
for(Entry<String, List<String>> entry : headers.entrySet()) {
builder.append(entry.getKey()).append("=[");
for(String value : entry.getValue()) {
builder.append(value).append(",");
}
builder.setLength(builder.length() - 1); // Get rid of trailing comma
builder.append("],");
}
builder.setLength(builder.length() - 1); // Get rid of trailing comma
return builder.toString();
}
private String bodyToString(InputStream body) throws IOException {
StringBuilder builder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(body, StandardCharsets.UTF_8));
String line = bufferedReader.readLine();
while (line != null) {
builder.append(line).append(System.lineSeparator());
line = bufferedReader.readLine();
}
bufferedReader.close();
return builder.toString();
}
}
}

View File

@ -0,0 +1,233 @@
package com.baeldung.petstore.client.invoker;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonTokenId;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.datatype.threetenbp.DecimalUtils;
import com.fasterxml.jackson.datatype.threetenbp.deser.ThreeTenDateTimeDeserializerBase;
import com.fasterxml.jackson.datatype.threetenbp.function.BiFunction;
import com.fasterxml.jackson.datatype.threetenbp.function.Function;
import java.io.IOException;
import java.math.BigDecimal;
import org.threeten.bp.DateTimeException;
import org.threeten.bp.DateTimeUtils;
import org.threeten.bp.Instant;
import org.threeten.bp.OffsetDateTime;
import org.threeten.bp.ZoneId;
import org.threeten.bp.ZonedDateTime;
import org.threeten.bp.format.DateTimeFormatter;
import org.threeten.bp.temporal.Temporal;
import org.threeten.bp.temporal.TemporalAccessor;
/**
* Deserializer for ThreeTen temporal {@link Instant}s, {@link OffsetDateTime}, and {@link ZonedDateTime}s.
* Adapted from the jackson threetenbp InstantDeserializer to add support for deserializing rfc822 format.
*
* @author Nick Williams
*/
public class CustomInstantDeserializer<T extends Temporal>
extends ThreeTenDateTimeDeserializerBase<T> {
private static final long serialVersionUID = 1L;
public static final CustomInstantDeserializer<Instant> INSTANT = new CustomInstantDeserializer<Instant>(
Instant.class, DateTimeFormatter.ISO_INSTANT,
new Function<TemporalAccessor, Instant>() {
@Override
public Instant apply(TemporalAccessor temporalAccessor) {
return Instant.from(temporalAccessor);
}
},
new Function<FromIntegerArguments, Instant>() {
@Override
public Instant apply(FromIntegerArguments a) {
return Instant.ofEpochMilli(a.value);
}
},
new Function<FromDecimalArguments, Instant>() {
@Override
public Instant apply(FromDecimalArguments a) {
return Instant.ofEpochSecond(a.integer, a.fraction);
}
},
null
);
public static final CustomInstantDeserializer<OffsetDateTime> OFFSET_DATE_TIME = new CustomInstantDeserializer<OffsetDateTime>(
OffsetDateTime.class, DateTimeFormatter.ISO_OFFSET_DATE_TIME,
new Function<TemporalAccessor, OffsetDateTime>() {
@Override
public OffsetDateTime apply(TemporalAccessor temporalAccessor) {
return OffsetDateTime.from(temporalAccessor);
}
},
new Function<FromIntegerArguments, OffsetDateTime>() {
@Override
public OffsetDateTime apply(FromIntegerArguments a) {
return OffsetDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId);
}
},
new Function<FromDecimalArguments, OffsetDateTime>() {
@Override
public OffsetDateTime apply(FromDecimalArguments a) {
return OffsetDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId);
}
},
new BiFunction<OffsetDateTime, ZoneId, OffsetDateTime>() {
@Override
public OffsetDateTime apply(OffsetDateTime d, ZoneId z) {
return d.withOffsetSameInstant(z.getRules().getOffset(d.toLocalDateTime()));
}
}
);
public static final CustomInstantDeserializer<ZonedDateTime> ZONED_DATE_TIME = new CustomInstantDeserializer<ZonedDateTime>(
ZonedDateTime.class, DateTimeFormatter.ISO_ZONED_DATE_TIME,
new Function<TemporalAccessor, ZonedDateTime>() {
@Override
public ZonedDateTime apply(TemporalAccessor temporalAccessor) {
return ZonedDateTime.from(temporalAccessor);
}
},
new Function<FromIntegerArguments, ZonedDateTime>() {
@Override
public ZonedDateTime apply(FromIntegerArguments a) {
return ZonedDateTime.ofInstant(Instant.ofEpochMilli(a.value), a.zoneId);
}
},
new Function<FromDecimalArguments, ZonedDateTime>() {
@Override
public ZonedDateTime apply(FromDecimalArguments a) {
return ZonedDateTime.ofInstant(Instant.ofEpochSecond(a.integer, a.fraction), a.zoneId);
}
},
new BiFunction<ZonedDateTime, ZoneId, ZonedDateTime>() {
@Override
public ZonedDateTime apply(ZonedDateTime zonedDateTime, ZoneId zoneId) {
return zonedDateTime.withZoneSameInstant(zoneId);
}
}
);
protected final Function<FromIntegerArguments, T> fromMilliseconds;
protected final Function<FromDecimalArguments, T> fromNanoseconds;
protected final Function<TemporalAccessor, T> parsedToValue;
protected final BiFunction<T, ZoneId, T> adjust;
protected CustomInstantDeserializer(Class<T> supportedType,
DateTimeFormatter parser,
Function<TemporalAccessor, T> parsedToValue,
Function<FromIntegerArguments, T> fromMilliseconds,
Function<FromDecimalArguments, T> fromNanoseconds,
BiFunction<T, ZoneId, T> adjust) {
super(supportedType, parser);
this.parsedToValue = parsedToValue;
this.fromMilliseconds = fromMilliseconds;
this.fromNanoseconds = fromNanoseconds;
this.adjust = adjust == null ? new BiFunction<T, ZoneId, T>() {
@Override
public T apply(T t, ZoneId zoneId) {
return t;
}
} : adjust;
}
@SuppressWarnings("unchecked")
protected CustomInstantDeserializer(CustomInstantDeserializer<T> base, DateTimeFormatter f) {
super((Class<T>) base.handledType(), f);
parsedToValue = base.parsedToValue;
fromMilliseconds = base.fromMilliseconds;
fromNanoseconds = base.fromNanoseconds;
adjust = base.adjust;
}
@Override
protected JsonDeserializer<T> withDateFormat(DateTimeFormatter dtf) {
if (dtf == _formatter) {
return this;
}
return new CustomInstantDeserializer<T>(this, dtf);
}
@Override
public T deserialize(JsonParser parser, DeserializationContext context) throws IOException {
//NOTE: Timestamps contain no timezone info, and are always in configured TZ. Only
//string values have to be adjusted to the configured TZ.
switch (parser.getCurrentTokenId()) {
case JsonTokenId.ID_NUMBER_FLOAT: {
BigDecimal value = parser.getDecimalValue();
long seconds = value.longValue();
int nanoseconds = DecimalUtils.extractNanosecondDecimal(value, seconds);
return fromNanoseconds.apply(new FromDecimalArguments(
seconds, nanoseconds, getZone(context)));
}
case JsonTokenId.ID_NUMBER_INT: {
long timestamp = parser.getLongValue();
if (context.isEnabled(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS)) {
return this.fromNanoseconds.apply(new FromDecimalArguments(
timestamp, 0, this.getZone(context)
));
}
return this.fromMilliseconds.apply(new FromIntegerArguments(
timestamp, this.getZone(context)
));
}
case JsonTokenId.ID_STRING: {
String string = parser.getText().trim();
if (string.length() == 0) {
return null;
}
if (string.endsWith("+0000")) {
string = string.substring(0, string.length() - 5) + "Z";
}
T value;
try {
TemporalAccessor acc = _formatter.parse(string);
value = parsedToValue.apply(acc);
if (context.isEnabled(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)) {
return adjust.apply(value, this.getZone(context));
}
} catch (DateTimeException e) {
throw _peelDTE(e);
}
return value;
}
}
throw context.mappingException("Expected type float, integer, or string.");
}
private ZoneId getZone(DeserializationContext context) {
// Instants are always in UTC, so don't waste compute cycles
return (_valueClass == Instant.class) ? null : DateTimeUtils.toZoneId(context.getTimeZone());
}
private static class FromIntegerArguments {
public final long value;
public final ZoneId zoneId;
private FromIntegerArguments(long value, ZoneId zoneId) {
this.value = value;
this.zoneId = zoneId;
}
}
private static class FromDecimalArguments {
public final long integer;
public final int fraction;
public final ZoneId zoneId;
private FromDecimalArguments(long integer, int fraction, ZoneId zoneId) {
this.integer = integer;
this.fraction = fraction;
this.zoneId = zoneId;
}
}
}

View File

@ -0,0 +1,32 @@
/*
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.3
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.baeldung.petstore.client.invoker;
import com.fasterxml.jackson.databind.util.ISO8601DateFormat;
import com.fasterxml.jackson.databind.util.ISO8601Utils;
import java.text.FieldPosition;
import java.util.Date;
public class RFC3339DateFormat extends ISO8601DateFormat {
// Same as ISO8601DateFormat but serializing milliseconds.
@Override
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
String value = ISO8601Utils.format(date, true);
toAppendTo.append(value);
return toAppendTo;
}
}

View File

@ -0,0 +1,62 @@
package com.baeldung.petstore.client.invoker.auth;
import org.springframework.http.HttpHeaders;
import org.springframework.util.MultiValueMap;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]")
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(MultiValueMap<String, String> queryParams, HttpHeaders headerParams, MultiValueMap<String, String> cookieParams) {
if (apiKey == null) {
return;
}
String value;
if (apiKeyPrefix != null) {
value = apiKeyPrefix + " " + apiKey;
} else {
value = apiKey;
}
if (location.equals("query")) {
queryParams.add(paramName, value);
} else if (location.equals("header")) {
headerParams.add(paramName, value);
} else if (location.equals("cookie")) {
cookieParams.add(paramName, value);
}
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.petstore.client.invoker.auth;
import org.springframework.http.HttpHeaders;
import org.springframework.util.MultiValueMap;
public interface Authentication {
/**
* Apply authentication settings to header and / or query parameters.
* @param queryParams The query parameters for the request
* @param headerParams The header parameters for the request
* @param cookieParams The cookie parameters for the request
*/
public void applyToParams(MultiValueMap<String, String> queryParams, HttpHeaders headerParams, MultiValueMap<String, String> cookieParams);
}

View File

@ -0,0 +1,38 @@
package com.baeldung.petstore.client.invoker.auth;
import java.nio.charset.StandardCharsets;
import org.springframework.http.HttpHeaders;
import org.springframework.util.Base64Utils;
import org.springframework.util.MultiValueMap;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]")
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(MultiValueMap<String, String> queryParams, HttpHeaders headerParams, MultiValueMap<String, String> cookieParams) {
if (username == null && password == null) {
return;
}
String str = (username == null ? "" : username) + ":" + (password == null ? "" : password);
headerParams.add(HttpHeaders.AUTHORIZATION, "Basic " + Base64Utils.encodeToString(str.getBytes(StandardCharsets.UTF_8)));
}
}

View File

@ -0,0 +1,34 @@
package com.baeldung.petstore.client.invoker.auth;
import org.springframework.http.HttpHeaders;
import org.springframework.util.MultiValueMap;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]")
public class HttpBearerAuth implements Authentication {
private final String scheme;
private String bearerToken;
public HttpBearerAuth(String scheme) {
this.scheme = scheme;
}
public String getBearerToken() {
return bearerToken;
}
public void setBearerToken(String bearerToken) {
this.bearerToken = bearerToken;
}
@Override
public void applyToParams(MultiValueMap<String, String> queryParams, HttpHeaders headerParams, MultiValueMap<String, String> cookieParams) {
if (bearerToken == null) {
return;
}
headerParams.add(HttpHeaders.AUTHORIZATION, (scheme != null ? upperCaseBearer(scheme) + " " : "") + bearerToken);
}
private static String upperCaseBearer(String scheme) {
return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme;
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.petstore.client.invoker.auth;
import org.springframework.http.HttpHeaders;
import org.springframework.util.MultiValueMap;
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]")
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(MultiValueMap<String, String> queryParams, HttpHeaders headerParams, MultiValueMap<String, String> cookieParams) {
if (accessToken != null) {
headerParams.add(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken);
}
}
}

View File

@ -0,0 +1,5 @@
package com.baeldung.petstore.client.invoker.auth;
public enum OAuthFlow {
accessCode, implicit, password, application
}

View File

@ -0,0 +1,131 @@
/*
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.3
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.baeldung.petstore.client.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import java.util.Objects;
import io.swagger.annotations.ApiModelProperty;
/**
* Category
*/
@JsonPropertyOrder({
Category.JSON_PROPERTY_ID,
Category.JSON_PROPERTY_NAME
})
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]")
public class Category {
public static final String JSON_PROPERTY_ID = "id";
private Long id;
public static final String JSON_PROPERTY_NAME = "name";
private String name;
public Category id(Long id) {
this.id = id;
return this;
}
/**
* Get id
* @return id
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
@JsonProperty(JSON_PROPERTY_ID)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Category name(String name) {
this.name = name;
return this;
}
/**
* Get name
* @return name
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
@JsonProperty(JSON_PROPERTY_NAME)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Category category = (Category) o;
return Objects.equals(this.id, category.id) &&
Objects.equals(this.name, category.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Category {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).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(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -0,0 +1,162 @@
/*
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.3
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.baeldung.petstore.client.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import java.util.Objects;
import io.swagger.annotations.ApiModelProperty;
/**
* ModelApiResponse
*/
@JsonPropertyOrder({
ModelApiResponse.JSON_PROPERTY_CODE,
ModelApiResponse.JSON_PROPERTY_TYPE,
ModelApiResponse.JSON_PROPERTY_MESSAGE
})
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]")
public class ModelApiResponse {
public static final String JSON_PROPERTY_CODE = "code";
private Integer code;
public static final String JSON_PROPERTY_TYPE = "type";
private String type;
public static final String JSON_PROPERTY_MESSAGE = "message";
private String message;
public ModelApiResponse code(Integer code) {
this.code = code;
return this;
}
/**
* Get code
* @return code
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
@JsonProperty(JSON_PROPERTY_CODE)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public ModelApiResponse type(String type) {
this.type = type;
return this;
}
/**
* Get type
* @return type
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
@JsonProperty(JSON_PROPERTY_TYPE)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public ModelApiResponse message(String message) {
this.message = message;
return this;
}
/**
* Get message
* @return message
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
@JsonProperty(JSON_PROPERTY_MESSAGE)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ModelApiResponse _apiResponse = (ModelApiResponse) o;
return Objects.equals(this.code, _apiResponse.code) &&
Objects.equals(this.type, _apiResponse.type) &&
Objects.equals(this.message, _apiResponse.message);
}
@Override
public int hashCode() {
return Objects.hash(code, type, message);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ModelApiResponse {\n");
sb.append(" code: ").append(toIndentedString(code)).append("\n");
sb.append(" type: ").append(toIndentedString(type)).append("\n");
sb.append(" message: ").append(toIndentedString(message)).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(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -0,0 +1,296 @@
/*
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.3
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.baeldung.petstore.client.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonValue;
import java.util.Objects;
import org.threeten.bp.OffsetDateTime;
import io.swagger.annotations.ApiModelProperty;
/**
* Order
*/
@JsonPropertyOrder({
Order.JSON_PROPERTY_ID,
Order.JSON_PROPERTY_PET_ID,
Order.JSON_PROPERTY_QUANTITY,
Order.JSON_PROPERTY_SHIP_DATE,
Order.JSON_PROPERTY_STATUS,
Order.JSON_PROPERTY_COMPLETE
})
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]")
public class Order {
public static final String JSON_PROPERTY_ID = "id";
private Long id;
public static final String JSON_PROPERTY_PET_ID = "petId";
private Long petId;
public static final String JSON_PROPERTY_QUANTITY = "quantity";
private Integer quantity;
public static final String JSON_PROPERTY_SHIP_DATE = "shipDate";
private OffsetDateTime shipDate;
/**
* Order Status
*/
public enum StatusEnum {
PLACED("placed"),
APPROVED("approved"),
DELIVERED("delivered");
private String value;
StatusEnum(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
@JsonCreator
public static StatusEnum fromValue(String value) {
for (StatusEnum b : StatusEnum.values()) {
if (b.value.equals(value)) {
return b;
}
}
throw new IllegalArgumentException("Unexpected value '" + value + "'");
}
}
public static final String JSON_PROPERTY_STATUS = "status";
private StatusEnum status;
public static final String JSON_PROPERTY_COMPLETE = "complete";
private Boolean complete;
public Order id(Long id) {
this.id = id;
return this;
}
/**
* Get id
* @return id
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
@JsonProperty(JSON_PROPERTY_ID)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Order petId(Long petId) {
this.petId = petId;
return this;
}
/**
* Get petId
* @return petId
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
@JsonProperty(JSON_PROPERTY_PET_ID)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public Long getPetId() {
return petId;
}
public void setPetId(Long petId) {
this.petId = petId;
}
public Order quantity(Integer quantity) {
this.quantity = quantity;
return this;
}
/**
* Get quantity
* @return quantity
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
@JsonProperty(JSON_PROPERTY_QUANTITY)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public Order shipDate(OffsetDateTime shipDate) {
this.shipDate = shipDate;
return this;
}
/**
* Get shipDate
* @return shipDate
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
@JsonProperty(JSON_PROPERTY_SHIP_DATE)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public OffsetDateTime getShipDate() {
return shipDate;
}
public void setShipDate(OffsetDateTime shipDate) {
this.shipDate = shipDate;
}
public Order status(StatusEnum status) {
this.status = status;
return this;
}
/**
* Order Status
* @return status
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "Order Status")
@JsonProperty(JSON_PROPERTY_STATUS)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public StatusEnum getStatus() {
return status;
}
public void setStatus(StatusEnum status) {
this.status = status;
}
public Order complete(Boolean complete) {
this.complete = complete;
return this;
}
/**
* Get complete
* @return complete
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
@JsonProperty(JSON_PROPERTY_COMPLETE)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public Boolean getComplete() {
return complete;
}
public void setComplete(Boolean complete) {
this.complete = complete;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Order order = (Order) o;
return Objects.equals(this.id, order.id) &&
Objects.equals(this.petId, order.petId) &&
Objects.equals(this.quantity, order.quantity) &&
Objects.equals(this.shipDate, order.shipDate) &&
Objects.equals(this.status, order.status) &&
Objects.equals(this.complete, order.complete);
}
@Override
public int hashCode() {
return Objects.hash(id, petId, quantity, shipDate, status, complete);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Order {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" petId: ").append(toIndentedString(petId)).append("\n");
sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n");
sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n");
sb.append(" status: ").append(toIndentedString(status)).append("\n");
sb.append(" complete: ").append(toIndentedString(complete)).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(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -0,0 +1,310 @@
/*
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.3
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.baeldung.petstore.client.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonValue;
import com.baeldung.petstore.client.model.Category;
import com.baeldung.petstore.client.model.Tag;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import io.swagger.annotations.ApiModelProperty;
/**
* Pet
*/
@JsonPropertyOrder({
Pet.JSON_PROPERTY_ID,
Pet.JSON_PROPERTY_CATEGORY,
Pet.JSON_PROPERTY_NAME,
Pet.JSON_PROPERTY_PHOTO_URLS,
Pet.JSON_PROPERTY_TAGS,
Pet.JSON_PROPERTY_STATUS
})
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]")
public class Pet {
public static final String JSON_PROPERTY_ID = "id";
private Long id;
public static final String JSON_PROPERTY_CATEGORY = "category";
private Category category;
public static final String JSON_PROPERTY_NAME = "name";
private String name;
public static final String JSON_PROPERTY_PHOTO_URLS = "photoUrls";
private List<String> photoUrls = new ArrayList<>();
public static final String JSON_PROPERTY_TAGS = "tags";
private List<Tag> tags = null;
/**
* pet status in the store
*/
public enum StatusEnum {
AVAILABLE("available"),
PENDING("pending"),
SOLD("sold");
private String value;
StatusEnum(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
@JsonCreator
public static StatusEnum fromValue(String value) {
for (StatusEnum b : StatusEnum.values()) {
if (b.value.equals(value)) {
return b;
}
}
throw new IllegalArgumentException("Unexpected value '" + value + "'");
}
}
public static final String JSON_PROPERTY_STATUS = "status";
private StatusEnum status;
public Pet id(Long id) {
this.id = id;
return this;
}
/**
* Get id
* @return id
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
@JsonProperty(JSON_PROPERTY_ID)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Pet category(Category category) {
this.category = category;
return this;
}
/**
* Get category
* @return category
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
@JsonProperty(JSON_PROPERTY_CATEGORY)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public Pet name(String name) {
this.name = name;
return this;
}
/**
* Get name
* @return name
**/
@ApiModelProperty(example = "doggie", required = true, value = "")
@JsonProperty(JSON_PROPERTY_NAME)
@JsonInclude(value = JsonInclude.Include.ALWAYS)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Pet photoUrls(List<String> photoUrls) {
this.photoUrls = photoUrls;
return this;
}
public Pet addPhotoUrlsItem(String photoUrlsItem) {
this.photoUrls.add(photoUrlsItem);
return this;
}
/**
* Get photoUrls
* @return photoUrls
**/
@ApiModelProperty(required = true, value = "")
@JsonProperty(JSON_PROPERTY_PHOTO_URLS)
@JsonInclude(value = JsonInclude.Include.ALWAYS)
public List<String> getPhotoUrls() {
return photoUrls;
}
public void setPhotoUrls(List<String> photoUrls) {
this.photoUrls = photoUrls;
}
public Pet tags(List<Tag> tags) {
this.tags = tags;
return this;
}
public Pet addTagsItem(Tag tagsItem) {
if (this.tags == null) {
this.tags = new ArrayList<>();
}
this.tags.add(tagsItem);
return this;
}
/**
* Get tags
* @return tags
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
@JsonProperty(JSON_PROPERTY_TAGS)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public List<Tag> getTags() {
return tags;
}
public void setTags(List<Tag> tags) {
this.tags = tags;
}
public Pet status(StatusEnum status) {
this.status = status;
return this;
}
/**
* pet status in the store
* @return status
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "pet status in the store")
@JsonProperty(JSON_PROPERTY_STATUS)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public StatusEnum getStatus() {
return status;
}
public void setStatus(StatusEnum status) {
this.status = status;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Pet pet = (Pet) o;
return Objects.equals(this.id, pet.id) &&
Objects.equals(this.category, pet.category) &&
Objects.equals(this.name, pet.name) &&
Objects.equals(this.photoUrls, pet.photoUrls) &&
Objects.equals(this.tags, pet.tags) &&
Objects.equals(this.status, pet.status);
}
@Override
public int hashCode() {
return Objects.hash(id, category, name, photoUrls, tags, status);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Pet {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" category: ").append(toIndentedString(category)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n");
sb.append(" tags: ").append(toIndentedString(tags)).append("\n");
sb.append(" status: ").append(toIndentedString(status)).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(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -0,0 +1,131 @@
/*
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.3
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.baeldung.petstore.client.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import java.util.Objects;
import io.swagger.annotations.ApiModelProperty;
/**
* Tag
*/
@JsonPropertyOrder({
Tag.JSON_PROPERTY_ID,
Tag.JSON_PROPERTY_NAME
})
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]")
public class Tag {
public static final String JSON_PROPERTY_ID = "id";
private Long id;
public static final String JSON_PROPERTY_NAME = "name";
private String name;
public Tag id(Long id) {
this.id = id;
return this;
}
/**
* Get id
* @return id
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
@JsonProperty(JSON_PROPERTY_ID)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Tag name(String name) {
this.name = name;
return this;
}
/**
* Get name
* @return name
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
@JsonProperty(JSON_PROPERTY_NAME)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Tag tag = (Tag) o;
return Objects.equals(this.id, tag.id) &&
Objects.equals(this.name, tag.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Tag {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).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(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -0,0 +1,317 @@
/*
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.3
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.baeldung.petstore.client.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import java.util.Objects;
import io.swagger.annotations.ApiModelProperty;
/**
* User
*/
@JsonPropertyOrder({
User.JSON_PROPERTY_ID,
User.JSON_PROPERTY_USERNAME,
User.JSON_PROPERTY_FIRST_NAME,
User.JSON_PROPERTY_LAST_NAME,
User.JSON_PROPERTY_EMAIL,
User.JSON_PROPERTY_PASSWORD,
User.JSON_PROPERTY_PHONE,
User.JSON_PROPERTY_USER_STATUS
})
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-03-15T06:14:01.568992-05:00[America/Chicago]")
public class User {
public static final String JSON_PROPERTY_ID = "id";
private Long id;
public static final String JSON_PROPERTY_USERNAME = "username";
private String username;
public static final String JSON_PROPERTY_FIRST_NAME = "firstName";
private String firstName;
public static final String JSON_PROPERTY_LAST_NAME = "lastName";
private String lastName;
public static final String JSON_PROPERTY_EMAIL = "email";
private String email;
public static final String JSON_PROPERTY_PASSWORD = "password";
private String password;
public static final String JSON_PROPERTY_PHONE = "phone";
private String phone;
public static final String JSON_PROPERTY_USER_STATUS = "userStatus";
private Integer userStatus;
public User id(Long id) {
this.id = id;
return this;
}
/**
* Get id
* @return id
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
@JsonProperty(JSON_PROPERTY_ID)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public User username(String username) {
this.username = username;
return this;
}
/**
* Get username
* @return username
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
@JsonProperty(JSON_PROPERTY_USERNAME)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public User firstName(String firstName) {
this.firstName = firstName;
return this;
}
/**
* Get firstName
* @return firstName
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
@JsonProperty(JSON_PROPERTY_FIRST_NAME)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public User lastName(String lastName) {
this.lastName = lastName;
return this;
}
/**
* Get lastName
* @return lastName
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
@JsonProperty(JSON_PROPERTY_LAST_NAME)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public User email(String email) {
this.email = email;
return this;
}
/**
* Get email
* @return email
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
@JsonProperty(JSON_PROPERTY_EMAIL)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public User password(String password) {
this.password = password;
return this;
}
/**
* Get password
* @return password
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
@JsonProperty(JSON_PROPERTY_PASSWORD)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User phone(String phone) {
this.phone = phone;
return this;
}
/**
* Get phone
* @return phone
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
@JsonProperty(JSON_PROPERTY_PHONE)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public User userStatus(Integer userStatus) {
this.userStatus = userStatus;
return this;
}
/**
* User Status
* @return userStatus
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "User Status")
@JsonProperty(JSON_PROPERTY_USER_STATUS)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public Integer getUserStatus() {
return userStatus;
}
public void setUserStatus(Integer userStatus) {
this.userStatus = userStatus;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
User user = (User) o;
return Objects.equals(this.id, user.id) &&
Objects.equals(this.username, user.username) &&
Objects.equals(this.firstName, user.firstName) &&
Objects.equals(this.lastName, user.lastName) &&
Objects.equals(this.email, user.email) &&
Objects.equals(this.password, user.password) &&
Objects.equals(this.phone, user.phone) &&
Objects.equals(this.userStatus, user.userStatus);
}
@Override
public int hashCode() {
return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class User {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" username: ").append(toIndentedString(username)).append("\n");
sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n");
sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n");
sb.append(" email: ").append(toIndentedString(email)).append("\n");
sb.append(" password: ").append(toIndentedString(password)).append("\n");
sb.append(" phone: ").append(toIndentedString(phone)).append("\n");
sb.append(" userStatus: ").append(toIndentedString(userStatus)).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(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}

View File

@ -0,0 +1,167 @@
/*
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.3
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.baeldung.petstore.client.api;
import com.baeldung.petstore.client.model.ModelApiResponse;
import com.baeldung.petstore.client.model.Pet;
import java.io.File;
import java.util.List;
import org.junit.Ignore;
import org.junit.Test;
/**
* API tests for PetApi
*/
@Ignore
public class PetApiTest {
private final PetApi api = new PetApi();
/**
* Add a new pet to the store
*
*
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void addPetTest() {
Pet body = null;
api.addPet(body);
// TODO: test validations
}
/**
* Deletes a pet
*
*
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void deletePetTest() {
Long petId = null;
String apiKey = null;
api.deletePet(petId, apiKey);
// TODO: test validations
}
/**
* Finds Pets by status
*
* Multiple status values can be provided with comma separated strings
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void findPetsByStatusTest() {
List<String> status = null;
List<Pet> response = api.findPetsByStatus(status);
// TODO: test validations
}
/**
* Finds Pets by tags
*
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void findPetsByTagsTest() {
List<String> tags = null;
List<Pet> response = api.findPetsByTags(tags);
// TODO: test validations
}
/**
* Find pet by ID
*
* Returns a single pet
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getPetByIdTest() {
Long petId = null;
Pet response = api.getPetById(petId);
// TODO: test validations
}
/**
* Update an existing pet
*
*
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void updatePetTest() {
Pet body = null;
api.updatePet(body);
// TODO: test validations
}
/**
* Updates a pet in the store with form data
*
*
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void updatePetWithFormTest() {
Long petId = null;
String name = null;
String status = null;
api.updatePetWithForm(petId, name, status);
// TODO: test validations
}
/**
* uploads an image
*
*
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void uploadFileTest() {
Long petId = null;
String additionalMetadata = null;
File file = null;
ModelApiResponse response = api.uploadFile(petId, additionalMetadata, file);
// TODO: test validations
}
}

View File

@ -0,0 +1,95 @@
/*
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.3
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.baeldung.petstore.client.api;
import com.baeldung.petstore.client.model.Order;
import java.util.Map;
import org.junit.Ignore;
import org.junit.Test;
/**
* API tests for StoreApi
*/
@Ignore
public class StoreApiTest {
private final StoreApi api = new StoreApi();
/**
* Delete purchase order by ID
*
* For valid response try integer IDs with positive integer value. Negative or non-integer values will generate API errors
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void deleteOrderTest() {
Long orderId = null;
api.deleteOrder(orderId);
// TODO: test validations
}
/**
* Returns pet inventories by status
*
* Returns a map of status codes to quantities
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getInventoryTest() {
Map<String, Integer> response = api.getInventory();
// TODO: test validations
}
/**
* Find purchase order by ID
*
* For valid response try integer IDs with value &gt;&#x3D; 1 and &lt;&#x3D; 10. Other values will generated exceptions
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getOrderByIdTest() {
Long orderId = null;
Order response = api.getOrderById(orderId);
// TODO: test validations
}
/**
* Place an order for a pet
*
*
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void placeOrderTest() {
Order body = null;
Order response = api.placeOrder(body);
// TODO: test validations
}
}

View File

@ -0,0 +1,161 @@
/*
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.3
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.baeldung.petstore.client.api;
import com.baeldung.petstore.client.model.User;
import java.util.List;
import org.junit.Ignore;
import org.junit.Test;
/**
* API tests for UserApi
*/
@Ignore
public class UserApiTest {
private final UserApi api = new UserApi();
/**
* Create user
*
* This can only be done by the logged in user.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void createUserTest() {
User body = null;
api.createUser(body);
// TODO: test validations
}
/**
* Creates list of users with given input array
*
*
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void createUsersWithArrayInputTest() {
List<User> body = null;
api.createUsersWithArrayInput(body);
// TODO: test validations
}
/**
* Creates list of users with given input array
*
*
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void createUsersWithListInputTest() {
List<User> body = null;
api.createUsersWithListInput(body);
// TODO: test validations
}
/**
* Delete user
*
* This can only be done by the logged in user.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void deleteUserTest() {
String username = null;
api.deleteUser(username);
// TODO: test validations
}
/**
* Get user by user name
*
*
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void getUserByNameTest() {
String username = null;
User response = api.getUserByName(username);
// TODO: test validations
}
/**
* Logs user into the system
*
*
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void loginUserTest() {
String username = null;
String password = null;
String response = api.loginUser(username, password);
// TODO: test validations
}
/**
* Logs out current logged in user session
*
*
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void logoutUserTest() {
api.logoutUser();
// TODO: test validations
}
/**
* Updated user
*
* This can only be done by the logged in user.
*
* @throws ApiException
* if the Api call fails
*/
@Test
public void updateUserTest() {
String username = null;
User body = null;
api.updateUser(username, body);
// TODO: test validations
}
}

View File

@ -0,0 +1,49 @@
/*
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.3
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.baeldung.petstore.client.model;
import org.junit.Test;
/**
* Model tests for Category
*/
public class CategoryTest {
private final Category model = new Category();
/**
* Model tests for Category
*/
@Test
public void testCategory() {
// TODO: test Category
}
/**
* Test the property 'id'
*/
@Test
public void idTest() {
// TODO: test id
}
/**
* Test the property 'name'
*/
@Test
public void nameTest() {
// TODO: test name
}
}

View File

@ -0,0 +1,57 @@
/*
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.3
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.baeldung.petstore.client.model;
import org.junit.Test;
/**
* Model tests for ModelApiResponse
*/
public class ModelApiResponseTest {
private final ModelApiResponse model = new ModelApiResponse();
/**
* Model tests for ModelApiResponse
*/
@Test
public void testModelApiResponse() {
// TODO: test ModelApiResponse
}
/**
* Test the property 'code'
*/
@Test
public void codeTest() {
// TODO: test code
}
/**
* Test the property 'type'
*/
@Test
public void typeTest() {
// TODO: test type
}
/**
* Test the property 'message'
*/
@Test
public void messageTest() {
// TODO: test message
}
}

View File

@ -0,0 +1,81 @@
/*
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.3
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.baeldung.petstore.client.model;
import org.junit.Test;
/**
* Model tests for Order
*/
public class OrderTest {
private final Order model = new Order();
/**
* Model tests for Order
*/
@Test
public void testOrder() {
// TODO: test Order
}
/**
* Test the property 'id'
*/
@Test
public void idTest() {
// TODO: test id
}
/**
* Test the property 'petId'
*/
@Test
public void petIdTest() {
// TODO: test petId
}
/**
* Test the property 'quantity'
*/
@Test
public void quantityTest() {
// TODO: test quantity
}
/**
* Test the property 'shipDate'
*/
@Test
public void shipDateTest() {
// TODO: test shipDate
}
/**
* Test the property 'status'
*/
@Test
public void statusTest() {
// TODO: test status
}
/**
* Test the property 'complete'
*/
@Test
public void completeTest() {
// TODO: test complete
}
}

View File

@ -0,0 +1,81 @@
/*
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.3
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.baeldung.petstore.client.model;
import org.junit.Test;
/**
* Model tests for Pet
*/
public class PetTest {
private final Pet model = new Pet();
/**
* Model tests for Pet
*/
@Test
public void testPet() {
// TODO: test Pet
}
/**
* Test the property 'id'
*/
@Test
public void idTest() {
// TODO: test id
}
/**
* Test the property 'category'
*/
@Test
public void categoryTest() {
// TODO: test category
}
/**
* Test the property 'name'
*/
@Test
public void nameTest() {
// TODO: test name
}
/**
* Test the property 'photoUrls'
*/
@Test
public void photoUrlsTest() {
// TODO: test photoUrls
}
/**
* Test the property 'tags'
*/
@Test
public void tagsTest() {
// TODO: test tags
}
/**
* Test the property 'status'
*/
@Test
public void statusTest() {
// TODO: test status
}
}

View File

@ -0,0 +1,49 @@
/*
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.3
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.baeldung.petstore.client.model;
import org.junit.Test;
/**
* Model tests for Tag
*/
public class TagTest {
private final Tag model = new Tag();
/**
* Model tests for Tag
*/
@Test
public void testTag() {
// TODO: test Tag
}
/**
* Test the property 'id'
*/
@Test
public void idTest() {
// TODO: test id
}
/**
* Test the property 'name'
*/
@Test
public void nameTest() {
// TODO: test name
}
}

View File

@ -0,0 +1,97 @@
/*
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.
*
* The version of the OpenAPI document: 1.0.3
* Contact: apiteam@swagger.io
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package com.baeldung.petstore.client.model;
import org.junit.Test;
/**
* Model tests for User
*/
public class UserTest {
private final User model = new User();
/**
* Model tests for User
*/
@Test
public void testUser() {
// TODO: test User
}
/**
* Test the property 'id'
*/
@Test
public void idTest() {
// TODO: test id
}
/**
* Test the property 'username'
*/
@Test
public void usernameTest() {
// TODO: test username
}
/**
* Test the property 'firstName'
*/
@Test
public void firstNameTest() {
// TODO: test firstName
}
/**
* Test the property 'lastName'
*/
@Test
public void lastNameTest() {
// TODO: test lastName
}
/**
* Test the property 'email'
*/
@Test
public void emailTest() {
// TODO: test email
}
/**
* Test the property 'password'
*/
@Test
public void passwordTest() {
// TODO: test password
}
/**
* Test the property 'phone'
*/
@Test
public void phoneTest() {
// TODO: test phone
}
/**
* Test the property 'userStatus'
*/
@Test
public void userStatusTest() {
// TODO: test userStatus
}
}