Skip to content

Commit 47111b3

Browse files
benrobotwing328
authored andcommitted
Issue 4824 fix gson deserialize format byte (#7473)
* Build sample prior to code changes so differences are easier to decipher * Add byte array type adapter for okhttp-gson (java8 only) * Unit revealed that Gson (or GsonFire) defaults to escape = (equal sign) out of base64 string. Add disableHtmlEscaping() to gsonbuilder. * Update specs and samples to include format=byte and include junit test of byte array serialization and deserialization. * 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. * Update spec and sample for java okhttp-gson library client * Undo addition of profilePhoto property. A format byte property is already available under the format_test definition. * Put previously deleted tests back. Modified testFindPetsByTags() to verify exception since the server now returns a 500 for this request. * 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)
1 parent 2d89851 commit 47111b3

File tree

16 files changed

+371
-248
lines changed

16 files changed

+371
-248
lines changed

bin/windows/java-petstore-okhttp-gson.bat

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,6 @@ If Not Exist %executable% (
55
)
66

77
REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M
8-
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
8+
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
99

1010
java %JAVA_OPTS% -jar %executable% %ags%

modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import org.threeten.bp.format.DateTimeFormatter;
2626
{{/threetenbp}}
2727

2828
import {{modelPackage}}.*;
29+
import okio.ByteString;
2930

3031
import java.io.IOException;
3132
import java.io.StringReader;
@@ -55,6 +56,7 @@ public class JSON {
5556
private OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter();
5657
private LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter();
5758
{{/jsr310}}
59+
private ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter();
5860

5961
public static GsonBuilder createGson() {
6062
GsonFireBuilder fireBuilder = new GsonFireBuilder()
@@ -105,6 +107,7 @@ public class JSON {
105107
.registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter)
106108
.registerTypeAdapter(LocalDate.class, localDateTypeAdapter)
107109
{{/jsr310}}
110+
.registerTypeAdapter(byte[].class, byteArrayAdapter)
108111
.create();
109112
}
110113

@@ -171,6 +174,34 @@ public class JSON {
171174
}
172175
}
173176

