Skip to content
GitLab
    • Explore Projects Groups Snippets
Projects Groups Snippets
  • /
  • Help
    • Help
    • Support
    • Community forum
    • Submit feedback
    • Contribute to GitLab
  • Sign in / Register
  • O openapi-generator
  • Project information
    • Project information
    • Activity
    • Labels
    • Members
  • Repository
    • Repository
    • Files
    • Commits
    • Branches
    • Tags
    • Contributors
    • Graph
    • Compare
  • Issues 3,476
    • Issues 3,476
    • List
    • Boards
    • Service Desk
    • Milestones
  • Merge requests 402
    • Merge requests 402
  • CI/CD
    • CI/CD
    • Pipelines
    • Jobs
    • Schedules
  • Deployments
    • Deployments
    • Environments
    • Releases
  • Packages and registries
    • Packages and registries
    • Package Registry
    • Infrastructure Registry
  • Monitor
    • Monitor
    • Incidents
  • Analytics
    • Analytics
    • Value stream
    • CI/CD
    • Repository
  • Wiki
    • Wiki
  • Snippets
    • Snippets
  • Activity
  • Graph
  • Create a new issue
  • Jobs
  • Commits
  • Issue Boards
Collapse sidebar
  • OpenAPI Tools
  • openapi-generator
  • Merge requests
  • !5732

[Java][Client][vert.x] Support per-call authentication and JsonNullable in client request bodies, fix path parameter encoding

  • Review changes

  • Download
  • Email patches
  • Plain diff
Merged Administrator requested to merge github/fork/jekkel/vertx-client-fixes into master 5 years ago
  • Overview 0
  • Commits 5
  • Pipelines 0
  • Changes 24

Created by: jekkel

Extensions

Since vertx is an asynchronous/reactive toolkit usage of mutable fields of ApiClient to store authentication prohibits delegation of authentication from incoming call without recreating the client everytime (which is prohibitively expensive due to instantiation of objectmapper). This commit adds a per call authentication override which takes precedence over the mutable fields so a single client can be safely reused. To ease usage a simple builder-style auxiliary AuthInfo object is provided providing methods for each specified authentication.

A new configuration option for ApiClient has been added: timeout. It gets applied as timeout for the vertx http request.

Fixes #6428 (closed)

Request bodies have been wrongly serialized using vert.x built-in ObjectMapper instance instead of the embedded instance thus usage of beans with JsonNullable wrapped fields in request bodies led to bad requests because the required Jackson module is not registered in the vert.x mapper instance.

Fixes #6876 (closed)

Path parameters have been replaced as is in the operation path template. This breaks whenever a parameter contains reserved characters. Now all path parameters are properly URL encoded prior to replacement.

PR checklist

  • Read the contribution guidelines.
  • If contributing template-only or documentation-only changes which will change sample output, build the project before.
  • Run the shell script(s) under ./bin/ (or Windows batch scripts under.\bin\windows) to update Petstore samples related to your fix. This is important, as CI jobs will verify all generator outputs of your HEAD commit, and these must match the expectations made by your contribution. You only need to run ./bin/{LANG}-petstore.sh, ./bin/openapi3/{LANG}-petstore.sh if updating the code or mustache templates for a language ({LANG}) (e.g. php, ruby, python, etc).
  • File the PR against the correct branch: master, 4.3.x, 5.0.x. Default: master.
  • Copy the technical committee to review the pull request if your PR is targeting a particular programming language.

@bbdouglas @sreeshas @jfiala @lukoyanov @cbornet @jeff9finger @karismann @Zomzog @lwlee2608 @bkabrda

Compare
  • master (base)

and
  • latest version
    f82e2112
    5 commits, 2 years ago

24 files
+ 2679
- 922

    Preferences

    File browser
    Compare changes
