From 42d955d7a36d2adc4d703ade421fa7652f366e72 Mon Sep 17 00:00:00 2001 From: Benjamin Roedell Date: Mon, 22 Jan 2018 12:28:18 -0500 Subject: [PATCH 1/9] Build sample prior to code changes so differences are easier to decipher --- bin/windows/java-petstore-okhttp-gson.bat | 2 +- .../client/petstore/java/okhttp-gson/.swagger-codegen/VERSION | 2 +- .../src/main/java/io/swagger/client/model/Animal.java | 3 +++ 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/bin/windows/java-petstore-okhttp-gson.bat b/bin/windows/java-petstore-okhttp-gson.bat index 2b61d1decbd..91e3a4f218c 100755 --- a/bin/windows/java-petstore-okhttp-gson.bat +++ b/bin/windows/java-petstore-okhttp-gson.bat @@ -5,6 +5,6 @@ If Not Exist %executable% ( ) REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -l java -o samples\client\petstore\java --library=okhttp-gson -DdateLibrary=joda -DhideGenerationTimestamp=true +set ags=generate -t modules\swagger-codegen\src\main\resources\Java\libraries\okhttp-gson -i modules\swagger-codegen\src\test\resources\2_0\petstore-with-fake-endpoints-models-for-testing.yaml -l java -c bin\java-petstore-okhttp-gson.json -o samples\client\petstore\java\okhttp-gson -DhideGenerationTimestamp=true java %JAVA_OPTS% -jar %executable% %ags% diff --git a/samples/client/petstore/java/okhttp-gson/.swagger-codegen/VERSION b/samples/client/petstore/java/okhttp-gson/.swagger-codegen/VERSION index 50794f17f1a..717311e32e3 100644 --- a/samples/client/petstore/java/okhttp-gson/.swagger-codegen/VERSION +++ b/samples/client/petstore/java/okhttp-gson/.swagger-codegen/VERSION @@ -1 +1 @@ -2.3.1-SNAPSHOT \ No newline at end of file +unset \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Animal.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Animal.java index f4b0464382d..fbbaef5c1e4 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Animal.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Animal.java @@ -36,6 +36,9 @@ public class Animal { @SerializedName("color") private String color = "red"; + public Animal() { + this.className = this.getClass().getSimpleName(); + } public Animal className(String className) { this.className = className; return this; From 6f14ef9629defb9b67772d204214c10f5cd2f568 Mon Sep 17 00:00:00 2001 From: Benjamin Roedell Date: Mon, 22 Jan 2018 16:10:52 -0500 Subject: [PATCH 2/9] Add byte array type adapter for okhttp-gson (java8 only) --- .../Java/libraries/okhttp-gson/JSON.mustache | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache index 34ae1795cf8..e7226878929 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache @@ -37,6 +37,7 @@ import java.text.ParsePosition; import java.time.LocalDate; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; +import java.util.Base64; {{/java8}} import java.util.Date; import java.util.Map; @@ -55,6 +56,9 @@ public class JSON { private OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter(); private LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); {{/jsr310}} + {{#java8}} + private LocalByteArrayAdapter localByteArrayAdapter = new LocalByteArrayAdapter(); + {{/java8}} public static GsonBuilder createGson() { GsonFireBuilder fireBuilder = new GsonFireBuilder() @@ -105,6 +109,9 @@ public class JSON { .registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter) .registerTypeAdapter(LocalDate.class, localDateTypeAdapter) {{/jsr310}} + {{#java8}} + .registerTypeAdapter(byte[].class, localByteArrayAdapter) + {{/java8}} .create(); } @@ -171,6 +178,35 @@ public class JSON { } } + {{#java8}} + /** + * Gson TypeAdapter for Byte Array type + */ + public class LocalByteArrayAdapter extends TypeAdapter { + + @Override + public void write(JsonWriter out, byte[] value) throws IOException { + if (value == null) { + out.nullValue(); + } else { + out.value(Base64.getEncoder().encodeToString(value)); + } + } + + @Override + public byte[] read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String bytesAsBase64 = in.nextString(); + return Base64.getDecoder().decode(bytesAsBase64); + } + } + } + + {{/java8}} {{#joda}} /** * Gson TypeAdapter for Joda DateTime type From e34cf18b60b19d692dceabdac815f53945a1413e Mon Sep 17 00:00:00 2001 From: Benjamin Roedell Date: Mon, 22 Jan 2018 17:08:58 -0500 Subject: [PATCH 3/9] Unit revealed that Gson (or GsonFire) defaults to escape = (equal sign) out of base64 string. Add disableHtmlEscaping() to gsonbuilder. --- .../src/main/resources/Java/libraries/okhttp-gson/JSON.mustache | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache index e7226878929..fe6ef5a0ee7 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache @@ -110,6 +110,7 @@ public class JSON { .registerTypeAdapter(LocalDate.class, localDateTypeAdapter) {{/jsr310}} {{#java8}} + .disableHtmlEscaping(){{! Added to prevent base64 = (equal sign) from being escaped }} .registerTypeAdapter(byte[].class, localByteArrayAdapter) {{/java8}} .create(); From 941181b83fc79d0de51410eec2a961603f78c47e Mon Sep 17 00:00:00 2001 From: Benjamin Roedell Date: Mon, 22 Jan 2018 17:14:53 -0500 Subject: [PATCH 4/9] Update specs and samples to include format=byte and include junit test of byte array serialization and deserialization. --- bin/java-petstore-okhttp-gson.json | 4 +- ...ith-fake-endpoints-models-for-testing.yaml | 3 + .../src/test/resources/2_0/petstore.json | 4 + .../src/test/resources/petstore.json | 4 + .../src/test/resources/petstore.json | 4 + .../petstore/java/okhttp-gson/README.md | 150 ++--- .../petstore/java/okhttp-gson/build.gradle | 17 +- .../petstore/java/okhttp-gson/build.sbt | 1 - .../java/okhttp-gson/docs/ApiResponse.md | 12 - .../docs/Fake_classname_tags123Api.md | 52 -- .../okhttp-gson/docs/FakeclassnametagsApi.md | 52 -- .../okhttp-gson/docs/InlineResponse200.md | 24 - .../java/okhttp-gson/docs/OuterBoolean.md | 9 - .../java/okhttp-gson/docs/OuterNumber.md | 9 - .../java/okhttp-gson/docs/OuterString.md | 9 - .../petstore/java/okhttp-gson/docs/Pet.md | 1 + .../client/petstore/java/okhttp-gson/pom.xml | 8 +- .../gen/io/swagger/client/BuildConfig.java | 8 - .../main/gen/io/swagger/client/Manifest.java | 7 - .../src/main/gen/io/swagger/client/R.java | 7 - .../java/io/swagger/client/ApiClient.java | 6 +- .../src/main/java/io/swagger/client/JSON.java | 37 +- .../java/io/swagger/client/api/FakeApi.java | 4 +- .../model/AdditionalPropertiesClass.java | 4 +- .../model/ArrayOfArrayOfNumberOnly.java | 2 +- .../client/model/ArrayOfNumberOnly.java | 2 +- .../io/swagger/client/model/ArrayTest.java | 6 +- .../io/swagger/client/model/EnumArrays.java | 2 +- .../io/swagger/client/model/FormatTest.java | 4 +- .../java/io/swagger/client/model/MapTest.java | 4 +- ...ropertiesAndAdditionalPropertiesClass.java | 4 +- .../java/io/swagger/client/model/Order.java | 2 +- .../java/io/swagger/client/model/Pet.java | 31 +- .../test/java/io/swagger/client/JSONTest.java | 67 ++- .../io/swagger/client/api/FakeApiTest.java | 166 +++++- .../io/swagger/client/api/PetApiTest.java | 519 +++++------------- .../io/swagger/client/api/StoreApiTest.java | 157 +++--- .../io/swagger/client/api/UserApiTest.java | 197 +++++-- 38 files changed, 773 insertions(+), 826 deletions(-) delete mode 100644 samples/client/petstore/java/okhttp-gson/docs/ApiResponse.md delete mode 100644 samples/client/petstore/java/okhttp-gson/docs/Fake_classname_tags123Api.md delete mode 100644 samples/client/petstore/java/okhttp-gson/docs/FakeclassnametagsApi.md delete mode 100644 samples/client/petstore/java/okhttp-gson/docs/InlineResponse200.md delete mode 100644 samples/client/petstore/java/okhttp-gson/docs/OuterBoolean.md delete mode 100644 samples/client/petstore/java/okhttp-gson/docs/OuterNumber.md delete mode 100644 samples/client/petstore/java/okhttp-gson/docs/OuterString.md delete mode 100644 samples/client/petstore/java/okhttp-gson/src/main/gen/io/swagger/client/BuildConfig.java delete mode 100644 samples/client/petstore/java/okhttp-gson/src/main/gen/io/swagger/client/Manifest.java delete mode 100644 samples/client/petstore/java/okhttp-gson/src/main/gen/io/swagger/client/R.java diff --git a/bin/java-petstore-okhttp-gson.json b/bin/java-petstore-okhttp-gson.json index b894d172630..997f3ab7aa5 100644 --- a/bin/java-petstore-okhttp-gson.json +++ b/bin/java-petstore-okhttp-gson.json @@ -1,4 +1,6 @@ { "library": "okhttp-gson", - "artifactId": "swagger-petstore-okhttp-gson" + "artifactId": "swagger-petstore-okhttp-gson", + "java8": "true", + "dateLibrary": "java8" } diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml index d84d621f687..9a712e3b4cb 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml @@ -1069,6 +1069,9 @@ definitions: - available - pending - sold + profilePhoto: + type: string + format: byte xml: name: Pet ApiResponse: diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore.json b/modules/swagger-codegen/src/test/resources/2_0/petstore.json index 4290daed14d..f44c31d8058 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore.json +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore.json @@ -917,6 +917,10 @@ "pending", "sold" ] + }, + "profilePhoto": { + "type": "string", + "format": "byte" } }, "xml": { diff --git a/modules/swagger-codegen/src/test/resources/petstore.json b/modules/swagger-codegen/src/test/resources/petstore.json index dd9b1f42edf..3632ac61413 100644 --- a/modules/swagger-codegen/src/test/resources/petstore.json +++ b/modules/swagger-codegen/src/test/resources/petstore.json @@ -918,6 +918,10 @@ "pending", "sold" ] + }, + "profilePhoto": { + "type": "string", + "format": "byte" } }, "xml": { diff --git a/modules/swagger-generator/src/test/resources/petstore.json b/modules/swagger-generator/src/test/resources/petstore.json index 1617f8d0ae6..5cc5369f82e 100644 --- a/modules/swagger-generator/src/test/resources/petstore.json +++ b/modules/swagger-generator/src/test/resources/petstore.json @@ -1016,6 +1016,10 @@ "pending", "sold" ] + }, + "profilePhoto": { + "type": "string", + "format": "byte" } }, "xml": { diff --git a/samples/client/petstore/java/okhttp-gson/README.md b/samples/client/petstore/java/okhttp-gson/README.md index 541407fec8b..cb9aa7a4531 100644 --- a/samples/client/petstore/java/okhttp-gson/README.md +++ b/samples/client/petstore/java/okhttp-gson/README.md @@ -1,24 +1,35 @@ # swagger-petstore-okhttp-gson +Swagger Petstore +- API version: 1.0.0 + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + +*Automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen)* + + ## Requirements -Building the API client library requires [Maven](https://maven.apache.org/) to be installed. +Building the API client library requires: +1. Java 1.7+ +2. Maven/Gradle ## Installation To install the API client library to your local Maven repository, simply execute: ```shell -mvn install +mvn clean install ``` To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: ```shell -mvn deploy +mvn clean deploy ``` -Refer to the [official documentation](https://maven.apache.org/plugins/maven-deploy-plugin/usage.html) for more information. +Refer to the [OSSRH Guide](http://central.sonatype.org/pages/ossrh-guide.html) for more information. ### Maven users @@ -26,10 +37,10 @@ Add this dependency to your project's POM: ```xml - io.swagger - swagger-petstore-okhttp-gson - 1.0.0 - compile + io.swagger + swagger-petstore-okhttp-gson + 1.0.0 + compile ``` @@ -45,12 +56,14 @@ compile "io.swagger:swagger-petstore-okhttp-gson:1.0.0" At first generate the JAR by executing: - mvn package +```shell +mvn clean package +``` Then manually install the following JARs: -* target/swagger-petstore-okhttp-gson-1.0.0.jar -* target/lib/*.jar +* `target/swagger-petstore-okhttp-gson-1.0.0.jar` +* `target/lib/*.jar` ## Getting Started @@ -61,30 +74,22 @@ Please follow the [installation](#installation) instruction and execute the foll import io.swagger.client.*; import io.swagger.client.auth.*; import io.swagger.client.model.*; -import io.swagger.client.api.PetApi; +import io.swagger.client.api.AnotherFakeApi; import java.io.File; import java.util.*; -public class PetApiExample { +public class AnotherFakeApiExample { public static void main(String[] args) { - ApiClient defaultClient = Configuration.getDefaultApiClient(); - - // 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(); - - Pet body = new Pet(); // Pet | Pet object that needs to be added to the store + AnotherFakeApi apiInstance = new AnotherFakeApi(); + Client body = new Client(); // Client | client model try { - apiInstance.addPet(body); + Client result = apiInstance.testSpecialTags(body); + System.out.println(result); } catch (ApiException e) { - System.err.println("Exception when calling PetApi#addPet"); + System.err.println("Exception when calling AnotherFakeApi#testSpecialTags"); e.printStackTrace(); } } @@ -94,26 +99,32 @@ public class PetApiExample { ## Documentation for API Endpoints -All URIs are relative to *http://petstore.swagger.io/v2* +All URIs are relative to *http://petstore.swagger.io:80/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- +*AnotherFakeApi* | [**testSpecialTags**](docs/AnotherFakeApi.md#testSpecialTags) | **PATCH** /another-fake/dummy | To test special tags +*FakeApi* | [**fakeOuterBooleanSerialize**](docs/FakeApi.md#fakeOuterBooleanSerialize) | **POST** /fake/outer/boolean | +*FakeApi* | [**fakeOuterCompositeSerialize**](docs/FakeApi.md#fakeOuterCompositeSerialize) | **POST** /fake/outer/composite | +*FakeApi* | [**fakeOuterNumberSerialize**](docs/FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | +*FakeApi* | [**fakeOuterStringSerialize**](docs/FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | +*FakeApi* | [**testClientModel**](docs/FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model +*FakeApi* | [**testEndpointParameters**](docs/FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeApi* | [**testEnumParameters**](docs/FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters +*FakeApi* | [**testInlineAdditionalProperties**](docs/FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +*FakeApi* | [**testJsonFormData**](docs/FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data +*FakeClassnameTags123Api* | [**testClassname**](docs/FakeClassnameTags123Api.md#testClassname) | **PATCH** /fake_classname_test | To test class name in snake case *PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store -*PetApi* | [**addPetUsingByteArray**](docs/PetApi.md#addPetUsingByteArray) | **POST** /pet?testing_byte_array=true | Fake endpoint to test byte array in body parameter for adding 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* | [**getPetByIdInObject**](docs/PetApi.md#getPetByIdInObject) | **GET** /pet/{petId}?response=inline_arbitrary_object | Fake endpoint to test inline arbitrary object return by 'Find pet by ID' -*PetApi* | [**petPetIdtestingByteArraytrueGet**](docs/PetApi.md#petPetIdtestingByteArraytrueGet) | **GET** /pet/{petId}?testing_byte_array=true | Fake endpoint to test byte array return by '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* | [**findOrdersByStatus**](docs/StoreApi.md#findOrdersByStatus) | **GET** /store/findByStatus | Finds orders by status +*StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteOrder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID *StoreApi* | [**getInventory**](docs/StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status -*StoreApi* | [**getInventoryInObject**](docs/StoreApi.md#getInventoryInObject) | **GET** /store/inventory?response=arbitrary_object | Fake endpoint to test arbitrary object return by 'Get inventory' -*StoreApi* | [**getOrderById**](docs/StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**getOrderById**](docs/StoreApi.md#getOrderById) | **GET** /store/order/{order_id} | 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 @@ -127,71 +138,72 @@ Class | Method | HTTP request | Description ## Documentation for Models + - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) - [Animal](docs/Animal.md) - - [Cat](docs/Cat.md) + - [AnimalFarm](docs/AnimalFarm.md) + - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) + - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) + - [ArrayTest](docs/ArrayTest.md) + - [Capitalization](docs/Capitalization.md) - [Category](docs/Category.md) - - [Dog](docs/Dog.md) - - [InlineResponse200](docs/InlineResponse200.md) + - [ClassModel](docs/ClassModel.md) + - [Client](docs/Client.md) + - [EnumArrays](docs/EnumArrays.md) + - [EnumClass](docs/EnumClass.md) + - [EnumTest](docs/EnumTest.md) + - [FormatTest](docs/FormatTest.md) + - [HasOnlyReadOnly](docs/HasOnlyReadOnly.md) + - [MapTest](docs/MapTest.md) + - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - [Model200Response](docs/Model200Response.md) + - [ModelApiResponse](docs/ModelApiResponse.md) - [ModelReturn](docs/ModelReturn.md) - [Name](docs/Name.md) + - [NumberOnly](docs/NumberOnly.md) - [Order](docs/Order.md) + - [OuterComposite](docs/OuterComposite.md) + - [OuterEnum](docs/OuterEnum.md) - [Pet](docs/Pet.md) + - [ReadOnlyFirst](docs/ReadOnlyFirst.md) - [SpecialModelName](docs/SpecialModelName.md) - [Tag](docs/Tag.md) - [User](docs/User.md) + - [Cat](docs/Cat.md) + - [Dog](docs/Dog.md) ## Documentation for Authorization Authentication schemes defined for the API: -### petstore_auth - -- **Type**: OAuth -- **Flow**: implicit -- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog -- **Scopes**: - - write:pets: modify pets in your account - - read:pets: read your pets - -### test_api_client_id - -- **Type**: API key -- **API key parameter name**: x-test_api_client_id -- **Location**: HTTP header - -### test_api_client_secret - -- **Type**: API key -- **API key parameter name**: x-test_api_client_secret -- **Location**: HTTP header - ### api_key - **Type**: API key - **API key parameter name**: api_key - **Location**: HTTP header -### test_http_basic - -- **Type**: HTTP basic authentication - -### test_api_key_query +### api_key_query - **Type**: API key -- **API key parameter name**: test_api_key_query +- **API key parameter name**: api_key_query - **Location**: URL query string -### test_api_key_header +### http_basic_test -- **Type**: API key -- **API key parameter name**: test_api_key_header -- **Location**: HTTP header +- **Type**: HTTP basic authentication + +### petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - write:pets: modify pets in your account + - read:pets: read your pets ## Recommendation -It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issue. +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. ## Author diff --git a/samples/client/petstore/java/okhttp-gson/build.gradle b/samples/client/petstore/java/okhttp-gson/build.gradle index c11d2e8f805..97acef84fd7 100644 --- a/samples/client/petstore/java/okhttp-gson/build.gradle +++ b/samples/client/petstore/java/okhttp-gson/build.gradle @@ -32,8 +32,8 @@ if(hasProperty('target') && target == 'android') { targetSdkVersion 25 } compileOptions { - sourceCompatibility JavaVersion.VERSION_1_7 - targetCompatibility JavaVersion.VERSION_1_7 + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 } // Rename the aar correctly @@ -78,8 +78,8 @@ if(hasProperty('target') && target == 'android') { apply plugin: 'java' apply plugin: 'maven' - sourceCompatibility = JavaVersion.VERSION_1_7 - targetCompatibility = JavaVersion.VERSION_1_7 + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 install { repositories.mavenInstaller { @@ -91,6 +91,14 @@ if(hasProperty('target') && target == 'android') { main = System.getProperty('mainClass') classpath = sourceSets.main.runtimeClasspath } + + compileJava { + options.encoding = "UTF8" + } + + compileTestJava { + options.encoding = "UTF8" + } } dependencies { @@ -99,6 +107,5 @@ dependencies { compile 'com.squareup.okhttp:logging-interceptor:2.7.5' compile 'com.google.code.gson:gson:2.8.1' compile 'io.gsonfire:gson-fire:1.8.0' - compile 'org.threeten:threetenbp:1.3.5' testCompile 'junit:junit:4.12' } diff --git a/samples/client/petstore/java/okhttp-gson/build.sbt b/samples/client/petstore/java/okhttp-gson/build.sbt index db083233db7..6e84ac02ac9 100644 --- a/samples/client/petstore/java/okhttp-gson/build.sbt +++ b/samples/client/petstore/java/okhttp-gson/build.sbt @@ -13,7 +13,6 @@ lazy val root = (project in file(".")). "com.squareup.okhttp" % "okhttp" % "2.7.5", "com.squareup.okhttp" % "logging-interceptor" % "2.7.5", "com.google.code.gson" % "gson" % "2.8.1", - "org.threeten" % "threetenbp" % "1.3.5" % "compile", "io.gsonfire" % "gson-fire" % "1.8.0" % "compile", "junit" % "junit" % "4.12" % "test", "com.novocode" % "junit-interface" % "0.10" % "test" diff --git a/samples/client/petstore/java/okhttp-gson/docs/ApiResponse.md b/samples/client/petstore/java/okhttp-gson/docs/ApiResponse.md deleted file mode 100644 index 1c17767c2b7..00000000000 --- a/samples/client/petstore/java/okhttp-gson/docs/ApiResponse.md +++ /dev/null @@ -1,12 +0,0 @@ - -# ApiResponse - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**code** | **Integer** | | [optional] -**type** | **String** | | [optional] -**message** | **String** | | [optional] - - - diff --git a/samples/client/petstore/java/okhttp-gson/docs/Fake_classname_tags123Api.md b/samples/client/petstore/java/okhttp-gson/docs/Fake_classname_tags123Api.md deleted file mode 100644 index 56f7c9ea1ff..00000000000 --- a/samples/client/petstore/java/okhttp-gson/docs/Fake_classname_tags123Api.md +++ /dev/null @@ -1,52 +0,0 @@ -# Fake_classname_tags123Api - -All URIs are relative to *http://petstore.swagger.io/v2* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**testClassname**](Fake_classname_tags123Api.md#testClassname) | **PATCH** /fake_classname_test | To test class name in snake case - - - -# **testClassname** -> Client testClassname(body) - -To test class name in snake case - -### Example -```java -// Import classes: -//import io.swagger.client.ApiException; -//import io.swagger.client.api.Fake_classname_tags123Api; - - -Fake_classname_tags123Api apiInstance = new Fake_classname_tags123Api(); -Client body = new Client(); // Client | client model -try { - Client result = apiInstance.testClassname(body); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling Fake_classname_tags123Api#testClassname"); - e.printStackTrace(); -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | [**Client**](Client.md)| client model | - -### Return type - -[**Client**](Client.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - diff --git a/samples/client/petstore/java/okhttp-gson/docs/FakeclassnametagsApi.md b/samples/client/petstore/java/okhttp-gson/docs/FakeclassnametagsApi.md deleted file mode 100644 index f8ec0768e1f..00000000000 --- a/samples/client/petstore/java/okhttp-gson/docs/FakeclassnametagsApi.md +++ /dev/null @@ -1,52 +0,0 @@ -# FakeclassnametagsApi - -All URIs are relative to *http://petstore.swagger.io/v2* - -Method | HTTP request | Description -------------- | ------------- | ------------- -[**testClassname**](FakeclassnametagsApi.md#testClassname) | **PATCH** /fake_classname_test | To test class name in snake case - - - -# **testClassname** -> Client testClassname(body) - -To test class name in snake case - -### Example -```java -// Import classes: -//import io.swagger.client.ApiException; -//import io.swagger.client.api.FakeclassnametagsApi; - - -FakeclassnametagsApi apiInstance = new FakeclassnametagsApi(); -Client body = new Client(); // Client | client model -try { - Client result = apiInstance.testClassname(body); - System.out.println(result); -} catch (ApiException e) { - System.err.println("Exception when calling FakeclassnametagsApi#testClassname"); - e.printStackTrace(); -} -``` - -### Parameters - -Name | Type | Description | Notes -------------- | ------------- | ------------- | ------------- - **body** | [**Client**](Client.md)| client model | - -### Return type - -[**Client**](Client.md) - -### Authorization - -No authorization required - -### HTTP request headers - - - **Content-Type**: application/json - - **Accept**: application/json - diff --git a/samples/client/petstore/java/okhttp-gson/docs/InlineResponse200.md b/samples/client/petstore/java/okhttp-gson/docs/InlineResponse200.md deleted file mode 100644 index 487ebe429e4..00000000000 --- a/samples/client/petstore/java/okhttp-gson/docs/InlineResponse200.md +++ /dev/null @@ -1,24 +0,0 @@ - -# InlineResponse200 - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**photoUrls** | **List<String>** | | [optional] -**name** | **String** | | [optional] -**id** | **Long** | | -**category** | **Object** | | [optional] -**tags** | [**List<Tag>**](Tag.md) | | [optional] -**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] - - - -## Enum: StatusEnum -Name | Value ----- | ----- -AVAILABLE | available -PENDING | pending -SOLD | sold - - - diff --git a/samples/client/petstore/java/okhttp-gson/docs/OuterBoolean.md b/samples/client/petstore/java/okhttp-gson/docs/OuterBoolean.md deleted file mode 100644 index 0c792032f84..00000000000 --- a/samples/client/petstore/java/okhttp-gson/docs/OuterBoolean.md +++ /dev/null @@ -1,9 +0,0 @@ - -# OuterBoolean - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - - - diff --git a/samples/client/petstore/java/okhttp-gson/docs/OuterNumber.md b/samples/client/petstore/java/okhttp-gson/docs/OuterNumber.md deleted file mode 100644 index ab7613b1810..00000000000 --- a/samples/client/petstore/java/okhttp-gson/docs/OuterNumber.md +++ /dev/null @@ -1,9 +0,0 @@ - -# OuterNumber - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - - - diff --git a/samples/client/petstore/java/okhttp-gson/docs/OuterString.md b/samples/client/petstore/java/okhttp-gson/docs/OuterString.md deleted file mode 100644 index 3079fce4a0d..00000000000 --- a/samples/client/petstore/java/okhttp-gson/docs/OuterString.md +++ /dev/null @@ -1,9 +0,0 @@ - -# OuterString - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - - - diff --git a/samples/client/petstore/java/okhttp-gson/docs/Pet.md b/samples/client/petstore/java/okhttp-gson/docs/Pet.md index 5b63109ef92..c05160aa4a3 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/Pet.md +++ b/samples/client/petstore/java/okhttp-gson/docs/Pet.md @@ -10,6 +10,7 @@ Name | Type | Description | Notes **photoUrls** | **List<String>** | | **tags** | [**List<Tag>**](Tag.md) | | [optional] **status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] +**profilePhoto** | **byte[]** | | [optional] diff --git a/samples/client/petstore/java/okhttp-gson/pom.xml b/samples/client/petstore/java/okhttp-gson/pom.xml index b9e81522265..e70877c1e00 100644 --- a/samples/client/petstore/java/okhttp-gson/pom.xml +++ b/samples/client/petstore/java/okhttp-gson/pom.xml @@ -213,11 +213,6 @@ gson-fire ${gson-fire-version} - - org.threeten - threetenbp - ${threetenbp-version} - junit @@ -227,14 +222,13 @@ - 1.7 + 1.8 ${java.version} ${java.version} 1.8.0 1.5.15 2.7.5 2.8.1 - 1.3.5 1.0.0 4.12 UTF-8 diff --git a/samples/client/petstore/java/okhttp-gson/src/main/gen/io/swagger/client/BuildConfig.java b/samples/client/petstore/java/okhttp-gson/src/main/gen/io/swagger/client/BuildConfig.java deleted file mode 100644 index 720765940d3..00000000000 --- a/samples/client/petstore/java/okhttp-gson/src/main/gen/io/swagger/client/BuildConfig.java +++ /dev/null @@ -1,8 +0,0 @@ -/*___Generated_by_IDEA___*/ - -package io.swagger.client; - -/* This stub is only used by the IDE. It is NOT the BuildConfig class actually packed into the APK */ -public final class BuildConfig { - public final static boolean DEBUG = Boolean.parseBoolean(null); -} \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson/src/main/gen/io/swagger/client/Manifest.java b/samples/client/petstore/java/okhttp-gson/src/main/gen/io/swagger/client/Manifest.java deleted file mode 100644 index 41e0523a208..00000000000 --- a/samples/client/petstore/java/okhttp-gson/src/main/gen/io/swagger/client/Manifest.java +++ /dev/null @@ -1,7 +0,0 @@ -/*___Generated_by_IDEA___*/ - -package io.swagger.client; - -/* This stub is only used by the IDE. It is NOT the Manifest class actually packed into the APK */ -public final class Manifest { -} \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson/src/main/gen/io/swagger/client/R.java b/samples/client/petstore/java/okhttp-gson/src/main/gen/io/swagger/client/R.java deleted file mode 100644 index cd0683364d5..00000000000 --- a/samples/client/petstore/java/okhttp-gson/src/main/gen/io/swagger/client/R.java +++ /dev/null @@ -1,7 +0,0 @@ -/*___Generated_by_IDEA___*/ - -package io.swagger.client; - -/* This stub is only used by the IDE. It is NOT the R class actually packed into the APK */ -public final class R { -} \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java index a82ca551679..7c01160a4da 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java @@ -19,9 +19,6 @@ import com.squareup.okhttp.logging.HttpLoggingInterceptor.Level; import okio.BufferedSink; import okio.Okio; -import org.threeten.bp.LocalDate; -import org.threeten.bp.OffsetDateTime; -import org.threeten.bp.format.DateTimeFormatter; import javax.net.ssl.*; import java.io.File; @@ -39,6 +36,9 @@ import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.text.DateFormat; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java index df84d970239..7c8f5321db9 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java @@ -23,9 +23,6 @@ import com.google.gson.JsonElement; import io.gsonfire.GsonFireBuilder; import io.gsonfire.TypeSelector; -import org.threeten.bp.LocalDate; -import org.threeten.bp.OffsetDateTime; -import org.threeten.bp.format.DateTimeFormatter; import io.swagger.client.model.*; @@ -35,6 +32,10 @@ import java.text.DateFormat; import java.text.ParseException; import java.text.ParsePosition; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Base64; import java.util.Date; import java.util.Map; import java.util.HashMap; @@ -46,6 +47,7 @@ public class JSON { private SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter(); private OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter(); private LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); + private LocalByteArrayAdapter localByteArrayAdapter = new LocalByteArrayAdapter(); public static GsonBuilder createGson() { GsonFireBuilder fireBuilder = new GsonFireBuilder() @@ -87,6 +89,8 @@ public JSON() { .registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter) .registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter) .registerTypeAdapter(LocalDate.class, localDateTypeAdapter) + .disableHtmlEscaping() + .registerTypeAdapter(byte[].class, localByteArrayAdapter) .create(); } @@ -153,6 +157,33 @@ public T deserialize(String body, Type returnType) { } } + /** + * Gson TypeAdapter for Byte Array type + */ + public class LocalByteArrayAdapter extends TypeAdapter { + + @Override + public void write(JsonWriter out, byte[] value) throws IOException { + if (value == null) { + out.nullValue(); + } else { + out.value(Base64.getEncoder().encodeToString(value)); + } + } + + @Override + public byte[] read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String bytesAsBase64 = in.nextString(); + return Base64.getDecoder().decode(bytesAsBase64); + } + } + } + /** * Gson TypeAdapter for JSR310 OffsetDateTime type */ diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java index beb9cb1f8ff..0a3fab2246e 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java @@ -29,8 +29,8 @@ import java.math.BigDecimal; import io.swagger.client.model.Client; -import org.threeten.bp.LocalDate; -import org.threeten.bp.OffsetDateTime; +import java.time.LocalDate; +import java.time.OffsetDateTime; import io.swagger.client.model.OuterComposite; import java.lang.reflect.Type; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index a1d984bdcf1..a39ff1ede1a 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -45,7 +45,7 @@ public AdditionalPropertiesClass mapProperty(Map mapProperty) { public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { if (this.mapProperty == null) { - this.mapProperty = new HashMap(); + this.mapProperty = new HashMap<>(); } this.mapProperty.put(key, mapPropertyItem); return this; @@ -71,7 +71,7 @@ public AdditionalPropertiesClass mapOfMapProperty(Map mapOfMapPropertyItem) { if (this.mapOfMapProperty == null) { - this.mapOfMapProperty = new HashMap>(); + this.mapOfMapProperty = new HashMap<>(); } this.mapOfMapProperty.put(key, mapOfMapPropertyItem); return this; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index fdcfdba6522..a31bce48927 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -42,7 +42,7 @@ public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArr public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { if (this.arrayArrayNumber == null) { - this.arrayArrayNumber = new ArrayList>(); + this.arrayArrayNumber = new ArrayList<>(); } this.arrayArrayNumber.add(arrayArrayNumberItem); return this; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index 26b4422e7b2..0fc22eb97a0 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -42,7 +42,7 @@ public ArrayOfNumberOnly arrayNumber(List arrayNumber) { public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { if (this.arrayNumber == null) { - this.arrayNumber = new ArrayList(); + this.arrayNumber = new ArrayList<>(); } this.arrayNumber.add(arrayNumberItem); return this; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java index df413692f8b..a8450724172 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java @@ -48,7 +48,7 @@ public ArrayTest arrayOfString(List arrayOfString) { public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { if (this.arrayOfString == null) { - this.arrayOfString = new ArrayList(); + this.arrayOfString = new ArrayList<>(); } this.arrayOfString.add(arrayOfStringItem); return this; @@ -74,7 +74,7 @@ public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { if (this.arrayArrayOfInteger == null) { - this.arrayArrayOfInteger = new ArrayList>(); + this.arrayArrayOfInteger = new ArrayList<>(); } this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); return this; @@ -100,7 +100,7 @@ public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { if (this.arrayArrayOfModel == null) { - this.arrayArrayOfModel = new ArrayList>(); + this.arrayArrayOfModel = new ArrayList<>(); } this.arrayArrayOfModel.add(arrayArrayOfModelItem); return this; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumArrays.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumArrays.java index 6e69be28d66..fe8eb7b4505 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumArrays.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumArrays.java @@ -156,7 +156,7 @@ public EnumArrays arrayEnum(List arrayEnum) { public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { if (this.arrayEnum == null) { - this.arrayEnum = new ArrayList(); + this.arrayEnum = new ArrayList<>(); } this.arrayEnum.add(arrayEnumItem); return this; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java index 3223d766753..2abc110ba6f 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java @@ -24,9 +24,9 @@ import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.math.BigDecimal; +import java.time.LocalDate; +import java.time.OffsetDateTime; import java.util.UUID; -import org.threeten.bp.LocalDate; -import org.threeten.bp.OffsetDateTime; /** * FormatTest diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MapTest.java index 26cf37c65d8..1062128da19 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MapTest.java @@ -92,7 +92,7 @@ public MapTest mapMapOfString(Map> mapMapOfString) { public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { if (this.mapMapOfString == null) { - this.mapMapOfString = new HashMap>(); + this.mapMapOfString = new HashMap<>(); } this.mapMapOfString.put(key, mapMapOfStringItem); return this; @@ -118,7 +118,7 @@ public MapTest mapOfEnumString(Map mapOfEnumString) { public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { if (this.mapOfEnumString == null) { - this.mapOfEnumString = new HashMap(); + this.mapOfEnumString = new HashMap<>(); } this.mapOfEnumString.put(key, mapOfEnumStringItem); return this; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 435dc7ec0ee..13dfbc415c9 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -24,11 +24,11 @@ import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; import java.io.IOException; +import java.time.OffsetDateTime; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; -import org.threeten.bp.OffsetDateTime; /** * MixedPropertiesAndAdditionalPropertiesClass @@ -87,7 +87,7 @@ public MixedPropertiesAndAdditionalPropertiesClass map(Map map) public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { if (this.map == null) { - this.map = new HashMap(); + this.map = new HashMap<>(); } this.map.put(key, mapItem); return this; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java index b121d4cf4af..4d4f9dad5ea 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java @@ -23,7 +23,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; -import org.threeten.bp.OffsetDateTime; +import java.time.OffsetDateTime; /** * Order diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java index 22c29a1bede..36639d4ed75 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java @@ -43,7 +43,7 @@ public class Pet { private String name = null; @SerializedName("photoUrls") - private List photoUrls = new ArrayList(); + private List photoUrls = new ArrayList<>(); @SerializedName("tags") private List tags = null; @@ -100,6 +100,9 @@ public StatusEnum read(final JsonReader jsonReader) throws IOException { @SerializedName("status") private StatusEnum status = null; + @SerializedName("profilePhoto") + private byte[] profilePhoto = null; + public Pet id(Long id) { this.id = id; return this; @@ -184,7 +187,7 @@ public Pet tags(List tags) { public Pet addTagsItem(Tag tagsItem) { if (this.tags == null) { - this.tags = new ArrayList(); + this.tags = new ArrayList<>(); } this.tags.add(tagsItem); return this; @@ -221,6 +224,24 @@ public void setStatus(StatusEnum status) { this.status = status; } + public Pet profilePhoto(byte[] profilePhoto) { + this.profilePhoto = profilePhoto; + return this; + } + + /** + * Get profilePhoto + * @return profilePhoto + **/ + @ApiModelProperty(value = "") + public byte[] getProfilePhoto() { + return profilePhoto; + } + + public void setProfilePhoto(byte[] profilePhoto) { + this.profilePhoto = profilePhoto; + } + @Override public boolean equals(java.lang.Object o) { @@ -236,12 +257,13 @@ public boolean equals(java.lang.Object o) { Objects.equals(this.name, pet.name) && Objects.equals(this.photoUrls, pet.photoUrls) && Objects.equals(this.tags, pet.tags) && - Objects.equals(this.status, pet.status); + Objects.equals(this.status, pet.status) && + Arrays.equals(this.profilePhoto, pet.profilePhoto); } @Override public int hashCode() { - return Objects.hash(id, category, name, photoUrls, tags, status); + return Objects.hash(id, category, name, photoUrls, tags, status, Arrays.hashCode(profilePhoto)); } @@ -256,6 +278,7 @@ public String toString() { 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(" profilePhoto: ").append(toIndentedString(profilePhoto)).append("\n"); sb.append("}"); return sb.toString(); } diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/JSONTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/JSONTest.java index bd95b8b94b3..2621542ab16 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/JSONTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/JSONTest.java @@ -6,19 +6,17 @@ import java.lang.Exception; import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; import java.text.DateFormat; import java.text.SimpleDateFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.GregorianCalendar; -import java.util.TimeZone; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.time.format.DateTimeFormatter; +import java.util.*; import org.junit.*; -import org.threeten.bp.LocalDate; -import org.threeten.bp.OffsetDateTime; -import org.threeten.bp.ZoneId; -import org.threeten.bp.ZoneOffset; -import org.threeten.bp.format.DateTimeFormatter; import static org.junit.Assert.*; @@ -41,7 +39,7 @@ public void testSqlDateTypeAdapter() { assertEquals(str, json.serialize(date)); assertEquals(json.deserialize(str, java.sql.Date.class), date); - assertEquals(json.deserialize("\"2015-11-07T03:49:09.356+00:00\"", java.sql.Date.class).toString(), date.toString()); + assertEquals(json.deserialize("\"2015-11-07T03:49:09.356" + getCurrentTimezoneOffset() + "\"", java.sql.Date.class).toString(), date.toString()); // custom date format: without day DateFormat format = new SimpleDateFormat("yyyy-MM"); @@ -127,7 +125,7 @@ public void testLocalDateTypeAdapter() { public void testDefaultDate() throws Exception { final DateTimeFormatter datetimeFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME; final String dateStr = "2015-11-07T14:11:05.267Z"; - order.setShipDate(datetimeFormat.parse(dateStr, OffsetDateTime.FROM)); + order.setShipDate(OffsetDateTime.from(datetimeFormat.parse(dateStr))); String str = json.serialize(order); Type type = new TypeToken() { }.getType(); @@ -139,11 +137,56 @@ public void testDefaultDate() throws Exception { public void testCustomDate() throws Exception { final DateTimeFormatter datetimeFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.of("Etc/GMT+2")); final String dateStr = "2015-11-07T14:11:05-02:00"; - order.setShipDate(datetimeFormat.parse(dateStr, OffsetDateTime.FROM)); + order.setShipDate(OffsetDateTime.from(datetimeFormat.parse(dateStr))); String str = json.serialize(order); Type type = new TypeToken() { }.getType(); Order o = json.deserialize(str, type); assertEquals(dateStr, datetimeFormat.format(o.getShipDate())); } + + @Test + public void testByteArrayTypeAdapterSerialization() { + // Arrange + final String expectedBytesAsString = "Let's pretend this a jpg or something"; + final byte[] expectedBytes = expectedBytesAsString.getBytes(StandardCharsets.UTF_8); + + // Act + String serializedBytesWithQuotes = json.serialize(expectedBytes); + + // Assert + String serializedBytes = serializedBytesWithQuotes.substring(1, serializedBytesWithQuotes.length() - 1); + byte[] actualBytes = Base64.getDecoder().decode(serializedBytes); + assertEquals(expectedBytesAsString, new String(actualBytes, StandardCharsets.UTF_8)); + } + + @Test + public void testByteArrayTypeAdapterDeserialization() { + // Arrange + final String expectedBytesAsString = "Let's pretend this a jpg or something"; + final byte[] expectedBytes = expectedBytesAsString.getBytes(StandardCharsets.UTF_8); + final String serializedBytes = Base64.getEncoder().encodeToString(expectedBytes); + final String serializedBytesWithQuotes = "\"" + serializedBytes + "\""; + Type type = new TypeToken() { }.getType(); + + // Act + byte[] actualDeserializedBytes = json.deserialize(serializedBytesWithQuotes, type); + + // Assert + assertEquals(expectedBytesAsString, new String(actualDeserializedBytes, StandardCharsets.UTF_8)); + } + + // Obtained 22JAN2018 from stackoverflow answer by PuguaSoft https://stackoverflow.com/questions/11399491/java-timezone-offset + // Direct link https://stackoverflow.com/a/16680815/3166133 + public static String getCurrentTimezoneOffset() { + + TimeZone tz = TimeZone.getDefault(); + Calendar cal = GregorianCalendar.getInstance(tz); + int offsetInMillis = tz.getOffset(cal.getTimeInMillis()); + + String offset = String.format("%02d:%02d", Math.abs(offsetInMillis / 3600000), Math.abs((offsetInMillis / 60000) % 60)); + offset = (offsetInMillis >= 0 ? "+" : "-") + offset; + + return offset; + } } \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/FakeApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/FakeApiTest.java index c564001ad70..9a7e76c1552 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/FakeApiTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/FakeApiTest.java @@ -1,9 +1,26 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + package io.swagger.client.api; import io.swagger.client.ApiException; import java.math.BigDecimal; -import java.util.Date; +import io.swagger.client.model.Client; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import io.swagger.client.model.OuterComposite; import org.junit.Test; +import org.junit.Ignore; import java.util.ArrayList; import java.util.HashMap; @@ -13,11 +30,92 @@ /** * API tests for FakeApi */ +@Ignore public class FakeApiTest { private final FakeApi api = new FakeApi(); + /** + * + * + * Test serialization of outer boolean types + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void fakeOuterBooleanSerializeTest() throws ApiException { + Boolean body = null; + Boolean response = api.fakeOuterBooleanSerialize(body); + + // TODO: test validations + } + + /** + * + * + * Test serialization of object with outer number type + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void fakeOuterCompositeSerializeTest() throws ApiException { + OuterComposite body = null; + OuterComposite response = api.fakeOuterCompositeSerialize(body); + + // TODO: test validations + } + + /** + * + * + * Test serialization of outer number types + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void fakeOuterNumberSerializeTest() throws ApiException { + BigDecimal body = null; + BigDecimal response = api.fakeOuterNumberSerialize(body); + + // TODO: test validations + } + + /** + * + * + * Test serialization of outer string types + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void fakeOuterStringSerializeTest() throws ApiException { + String body = null; + String response = api.fakeOuterStringSerialize(body); + + // TODO: test validations + } + + /** + * To test \"client\" model + * + * To test \"client\" model + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testClientModelTest() throws ApiException { + Client body = null; + Client response = api.testClientModel(body); + + // TODO: test validations + } + /** * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * @@ -30,17 +128,75 @@ public class FakeApiTest { public void testEndpointParametersTest() throws ApiException { BigDecimal number = null; Double _double = null; - String string = null; + String patternWithoutDelimiter = null; byte[] _byte = null; Integer integer = null; Integer int32 = null; Long int64 = null; Float _float = null; + String string = null; byte[] binary = null; - Date date = null; - Date dateTime = null; + LocalDate date = null; + OffsetDateTime dateTime = null; String password = null; - // api.testEndpointParameters(number, _double, string, _byte, integer, int32, int64, _float, binary, date, dateTime, password); + String paramCallback = null; + api.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); + + // TODO: test validations + } + + /** + * To test enum parameters + * + * To test enum parameters + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testEnumParametersTest() throws ApiException { + List enumFormStringArray = null; + String enumFormString = null; + List enumHeaderStringArray = null; + String enumHeaderString = null; + List enumQueryStringArray = null; + String enumQueryString = null; + Integer enumQueryInteger = null; + Double enumQueryDouble = null; + api.testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); + + // TODO: test validations + } + + /** + * test inline additionalProperties + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testInlineAdditionalPropertiesTest() throws ApiException { + Object param = null; + api.testInlineAdditionalProperties(param); + + // TODO: test validations + } + + /** + * test json serialization of form data + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testJsonFormDataTest() throws ApiException { + String param = null; + String param2 = null; + api.testJsonFormData(param, param2); // TODO: test validations } diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/PetApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/PetApiTest.java index b949d90ebdb..349a55d93dc 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/PetApiTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/PetApiTest.java @@ -1,393 +1,170 @@ -package io.swagger.client.api; +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ -import io.swagger.TestUtils; -import io.swagger.client.*; -import io.swagger.client.auth.*; -import io.swagger.client.model.*; +package io.swagger.client.api; -import java.io.BufferedWriter; +import io.swagger.client.ApiException; import java.io.File; -import java.io.FileWriter; -import java.lang.reflect.Type; +import io.swagger.client.model.ModelApiResponse; +import io.swagger.client.model.Pet; +import org.junit.Test; +import org.junit.Ignore; + import java.util.ArrayList; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -import org.junit.*; -import static org.junit.Assert.*; - +/** + * API tests for PetApi + */ +@Ignore public class PetApiTest { - PetApi api = null; - - @Before - public void setup() { - api = new PetApi(); - // setup authentication - ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); - apiKeyAuth.setApiKey("special-key"); - } + private final PetApi api = new PetApi(); + + + /** + * Add a new pet to the store + * + * + * + * @throws ApiException + * if the Api call fails + */ @Test - public void testApiClient() { - // the default api client is used - assertEquals(Configuration.getDefaultApiClient(), api.getApiClient()); - assertNotNull(api.getApiClient()); - assertEquals("http://petstore.swagger.io:80/v2", api.getApiClient().getBasePath()); - assertFalse(api.getApiClient().isDebugging()); - - ApiClient oldClient = api.getApiClient(); - - ApiClient newClient = new ApiClient(); - newClient.setBasePath("http://example.com"); - newClient.setDebugging(true); - - // set api client via constructor - api = new PetApi(newClient); - assertNotNull(api.getApiClient()); - assertEquals("http://example.com", api.getApiClient().getBasePath()); - assertTrue(api.getApiClient().isDebugging()); - - // set api client via setter method - api.setApiClient(oldClient); - assertNotNull(api.getApiClient()); - assertEquals("http://petstore.swagger.io:80/v2", api.getApiClient().getBasePath()); - assertFalse(api.getApiClient().isDebugging()); - } - + public void addPetTest() throws ApiException { + Pet body = null; + api.addPet(body); + + // TODO: test validations + } + + /** + * Deletes a pet + * + * + * + * @throws ApiException + * if the Api call fails + */ @Test - public void testCreateAndGetPet() throws Exception { - Pet pet = createRandomPet(); - api.addPet(pet); - - Pet fetched = api.getPetById(pet.getId()); - assertNotNull(fetched); - assertEquals(pet.getId(), fetched.getId()); - assertNotNull(fetched.getCategory()); - assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); - } - - /* + public void deletePetTest() throws ApiException { + 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 testCreateAndGetPetWithByteArray() throws Exception { - Pet pet = createRandomPet(); - byte[] bytes = serializeJson(pet, api.getApiClient()).getBytes(); - api.addPetUsingByteArray(bytes); - - byte[] fetchedBytes = api.petPetIdtestingByteArraytrueGet(pet.getId()); - Type type = new TypeToken(){}.getType(); - Pet fetched = deserializeJson(new String(fetchedBytes), type, api.getApiClient()); - assertNotNull(fetched); - assertEquals(pet.getId(), fetched.getId()); - assertNotNull(fetched.getCategory()); - assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); - } - */ - + public void findPetsByStatusTest() throws ApiException { + List status = null; + List 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 testCreateAndGetPetWithHttpInfo() throws Exception { - Pet pet = createRandomPet(); - api.addPetWithHttpInfo(pet); - - ApiResponse resp = api.getPetByIdWithHttpInfo(pet.getId()); - assertEquals(200, resp.getStatusCode()); - assertEquals("application/json", resp.getHeaders().get("Content-Type").get(0)); - Pet fetched = resp.getData(); - assertNotNull(fetched); - assertEquals(pet.getId(), fetched.getId()); - assertNotNull(fetched.getCategory()); - assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); - } - + public void findPetsByTagsTest() throws ApiException { + List tags = null; + List 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 testCreateAndGetPetAsync() throws Exception { - Pet pet = createRandomPet(); - api.addPet(pet); - // to store returned Pet or error message/exception - final Map result = new HashMap(); - - api.getPetByIdAsync(pet.getId(), new ApiCallback() { - @Override - public void onFailure(ApiException e, int statusCode, Map> responseHeaders) { - result.put("error", e.getMessage()); - } - - @Override - public void onSuccess(Pet pet, int statusCode, Map> responseHeaders) { - result.put("pet", pet); - } - - @Override - public void onUploadProgress(long bytesWritten, long contentLength, boolean done) { - //empty - } - - @Override - public void onDownloadProgress(long bytesRead, long contentLength, boolean done) { - //empty - } - }); - // the API call should be executed asynchronously, so result should be empty at the moment - assertTrue(result.isEmpty()); - - // wait for the asynchronous call to finish (at most 10 seconds) - final int maxTry = 10; - int tryCount = 1; - Pet fetched = null; - do { - if (tryCount > maxTry) fail("have not got result of getPetByIdAsync after 10 seconds"); - Thread.sleep(1000); - tryCount += 1; - if (result.get("error") != null) fail((String) result.get("error")); - if (result.get("pet") != null) { - fetched = (Pet) result.get("pet"); - break; - } - } while (result.isEmpty()); - assertNotNull(fetched); - assertEquals(pet.getId(), fetched.getId()); - assertNotNull(fetched.getCategory()); - assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); - - // test getting a nonexistent pet - result.clear(); - api.getPetByIdAsync(-10000L, new ApiCallback() { - @Override - public void onFailure(ApiException e, int statusCode, Map> responseHeaders) { - result.put("exception", e); - } - - @Override - public void onSuccess(Pet pet, int statusCode, Map> responseHeaders) { - result.put("pet", pet); - } - - @Override - public void onUploadProgress(long bytesWritten, long contentLength, boolean done) { - //empty - } - - @Override - public void onDownloadProgress(long bytesRead, long contentLength, boolean done) { - //empty - } - }); - - // wait for the asynchronous call to finish (at most 10 seconds) - tryCount = 1; - ApiException exception = null; - do { - if (tryCount > maxTry) fail("have not got result of getPetByIdAsync after 10 seconds"); - Thread.sleep(1000); - tryCount += 1; - if (result.get("pet") != null) fail("expected an error"); - if (result.get("exception") != null) { - exception = (ApiException) result.get("exception"); - break; - } - } while (result.isEmpty()); - assertNotNull(exception); - assertEquals(404, exception.getCode()); - assertEquals("Not Found", exception.getMessage()); - assertEquals("application/json", exception.getResponseHeaders().get("Content-Type").get(0)); - } - - /* + public void getPetByIdTest() throws ApiException { + 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 testGetPetByIdInObject() throws Exception { - Pet pet = new Pet(); - pet.setId(TestUtils.nextId()); - pet.setName("pet " + pet.getId()); - - Category category = new Category(); - category.setId(TestUtils.nextId()); - category.setName("category " + category.getId()); - pet.setCategory(category); - - pet.setStatus(Pet.StatusEnum.PENDING); - List photos = Arrays.asList(new String[]{"http://foo.bar.com/1"}); - pet.setPhotoUrls(photos); - - api.addPet(pet); - - InlineResponse200 fetched = api.getPetByIdInObject(pet.getId()); - assertEquals(pet.getId(), fetched.getId()); - assertEquals(pet.getName(), fetched.getName()); - - Object categoryObj = fetched.getCategory(); - assertNotNull(categoryObj); - assertTrue(categoryObj instanceof Map); - - Map categoryMap = (Map) categoryObj; - Object categoryIdObj = categoryMap.get("id"); - // NOTE: Gson parses integer value to double. - assertTrue(categoryIdObj instanceof Double); - Long categoryIdLong = ((Double) categoryIdObj).longValue(); - assertEquals(category.getId(), categoryIdLong); - assertEquals(category.getName(), categoryMap.get("name")); - } - */ - + public void updatePetTest() throws ApiException { + 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 testUpdatePet() throws Exception { - Pet pet = createRandomPet(); - pet.setName("programmer"); - - api.updatePet(pet); - - Pet fetched = api.getPetById(pet.getId()); - assertNotNull(fetched); - assertEquals(pet.getId(), fetched.getId()); - assertNotNull(fetched.getCategory()); - assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); - } - - @Test - public void testFindPetsByStatus() throws Exception { - Pet pet = createRandomPet(); - pet.setName("programmer"); - pet.setStatus(Pet.StatusEnum.PENDING); - - api.updatePet(pet); - - List pets = api.findPetsByStatus(Arrays.asList("pending")); - assertNotNull(pets); - - boolean found = false; - for (Pet fetched : pets) { - if (fetched.getId().equals(pet.getId())) { - found = true; - break; - } - } - - assertTrue(found); - - api.deletePet(pet.getId(), null); - } - - @Test - public void testFindPetsByTags() throws Exception { - Pet pet = createRandomPet(); - pet.setName("monster"); - pet.setStatus(Pet.StatusEnum.AVAILABLE); - - List tags = new ArrayList(); - Tag tag1 = new Tag(); - tag1.setName("friendly"); - tags.add(tag1); - pet.setTags(tags); - - api.updatePet(pet); - - List pets = api.findPetsByTags(Arrays.asList("friendly")); - assertNotNull(pets); - - boolean found = false; - for (Pet fetched : pets) { - if (fetched.getId().equals(pet.getId())) { - found = true; - break; - } - } - assertTrue(found); - - api.deletePet(pet.getId(), null); - } - + public void updatePetWithFormTest() throws ApiException { + 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 testUpdatePetWithForm() throws Exception { - Pet pet = createRandomPet(); - pet.setName("frank"); - api.addPet(pet); - - Pet fetched = api.getPetById(pet.getId()); - - api.updatePetWithForm(fetched.getId(), "furt", null); - Pet updated = api.getPetById(fetched.getId()); - - assertEquals(updated.getName(), "furt"); - } - - @Test - public void testDeletePet() throws Exception { - Pet pet = createRandomPet(); - api.addPet(pet); - - Pet fetched = api.getPetById(pet.getId()); - api.deletePet(fetched.getId(), null); - - try { - fetched = api.getPetById(fetched.getId()); - fail("expected an error"); - } catch (ApiException e) { - assertEquals(404, e.getCode()); - } - } - - @Test - public void testUploadFile() throws Exception { - Pet pet = createRandomPet(); - api.addPet(pet); - - File file = new File("hello.txt"); - BufferedWriter writer = new BufferedWriter(new FileWriter(file)); - writer.write("Hello world!"); - writer.close(); - - api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath())); - } - - @Test - public void testEqualsAndHashCode() { - Pet pet1 = new Pet(); - Pet pet2 = new Pet(); - assertTrue(pet1.equals(pet2)); - assertTrue(pet2.equals(pet1)); - assertTrue(pet1.hashCode() == pet2.hashCode()); - assertTrue(pet1.equals(pet1)); - assertTrue(pet1.hashCode() == pet1.hashCode()); - - pet2.setName("really-happy"); - pet2.setPhotoUrls(Arrays.asList("http://foo.bar.com/1", "http://foo.bar.com/2")); - assertFalse(pet1.equals(pet2)); - assertFalse(pet2.equals(pet1)); - assertFalse(pet1.hashCode() == (pet2.hashCode())); - assertTrue(pet2.equals(pet2)); - assertTrue(pet2.hashCode() == pet2.hashCode()); - - pet1.setName("really-happy"); - pet1.setPhotoUrls(Arrays.asList("http://foo.bar.com/1", "http://foo.bar.com/2")); - assertTrue(pet1.equals(pet2)); - assertTrue(pet2.equals(pet1)); - assertTrue(pet1.hashCode() == pet2.hashCode()); - assertTrue(pet1.equals(pet1)); - assertTrue(pet1.hashCode() == pet1.hashCode()); - } - - private Pet createRandomPet() { - Pet pet = new Pet(); - pet.setId(TestUtils.nextId()); - pet.setName("gorilla"); - - Category category = new Category(); - category.setName("really-happy"); - - pet.setCategory(category); - pet.setStatus(Pet.StatusEnum.AVAILABLE); - List photos = Arrays.asList("http://foo.bar.com/1", "http://foo.bar.com/2"); - pet.setPhotoUrls(photos); - - return pet; - } - - private String serializeJson(Object o, ApiClient apiClient) { - return apiClient.getJSON().serialize(o); - } + public void uploadFileTest() throws ApiException { + Long petId = null; + String additionalMetadata = null; + File file = null; + ModelApiResponse response = api.uploadFile(petId, additionalMetadata, file); - private T deserializeJson(String json, Type type, ApiClient apiClient) { - return (T) apiClient.getJSON().deserialize(json, type); + // TODO: test validations } + } diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/StoreApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/StoreApiTest.java index c4c64fdda79..bef0884a2da 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/StoreApiTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/StoreApiTest.java @@ -1,99 +1,98 @@ +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ + + package io.swagger.client.api; -import io.swagger.TestUtils; import io.swagger.client.ApiException; +import io.swagger.client.model.Order; +import org.junit.Test; +import org.junit.Ignore; -import io.swagger.client.auth.*; -import io.swagger.client.model.*; - -import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; import java.util.Map; -import org.junit.*; -import org.threeten.bp.OffsetDateTime; - -import static org.junit.Assert.*; - +/** + * API tests for StoreApi + */ +@Ignore public class StoreApiTest { - StoreApi api = null; - - @Before - public void setup() { - api = new StoreApi(); - // setup authentication - ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); - apiKeyAuth.setApiKey("special-key"); - } - - @Test - public void testGetInventory() throws Exception { - Map inventory = api.getInventory(); - assertTrue(inventory.keySet().size() > 0); - } - /* + private final StoreApi api = new StoreApi(); + + + /** + * Delete purchase order by ID + * + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + * @throws ApiException + * if the Api call fails + */ @Test - public void testGetInventoryInObject() throws Exception { - Object inventoryObj = api.getInventoryInObject(); - assertTrue(inventoryObj instanceof Map); - - Map inventoryMap = (Map) inventoryObj; - assertTrue(inventoryMap.keySet().size() > 0); + public void deleteOrderTest() throws ApiException { + String orderId = null; + api.deleteOrder(orderId); - Map.Entry firstEntry = (Map.Entry) inventoryMap.entrySet().iterator().next(); - assertTrue(firstEntry.getKey() instanceof String); - // NOTE: Gson parses integer value to double. - assertTrue(firstEntry.getValue() instanceof Double); + // 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 testPlaceOrder() throws Exception { - Order order = createOrder(); - api.placeOrder(order); + public void getInventoryTest() throws ApiException { + Map response = api.getInventory(); - Order fetched = api.getOrderById(order.getId()); - assertEquals(order.getId(), fetched.getId()); - assertEquals(order.getPetId(), fetched.getPetId()); - assertEquals(order.getQuantity(), fetched.getQuantity()); - assertTrue(order.getShipDate().isEqual(fetched.getShipDate())); + // TODO: test validations } - + + /** + * Find purchase order by ID + * + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * + * @throws ApiException + * if the Api call fails + */ @Test - public void testDeleteOrder() throws Exception { - Order order = createOrder(); - api.placeOrder(order); - - Order fetched = api.getOrderById(order.getId()); - assertEquals(fetched.getId(), order.getId()); + public void getOrderByIdTest() throws ApiException { + Long orderId = null; + Order response = api.getOrderById(orderId); - api.deleteOrder(String.valueOf(order.getId())); - - try { - api.getOrderById(order.getId()); - // fail("expected an error"); - } catch (ApiException e) { - // ok - } + // TODO: test validations } + + /** + * Place an order for a pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void placeOrderTest() throws ApiException { + Order body = null; + Order response = api.placeOrder(body); - private Order createOrder() { - Order order = new Order(); - order.setPetId(200L); - order.setQuantity(13); - //Ensure 3 fractional digits because of a bug in the petstore server - order.setShipDate(OffsetDateTime.now().withNano(123000000)); - order.setStatus(Order.StatusEnum.PLACED); - order.setComplete(true); - - try { - Field idField = Order.class.getDeclaredField("id"); - idField.setAccessible(true); - idField.set(order, TestUtils.nextId()); - } catch (Exception e) { - throw new RuntimeException(e); - } - - return order; + // TODO: test validations } + } diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/UserApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/UserApiTest.java index b47a146d737..4455b3920b9 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/UserApiTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/UserApiTest.java @@ -1,87 +1,164 @@ -package io.swagger.client.api; +/* + * Swagger Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * Contact: apiteam@swagger.io + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen.git + * Do not edit the class manually. + */ -import io.swagger.TestUtils; -import io.swagger.client.auth.*; -import io.swagger.client.model.*; +package io.swagger.client.api; -import java.util.Arrays; +import io.swagger.client.ApiException; +import io.swagger.client.model.User; +import org.junit.Test; +import org.junit.Ignore; -import org.junit.*; -import static org.junit.Assert.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +/** + * API tests for UserApi + */ +@Ignore public class UserApiTest { - UserApi api = null; - - @Before - public void setup() { - api = new UserApi(); - // setup authentication - ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); - apiKeyAuth.setApiKey("special-key"); - } + 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 testCreateUser() throws Exception { - User user = createUser(); + public void createUserTest() throws ApiException { + User body = null; + api.createUser(body); - api.createUser(user); - - User fetched = api.getUserByName(user.getUsername()); - assertEquals(user.getId(), fetched.getId()); + // TODO: test validations } - + + /** + * Creates list of users with given input array + * + * + * + * @throws ApiException + * if the Api call fails + */ @Test - public void testCreateUsersWithArray() throws Exception { - User user1 = createUser(); - user1.setUsername("user" + user1.getId()); - User user2 = createUser(); - user2.setUsername("user" + user2.getId()); + public void createUsersWithArrayInputTest() throws ApiException { + List body = null; + api.createUsersWithArrayInput(body); - api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); - - User fetched = api.getUserByName(user1.getUsername()); - assertEquals(user1.getId(), fetched.getId()); + // TODO: test validations } - + + /** + * Creates list of users with given input array + * + * + * + * @throws ApiException + * if the Api call fails + */ @Test - public void testCreateUsersWithList() throws Exception { - User user1 = createUser(); - user1.setUsername("user" + user1.getId()); - User user2 = createUser(); - user2.setUsername("user" + user2.getId()); + public void createUsersWithListInputTest() throws ApiException { + List body = null; + api.createUsersWithListInput(body); - api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); - - User fetched = api.getUserByName(user1.getUsername()); - assertEquals(user1.getId(), fetched.getId()); + // 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() throws ApiException { + String username = null; + api.deleteUser(username); + // TODO: test validations + } + + /** + * Get user by user name + * + * + * + * @throws ApiException + * if the Api call fails + */ @Test - public void testLoginUser() throws Exception { - User user = createUser(); - api.createUser(user); + public void getUserByNameTest() throws ApiException { + String username = null; + User response = api.getUserByName(username); - String token = api.loginUser(user.getUsername(), user.getPassword()); - assertTrue(token.startsWith("logged in user session:")); + // TODO: test validations } + + /** + * Logs user into the system + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void loginUserTest() throws ApiException { + 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 logoutUser() throws Exception { + public void logoutUserTest() throws ApiException { api.logoutUser(); - } - private User createUser() { - User user = new User(); - user.setId(TestUtils.nextId()); - user.setUsername("fred" + user.getId()); - user.setFirstName("Fred"); - user.setLastName("Meyer"); - user.setEmail("fred@fredmeyer.com"); - user.setPassword("xxXXxx"); - user.setPhone("408-867-5309"); - user.setUserStatus(123); + // 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() throws ApiException { + String username = null; + User body = null; + api.updateUser(username, body); - return user; + // TODO: test validations } + } From c541139ad863335ca4aedb3d1f8d92327a8a024b Mon Sep 17 00:00:00 2001 From: Benjamin Roedell Date: Mon, 22 Jan 2018 22:16:46 -0500 Subject: [PATCH 5/9] Implement recommendations by @cbornet including: Use okio.ByteString for base64 conversions instead of java 8 lib since the okhttp-gson client already includes okio. Remove setting to disableHtmlEscaping. Rename LocalByteArrayAdapter to ByteArrayAdapter. --- .../Java/libraries/okhttp-gson/JSON.mustache | 22 +++++++------------ 1 file changed, 8 insertions(+), 14 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache index fe6ef5a0ee7..63814a361fc 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache @@ -26,6 +26,7 @@ import org.threeten.bp.format.DateTimeFormatter; {{/threetenbp}} import {{modelPackage}}.*; +import okio.ByteString; import java.io.IOException; import java.io.StringReader; @@ -37,7 +38,6 @@ import java.text.ParsePosition; import java.time.LocalDate; import java.time.OffsetDateTime; import java.time.format.DateTimeFormatter; -import java.util.Base64; {{/java8}} import java.util.Date; import java.util.Map; @@ -56,9 +56,7 @@ public class JSON { private OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter(); private LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); {{/jsr310}} - {{#java8}} - private LocalByteArrayAdapter localByteArrayAdapter = new LocalByteArrayAdapter(); - {{/java8}} + private ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); public static GsonBuilder createGson() { GsonFireBuilder fireBuilder = new GsonFireBuilder() @@ -109,10 +107,7 @@ public class JSON { .registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter) .registerTypeAdapter(LocalDate.class, localDateTypeAdapter) {{/jsr310}} - {{#java8}} - .disableHtmlEscaping(){{! Added to prevent base64 = (equal sign) from being escaped }} - .registerTypeAdapter(byte[].class, localByteArrayAdapter) - {{/java8}} + .registerTypeAdapter(byte[].class, byteArrayAdapter) .create(); } @@ -179,18 +174,17 @@ public class JSON { } } - {{#java8}} /** * Gson TypeAdapter for Byte Array type */ - public class LocalByteArrayAdapter extends TypeAdapter { + public class ByteArrayAdapter extends TypeAdapter { @Override public void write(JsonWriter out, byte[] value) throws IOException { if (value == null) { out.nullValue(); } else { - out.value(Base64.getEncoder().encodeToString(value)); + out.value(ByteString.of(value).base64()); } } @@ -202,12 +196,12 @@ public class JSON { return null; default: String bytesAsBase64 = in.nextString(); - return Base64.getDecoder().decode(bytesAsBase64); + ByteString byteString = ByteString.decodeBase64(bytesAsBase64); + return byteString.toByteArray(); } } } - - {{/java8}} + {{#joda}} /** * Gson TypeAdapter for Joda DateTime type From 53018c475ad6bbc097f29d47b11a2bc55b5142ea Mon Sep 17 00:00:00 2001 From: Benjamin Roedell Date: Mon, 22 Jan 2018 22:18:39 -0500 Subject: [PATCH 6/9] Update spec and sample for java okhttp-gson library client --- bin/java-petstore-okhttp-gson.json | 4 +-- .../petstore/java/okhttp-gson/build.gradle | 9 +++--- .../petstore/java/okhttp-gson/build.sbt | 1 + .../client/petstore/java/okhttp-gson/pom.xml | 8 ++++- .../java/io/swagger/client/ApiClient.java | 6 ++-- .../src/main/java/io/swagger/client/JSON.java | 22 +++++++------- .../java/io/swagger/client/api/FakeApi.java | 4 +-- .../model/AdditionalPropertiesClass.java | 4 +-- .../model/ArrayOfArrayOfNumberOnly.java | 2 +- .../client/model/ArrayOfNumberOnly.java | 2 +- .../io/swagger/client/model/ArrayTest.java | 6 ++-- .../io/swagger/client/model/EnumArrays.java | 2 +- .../io/swagger/client/model/FormatTest.java | 4 +-- .../java/io/swagger/client/model/MapTest.java | 4 +-- ...ropertiesAndAdditionalPropertiesClass.java | 4 +-- .../java/io/swagger/client/model/Order.java | 2 +- .../java/io/swagger/client/model/Pet.java | 4 +-- .../test/java/io/swagger/client/JSONTest.java | 29 ++++++++++++------- .../io/swagger/client/api/FakeApiTest.java | 4 +-- 19 files changed, 68 insertions(+), 53 deletions(-) diff --git a/bin/java-petstore-okhttp-gson.json b/bin/java-petstore-okhttp-gson.json index 997f3ab7aa5..b894d172630 100644 --- a/bin/java-petstore-okhttp-gson.json +++ b/bin/java-petstore-okhttp-gson.json @@ -1,6 +1,4 @@ { "library": "okhttp-gson", - "artifactId": "swagger-petstore-okhttp-gson", - "java8": "true", - "dateLibrary": "java8" + "artifactId": "swagger-petstore-okhttp-gson" } diff --git a/samples/client/petstore/java/okhttp-gson/build.gradle b/samples/client/petstore/java/okhttp-gson/build.gradle index 97acef84fd7..eaea7ef9911 100644 --- a/samples/client/petstore/java/okhttp-gson/build.gradle +++ b/samples/client/petstore/java/okhttp-gson/build.gradle @@ -32,8 +32,8 @@ if(hasProperty('target') && target == 'android') { targetSdkVersion 25 } compileOptions { - sourceCompatibility JavaVersion.VERSION_1_8 - targetCompatibility JavaVersion.VERSION_1_8 + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 } // Rename the aar correctly @@ -78,8 +78,8 @@ if(hasProperty('target') && target == 'android') { apply plugin: 'java' apply plugin: 'maven' - sourceCompatibility = JavaVersion.VERSION_1_8 - targetCompatibility = JavaVersion.VERSION_1_8 + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 install { repositories.mavenInstaller { @@ -107,5 +107,6 @@ dependencies { compile 'com.squareup.okhttp:logging-interceptor:2.7.5' compile 'com.google.code.gson:gson:2.8.1' compile 'io.gsonfire:gson-fire:1.8.0' + compile 'org.threeten:threetenbp:1.3.5' testCompile 'junit:junit:4.12' } diff --git a/samples/client/petstore/java/okhttp-gson/build.sbt b/samples/client/petstore/java/okhttp-gson/build.sbt index 6e84ac02ac9..db083233db7 100644 --- a/samples/client/petstore/java/okhttp-gson/build.sbt +++ b/samples/client/petstore/java/okhttp-gson/build.sbt @@ -13,6 +13,7 @@ lazy val root = (project in file(".")). "com.squareup.okhttp" % "okhttp" % "2.7.5", "com.squareup.okhttp" % "logging-interceptor" % "2.7.5", "com.google.code.gson" % "gson" % "2.8.1", + "org.threeten" % "threetenbp" % "1.3.5" % "compile", "io.gsonfire" % "gson-fire" % "1.8.0" % "compile", "junit" % "junit" % "4.12" % "test", "com.novocode" % "junit-interface" % "0.10" % "test" diff --git a/samples/client/petstore/java/okhttp-gson/pom.xml b/samples/client/petstore/java/okhttp-gson/pom.xml index e70877c1e00..b9e81522265 100644 --- a/samples/client/petstore/java/okhttp-gson/pom.xml +++ b/samples/client/petstore/java/okhttp-gson/pom.xml @@ -213,6 +213,11 @@ gson-fire ${gson-fire-version} + + org.threeten + threetenbp + ${threetenbp-version} + junit @@ -222,13 +227,14 @@ - 1.8 + 1.7 ${java.version} ${java.version} 1.8.0 1.5.15 2.7.5 2.8.1 + 1.3.5 1.0.0 4.12 UTF-8 diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java index 7c01160a4da..a82ca551679 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java @@ -19,6 +19,9 @@ import com.squareup.okhttp.logging.HttpLoggingInterceptor.Level; import okio.BufferedSink; import okio.Okio; +import org.threeten.bp.LocalDate; +import org.threeten.bp.OffsetDateTime; +import org.threeten.bp.format.DateTimeFormatter; import javax.net.ssl.*; import java.io.File; @@ -36,9 +39,6 @@ import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.text.DateFormat; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import java.time.format.DateTimeFormatter; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java index 7c8f5321db9..15ce43f658a 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java @@ -23,8 +23,12 @@ import com.google.gson.JsonElement; import io.gsonfire.GsonFireBuilder; import io.gsonfire.TypeSelector; +import org.threeten.bp.LocalDate; +import org.threeten.bp.OffsetDateTime; +import org.threeten.bp.format.DateTimeFormatter; import io.swagger.client.model.*; +import okio.ByteString; import java.io.IOException; import java.io.StringReader; @@ -32,10 +36,6 @@ import java.text.DateFormat; import java.text.ParseException; import java.text.ParsePosition; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import java.time.format.DateTimeFormatter; -import java.util.Base64; import java.util.Date; import java.util.Map; import java.util.HashMap; @@ -47,7 +47,7 @@ public class JSON { private SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter(); private OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter(); private LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); - private LocalByteArrayAdapter localByteArrayAdapter = new LocalByteArrayAdapter(); + private ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); public static GsonBuilder createGson() { GsonFireBuilder fireBuilder = new GsonFireBuilder() @@ -89,8 +89,7 @@ public JSON() { .registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter) .registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter) .registerTypeAdapter(LocalDate.class, localDateTypeAdapter) - .disableHtmlEscaping() - .registerTypeAdapter(byte[].class, localByteArrayAdapter) + .registerTypeAdapter(byte[].class, byteArrayAdapter) .create(); } @@ -160,14 +159,14 @@ public T deserialize(String body, Type returnType) { /** * Gson TypeAdapter for Byte Array type */ - public class LocalByteArrayAdapter extends TypeAdapter { + public class ByteArrayAdapter extends TypeAdapter { @Override public void write(JsonWriter out, byte[] value) throws IOException { if (value == null) { out.nullValue(); } else { - out.value(Base64.getEncoder().encodeToString(value)); + out.value(ByteString.of(value).base64()); } } @@ -179,11 +178,12 @@ public byte[] read(JsonReader in) throws IOException { return null; default: String bytesAsBase64 = in.nextString(); - return Base64.getDecoder().decode(bytesAsBase64); + ByteString byteString = ByteString.decodeBase64(bytesAsBase64); + return byteString.toByteArray(); } } } - + /** * Gson TypeAdapter for JSR310 OffsetDateTime type */ diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java index 0a3fab2246e..beb9cb1f8ff 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/FakeApi.java @@ -29,8 +29,8 @@ import java.math.BigDecimal; import io.swagger.client.model.Client; -import java.time.LocalDate; -import java.time.OffsetDateTime; +import org.threeten.bp.LocalDate; +import org.threeten.bp.OffsetDateTime; import io.swagger.client.model.OuterComposite; import java.lang.reflect.Type; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java index a39ff1ede1a..a1d984bdcf1 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/AdditionalPropertiesClass.java @@ -45,7 +45,7 @@ public AdditionalPropertiesClass mapProperty(Map mapProperty) { public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { if (this.mapProperty == null) { - this.mapProperty = new HashMap<>(); + this.mapProperty = new HashMap(); } this.mapProperty.put(key, mapPropertyItem); return this; @@ -71,7 +71,7 @@ public AdditionalPropertiesClass mapOfMapProperty(Map mapOfMapPropertyItem) { if (this.mapOfMapProperty == null) { - this.mapOfMapProperty = new HashMap<>(); + this.mapOfMapProperty = new HashMap>(); } this.mapOfMapProperty.put(key, mapOfMapPropertyItem); return this; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java index a31bce48927..fdcfdba6522 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfArrayOfNumberOnly.java @@ -42,7 +42,7 @@ public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArr public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { if (this.arrayArrayNumber == null) { - this.arrayArrayNumber = new ArrayList<>(); + this.arrayArrayNumber = new ArrayList>(); } this.arrayArrayNumber.add(arrayArrayNumberItem); return this; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java index 0fc22eb97a0..26b4422e7b2 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayOfNumberOnly.java @@ -42,7 +42,7 @@ public ArrayOfNumberOnly arrayNumber(List arrayNumber) { public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { if (this.arrayNumber == null) { - this.arrayNumber = new ArrayList<>(); + this.arrayNumber = new ArrayList(); } this.arrayNumber.add(arrayNumberItem); return this; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java index a8450724172..df413692f8b 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/ArrayTest.java @@ -48,7 +48,7 @@ public ArrayTest arrayOfString(List arrayOfString) { public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { if (this.arrayOfString == null) { - this.arrayOfString = new ArrayList<>(); + this.arrayOfString = new ArrayList(); } this.arrayOfString.add(arrayOfStringItem); return this; @@ -74,7 +74,7 @@ public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { if (this.arrayArrayOfInteger == null) { - this.arrayArrayOfInteger = new ArrayList<>(); + this.arrayArrayOfInteger = new ArrayList>(); } this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); return this; @@ -100,7 +100,7 @@ public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { if (this.arrayArrayOfModel == null) { - this.arrayArrayOfModel = new ArrayList<>(); + this.arrayArrayOfModel = new ArrayList>(); } this.arrayArrayOfModel.add(arrayArrayOfModelItem); return this; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumArrays.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumArrays.java index fe8eb7b4505..6e69be28d66 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumArrays.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/EnumArrays.java @@ -156,7 +156,7 @@ public EnumArrays arrayEnum(List arrayEnum) { public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { if (this.arrayEnum == null) { - this.arrayEnum = new ArrayList<>(); + this.arrayEnum = new ArrayList(); } this.arrayEnum.add(arrayEnumItem); return this; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java index 2abc110ba6f..3223d766753 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/FormatTest.java @@ -24,9 +24,9 @@ import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.math.BigDecimal; -import java.time.LocalDate; -import java.time.OffsetDateTime; import java.util.UUID; +import org.threeten.bp.LocalDate; +import org.threeten.bp.OffsetDateTime; /** * FormatTest diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MapTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MapTest.java index 1062128da19..26cf37c65d8 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MapTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MapTest.java @@ -92,7 +92,7 @@ public MapTest mapMapOfString(Map> mapMapOfString) { public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { if (this.mapMapOfString == null) { - this.mapMapOfString = new HashMap<>(); + this.mapMapOfString = new HashMap>(); } this.mapMapOfString.put(key, mapMapOfStringItem); return this; @@ -118,7 +118,7 @@ public MapTest mapOfEnumString(Map mapOfEnumString) { public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { if (this.mapOfEnumString == null) { - this.mapOfEnumString = new HashMap<>(); + this.mapOfEnumString = new HashMap(); } this.mapOfEnumString.put(key, mapOfEnumStringItem); return this; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 13dfbc415c9..435dc7ec0ee 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -24,11 +24,11 @@ import io.swagger.annotations.ApiModelProperty; import io.swagger.client.model.Animal; import java.io.IOException; -import java.time.OffsetDateTime; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; +import org.threeten.bp.OffsetDateTime; /** * MixedPropertiesAndAdditionalPropertiesClass @@ -87,7 +87,7 @@ public MixedPropertiesAndAdditionalPropertiesClass map(Map map) public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { if (this.map == null) { - this.map = new HashMap<>(); + this.map = new HashMap(); } this.map.put(key, mapItem); return this; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java index 4d4f9dad5ea..b121d4cf4af 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java @@ -23,7 +23,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; -import java.time.OffsetDateTime; +import org.threeten.bp.OffsetDateTime; /** * Order diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java index 36639d4ed75..c4aab3b100f 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java @@ -43,7 +43,7 @@ public class Pet { private String name = null; @SerializedName("photoUrls") - private List photoUrls = new ArrayList<>(); + private List photoUrls = new ArrayList(); @SerializedName("tags") private List tags = null; @@ -187,7 +187,7 @@ public Pet tags(List tags) { public Pet addTagsItem(Tag tagsItem) { if (this.tags == null) { - this.tags = new ArrayList<>(); + this.tags = new ArrayList(); } this.tags.add(tagsItem); return this; diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/JSONTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/JSONTest.java index 2621542ab16..a3fefc96895 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/JSONTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/JSONTest.java @@ -9,14 +9,18 @@ import java.nio.charset.StandardCharsets; import java.text.DateFormat; import java.text.SimpleDateFormat; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import java.time.ZoneId; -import java.time.ZoneOffset; -import java.time.format.DateTimeFormatter; -import java.util.*; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; +import okio.ByteString; import org.junit.*; +import org.threeten.bp.LocalDate; +import org.threeten.bp.OffsetDateTime; +import org.threeten.bp.ZoneId; +import org.threeten.bp.ZoneOffset; +import org.threeten.bp.format.DateTimeFormatter; import static org.junit.Assert.*; @@ -125,7 +129,7 @@ public void testLocalDateTypeAdapter() { public void testDefaultDate() throws Exception { final DateTimeFormatter datetimeFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME; final String dateStr = "2015-11-07T14:11:05.267Z"; - order.setShipDate(OffsetDateTime.from(datetimeFormat.parse(dateStr))); + order.setShipDate(datetimeFormat.parse(dateStr, OffsetDateTime.FROM)); String str = json.serialize(order); Type type = new TypeToken() { }.getType(); @@ -137,7 +141,7 @@ public void testDefaultDate() throws Exception { public void testCustomDate() throws Exception { final DateTimeFormatter datetimeFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.of("Etc/GMT+2")); final String dateStr = "2015-11-07T14:11:05-02:00"; - order.setShipDate(OffsetDateTime.from(datetimeFormat.parse(dateStr))); + order.setShipDate(datetimeFormat.parse(dateStr, OffsetDateTime.FROM)); String str = json.serialize(order); Type type = new TypeToken() { }.getType(); @@ -156,7 +160,11 @@ public void testByteArrayTypeAdapterSerialization() { // Assert String serializedBytes = serializedBytesWithQuotes.substring(1, serializedBytesWithQuotes.length() - 1); - byte[] actualBytes = Base64.getDecoder().decode(serializedBytes); + if (json.getGson().htmlSafe()) { + serializedBytes = serializedBytes.replaceAll("\\\\u003d", "="); + } + ByteString actualAsByteString = ByteString.decodeBase64(serializedBytes); + byte[] actualBytes = actualAsByteString.toByteArray(); assertEquals(expectedBytesAsString, new String(actualBytes, StandardCharsets.UTF_8)); } @@ -165,7 +173,8 @@ public void testByteArrayTypeAdapterDeserialization() { // Arrange final String expectedBytesAsString = "Let's pretend this a jpg or something"; final byte[] expectedBytes = expectedBytesAsString.getBytes(StandardCharsets.UTF_8); - final String serializedBytes = Base64.getEncoder().encodeToString(expectedBytes); + final ByteString expectedByteString = ByteString.of(expectedBytes); + final String serializedBytes = expectedByteString.base64(); final String serializedBytesWithQuotes = "\"" + serializedBytes + "\""; Type type = new TypeToken() { }.getType(); diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/FakeApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/FakeApiTest.java index 9a7e76c1552..0e4979b2906 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/FakeApiTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/FakeApiTest.java @@ -16,8 +16,8 @@ import io.swagger.client.ApiException; import java.math.BigDecimal; import io.swagger.client.model.Client; -import java.time.LocalDate; -import java.time.OffsetDateTime; +import org.threeten.bp.LocalDate; +import org.threeten.bp.OffsetDateTime; import io.swagger.client.model.OuterComposite; import org.junit.Test; import org.junit.Ignore; From a8fd79379201d0326ef5a9218a44bede1bc52407 Mon Sep 17 00:00:00 2001 From: Benjamin Roedell Date: Tue, 23 Jan 2018 12:24:17 -0500 Subject: [PATCH 7/9] Undo addition of profilePhoto property. A format byte property is already available under the format_test definition. --- ...ith-fake-endpoints-models-for-testing.yaml | 3 --- .../src/test/resources/2_0/petstore.json | 4 --- .../src/test/resources/petstore.json | 4 --- .../src/test/resources/petstore.json | 4 --- .../petstore/java/okhttp-gson/docs/Pet.md | 1 - .../java/io/swagger/client/model/Pet.java | 27 ++----------------- 6 files changed, 2 insertions(+), 41 deletions(-) diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml index 9a712e3b4cb..d84d621f687 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml @@ -1069,9 +1069,6 @@ definitions: - available - pending - sold - profilePhoto: - type: string - format: byte xml: name: Pet ApiResponse: diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore.json b/modules/swagger-codegen/src/test/resources/2_0/petstore.json index f44c31d8058..4290daed14d 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore.json +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore.json @@ -917,10 +917,6 @@ "pending", "sold" ] - }, - "profilePhoto": { - "type": "string", - "format": "byte" } }, "xml": { diff --git a/modules/swagger-codegen/src/test/resources/petstore.json b/modules/swagger-codegen/src/test/resources/petstore.json index 3632ac61413..dd9b1f42edf 100644 --- a/modules/swagger-codegen/src/test/resources/petstore.json +++ b/modules/swagger-codegen/src/test/resources/petstore.json @@ -918,10 +918,6 @@ "pending", "sold" ] - }, - "profilePhoto": { - "type": "string", - "format": "byte" } }, "xml": { diff --git a/modules/swagger-generator/src/test/resources/petstore.json b/modules/swagger-generator/src/test/resources/petstore.json index 5cc5369f82e..1617f8d0ae6 100644 --- a/modules/swagger-generator/src/test/resources/petstore.json +++ b/modules/swagger-generator/src/test/resources/petstore.json @@ -1016,10 +1016,6 @@ "pending", "sold" ] - }, - "profilePhoto": { - "type": "string", - "format": "byte" } }, "xml": { diff --git a/samples/client/petstore/java/okhttp-gson/docs/Pet.md b/samples/client/petstore/java/okhttp-gson/docs/Pet.md index c05160aa4a3..5b63109ef92 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/Pet.md +++ b/samples/client/petstore/java/okhttp-gson/docs/Pet.md @@ -10,7 +10,6 @@ Name | Type | Description | Notes **photoUrls** | **List<String>** | | **tags** | [**List<Tag>**](Tag.md) | | [optional] **status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] -**profilePhoto** | **byte[]** | | [optional] diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java index c4aab3b100f..22c29a1bede 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java @@ -100,9 +100,6 @@ public StatusEnum read(final JsonReader jsonReader) throws IOException { @SerializedName("status") private StatusEnum status = null; - @SerializedName("profilePhoto") - private byte[] profilePhoto = null; - public Pet id(Long id) { this.id = id; return this; @@ -224,24 +221,6 @@ public void setStatus(StatusEnum status) { this.status = status; } - public Pet profilePhoto(byte[] profilePhoto) { - this.profilePhoto = profilePhoto; - return this; - } - - /** - * Get profilePhoto - * @return profilePhoto - **/ - @ApiModelProperty(value = "") - public byte[] getProfilePhoto() { - return profilePhoto; - } - - public void setProfilePhoto(byte[] profilePhoto) { - this.profilePhoto = profilePhoto; - } - @Override public boolean equals(java.lang.Object o) { @@ -257,13 +236,12 @@ public boolean equals(java.lang.Object o) { Objects.equals(this.name, pet.name) && Objects.equals(this.photoUrls, pet.photoUrls) && Objects.equals(this.tags, pet.tags) && - Objects.equals(this.status, pet.status) && - Arrays.equals(this.profilePhoto, pet.profilePhoto); + Objects.equals(this.status, pet.status); } @Override public int hashCode() { - return Objects.hash(id, category, name, photoUrls, tags, status, Arrays.hashCode(profilePhoto)); + return Objects.hash(id, category, name, photoUrls, tags, status); } @@ -278,7 +256,6 @@ public String toString() { 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(" profilePhoto: ").append(toIndentedString(profilePhoto)).append("\n"); sb.append("}"); return sb.toString(); } From 18ffb016dd2524f235541ea453db3605f1b21e2a Mon Sep 17 00:00:00 2001 From: Benjamin Roedell Date: Tue, 23 Jan 2018 14:24:23 -0500 Subject: [PATCH 8/9] Put previously deleted tests back. Modified testFindPetsByTags() to verify exception since the server now returns a 500 for this request. --- .../io/swagger/client/api/PetApiTest.java | 519 +++++++++++++----- .../io/swagger/client/api/StoreApiTest.java | 157 +++--- .../io/swagger/client/api/UserApiTest.java | 197 ++----- 3 files changed, 510 insertions(+), 363 deletions(-) diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/PetApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/PetApiTest.java index 349a55d93dc..e29c478a8d8 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/PetApiTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/PetApiTest.java @@ -1,170 +1,393 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ +package io.swagger.client.api; +import io.swagger.TestUtils; -package io.swagger.client.api; +import io.swagger.client.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; -import io.swagger.client.ApiException; +import java.io.BufferedWriter; import java.io.File; -import io.swagger.client.model.ModelApiResponse; -import io.swagger.client.model.Pet; -import org.junit.Test; -import org.junit.Ignore; - +import java.io.FileWriter; +import java.lang.reflect.Type; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; -/** - * API tests for PetApi - */ -@Ignore +import org.junit.*; +import static org.junit.Assert.*; + public class PetApiTest { + PetApi api = null; + + @Before + public void setup() { + api = new PetApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); + } - private final PetApi api = new PetApi(); - - - /** - * Add a new pet to the store - * - * - * - * @throws ApiException - * if the Api call fails - */ @Test - public void addPetTest() throws ApiException { - Pet body = null; - api.addPet(body); - - // TODO: test validations - } - - /** - * Deletes a pet - * - * - * - * @throws ApiException - * if the Api call fails - */ + public void testApiClient() { + // the default api client is used + assertEquals(Configuration.getDefaultApiClient(), api.getApiClient()); + assertNotNull(api.getApiClient()); + assertEquals("http://petstore.swagger.io:80/v2", api.getApiClient().getBasePath()); + assertFalse(api.getApiClient().isDebugging()); + + ApiClient oldClient = api.getApiClient(); + + ApiClient newClient = new ApiClient(); + newClient.setBasePath("http://example.com"); + newClient.setDebugging(true); + + // set api client via constructor + api = new PetApi(newClient); + assertNotNull(api.getApiClient()); + assertEquals("http://example.com", api.getApiClient().getBasePath()); + assertTrue(api.getApiClient().isDebugging()); + + // set api client via setter method + api.setApiClient(oldClient); + assertNotNull(api.getApiClient()); + assertEquals("http://petstore.swagger.io:80/v2", api.getApiClient().getBasePath()); + assertFalse(api.getApiClient().isDebugging()); + } + @Test - public void deletePetTest() throws ApiException { - 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 - */ + public void testCreateAndGetPet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + + /* @Test - public void findPetsByStatusTest() throws ApiException { - List status = null; - List 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 - */ + public void testCreateAndGetPetWithByteArray() throws Exception { + Pet pet = createRandomPet(); + byte[] bytes = serializeJson(pet, api.getApiClient()).getBytes(); + api.addPetUsingByteArray(bytes); + + byte[] fetchedBytes = api.petPetIdtestingByteArraytrueGet(pet.getId()); + Type type = new TypeToken(){}.getType(); + Pet fetched = deserializeJson(new String(fetchedBytes), type, api.getApiClient()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + */ + @Test - public void findPetsByTagsTest() throws ApiException { - List tags = null; - List response = api.findPetsByTags(tags); - - // TODO: test validations - } - - /** - * Find pet by ID - * - * Returns a single pet - * - * @throws ApiException - * if the Api call fails - */ + public void testCreateAndGetPetWithHttpInfo() throws Exception { + Pet pet = createRandomPet(); + api.addPetWithHttpInfo(pet); + + ApiResponse resp = api.getPetByIdWithHttpInfo(pet.getId()); + assertEquals(200, resp.getStatusCode()); + assertEquals("application/json", resp.getHeaders().get("Content-Type").get(0)); + Pet fetched = resp.getData(); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + @Test - public void getPetByIdTest() throws ApiException { - Long petId = null; - Pet response = api.getPetById(petId); - - // TODO: test validations - } - - /** - * Update an existing pet - * - * - * - * @throws ApiException - * if the Api call fails - */ + public void testCreateAndGetPetAsync() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + // to store returned Pet or error message/exception + final Map result = new HashMap(); + + api.getPetByIdAsync(pet.getId(), new ApiCallback() { + @Override + public void onFailure(ApiException e, int statusCode, Map> responseHeaders) { + result.put("error", e.getMessage()); + } + + @Override + public void onSuccess(Pet pet, int statusCode, Map> responseHeaders) { + result.put("pet", pet); + } + + @Override + public void onUploadProgress(long bytesWritten, long contentLength, boolean done) { + //empty + } + + @Override + public void onDownloadProgress(long bytesRead, long contentLength, boolean done) { + //empty + } + }); + // the API call should be executed asynchronously, so result should be empty at the moment + assertTrue(result.isEmpty()); + + // wait for the asynchronous call to finish (at most 10 seconds) + final int maxTry = 10; + int tryCount = 1; + Pet fetched = null; + do { + if (tryCount > maxTry) fail("have not got result of getPetByIdAsync after 10 seconds"); + Thread.sleep(1000); + tryCount += 1; + if (result.get("error") != null) fail((String) result.get("error")); + if (result.get("pet") != null) { + fetched = (Pet) result.get("pet"); + break; + } + } while (result.isEmpty()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + + // test getting a nonexistent pet + result.clear(); + api.getPetByIdAsync(-10000L, new ApiCallback() { + @Override + public void onFailure(ApiException e, int statusCode, Map> responseHeaders) { + result.put("exception", e); + } + + @Override + public void onSuccess(Pet pet, int statusCode, Map> responseHeaders) { + result.put("pet", pet); + } + + @Override + public void onUploadProgress(long bytesWritten, long contentLength, boolean done) { + //empty + } + + @Override + public void onDownloadProgress(long bytesRead, long contentLength, boolean done) { + //empty + } + }); + + // wait for the asynchronous call to finish (at most 10 seconds) + tryCount = 1; + ApiException exception = null; + do { + if (tryCount > maxTry) fail("have not got result of getPetByIdAsync after 10 seconds"); + Thread.sleep(1000); + tryCount += 1; + if (result.get("pet") != null) fail("expected an error"); + if (result.get("exception") != null) { + exception = (ApiException) result.get("exception"); + break; + } + } while (result.isEmpty()); + assertNotNull(exception); + assertEquals(404, exception.getCode()); + assertEquals("Not Found", exception.getMessage()); + assertEquals("application/json", exception.getResponseHeaders().get("Content-Type").get(0)); + } + + /* @Test - public void updatePetTest() throws ApiException { - 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 - */ + public void testGetPetByIdInObject() throws Exception { + Pet pet = new Pet(); + pet.setId(TestUtils.nextId()); + pet.setName("pet " + pet.getId()); + + Category category = new Category(); + category.setId(TestUtils.nextId()); + category.setName("category " + category.getId()); + pet.setCategory(category); + + pet.setStatus(Pet.StatusEnum.PENDING); + List photos = Arrays.asList(new String[]{"http://foo.bar.com/1"}); + pet.setPhotoUrls(photos); + + api.addPet(pet); + + InlineResponse200 fetched = api.getPetByIdInObject(pet.getId()); + assertEquals(pet.getId(), fetched.getId()); + assertEquals(pet.getName(), fetched.getName()); + + Object categoryObj = fetched.getCategory(); + assertNotNull(categoryObj); + assertTrue(categoryObj instanceof Map); + + Map categoryMap = (Map) categoryObj; + Object categoryIdObj = categoryMap.get("id"); + // NOTE: Gson parses integer value to double. + assertTrue(categoryIdObj instanceof Double); + Long categoryIdLong = ((Double) categoryIdObj).longValue(); + assertEquals(category.getId(), categoryIdLong); + assertEquals(category.getName(), categoryMap.get("name")); + } + */ + @Test - public void updatePetWithFormTest() throws ApiException { - 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 - */ + public void testUpdatePet() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + + api.updatePet(pet); + + Pet fetched = api.getPetById(pet.getId()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + + @Test + public void testFindPetsByStatus() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + pet.setStatus(Pet.StatusEnum.PENDING); + + api.updatePet(pet); + + List pets = api.findPetsByStatus(Arrays.asList("pending")); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + + assertTrue(found); + + api.deletePet(pet.getId(), null); + } + + @Test + public void testFindPetsByTags() throws Exception { + Pet pet = createRandomPet(); + pet.setName("monster"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + List tags = new ArrayList(); + Tag tag1 = new Tag(); + tag1.setName("friendly"); + tags.add(tag1); + pet.setTags(tags); + + api.updatePet(pet); + + Exception actualException = null; + try { + List pets = api.findPetsByTags(Arrays.asList("friendly")); + } catch (Exception e) { + actualException = e; + } + + assertNotNull(actualException); + assertTrue("The exception should be of type ApiException", actualException instanceof ApiException); + ApiException actualApiException = (ApiException) actualException; + assertEquals("Status code should be 500", actualApiException.getCode(), 500); + + api.deletePet(pet.getId(), null); + } + @Test - public void uploadFileTest() throws ApiException { - Long petId = null; - String additionalMetadata = null; - File file = null; - ModelApiResponse response = api.uploadFile(petId, additionalMetadata, file); + public void testUpdatePetWithForm() throws Exception { + Pet pet = createRandomPet(); + pet.setName("frank"); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + + api.updatePetWithForm(fetched.getId(), "furt", null); + Pet updated = api.getPetById(fetched.getId()); + + assertEquals(updated.getName(), "furt"); + } + + @Test + public void testDeletePet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + api.deletePet(fetched.getId(), null); + + try { + fetched = api.getPetById(fetched.getId()); + fail("expected an error"); + } catch (ApiException e) { + assertEquals(404, e.getCode()); + } + } + + @Test + public void testUploadFile() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + File file = new File("hello.txt"); + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + writer.write("Hello world!"); + writer.close(); + + api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath())); + } + + @Test + public void testEqualsAndHashCode() { + Pet pet1 = new Pet(); + Pet pet2 = new Pet(); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + + pet2.setName("really-happy"); + pet2.setPhotoUrls(Arrays.asList("http://foo.bar.com/1", "http://foo.bar.com/2")); + assertFalse(pet1.equals(pet2)); + assertFalse(pet2.equals(pet1)); + assertFalse(pet1.hashCode() == (pet2.hashCode())); + assertTrue(pet2.equals(pet2)); + assertTrue(pet2.hashCode() == pet2.hashCode()); + + pet1.setName("really-happy"); + pet1.setPhotoUrls(Arrays.asList("http://foo.bar.com/1", "http://foo.bar.com/2")); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + } + + private Pet createRandomPet() { + Pet pet = new Pet(); + pet.setId(TestUtils.nextId()); + pet.setName("gorilla"); + + Category category = new Category(); + category.setName("really-happy"); + + pet.setCategory(category); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + List photos = Arrays.asList("http://foo.bar.com/1", "http://foo.bar.com/2"); + pet.setPhotoUrls(photos); + + return pet; + } + + private String serializeJson(Object o, ApiClient apiClient) { + return apiClient.getJSON().serialize(o); + } - // TODO: test validations + private T deserializeJson(String json, Type type, ApiClient apiClient) { + return (T) apiClient.getJSON().deserialize(json, type); } - } diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/StoreApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/StoreApiTest.java index bef0884a2da..655e7be65b8 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/StoreApiTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/StoreApiTest.java @@ -1,98 +1,99 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ - - package io.swagger.client.api; +import io.swagger.TestUtils; import io.swagger.client.ApiException; -import io.swagger.client.model.Order; -import org.junit.Test; -import org.junit.Ignore; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; + +import java.lang.reflect.Field; import java.util.Map; -/** - * API tests for StoreApi - */ -@Ignore +import org.junit.*; +import org.threeten.bp.OffsetDateTime; + +import static org.junit.Assert.*; + public class StoreApiTest { + StoreApi api = null; - private final StoreApi api = new StoreApi(); - - - /** - * Delete purchase order by ID - * - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void deleteOrderTest() throws ApiException { - String orderId = null; - api.deleteOrder(orderId); + @Before + public void setup() { + api = new StoreApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); + } - // TODO: test validations + @Test + public void testGetInventory() throws Exception { + Map inventory = api.getInventory(); + assertTrue(inventory.keySet().size() > 0); } - - /** - * Returns pet inventories by status - * - * Returns a map of status codes to quantities - * - * @throws ApiException - * if the Api call fails - */ + + /* @Test - public void getInventoryTest() throws ApiException { - Map response = api.getInventory(); + public void testGetInventoryInObject() throws Exception { + Object inventoryObj = api.getInventoryInObject(); + assertTrue(inventoryObj instanceof Map); - // TODO: test validations + Map inventoryMap = (Map) inventoryObj; + assertTrue(inventoryMap.keySet().size() > 0); + + Map.Entry firstEntry = (Map.Entry) inventoryMap.entrySet().iterator().next(); + assertTrue(firstEntry.getKey() instanceof String); + // NOTE: Gson parses integer value to double. + assertTrue(firstEntry.getValue() instanceof Double); } - - /** - * Find purchase order by ID - * - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * - * @throws ApiException - * if the Api call fails - */ + */ + @Test - public void getOrderByIdTest() throws ApiException { - Long orderId = null; - Order response = api.getOrderById(orderId); + public void testPlaceOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); - // TODO: test validations + Order fetched = api.getOrderById(order.getId()); + assertEquals(order.getId(), fetched.getId()); + assertEquals(order.getPetId(), fetched.getPetId()); + assertEquals(order.getQuantity(), fetched.getQuantity()); + assertTrue(order.getShipDate().isEqual(fetched.getShipDate())); } - - /** - * Place an order for a pet - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void placeOrderTest() throws ApiException { - Order body = null; - Order response = api.placeOrder(body); + public void testDeleteOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); + + Order fetched = api.getOrderById(order.getId()); + assertEquals(fetched.getId(), order.getId()); + + api.deleteOrder(String.valueOf(order.getId())); + + try { + api.getOrderById(order.getId()); + // fail("expected an error"); + } catch (ApiException e) { + // ok + } + } + + private Order createOrder() { + Order order = new Order(); + order.setPetId(200L); + order.setQuantity(13); + //Ensure 3 fractional digits because of a bug in the petstore server + order.setShipDate(OffsetDateTime.now().withNano(123000000)); + order.setStatus(Order.StatusEnum.PLACED); + order.setComplete(true); + + try { + Field idField = Order.class.getDeclaredField("id"); + idField.setAccessible(true); + idField.set(order, TestUtils.nextId()); + } catch (Exception e) { + throw new RuntimeException(e); + } - // TODO: test validations + return order; } - } diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/UserApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/UserApiTest.java index 4455b3920b9..b47a146d737 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/UserApiTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/UserApiTest.java @@ -1,164 +1,87 @@ -/* - * Swagger Petstore - * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ - * - * OpenAPI spec version: 1.0.0 - * Contact: apiteam@swagger.io - * - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen.git - * Do not edit the class manually. - */ +package io.swagger.client.api; +import io.swagger.TestUtils; -package io.swagger.client.api; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; -import io.swagger.client.ApiException; -import io.swagger.client.model.User; -import org.junit.Test; -import org.junit.Ignore; +import java.util.Arrays; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; +import org.junit.*; +import static org.junit.Assert.*; -/** - * API tests for UserApi - */ -@Ignore public class UserApiTest { + UserApi api = null; - 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() throws ApiException { - User body = null; - api.createUser(body); - - // TODO: test validations + @Before + public void setup() { + api = new UserApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); } - - /** - * Creates list of users with given input array - * - * - * - * @throws ApiException - * if the Api call fails - */ - @Test - public void createUsersWithArrayInputTest() throws ApiException { - List 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() throws ApiException { - List body = null; - api.createUsersWithListInput(body); + public void testCreateUser() throws Exception { + User user = createUser(); - // TODO: test validations + api.createUser(user); + + User fetched = api.getUserByName(user.getUsername()); + assertEquals(user.getId(), fetched.getId()); } - - /** - * Delete user - * - * This can only be done by the logged in user. - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void deleteUserTest() throws ApiException { - String username = null; - api.deleteUser(username); + public void testCreateUsersWithArray() throws Exception { + User user1 = createUser(); + user1.setUsername("user" + user1.getId()); + User user2 = createUser(); + user2.setUsername("user" + user2.getId()); - // TODO: test validations + api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); } - - /** - * Get user by user name - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void getUserByNameTest() throws ApiException { - String username = null; - User response = api.getUserByName(username); + public void testCreateUsersWithList() throws Exception { + User user1 = createUser(); + user1.setUsername("user" + user1.getId()); + User user2 = createUser(); + user2.setUsername("user" + user2.getId()); - // TODO: test validations + api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); } - - /** - * Logs user into the system - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void loginUserTest() throws ApiException { - String username = null; - String password = null; - String response = api.loginUser(username, password); + public void testLoginUser() throws Exception { + User user = createUser(); + api.createUser(user); - // TODO: test validations + String token = api.loginUser(user.getUsername(), user.getPassword()); + assertTrue(token.startsWith("logged in user session:")); } - - /** - * Logs out current logged in user session - * - * - * - * @throws ApiException - * if the Api call fails - */ + @Test - public void logoutUserTest() throws ApiException { + public void logoutUser() throws Exception { 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() throws ApiException { - String username = null; - User body = null; - api.updateUser(username, body); - // TODO: test validations + private User createUser() { + User user = new User(); + user.setId(TestUtils.nextId()); + user.setUsername("fred" + user.getId()); + user.setFirstName("Fred"); + user.setLastName("Meyer"); + user.setEmail("fred@fredmeyer.com"); + user.setPassword("xxXXxx"); + user.setPhone("408-867-5309"); + user.setUserStatus(123); + + return user; } - } From 831048545efa2788277924397723f90bf468fbf2 Mon Sep 17 00:00:00 2001 From: Benjamin Roedell Date: Tue, 23 Jan 2018 18:11:18 -0500 Subject: [PATCH 9/9] Update test to pass when run against docker containerized server swaggerapi/petstore (heads up, this test fails if calling out to the internet published version of http://petstore.swagger.io) --- .../io/swagger/client/api/PetApiTest.java | 20 +++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/PetApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/PetApiTest.java index e29c478a8d8..b949d90ebdb 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/PetApiTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/api/PetApiTest.java @@ -282,17 +282,17 @@ public void testFindPetsByTags() throws Exception { api.updatePet(pet); - Exception actualException = null; - try { - List pets = api.findPetsByTags(Arrays.asList("friendly")); - } catch (Exception e) { - actualException = e; - } + List pets = api.findPetsByTags(Arrays.asList("friendly")); + assertNotNull(pets); - assertNotNull(actualException); - assertTrue("The exception should be of type ApiException", actualException instanceof ApiException); - ApiException actualApiException = (ApiException) actualException; - assertEquals("Status code should be 500", actualApiException.getCode(), 500); + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + assertTrue(found); api.deletePet(pet.getId(), null); }