177+
/**
178+
* Gson TypeAdapter for Byte Array type
179+
*/
180+
public class ByteArrayAdapter extends TypeAdapter<byte[]> {
181+
182+
@Override
183+
public void write(JsonWriter out, byte[] value) throws IOException {
184+
if (value == null) {
185+
out.nullValue();
186+
} else {
187+
out.value(ByteString.of(value).base64());
188+
}
189+
}
190+
191+
@Override
192+
public byte[] read(JsonReader in) throws IOException {
193+
switch (in.peek()) {
194+
case NULL:
195+
in.nextNull();
196+
return null;
197+
default:
198+
String bytesAsBase64 = in.nextString();
199+
ByteString byteString = ByteString.decodeBase64(bytesAsBase64);
200+
return byteString.toByteArray();
201+
}
202+
}
203+
}
204+
174205
{{#joda}}
175206
/**
176207
* Gson TypeAdapter for Joda DateTime type
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
2.4.0-SNAPSHOT
1+
2.4.0-SNAPSHOT

samples/client/petstore/java/okhttp-gson/README.md

Lines changed: 81 additions & 69 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,46 @@
11
# swagger-petstore-okhttp-gson
22

3+
Swagger Petstore
4+
- API version: 1.0.0
5+
6+
This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
7+
8+
9+
*Automatically generated by the [Swagger Codegen](https://github.com/swagger-api/swagger-codegen)*
10+
11+
312
## Requirements
413

5-
Building the API client library requires [Maven](https://maven.apache.org/) to be installed.
14+
Building the API client library requires:
15+
1. Java 1.7+
16+
2. Maven/Gradle
617

718
## Installation
819

920
To install the API client library to your local Maven repository, simply execute:
1021

1122
```shell
12-
mvn install
23+
mvn clean install
1324
```
1425

1526
To deploy it to a remote Maven repository instead, configure the settings of the repository and execute:
1627

1728
```shell
18-
mvn deploy
29+
mvn clean deploy
1930
```
2031

21-
Refer to the [official documentation](https://maven.apache.org/plugins/maven-deploy-plugin/usage.html) for more information.
32+
Refer to the [OSSRH Guide](http://central.sonatype.org/pages/ossrh-guide.html) for more information.
2233

2334
### Maven users
2435

2536
Add this dependency to your project's POM:
2637

2738
```xml
2839
<dependency>
29-
<groupId>io.swagger</groupId>
30-
<artifactId>swagger-petstore-okhttp-gson</artifactId>
31-
<version>1.0.0</version>
32-
<scope>compile</scope>
40+
<groupId>io.swagger</groupId>
41+
<artifactId>swagger-petstore-okhttp-gson</artifactId>
42+
<version>1.0.0</version>
43+
<scope>compile</scope>
3344
</dependency>
3445
```
3546

@@ -45,12 +56,14 @@ compile "io.swagger:swagger-petstore-okhttp-gson:1.0.0"
4556

4657
At first generate the JAR by executing:
4758

48-
mvn package
59+
```shell
60+
mvn clean package
61+
```
4962

5063
Then manually install the following JARs:
5164

52-
* target/swagger-petstore-okhttp-gson-1.0.0.jar
53-
* target/lib/*.jar
65+
* `target/swagger-petstore-okhttp-gson-1.0.0.jar`
66+
* `target/lib/*.jar`
5467

5568
## Getting Started
5669

@@ -61,30 +74,22 @@ Please follow the [installation](#installation) instruction and execute the foll
6174
import io.swagger.client.*;
6275
import io.swagger.client.auth.*;
6376
import io.swagger.client.model.*;
64-
import io.swagger.client.api.PetApi;
77+
import io.swagger.client.api.AnotherFakeApi;
6578

6679
import java.io.File;
6780
import java.util.*;
6881

69-
public class PetApiExample {
82+
public class AnotherFakeApiExample {
7083

7184
public static void main(String[] args) {
72-
ApiClient defaultClient = Configuration.getDefaultApiClient();
73-
74-
// Configure OAuth2 access token for authorization: petstore_auth
75-
OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth");
76-
petstore_auth.setAccessToken("YOUR ACCESS TOKEN");
77-
78-
79-
80-
PetApi apiInstance = new PetApi();
81-
82-
Pet body = new Pet(); // Pet | Pet object that needs to be added to the store
8385

86+
AnotherFakeApi apiInstance = new AnotherFakeApi();
87+
Client body = new Client(); // Client | client model
8488
try {
85-
apiInstance.addPet(body);
89+
Client result = apiInstance.testSpecialTags(body);
90+
System.out.println(result);
8691
} catch (ApiException e) {
87-
System.err.println("Exception when calling PetApi#addPet");
92+
System.err.println("Exception when calling AnotherFakeApi#testSpecialTags");
8893
e.printStackTrace();
8994
}
9095
}
@@ -94,26 +99,32 @@ public class PetApiExample {
9499

95100
## Documentation for API Endpoints
96101

97-
All URIs are relative to *http://petstore.swagger.io/v2*
102+
All URIs are relative to *http://petstore.swagger.io:80/v2*
98103

99104
Class | Method | HTTP request | Description
100105
------------ | ------------- | ------------- | -------------
106+
*AnotherFakeApi* | [**testSpecialTags**](docs/AnotherFakeApi.md#testSpecialTags) | **PATCH** /another-fake/dummy | To test special tags
107+
*FakeApi* | [**fakeOuterBooleanSerialize**](docs/FakeApi.md#fakeOuterBooleanSerialize) | **POST** /fake/outer/boolean |
108+
*FakeApi* | [**fakeOuterCompositeSerialize**](docs/FakeApi.md#fakeOuterCompositeSerialize) | **POST** /fake/outer/composite |
109+
*FakeApi* | [**fakeOuterNumberSerialize**](docs/FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number |
110+
*FakeApi* | [**fakeOuterStringSerialize**](docs/FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string |
111+
*FakeApi* | [**testClientModel**](docs/FakeApi.md#testClientModel) | **PATCH** /fake | To test \&quot;client\&quot; model
112+
*FakeApi* | [**testEndpointParameters**](docs/FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트
113+
*FakeApi* | [**testEnumParameters**](docs/FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters
114+
*FakeApi* | [**testInlineAdditionalProperties**](docs/FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties
115+
*FakeApi* | [**testJsonFormData**](docs/FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data
116+
*FakeClassnameTags123Api* | [**testClassname**](docs/FakeClassnameTags123Api.md#testClassname) | **PATCH** /fake_classname_test | To test class name in snake case
101117
*PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store
102-
*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
103118
*PetApi* | [**deletePet**](docs/PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet
104119
*PetApi* | [**findPetsByStatus**](docs/PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status
105120
*PetApi* | [**findPetsByTags**](docs/PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags
106121
*PetApi* | [**getPetById**](docs/PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID
107-
*PetApi* | [**getPetByIdInObject**](docs/PetApi.md#getPetByIdInObject) | **GET** /pet/{petId}?response=inline_arbitrary_object | Fake endpoint to test inline arbitrary object return by &#39;Find pet by ID&#39;
108-
*PetApi* | [**petPetIdtestingByteArraytrueGet**](docs/PetApi.md#petPetIdtestingByteArraytrueGet) | **GET** /pet/{petId}?testing_byte_array=true | Fake endpoint to test byte array return by &#39;Find pet by ID&#39;
109122
*PetApi* | [**updatePet**](docs/PetApi.md#updatePet) | **PUT** /pet | Update an existing pet
110123
*PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data
111124
*PetApi* | [**uploadFile**](docs/PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image
112-
*StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID
113-
*StoreApi* | [**findOrdersByStatus**](docs/StoreApi.md#findOrdersByStatus) | **GET** /store/findByStatus | Finds orders by status
125+
*StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteOrder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID
114126
*StoreApi* | [**getInventory**](docs/StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status
115-
*StoreApi* | [**getInventoryInObject**](docs/StoreApi.md#getInventoryInObject) | **GET** /store/inventory?response=arbitrary_object | Fake endpoint to test arbitrary object return by &#39;Get inventory&#39;
116-
*StoreApi* | [**getOrderById**](docs/StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID
127+
*StoreApi* | [**getOrderById**](docs/StoreApi.md#getOrderById) | **GET** /store/order/{order_id} | Find purchase order by ID
117128
*StoreApi* | [**placeOrder**](docs/StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet
118129
*UserApi* | [**createUser**](docs/UserApi.md#createUser) | **POST** /user | Create user
119130
*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
127138

128139
## Documentation for Models
129140

141+
- [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md)
130142
- [Animal](docs/Animal.md)
131-
- [Cat](docs/Cat.md)
143+
- [AnimalFarm](docs/AnimalFarm.md)
144+
- [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md)
145+
- [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md)
146+
- [ArrayTest](docs/ArrayTest.md)
147+
- [Capitalization](docs/Capitalization.md)
132148
- [Category](docs/Category.md)
133-
- [Dog](docs/Dog.md)
134-
- [InlineResponse200](docs/InlineResponse200.md)
149+
- [ClassModel](docs/ClassModel.md)
150+
- [Client](docs/Client.md)
151+
- [EnumArrays](docs/EnumArrays.md)
152+
- [EnumClass](docs/EnumClass.md)
153+
- [EnumTest](docs/EnumTest.md)
154+
- [FormatTest](docs/FormatTest.md)
155+
- [HasOnlyReadOnly](docs/HasOnlyReadOnly.md)
156+
- [MapTest](docs/MapTest.md)
157+
- [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md)
135158
- [Model200Response](docs/Model200Response.md)
159+
- [ModelApiResponse](docs/ModelApiResponse.md)
136160
- [ModelReturn](docs/ModelReturn.md)
137161
- [Name](docs/Name.md)
162+
- [NumberOnly](docs/NumberOnly.md)
138163
- [Order](docs/Order.md)
164+
- [OuterComposite](docs/OuterComposite.md)
165+
- [OuterEnum](docs/OuterEnum.md)
139166
- [Pet](docs/Pet.md)
167+
- [ReadOnlyFirst](docs/ReadOnlyFirst.md)
140168
- [SpecialModelName](docs/SpecialModelName.md)
141169
- [Tag](docs/Tag.md)
142170
- [User](docs/User.md)
171+
- [Cat](docs/Cat.md)
172+
- [Dog](docs/Dog.md)
143173

144174

145175
## Documentation for Authorization
146176

147177
Authentication schemes defined for the API:
148-
### petstore_auth
149-
150-
- **Type**: OAuth
151-
- **Flow**: implicit
152-
- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog
153-
- **Scopes**:
154-
- write:pets: modify pets in your account
155-
- read:pets: read your pets
156-
157-
### test_api_client_id
158-
159-
- **Type**: API key
160-
- **API key parameter name**: x-test_api_client_id
161-
- **Location**: HTTP header
162-
163-
### test_api_client_secret
164-
165-
- **Type**: API key
166-
- **API key parameter name**: x-test_api_client_secret
167-
- **Location**: HTTP header
168-
169178
### api_key
170179

171180
- **Type**: API key
172181
- **API key parameter name**: api_key
173182
- **Location**: HTTP header
174183

175-
### test_http_basic
176-
177-
- **Type**: HTTP basic authentication
178-
179-
### test_api_key_query
184+
### api_key_query
180185

181186
- **Type**: API key
182-
- **API key parameter name**: test_api_key_query
187+
- **API key parameter name**: api_key_query
183188
- **Location**: URL query string
184189

185-
### test_api_key_header
190+
### http_basic_test
186191

187-
- **Type**: API key
188-
- **API key parameter name**: test_api_key_header
189-
- **Location**: HTTP header
192+
- **Type**: HTTP basic authentication
193+
194+
### petstore_auth
195+
196+
- **Type**: OAuth
197+
- **Flow**: implicit
198+
- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog
199+
- **Scopes**:
200+
- write:pets: modify pets in your account
201+
- read:pets: read your pets
190202

191203

192204
## Recommendation
193205

194-
It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issue.
206+
It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues.
195207

196208
## Author
197209

samples/client/petstore/java/okhttp-gson/build.gradle

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,14 @@ if(hasProperty('target') && target == 'android') {
9191
main = System.getProperty('mainClass')
9292
classpath = sourceSets.main.runtimeClasspath
9393
}
94+
95+
compileJava {
96+
options.encoding = "UTF8"
97+
}
98+
99+
compileTestJava {
100+
options.encoding = "UTF8"
101+
}
94102
}
95103

96104
dependencies {

samples/client/petstore/java/okhttp-gson/docs/ApiResponse.md

Lines changed: 0 additions & 12 deletions
This file was deleted.

0 commit comments

Comments
 (0)