Skip to content

Commit

Permalink
Port of @ngaya-ll 's pull request from swagger to openapi. (#2356)
Browse files Browse the repository at this point in the history
  • Loading branch information
burberius authored and wing328 committed Mar 12, 2019
1 parent b1dc2ee commit fde3252
Show file tree
Hide file tree
Showing 52 changed files with 984 additions and 3,466 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,9 @@ public class ApiClient {
{{/oauthMethods}}
{{/hasOAuthMethods}}
private void init() {
httpClient = new OkHttpClient();
OkHttpClient.Builder builder = new OkHttpClient.Builder();
builder.addInterceptor(getProgressInterceptor());
httpClient = builder.build();
{{#useGzipFeature}}
// Enable gzip request compression
Expand Down Expand Up @@ -189,7 +191,7 @@ public class ApiClient {
* @return Api Client
*/
public ApiClient setHttpClient(OkHttpClient httpClient) {
this.httpClient = httpClient;
this.httpClient = httpClient.newBuilder().addInterceptor(getProgressInterceptor()).build();
return this;
}

Expand Down Expand Up @@ -1066,12 +1068,12 @@ public class ApiClient {
* @param headerParams The header parameters
* @param formParams The form parameters
* @param authNames The authentications to apply
* @param progressRequestListener Progress request listener
* @param callback Callback for upload/download progress
* @return The HTTP call
* @throws ApiException If fail to serialize the request body object
*/
public Call buildCall(String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Request request = buildRequest(path, method, queryParams, collectionQueryParams, body, headerParams, formParams, authNames, progressRequestListener);
public Call buildCall(String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String[] authNames, ApiCallback callback) throws ApiException {
Request request = buildRequest(path, method, queryParams, collectionQueryParams, body, headerParams, formParams, authNames, callback);
return httpClient.newCall(request);
}
Expand All @@ -1087,11 +1089,11 @@ public class ApiClient {
* @param headerParams The header parameters
* @param formParams The form parameters
* @param authNames The authentications to apply
* @param progressRequestListener Progress request listener
* @param callback Callback for upload/download progress
* @return The HTTP request
* @throws ApiException If fail to serialize the request body object
*/
public Request buildRequest(String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String[] authNames, ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
public Request buildRequest(String path, String method, List<Pair> queryParams, List<Pair> collectionQueryParams, Object body, Map<String, String> headerParams, Map<String, Object> formParams, String[] authNames, ApiCallback callback) throws ApiException {
updateParamsForAuth(authNames, queryParams, headerParams);
final String url = buildUrl(path, queryParams, collectionQueryParams);
Expand Down Expand Up @@ -1123,10 +1125,14 @@ public class ApiClient {
reqBody = serialize(body, contentType);
}

// Associate callback with request (if not null) so interceptor can
// access it when creating ProgressResponseBody
reqBuilder.tag(callback);

Request request = null;

if (progressRequestListener != null && reqBody != null) {
ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, progressRequestListener);
if (callback != null && reqBody != null) {
ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, callback);
request = reqBuilder.method(method, progressRequestBody).build();
} else {
request = reqBuilder.method(method, reqBody).build();
Expand Down Expand Up @@ -1270,6 +1276,27 @@ public class ApiClient {
}
}

/**
* Get network interceptor to add it to the httpClient to track download progress for
* async requests.
*/
private Interceptor getProgressInterceptor() {
return new Interceptor() {
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
final Request request = chain.request();
final Response originalResponse = chain.proceed(request);
if (request.tag() instanceof ApiCallback) {
final ApiCallback callback = (ApiCallback) request.tag();
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), callback))
.build();
}
return originalResponse;
}
};
}

/**
* Apply SSL related settings to httpClient according to the current values of
* verifyingSsl and sslCaCert.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,13 @@ import okio.Sink;

public class ProgressRequestBody extends RequestBody {
public interface ProgressRequestListener {
void onRequestProgress(long bytesWritten, long contentLength, boolean done);
}

private final RequestBody requestBody;
private final ProgressRequestListener progressListener;
private final ApiCallback callback;
public ProgressRequestBody(RequestBody requestBody, ProgressRequestListener progressListener) {
public ProgressRequestBody(RequestBody requestBody, ApiCallback callback) {
this.requestBody = requestBody;
this.progressListener = progressListener;
this.callback = callback;
}

@Override
Expand Down Expand Up @@ -59,7 +55,7 @@ public class ProgressRequestBody extends RequestBody {
}

bytesWritten += byteCount;
progressListener.onRequestProgress(bytesWritten, contentLength, bytesWritten == contentLength);
callback.onUploadProgress(bytesWritten, contentLength, bytesWritten == contentLength);
}
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,13 @@ import okio.Source;

public class ProgressResponseBody extends ResponseBody {
public interface ProgressListener {
void update(long bytesRead, long contentLength, boolean done);
}

private final ResponseBody responseBody;
private final ProgressListener progressListener;
private final ApiCallback callback;
private BufferedSource bufferedSource;
public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) {
public ProgressResponseBody(ResponseBody responseBody, ApiCallback callback) {
this.responseBody = responseBody;
this.progressListener = progressListener;
this.callback = callback;
}

@Override
Expand Down Expand Up @@ -55,7 +51,7 @@ public class ProgressResponseBody extends ResponseBody {
long bytesRead = super.read(sink, byteCount);
// read() returns the number of bytes read, or -1 if this source is exhausted.
totalBytesRead += bytesRead != -1 ? bytesRead : 0;
progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1);
callback.onDownloadProgress(totalBytesRead, responseBody.contentLength(), bytesRead == -1);
return bytesRead;
}
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,7 @@ public class {{classname}} {
{{^vendorExtensions.x-group-parameters}}/**
* Build call for {{operationId}}{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{^isContainer}}{{#defaultValue}}, default to {{.}}{{/defaultValue}}{{/isContainer}}){{/required}}{{/allParams}}
* @param _progressListener Progress listener
* @param _progressRequestListener Progress request listener
* @param _callback Callback for upload/download progress
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
{{#isDeprecated}}
Expand All @@ -81,7 +80,7 @@ public class {{classname}} {
{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
public{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}private{{/vendorExtensions.x-group-parameters}} okhttp3.Call {{operationId}}Call({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener _progressListener, final ProgressRequestBody.ProgressRequestListener _progressRequestListener) throws ApiException {
public{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}private{{/vendorExtensions.x-group-parameters}} okhttp3.Call {{operationId}}Call({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback _callback) throws ApiException {
Object localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}new Object(){{/bodyParam}};

// create path and map variables
Expand Down Expand Up @@ -124,27 +123,15 @@ public class {{classname}} {
final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);

if (_progressListener != null) {
localVarApiClient.setHttpClient(localVarApiClient.getHttpClient().newBuilder().addNetworkInterceptor(new okhttp3.Interceptor() {
@Override
public okhttp3.Response intercept(okhttp3.Interceptor.Chain chain) throws IOException {
okhttp3.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), _progressListener))
.build();
}
}).build());
}

String[] localVarAuthNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} };
return localVarApiClient.buildCall(localVarPath, "{{httpMethod}}", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, _progressRequestListener);
return localVarApiClient.buildCall(localVarPath, "{{httpMethod}}", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, _callback);
}

{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
@SuppressWarnings("rawtypes")
private okhttp3.Call {{operationId}}ValidateBeforeCall({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener _progressListener, final ProgressRequestBody.ProgressRequestListener _progressRequestListener) throws ApiException {
private okhttp3.Call {{operationId}}ValidateBeforeCall({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback _callback) throws ApiException {
{{^performBeanValidation}}
{{#allParams}}{{#required}}
// verify the required parameter '{{paramName}}' is set
Expand All @@ -153,7 +140,7 @@ public class {{classname}} {
}
{{/required}}{{/allParams}}

okhttp3.Call localVarCall = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}_progressListener, _progressRequestListener);
okhttp3.Call localVarCall = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}_callback);
return localVarCall;

{{/performBeanValidation}}
Expand All @@ -168,7 +155,7 @@ public class {{classname}} {
parameterValues);

if (violations.size() == 0) {
okhttp3.Call localVarCall = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}_progressListener, _progressRequestListener);
okhttp3.Call localVarCall = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}_callback);
return localVarCall;

} else {
Expand Down Expand Up @@ -227,7 +214,7 @@ public class {{classname}} {
@Deprecated
{{/isDeprecated}}
public{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}private{{/vendorExtensions.x-group-parameters}} ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
okhttp3.Call localVarCall = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}null, null);
okhttp3.Call localVarCall = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}null);
{{#returnType}}Type localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType();
return localVarApiClient.execute(localVarCall, localVarReturnType);{{/returnType}}{{^returnType}}return localVarApiClient.execute(localVarCall);{{/returnType}}
}
Expand All @@ -252,26 +239,7 @@ public class {{classname}} {
{{/isDeprecated}}
public{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}private{{/vendorExtensions.x-group-parameters}} okhttp3.Call {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> _callback) throws ApiException {
ProgressResponseBody.ProgressListener _progressListener = null;
ProgressRequestBody.ProgressRequestListener _progressRequestListener = null;
if (_callback != null) {
_progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
_callback.onDownloadProgress(bytesRead, contentLength, done);
}
};

_progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
_callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}

okhttp3.Call localVarCall = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}_progressListener, _progressRequestListener);
okhttp3.Call localVarCall = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}_callback);
{{#returnType}}Type localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType();
localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback);{{/returnType}}{{^returnType}}localVarApiClient.executeAsync(localVarCall, _callback);{{/returnType}}
return localVarCall;
Expand Down Expand Up @@ -317,8 +285,8 @@ public class {{classname}} {
{{#isDeprecated}}
@Deprecated
{{/isDeprecated}}
public okhttp3.Call buildCall(final ProgressResponseBody.ProgressListener _progressListener, final ProgressRequestBody.ProgressRequestListener _progressRequestListener) throws ApiException {
return {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}_progressListener, _progressRequestListener);
public okhttp3.Call buildCall(final ApiCallback _callback) throws ApiException {
return {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}_callback);
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1 +1 @@
3.3.4-SNAPSHOT
4.0.0-SNAPSHOT
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,9 @@ public class FakeApiExample {
public static void main(String[] args) {

FakeApi apiInstance = new FakeApi();
Object UNKNOWN_BASE_TYPE = new UNKNOWN_BASE_TYPE(); // Object |
String testCodeInjectStarSlashQuoteDoubleQuoteEqualEndBackSlashRBackSlashNBackSlashNBackSlashR = "testCodeInjectStarSlashQuoteDoubleQuoteEqualEndBackSlashRBackSlashNBackSlashNBackSlashR_example"; // String | To test code injection *_/ ' \\\" =end -- \\\\r\\\\n \\\\n \\\\r
try {
apiInstance.testCodeInjectEndRnNR(UNKNOWN_BASE_TYPE);
apiInstance.testCodeInjectEndRnNR(testCodeInjectStarSlashQuoteDoubleQuoteEqualEndBackSlashRBackSlashNBackSlashNBackSlashR);
} catch (ApiException e) {
System.err.println("Exception when calling FakeApi#testCodeInjectEndRnNR");
e.printStackTrace();
Expand All @@ -98,7 +98,7 @@ public class FakeApiExample {

## Documentation for API Endpoints

All URIs are relative to *petstore.swagger.io *_/ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r/v2 *_/ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r*
All URIs are relative to *http://petstore.swagger.io *_/ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r/v2 *_/ &#39; \&quot; &#x3D;end -- \\r\\n \\n \\r*

Class | Method | HTTP request | Description
------------ | ------------- | ------------- | -------------
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
apply plugin: 'idea'
apply plugin: 'eclipse'
apply plugin: 'java'

group = 'org.openapitools'
version = '1.0.0'

buildscript {
repositories {
mavenCentral()
jcenter()
}
dependencies {
Expand All @@ -17,7 +19,9 @@ buildscript {
repositories {
jcenter()
}

sourceSets {
main.java.srcDirs = ['src/main/java']
}

if(hasProperty('target') && target == 'android') {

Expand Down Expand Up @@ -94,12 +98,13 @@ if(hasProperty('target') && target == 'android') {
}

dependencies {
compile 'io.swagger:swagger-annotations:1.5.17'
compile 'com.squareup.okhttp:okhttp:2.7.5'
compile 'com.squareup.okhttp:logging-interceptor:2.7.5'
compile 'com.google.code.gson:gson:2.8.1'
compile 'io.swagger:swagger-annotations:1.5.21'
compile 'com.squareup.okhttp3:okhttp:3.12.1'
compile 'com.squareup.okhttp3:logging-interceptor:3.12.1'
compile 'com.google.code.gson:gson:2.8.5'
compile 'io.gsonfire:gson-fire:1.8.0'
compile group: 'org.apache.oltu.oauth2', name: 'org.apache.oltu.oauth2.client', version: '1.0.1'
compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.8.1'
compile 'org.threeten:threetenbp:1.3.5'
testCompile 'junit:junit:4.12'
}
10 changes: 6 additions & 4 deletions samples/client/petstore-security-test/java/okhttp-gson/build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@ lazy val root = (project in file(".")).
publishArtifact in (Compile, packageDoc) := false,
resolvers += Resolver.mavenLocal,
libraryDependencies ++= Seq(
"io.swagger" % "swagger-annotations" % "1.5.17",
"com.squareup.okhttp" % "okhttp" % "2.7.5",
"com.squareup.okhttp" % "logging-interceptor" % "2.7.5",
"com.google.code.gson" % "gson" % "2.8.1",
"io.swagger" % "swagger-annotations" % "1.5.21",
"com.squareup.okhttp3" % "okhttp" % "3.12.1",
"com.squareup.okhttp3" % "logging-interceptor" % "3.12.1",
"com.google.code.gson" % "gson" % "2.8.5",
"org.apache.commons" % "commons-lang3" % "3.8.1",
"org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1",
"org.threeten" % "threetenbp" % "1.3.5" % "compile",
"io.gsonfire" % "gson-fire" % "1.8.0" % "compile",
"junit" % "junit" % "4.12" % "test",
Expand Down
Loading

0 comments on commit fde3252

Please sign in to comment.