modules/…/…/‎…/…/…/…/vertx‎
ApiClient‎.mustache‎ +75 -5
api.mu‎stache‎ +3 -0
apiImpl.‎mustache‎ +34 -10
api_test‎.mustache‎ +2 -2
rxApiImpl‎.mustache‎ +52 -23
samples/client/…/…‎/…/…/…/…/…/…/client‎
a‎pi‎
rxj‎ava‎
AnotherFa‎keApi.java‎ +44 -19
FakeAp‎i.java‎ +657 -258
FakeClassnameT‎ags123Api.java‎ +44 -19
PetAp‎i.java‎ +374 -143
StoreA‎pi.java‎ +151 -56
UserAp‎i.java‎ +307 -112
AnotherFa‎keApi.java‎ +3 -0
AnotherFake‎ApiImpl.java‎ +28 -6
FakeAp‎i.java‎ +29 -0
FakeApiI‎mpl.java‎ +311 -115
FakeClassnameT‎ags123Api.java‎ +3 -0
FakeClassnameTag‎s123ApiImpl.java‎ +28 -6
PetAp‎i.java‎ +19 -0
PetApiI‎mpl.java‎ +183 -66
StoreA‎pi.java‎ +9 -0
StoreApi‎Impl.java‎ +79 -25
UserAp‎i.java‎ +17 -0
UserApiI‎mpl.java‎ +152 -52
ApiClie‎nt.java‎ +75 -5
modules/openapi-generator/src/main/resources/Java/libraries/vertx/ApiClient.mustache
+ 75
- 5
  • View file @ f82e2112

  • Edit in single-file editor

  • Open in Web IDE


@@ -9,6 +9,7 @@ import {{invokerPackage}}.auth.OAuth;
{{/hasOAuthMethods}}
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
@@ -55,6 +56,7 @@ public class ApiClient {
private DateFormat dateFormat;
private ObjectMapper objectMapper;
private String downloadsDir = "";
private int timeout = -1;
public ApiClient(Vertx vertx, JsonObject config) {
Objects.requireNonNull(vertx, "Vertx must not be null");
@@ -96,6 +98,7 @@ public class ApiClient {
this.downloadsDir = config.getString("downloadsDir", this.downloadsDir);
this.config = config;
this.identifier = UUID.randomUUID().toString();
this.timeout = config.getInteger("timeout", -1);
}
public Vertx getVertx() {
@@ -428,7 +431,11 @@ public class ApiClient {
AsyncFile file = (AsyncFile) body;
request.sendStream(file, responseHandler);
} else {
request.sendJson(body, responseHandler);
try {
request.sendBuffer(Buffer.buffer(this.objectMapper.writeValueAsBytes(body)), responseHandler);
} catch (JsonProcessingException jsonProcessingException) {
responseHandler.handle(Future.failedFuture(jsonProcessingException));
}
}
}
@@ -446,14 +453,15 @@ public class ApiClient {
* @param accepts The request's Accept headers
* @param contentTypes The request's Content-Type headers
* @param authNames The authentications to apply
* @param authInfo The call specific auth override
* @param returnType The return type into which to deserialize the response
* @param resultHandler The asynchronous response handler
*/
public <T> void invokeAPI(String path, String method, List<Pair> queryParams, Object body, MultiMap headerParams,
MultiMap cookieParams, Map<String, Object> formParams, String[] accepts, String[] contentTypes, String[] authNames,
MultiMap cookieParams, Map<String, Object> formParams, String[] accepts, String[] contentTypes, String[] authNames, AuthInfo authInfo,
TypeReference<T> returnType, Handler<AsyncResult<T>> resultHandler) {
updateParamsForAuth(authNames, queryParams, headerParams, cookieParams);
updateParamsForAuth(authNames, authInfo, queryParams, headerParams, cookieParams);
if (accepts != null && accepts.length > 0) {
headerParams.add(HttpHeaders.ACCEPT, selectHeaderAccept(accepts));
@@ -465,6 +473,7 @@ public class ApiClient {
HttpMethod httpMethod = HttpMethod.valueOf(method);
HttpRequest<Buffer> request = getWebClient().requestAbs(httpMethod, basePath + path);
request.timeout(this.timeout);
if (httpMethod == HttpMethod.PATCH) {
request.putHeader("X-HTTP-Method-Override", "PATCH");
@@ -645,11 +654,72 @@ public class ApiClient {
*
* @param authNames The authentications to apply
*/
protected void updateParamsForAuth(String[] authNames, List<Pair> queryParams, MultiMap headerParams, MultiMap cookieParams) {
protected void updateParamsForAuth(String[] authNames, AuthInfo authInfo, List<Pair> queryParams, MultiMap headerParams, MultiMap cookieParams) {
for (String authName : authNames) {
Authentication auth = authentications.get(authName);
Authentication auth;
if (authInfo != null && authInfo.authentications.containsKey(authName)) {
auth = authInfo.authentications.get(authName);
} else {
auth = authentications.get(authName);
}
if (auth == null) throw new RuntimeException("Authentication undefined: " + authName);
auth.applyToParams(queryParams, headerParams, cookieParams);
}
}
public static class AuthInfo {
private final Map<String, Authentication> authentications = new LinkedHashMap<>();{{#authMethods}}{{#isBasic}}{{#isBasicBasic}}
public void add{{#lambda.titlecase}}{{name}}{{/lambda.titlecase}}Authentication(String username, String password) {
HttpBasicAuth auth = new HttpBasicAuth();
auth.setUsername(username);
auth.setPassword(password);
authentications.put("{{name}}", auth);
}{{/isBasicBasic}}{{^isBasicBasic}}
public void add{{#lambda.titlecase}}{{name}}{{/lambda.titlecase}}Authentication(String bearerToken) {
HttpBearerAuth auth = new
HttpBearerAuth("{{scheme}}");
auth.setBearerToken(bearerToken);
authentications.put("{{name}}", auth);
}{{/isBasicBasic}}{{/isBasic}}{{#isApiKey}}
public void add{{#lambda.titlecase}}{{name}}{{/lambda.titlecase}}Authentication(String apikey, String apiKeyPrefix) {
ApiKeyAuth auth = new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{#isKeyInQuery}}"query"{{/isKeyInQuery}}{{#isKeyInCookie}}"cookie"{{/isKeyInCookie}},"{{keyParamName}}");
auth.setApiKey(apikey);
auth.setApiKeyPrefix(apiKeyPrefix);
authentications.put("{{name}}", auth);
}{{/isApiKey}}{{#isOAuth}}
public void add{{#lambda.titlecase}}{{name}}{{/lambda.titlecase}}Authentication(String accessToken) {
OAuth auth = new OAuth();
auth.setAccessToken(accessToken);
authentications.put("{{name}}", auth);
}{{/isOAuth}}{{/authMethods}}{{#authMethods}}{{#isBasic}}{{#isBasicBasic}}
public static AuthInfo for{{#lambda.titlecase}}{{name}}{{/lambda.titlecase}}(String username, String password) {
AuthInfo authInfo = new AuthInfo();
authInfo.add{{#lambda.titlecase}}{{name}}{{/lambda.titlecase}}Authentication(username, password);
return authInfo;
}{{/isBasicBasic}}{{^isBasicBasic}}
public static AuthInfo for{{#lambda.titlecase}}{{name}}{{/lambda.titlecase}}Authentication(String bearerToken) {
AuthInfo authInfo = new AuthInfo();
authInfo.add{{#lambda.titlecase}}{{name}}{{/lambda.titlecase}}Authentication(bearerToken);
return authInfo;
}{{/isBasicBasic}}{{/isBasic}}{{#isApiKey}}
public static AuthInfo for{{#lambda.titlecase}}{{name}}{{/lambda.titlecase}}Authentication(String apikey, String apiKeyPrefix) {
AuthInfo authInfo = new AuthInfo();
authInfo.add{{#lambda.titlecase}}{{name}}{{/lambda.titlecase}}Authentication(apikey, apiKeyPrefix);
return authInfo;
}{{/isApiKey}}{{#isOAuth}}
public static AuthInfo for{{#lambda.titlecase}}{{name}}{{/lambda.titlecase}}Authentication(String accessToken) {
AuthInfo authInfo = new AuthInfo();
authInfo.add{{#lambda.titlecase}}{{name}}{{/lambda.titlecase}}Authentication(accessToken);
return authInfo;
}{{/isOAuth}}{{/authMethods}}
}
}
modules/openapi-generator/src/main/resources/Java/libraries/vertx/api.mustache
+ 3
- 0
  • View file @ f82e2112

  • Edit in single-file editor

  • Open in Web IDE


package {{package}};
import {{invokerPackage}}.ApiClient;
{{#imports}}import {{import}};
{{/imports}}
import io.vertx.core.AsyncResult;
@@ -14,6 +15,8 @@ public interface {{classname}} {
{{#operation}}
void {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}Handler<AsyncResult<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>> handler);
void {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}ApiClient.AuthInfo authInfo, Handler<AsyncResult<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>> handler);
{{/operation}}
{{/operations}}
}
modules/openapi-generator/src/main/resources/Java/libraries/vertx/apiImpl.mustache
+ 34
- 10
  • View file @ f82e2112

  • Edit in single-file editor

  • Open in Web IDE


@@ -11,6 +11,9 @@ import io.vertx.core.json.JsonObject;
import com.fasterxml.jackson.core.type.TypeReference;
import java.util.*;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import {{invokerPackage}}.ApiClient;
import {{invokerPackage}}.ApiException;
@@ -41,14 +44,27 @@ public class {{classname}}Impl implements {{classname}} {
{{#operation}}
/**
* {{summary}}
* {{notes}}
{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
{{/allParams}}
* @param resultHandler Asynchronous result handler
*/
* {{summary}}
* {{notes}}
{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
{{/allParams}}
* @param resultHandler Asynchronous result handler
*/
public void {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}Handler<AsyncResult<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>> resultHandler) {
{{operationId}}({{#allParams}}{{paramName}}, {{/allParams}}null, resultHandler);
}
/**
* {{summary}}
* {{notes}}
{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
{{/allParams}}
* @param authInfo per call authentication override.
* @param resultHandler Asynchronous result handler
*/
public void {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}ApiClient.AuthInfo authInfo, Handler<AsyncResult<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>> resultHandler) {
Object localVarBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
{{#allParams}}{{#required}}
// verify the required parameter '{{paramName}}' is set
@@ -58,7 +74,7 @@ public class {{classname}}Impl implements {{classname}} {
}
{{/required}}{{/allParams}}
// create path and map variables
String localVarPath = "{{{path}}}"{{#pathParams}}.replaceAll("\\{" + "{{baseName}}" + "\\}", {{{paramName}}}.toString()){{/pathParams}};
String localVarPath = "{{{path}}}"{{#pathParams}}.replaceAll("\\{" + "{{baseName}}" + "\\}", encodeParameter({{{paramName}}}.toString())){{/pathParams}};
// query params
List<Pair> localVarQueryParams = new ArrayList<>();
@@ -89,9 +105,17 @@ public class {{classname}}Impl implements {{classname}} {
String[] localVarAuthNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} };
{{#returnType}}
TypeReference<{{{returnType}}}> localVarReturnType = new TypeReference<{{{returnType}}}>() {};
apiClient.invokeAPI(localVarPath, "{{httpMethod}}", localVarQueryParams, localVarBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccepts, localVarContentTypes, localVarAuthNames, localVarReturnType, resultHandler);{{/returnType}}{{^returnType}}
apiClient.invokeAPI(localVarPath, "{{httpMethod}}", localVarQueryParams, localVarBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccepts, localVarContentTypes, localVarAuthNames, null, resultHandler);{{/returnType}}
apiClient.invokeAPI(localVarPath, "{{httpMethod}}", localVarQueryParams, localVarBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccepts, localVarContentTypes, localVarAuthNames, authInfo, localVarReturnType, resultHandler);{{/returnType}}{{^returnType}}
apiClient.invokeAPI(localVarPath, "{{httpMethod}}", localVarQueryParams, localVarBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccepts, localVarContentTypes, localVarAuthNames, authInfo, null, resultHandler);{{/returnType}}
}
{{/operation}}
private String encodeParameter(String parameter) {
try {
return URLEncoder.encode(parameter, StandardCharsets.UTF_8.name());
} catch (UnsupportedEncodingException e) {
return parameter;
}
}
}
{{/operations}}
modules/openapi-generator/src/main/resources/Java/libraries/vertx/api_test.mustache
+ 2
- 2
  • View file @ f82e2112

  • Edit in single-file editor

  • Open in Web IDE


@@ -56,8 +56,8 @@ public class {{classname}}Test {
* @param context Vertx test context for doing assertions
*/
@Test
public void {{operationId}}Test(TestContext context) {
Async async = context.async();
public void {{operationId}}Test(TestContext testContext) {
Async async = testContext.async();
{{#allParams}}
{{{dataType}}} {{paramName}} = null;
{{/allParams}}
modules/openapi-generator/src/main/resources/Java/libraries/vertx/rxApiImpl.mustache
+ 52
- 23
  • View file @ f82e2112

  • Edit in single-file editor

  • Open in Web IDE


@@ -2,6 +2,7 @@ package {{package}}.rxjava;
{{#imports}}import {{import}};
{{/imports}}
import {{invokerPackage}}.ApiClient;
import java.util.*;
@@ -13,41 +14,69 @@ import io.vertx.core.Handler;
{{#operations}}
public class {{classname}} {
private final {{package}}.{{classname}} delegate;
private final {{package}}.{{classname}} delegate;
public {{classname}}({{package}}.{{classname}} delegate) {
this.delegate = delegate;
public {{classname}}({{package}}.{{classname}} delegate) {
this.delegate = delegate;
}
public {{package}}.{{classname}} getDelegate() {
return delegate;
}
public {{package}}.{{classname}} getDelegate() {
return delegate;
}
{{#operation}}
/**
* {{summary}}
* {{notes}}
{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
{{/allParams}}
* @param resultHandler Asynchronous result handler
*/
* {{summary}}
* {{notes}}
{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
{{/allParams}}
* @param resultHandler Asynchronous result handler
*/
public void {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}Handler<AsyncResult<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>> resultHandler) {
delegate.{{operationId}}({{#allParams}}{{paramName}}, {{/allParams}}resultHandler);
}
/**
* {{summary}}
* {{notes}}
{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
{{/allParams}}
* @return Asynchronous result handler (RxJava Single)
*/
* {{summary}}
* {{notes}}
{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
{{/allParams}}
* @param authInfo call specific auth overrides
* @param resultHandler Asynchronous result handler
*/
public void {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}ApiClient.AuthInfo authInfo, Handler<AsyncResult<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>> resultHandler) {
delegate.{{operationId}}({{#allParams}}{{paramName}}, {{/allParams}}authInfo, resultHandler);
}
/**
* {{summary}}
* {{notes}}
{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
{{/allParams}}
* @return Asynchronous result handler (RxJava Single)
*/
public Single<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> rx{{operationIdCamelCase}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) {
return Single.create(new io.vertx.rx.java.SingleOnSubscribeAdapter<>(fut -> {
delegate.{{operationId}}({{#allParams}}{{paramName}}, {{/allParams}}fut);
}));
return Single.create(new io.vertx.rx.java.SingleOnSubscribeAdapter<>(fut ->
delegate.{{operationId}}({{#allParams}}{{paramName}}, {{/allParams}}fut)
));
}
/**
* {{summary}}
* {{notes}}
{{#allParams}}
* @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}
{{/allParams}}
* @param authInfo call specific auth overrides
* @return Asynchronous result handler (RxJava Single)
*/
public Single<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> rx{{operationIdCamelCase}}({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}ApiClient.AuthInfo authInfo) {
return Single.create(new io.vertx.rx.java.SingleOnSubscribeAdapter<>(fut ->
delegate.{{operationId}}({{#allParams}}{{paramName}}, {{/allParams}}authInfo, fut)
));
}
{{/operation}}
0 Assignees
None
Assign to
0 Reviewers
None
Request review from
Labels
2
Client: Java Enhancement: General
2
Client: Java Enhancement: General
    Assign labels
  • Manage project labels

Milestone
5.0.0
5.0.0 (expired)
None
Time tracking
No estimate or time spent
Lock merge request
Unlocked
1
1 participant
Administrator
Reference: OpenAPITools/openapi-generator!5732
Source branch: github/fork/jekkel/vertx-client-fixes

Menu

Explore Projects Groups Snippets