diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/ApiClient.mustache deleted file mode 100644 index c4c422b7ba0c..000000000000 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/ApiClient.mustache +++ /dev/null @@ -1,448 +0,0 @@ -package {{invokerPackage}}; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Type; -import java.util.LinkedHashMap; -import java.util.Map; - -{{#hasOAuthMethods}} -import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; -import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; -{{/hasOAuthMethods}} - -import org.joda.time.DateTime; -import org.joda.time.LocalDate; -import org.joda.time.format.DateTimeFormatter; -import org.joda.time.format.ISODateTimeFormat; - -import retrofit.RestAdapter; -import retrofit.client.OkClient; -import retrofit.converter.ConversionException; -import retrofit.converter.Converter; -import retrofit.converter.GsonConverter; -import retrofit.mime.TypedByteArray; -import retrofit.mime.TypedInput; -import retrofit.mime.TypedOutput; - -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonParseException; -import com.google.gson.TypeAdapter; -import com.google.gson.stream.JsonReader; -import com.google.gson.stream.JsonWriter; -import com.squareup.okhttp.Interceptor; -import com.squareup.okhttp.OkHttpClient; - -import {{invokerPackage}}.auth.HttpBasicAuth; -import {{invokerPackage}}.auth.HttpBearerAuth; -import {{invokerPackage}}.auth.ApiKeyAuth; -{{#hasOAuthMethods}} -import {{invokerPackage}}.auth.OAuth; -import {{invokerPackage}}.auth.OAuth.AccessTokenListener; -import {{invokerPackage}}.auth.OAuthFlow; -{{/hasOAuthMethods}} - -public class ApiClient { - - private Map apiAuthorizations; - private OkHttpClient okClient; - private RestAdapter.Builder adapterBuilder; - - public ApiClient() { - apiAuthorizations = new LinkedHashMap(); - createDefaultAdapter(); - } - - public ApiClient(String[] authNames) { - this(); - for(String authName : authNames) { - {{#hasAuthMethods}} - Interceptor auth = null; - {{#authMethods}}if ("{{name}}".equals(authName)) { - {{#isBasicBasic}} - auth = new HttpBasicAuth(); - {{/isBasicBasic}} - {{#isBasicBearer}} - auth = new HttpBearerAuth("{{scheme}}"); - {{/isBasicBearer}} - {{#isApiKey}} - auth = new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{#isKeyInQuery}}"query"{{/isKeyInQuery}}{{#isKeyInCookie}}"cookie"{{/isKeyInCookie}}, "{{keyParamName}}"); - {{/isApiKey}} - {{#isOAuth}} - auth = new OAuth(OAuthFlow.{{flow}}, "{{{authorizationUrl}}}", "{{{tokenUrl}}}", "{{#scopes}}{{scope}}{{^-last}}, {{/-last}}{{/scopes}}"); - {{/isOAuth}} - } else {{/authMethods}}{ - throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); - } - if (auth != null) { - addAuthorization(authName, auth); - } - {{/hasAuthMethods}} - {{^hasAuthMethods}} - throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); - {{/hasAuthMethods}} - } - } - - /** - * Basic constructor for single auth name - * @param authName Authentication name - */ - public ApiClient(String authName) { - this(new String[]{authName}); - } - - /** - * Helper constructor for single api key - * @param authName Authentication name - * @param apiKey API key - */ - public ApiClient(String authName, String apiKey) { - this(authName); - this.setApiKey(apiKey); - } - - /** - * Helper constructor for single basic auth or password oauth2 - * @param authName Authentication name - * @param username Username - * @param password Password - */ - public ApiClient(String authName, String username, String password) { - this(authName); - this.setCredentials(username, password); - } - - {{#hasOAuthMethods}} - /** - * Helper constructor for single password oauth2 - * @param authName Authentication name - * @param clientId Client ID - * @param secret Client secret - * @param username Username - * @param password Password - */ - public ApiClient(String authName, String clientId, String secret, String username, String password) { - this(authName); - this.getTokenEndPoint() - .setClientId(clientId) - .setClientSecret(secret) - .setUsername(username) - .setPassword(password); - } - - {{/hasOAuthMethods}} - public void createDefaultAdapter() { - Gson gson = new GsonBuilder() - .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") - .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) - .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter()) - .create(); - - okClient = new OkHttpClient(); - - adapterBuilder = new RestAdapter - .Builder() - .setEndpoint("{{{basePath}}}") - .setClient(new OkClient(okClient)) - .setConverter(new GsonConverterWrapper(gson)); - } - - public S createService(Class serviceClass) { - return adapterBuilder.build().create(serviceClass); - - } - - /** - * Helper method to configure the first api key found - * @param apiKey API key - */ - private void setApiKey(String apiKey) { - for(Interceptor apiAuthorization : apiAuthorizations.values()) { - if (apiAuthorization instanceof ApiKeyAuth) { - ApiKeyAuth keyAuth = (ApiKeyAuth) apiAuthorization; - keyAuth.setApiKey(apiKey); - return; - } - } - } - - /** - * Helper method to set token for the first Http Bearer authentication found. - * @param bearerToken Bearer token - */ - public void setBearerToken(String bearerToken) { - for (Interceptor apiAuthorization : apiAuthorizations.values()) { - if (apiAuthorization instanceof HttpBearerAuth) { - ((HttpBearerAuth) apiAuthorization).setBearerToken(bearerToken); - return; - } - } - } - - /** - * Helper method to configure the username/password for basic auth or password oauth - * @param username Username - * @param password Password - */ - private void setCredentials(String username, String password) { - for(Interceptor apiAuthorization : apiAuthorizations.values()) { - if (apiAuthorization instanceof HttpBasicAuth) { - HttpBasicAuth basicAuth = (HttpBasicAuth) apiAuthorization; - basicAuth.setCredentials(username, password); - return; - } - {{#hasOAuthMethods}} - if (apiAuthorization instanceof OAuth) { - OAuth oauth = (OAuth) apiAuthorization; - oauth.getTokenRequestBuilder().setUsername(username).setPassword(password); - return; - } - {{/hasOAuthMethods}} - } - } - - {{#hasOAuthMethods}} - /** - * Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one) - * @return Token request builder - */ - public TokenRequestBuilder getTokenEndPoint() { - for(Interceptor apiAuthorization : apiAuthorizations.values()) { - if (apiAuthorization instanceof OAuth) { - OAuth oauth = (OAuth) apiAuthorization; - return oauth.getTokenRequestBuilder(); - } - } - return null; - } - - /** - * Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one) - * @return Authentication request builder - */ - public AuthenticationRequestBuilder getAuthorizationEndPoint() { - for(Interceptor apiAuthorization : apiAuthorizations.values()) { - if (apiAuthorization instanceof OAuth) { - OAuth oauth = (OAuth) apiAuthorization; - return oauth.getAuthenticationRequestBuilder(); - } - } - return null; - } - - /** - * Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one) - * @param accessToken Access token - */ - public void setAccessToken(String accessToken) { - for(Interceptor apiAuthorization : apiAuthorizations.values()) { - if (apiAuthorization instanceof OAuth) { - OAuth oauth = (OAuth) apiAuthorization; - oauth.setAccessToken(accessToken); - return; - } - } - } - - /** - * Helper method to configure the oauth accessCode/implicit flow parameters - * @param clientId Client ID - * @param clientSecret Client secret - * @param redirectURI Redirect URI - */ - public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) { - for(Interceptor apiAuthorization : apiAuthorizations.values()) { - if (apiAuthorization instanceof OAuth) { - OAuth oauth = (OAuth) apiAuthorization; - oauth.getTokenRequestBuilder() - .setClientId(clientId) - .setClientSecret(clientSecret) - .setRedirectURI(redirectURI); - oauth.getAuthenticationRequestBuilder() - .setClientId(clientId) - .setRedirectURI(redirectURI); - return; - } - } - } - - /** - * Configures a listener which is notified when a new access token is received. - * @param accessTokenListener Access token listener - */ - public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { - for(Interceptor apiAuthorization : apiAuthorizations.values()) { - if (apiAuthorization instanceof OAuth) { - OAuth oauth = (OAuth) apiAuthorization; - oauth.registerAccessTokenListener(accessTokenListener); - return; - } - } - } - {{/hasOAuthMethods}} - - /** - * Adds an authorization to be used by the client - * @param authName Authentication name - * @param authorization Authorization - */ - public void addAuthorization(String authName, Interceptor authorization) { - if (apiAuthorizations.containsKey(authName)) { - throw new RuntimeException("auth name \"" + authName + "\" already in api authorizations"); - } - apiAuthorizations.put(authName, authorization); - okClient.interceptors().add(authorization); - } - - public Map getApiAuthorizations() { - return apiAuthorizations; - } - - public void setApiAuthorizations(Map apiAuthorizations) { - this.apiAuthorizations = apiAuthorizations; - } - - public RestAdapter.Builder getAdapterBuilder() { - return adapterBuilder; - } - - public void setAdapterBuilder(RestAdapter.Builder adapterBuilder) { - this.adapterBuilder = adapterBuilder; - } - - public OkHttpClient getOkClient() { - return okClient; - } - - public void addAuthsToOkClient(OkHttpClient okClient) { - for(Interceptor apiAuthorization : apiAuthorizations.values()) { - okClient.interceptors().add(apiAuthorization); - } - } - - /** - * Clones the okClient given in parameter, adds the auth interceptors and uses it to configure the RestAdapter - * @param okClient OkHttp client - */ - public void configureFromOkclient(OkHttpClient okClient) { - OkHttpClient clone = okClient.clone(); - addAuthsToOkClient(clone); - adapterBuilder.setClient(new OkClient(clone)); - } -} - -/** - * This wrapper is to take care of this case: - * when the deserialization fails due to JsonParseException and the - * expected type is String, then just return the body string. - */ -class GsonConverterWrapper implements Converter { - private GsonConverter converter; - - public GsonConverterWrapper(Gson gson) { - converter = new GsonConverter(gson); - } - - @Override public Object fromBody(TypedInput body, Type type) throws ConversionException { - byte[] bodyBytes = readInBytes(body); - TypedByteArray newBody = new TypedByteArray(body.mimeType(), bodyBytes); - try { - return converter.fromBody(newBody, type); - } catch (ConversionException e) { - if (e.getCause() instanceof JsonParseException && type.equals(String.class)) { - return new String(bodyBytes); - } else { - throw e; - } - } - } - - @Override public TypedOutput toBody(Object object) { - return converter.toBody(object); - } - - private byte[] readInBytes(TypedInput body) throws ConversionException { - InputStream in = null; - try { - in = body.in(); - ByteArrayOutputStream os = new ByteArrayOutputStream(); - byte[] buffer = new byte[0xFFFF]; - for (int len; (len = in.read(buffer)) != -1;) - os.write(buffer, 0, len); - os.flush(); - return os.toByteArray(); - } catch (IOException e) { - throw new ConversionException(e); - } finally { - if (in != null) { - try { - in.close(); - } catch (IOException ignored) { - } - } - } - - } -} - -/** - * Gson TypeAdapter for Joda DateTime type - */ -class DateTimeTypeAdapter extends TypeAdapter { - - private final DateTimeFormatter parseFormatter = ISODateTimeFormat.dateOptionalTimeParser(); - private final DateTimeFormatter printFormatter = ISODateTimeFormat.dateTime(); - - @Override - public void write(JsonWriter out, DateTime date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - out.value(printFormatter.print(date)); - } - } - - @Override - public DateTime read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - return parseFormatter.parseDateTime(date); - } - } -} - -/** - * Gson TypeAdapter for Joda DateTime type - */ -class LocalDateTypeAdapter extends TypeAdapter { - - private final DateTimeFormatter formatter = ISODateTimeFormat.date(); - - @Override - public void write(JsonWriter out, LocalDate date) throws IOException { - if (date == null) { - out.nullValue(); - } else { - out.value(formatter.print(date)); - } - } - - @Override - public LocalDate read(JsonReader in) throws IOException { - switch (in.peek()) { - case NULL: - in.nextNull(); - return null; - default: - String date = in.nextString(); - return formatter.parseLocalDate(date); - } - } -} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/CollectionFormats.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/CollectionFormats.mustache deleted file mode 100644 index dbfa4ae767bb..000000000000 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/CollectionFormats.mustache +++ /dev/null @@ -1,99 +0,0 @@ -package {{invokerPackage}}; - -import java.util.Arrays; -import java.util.List; - -public class CollectionFormats { - - public static class CSVParams { - - protected List params; - - public CSVParams() { - } - - public CSVParams(List params) { - this.params = params; - } - - public CSVParams(String... params) { - this.params = Arrays.asList(params); - } - - public List getParams() { - return params; - } - - public void setParams(List params) { - this.params = params; - } - - @Override - public String toString() { - return StringUtil.join(params.toArray(new String[0]), ","); - } - - } - - public static class SPACEParams extends SSVParams { - - } - - public static class SSVParams extends CSVParams { - - public SSVParams() { - } - - public SSVParams(List params) { - super(params); - } - - public SSVParams(String... params) { - super(params); - } - - @Override - public String toString() { - return StringUtil.join(params.toArray(new String[0]), " "); - } - } - - public static class TSVParams extends CSVParams { - - public TSVParams() { - } - - public TSVParams(List params) { - super(params); - } - - public TSVParams(String... params) { - super(params); - } - - @Override - public String toString() { - return StringUtil.join( params.toArray(new String[0]), "\t"); - } - } - - public static class PIPESParams extends CSVParams { - - public PIPESParams() { - } - - public PIPESParams(List params) { - super(params); - } - - public PIPESParams(String... params) { - super(params); - } - - @Override - public String toString() { - return StringUtil.join(params.toArray(new String[0]), "|"); - } - } - -} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/README.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/README.mustache deleted file mode 100644 index c9877589b5ff..000000000000 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/README.mustache +++ /dev/null @@ -1,42 +0,0 @@ -# {{artifactId}} - -## Requirements - -Building the API client library requires [Maven](https://maven.apache.org/) to be installed. - -## Installation & Usage - -To install the API client library to your local Maven repository, simply execute: - -```shell -mvn install -``` - -To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: - -```shell -mvn deploy -``` - -Refer to the [official documentation](https://maven.apache.org/plugins/maven-deploy-plugin/usage.html) for more information. - -After the client library is installed/deployed, you can use it in your Maven project by adding the following to your *pom.xml*: - -```xml - - {{groupId}} - {{artifactId}} - {{artifactVersion}} - compile - - -``` - -## Recommendation - -It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. - -## Author - -{{#apiInfo}}{{#apis}}{{#-last}}{{infoEmail}} -{{/-last}}{{/apis}}{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/api.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/api.mustache deleted file mode 100644 index bd3d62f8b7a3..000000000000 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/api.mustache +++ /dev/null @@ -1,72 +0,0 @@ -package {{package}}; - -import {{invokerPackage}}.CollectionFormats.*; - -import retrofit.Callback; -import retrofit.http.*; -import retrofit.mime.*; - -{{#imports}}import {{import}}; -{{/imports}} - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -{{#operations}} -public interface {{classname}} { - {{#operation}} - /** - * {{summary}} - * Sync method - * {{notes}} -{{#allParams}} - * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} -{{/allParams}} - * @return {{returnType}}{{^returnType}}Void{{/returnType}} -{{#externalDocs}} - * {{description}} - * @see {{summary}} Documentation -{{/externalDocs}} -{{#isDeprecated}} - * @deprecated -{{/isDeprecated}} - */ - {{#isDeprecated}} - @Deprecated - {{/isDeprecated}} - {{#formParams}}{{#-first}} - {{#isMultipart}}@retrofit.http.Multipart{{/isMultipart}}{{^isMultipart}}@retrofit.http.FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} - @{{httpMethod}}("{{{path}}}") - {{{returnType}}}{{^returnType}}Void{{/returnType}} {{operationId}}({{^allParams}});{{/allParams}} - {{#allParams}}{{>libraries/retrofit/queryParams}}{{>libraries/retrofit/pathParams}}{{>libraries/retrofit/headerParams}}{{>libraries/retrofit/bodyParams}}{{>libraries/retrofit/formParams}}{{^-last}}, {{/-last}}{{#-last}} - );{{/-last}}{{/allParams}} - - /** - * {{summary}} - * Async method -{{#allParams}} - * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} -{{/allParams}} - * @param cb callback method -{{#externalDocs}} - * {{description}} - * @see {{summary}} Documentation -{{/externalDocs}} -{{#isDeprecated}} - * @deprecated -{{/isDeprecated}} - */ - {{#isDeprecated}} - @Deprecated - {{/isDeprecated}} - {{#formParams}}{{#-first}} - {{#isMultipart}}@retrofit.http.Multipart{{/isMultipart}}{{^isMultipart}}@retrofit.http.FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} - @{{httpMethod}}("{{{path}}}") - void {{operationId}}( - {{#allParams}}{{>libraries/retrofit/queryParams}}{{>libraries/retrofit/pathParams}}{{>libraries/retrofit/headerParams}}{{>libraries/retrofit/bodyParams}}{{>libraries/retrofit/formParams}}, {{/allParams}}Callback<{{{returnType}}}{{^returnType}}Void{{/returnType}}> cb - ); - {{/operation}} -} -{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/api_test.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/api_test.mustache deleted file mode 100644 index 771b84de2232..000000000000 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/api_test.mustache +++ /dev/null @@ -1,42 +0,0 @@ -package {{package}}; - -import {{invokerPackage}}.ApiClient; -{{#imports}}import {{import}}; -{{/imports}} -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * API tests for {{classname}} - */ -public class {{classname}}Test { - - private {{classname}} api; - - @Before - public void setup() { - api = new ApiClient().createService({{classname}}.class); - } - - {{#operations}}{{#operation}} - /** - * {{summary}} - * - * {{notes}} - */ - @Test - public void {{operationId}}Test() { - {{#allParams}} - {{{dataType}}} {{paramName}} = null; - {{/allParams}} - // {{#returnType}}{{{.}}} response = {{/returnType}}api.{{operationId}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); - - // TODO: test validations - } - {{/operation}}{{/operations}} -} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/auth/ApiKeyAuth.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/auth/ApiKeyAuth.mustache deleted file mode 100644 index 69205bb20832..000000000000 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/auth/ApiKeyAuth.mustache +++ /dev/null @@ -1,72 +0,0 @@ -package {{invokerPackage}}.auth; - -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; - -import com.squareup.okhttp.Interceptor; -import com.squareup.okhttp.Request; -import com.squareup.okhttp.Response; - -public class ApiKeyAuth implements Interceptor { - private final String location; - private final String paramName; - - private String apiKey; - - public ApiKeyAuth(String location, String paramName) { - this.location = location; - this.paramName = paramName; - } - - public String getLocation() { - return location; - } - - public String getParamName() { - return paramName; - } - - public String getApiKey() { - return apiKey; - } - - public void setApiKey(String apiKey) { - this.apiKey = apiKey; - } - - @Override - public Response intercept(Chain chain) throws IOException { - String paramValue; - Request request = chain.request(); - - if ("query".equals(location)) { - String newQuery = request.uri().getQuery(); - paramValue = paramName + "=" + apiKey; - if (newQuery == null) { - newQuery = paramValue; - } else { - newQuery += "&" + paramValue; - } - - URI newUri; - try { - newUri = new URI(request.uri().getScheme(), request.uri().getAuthority(), - request.uri().getPath(), newQuery, request.uri().getFragment()); - } catch (URISyntaxException e) { - throw new IOException(e); - } - - request = request.newBuilder().url(newUri.toURL()).build(); - } else if ("header".equals(location)) { - request = request.newBuilder() - .addHeader(paramName, apiKey) - .build(); - } else if ("cookie".equals(location)) { - request = request.newBuilder() - .addHeader("Cookie", String.format("%s=%s", paramName, apiKey)) - .build(); - } - return chain.proceed(request); - } -} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/auth/HttpBasicAuth.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/auth/HttpBasicAuth.mustache deleted file mode 100644 index cf82b2775a7d..000000000000 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/auth/HttpBasicAuth.mustache +++ /dev/null @@ -1,49 +0,0 @@ -package {{invokerPackage}}.auth; - -import java.io.IOException; - -import com.squareup.okhttp.Credentials; -import com.squareup.okhttp.Interceptor; -import com.squareup.okhttp.Request; -import com.squareup.okhttp.Response; - -public class HttpBasicAuth implements Interceptor { - - private String username; - private String password; - - public String getUsername() { - return username; - } - - public void setUsername(String username) { - this.username = username; - } - - public String getPassword() { - return password; - } - - public void setPassword(String password) { - this.password = password; - } - - public void setCredentials(String username, String password) { - this.username = username; - this.password = password; - } - - @Override - public Response intercept(Chain chain) throws IOException { - Request request = chain.request(); - - // If the request already have an authorization (eg. Basic auth), do nothing - if (request.header("Authorization") == null) { - String credentials = Credentials.basic(username, password); - request = request.newBuilder() - .addHeader("Authorization", credentials) - .build(); - } - return chain.proceed(request); - } -} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/auth/HttpBearerAuth.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/auth/HttpBearerAuth.mustache deleted file mode 100644 index 9b910c461cba..000000000000 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/auth/HttpBearerAuth.mustache +++ /dev/null @@ -1,42 +0,0 @@ -package {{invokerPackage}}.auth; - -import java.io.IOException; - -import com.squareup.okhttp.Interceptor; -import com.squareup.okhttp.Request; -import com.squareup.okhttp.Response; - -public class HttpBearerAuth implements Interceptor { - private final String scheme; - private String bearerToken; - - public HttpBearerAuth(String scheme) { - this.scheme = scheme; - } - - public String getBearerToken() { - return bearerToken; - } - - public void setBearerToken(String bearerToken) { - this.bearerToken = bearerToken; - } - - @Override - public Response intercept(Chain chain) throws IOException { - Request request = chain.request(); - - // If the request already have an authorization (eg. Basic auth), do nothing - if (request.header("Authorization") == null && bearerToken != null) { - request = request.newBuilder() - .addHeader("Authorization", (scheme != null ? upperCaseBearer(scheme) + " " : "") + bearerToken) - .build(); - } - return chain.proceed(request); - } - - private static String upperCaseBearer(String scheme) { - return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme; - } - -} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/auth/OAuth.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/auth/OAuth.mustache deleted file mode 100644 index bc0bad711446..000000000000 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/auth/OAuth.mustache +++ /dev/null @@ -1,185 +0,0 @@ -package {{invokerPackage}}.auth; - -import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; -import static java.net.HttpURLConnection.HTTP_FORBIDDEN; - -import java.io.IOException; -import java.util.Map; - -import org.apache.oltu.oauth2.client.OAuthClient; -import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest; -import org.apache.oltu.oauth2.client.request.OAuthClientRequest; -import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; -import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; -import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse; -import org.apache.oltu.oauth2.common.exception.OAuthProblemException; -import org.apache.oltu.oauth2.common.exception.OAuthSystemException; -import org.apache.oltu.oauth2.common.message.types.GrantType; -import org.apache.oltu.oauth2.common.token.BasicOAuthToken; - -import com.squareup.okhttp.Interceptor; -import com.squareup.okhttp.OkHttpClient; -import com.squareup.okhttp.Request; -import com.squareup.okhttp.Request.Builder; -import com.squareup.okhttp.Response; - -public class OAuth implements Interceptor { - - public interface AccessTokenListener { - public void notify(BasicOAuthToken token); - } - - private volatile String accessToken; - private OAuthClient oauthClient; - - private TokenRequestBuilder tokenRequestBuilder; - private AuthenticationRequestBuilder authenticationRequestBuilder; - - private AccessTokenListener accessTokenListener; - - public OAuth( OkHttpClient client, TokenRequestBuilder requestBuilder ) { - this.oauthClient = new OAuthClient(new OAuthOkHttpClient(client)); - this.tokenRequestBuilder = requestBuilder; - } - - public OAuth(TokenRequestBuilder requestBuilder ) { - this(new OkHttpClient(), requestBuilder); - } - - public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { - this(OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes)); - setFlow(flow); - authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl); - } - - public void setFlow(OAuthFlow flow) { - switch(flow) { - case ACCESS_CODE: - case IMPLICIT: - tokenRequestBuilder.setGrantType(GrantType.AUTHORIZATION_CODE); - break; - case PASSWORD: - tokenRequestBuilder.setGrantType(GrantType.PASSWORD); - break; - case APPLICATION: - tokenRequestBuilder.setGrantType(GrantType.CLIENT_CREDENTIALS); - break; - default: - break; - } - } - - @Override - public Response intercept(Chain chain) - throws IOException { - - return retryingIntercept(chain, true); - } - - private Response retryingIntercept(Chain chain, boolean updateTokenAndRetryOnAuthorizationFailure) throws IOException { - Request request = chain.request(); - - // If the request already have an authorization (eg. Basic auth), do nothing - if (request.header("Authorization") != null) { - return chain.proceed(request); - } - - // If first time, get the token - OAuthClientRequest oAuthRequest; - if (getAccessToken() == null) { - updateAccessToken(null); - } - - if (getAccessToken() != null) { - // Build the request - Builder rb = request.newBuilder(); - - String requestAccessToken = new String(getAccessToken()); - try { - oAuthRequest = new OAuthBearerClientRequest(request.urlString()) - .setAccessToken(requestAccessToken) - .buildHeaderMessage(); - } catch (OAuthSystemException e) { - throw new IOException(e); - } - - for ( Map.Entry header : oAuthRequest.getHeaders().entrySet() ) { - rb.addHeader(header.getKey(), header.getValue()); - } - rb.url( oAuthRequest.getLocationUri()); - - //Execute the request - Response response = chain.proceed(rb.build()); - - // 401/403 most likely indicates that access token has expired. Unless it happens two times in a row. - if ( response != null && (response.code() == HTTP_UNAUTHORIZED || response.code() == HTTP_FORBIDDEN) && updateTokenAndRetryOnAuthorizationFailure ) { - try { - if (updateAccessToken(requestAccessToken)) { - response.body().close(); - return retryingIntercept( chain, false ); - } - } catch (Exception e) { - response.body().close(); - throw e; - } - } - return response; - } else { - return chain.proceed(chain.request()); - } - } - - /* - * Returns true if the access token has been updated - */ - public synchronized boolean updateAccessToken(String requestAccessToken) throws IOException { - if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) { - try { - OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(this.tokenRequestBuilder.buildBodyMessage()); - if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) { - setAccessToken(accessTokenResponse.getAccessToken()); - if (accessTokenListener != null) { - accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); - } - return !getAccessToken().equals(requestAccessToken); - } else { - return false; - } - } catch (OAuthSystemException e) { - throw new IOException(e); - } catch (OAuthProblemException e) { - throw new IOException(e); - } - } - return true; - } - - public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { - this.accessTokenListener = accessTokenListener; - } - - public synchronized String getAccessToken() { - return accessToken; - } - - public synchronized void setAccessToken(String accessToken) { - this.accessToken = accessToken; - } - - public TokenRequestBuilder getTokenRequestBuilder() { - return tokenRequestBuilder; - } - - public void setTokenRequestBuilder(TokenRequestBuilder tokenRequestBuilder) { - this.tokenRequestBuilder = tokenRequestBuilder; - } - - public AuthenticationRequestBuilder getAuthenticationRequestBuilder() { - return authenticationRequestBuilder; - } - - public void setAuthenticationRequestBuilder(AuthenticationRequestBuilder authenticationRequestBuilder) { - this.authenticationRequestBuilder = authenticationRequestBuilder; - } - -} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/auth/OAuthOkHttpClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/auth/OAuthOkHttpClient.mustache deleted file mode 100644 index 48fc7ea4c1fc..000000000000 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/auth/OAuthOkHttpClient.mustache +++ /dev/null @@ -1,69 +0,0 @@ -package {{invokerPackage}}.auth; - -import java.io.IOException; -import java.util.Map; -import java.util.Map.Entry; - -import org.apache.oltu.oauth2.client.HttpClient; -import org.apache.oltu.oauth2.client.request.OAuthClientRequest; -import org.apache.oltu.oauth2.client.response.OAuthClientResponse; -import org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory; -import org.apache.oltu.oauth2.common.exception.OAuthProblemException; -import org.apache.oltu.oauth2.common.exception.OAuthSystemException; - -import com.squareup.okhttp.MediaType; -import com.squareup.okhttp.OkHttpClient; -import com.squareup.okhttp.Request; -import com.squareup.okhttp.RequestBody; -import com.squareup.okhttp.Response; - - -public class OAuthOkHttpClient implements HttpClient { - - private OkHttpClient client; - - public OAuthOkHttpClient() { - this.client = new OkHttpClient(); - } - - public OAuthOkHttpClient(OkHttpClient client) { - this.client = client; - } - - public T execute(OAuthClientRequest request, Map headers, - String requestMethod, Class responseClass) - throws OAuthSystemException, OAuthProblemException { - - MediaType mediaType = MediaType.parse("application/json"); - Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri()); - - if(headers != null) { - for (Entry entry : headers.entrySet()) { - if (entry.getKey().equalsIgnoreCase("Content-Type")) { - mediaType = MediaType.parse(entry.getValue()); - } else { - requestBuilder.addHeader(entry.getKey(), entry.getValue()); - } - } - } - - RequestBody body = request.getBody() != null ? RequestBody.create(mediaType, request.getBody()) : null; - requestBuilder.method(requestMethod, body); - - try { - Response response = client.newCall(requestBuilder.build()).execute(); - return OAuthClientResponseFactory.createCustomResponse( - response.body().string(), - response.body().contentType().toString(), - response.code(), - responseClass); - } catch (IOException e) { - throw new OAuthSystemException(e); - } - } - - public void shutdown() { - // Nothing to do here - } - -} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/bodyParams.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/bodyParams.mustache deleted file mode 100644 index 81de324b691f..000000000000 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/bodyParams.mustache +++ /dev/null @@ -1 +0,0 @@ -{{#isBodyParam}}@retrofit.http.Body {{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/build.gradle.mustache deleted file mode 100644 index 2496d2edb50f..000000000000 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/build.gradle.mustache +++ /dev/null @@ -1,118 +0,0 @@ -apply plugin: 'idea' -apply plugin: 'eclipse' - -group = '{{groupId}}' -version = '{{artifactVersion}}' - -buildscript { - repositories { - mavenCentral() - } - dependencies { - classpath 'com.android.tools.build:gradle:2.3.+' - classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5' - } -} - -repositories { - mavenCentral() -} - - -if(hasProperty('target') && target == 'android') { - - apply plugin: 'com.android.library' - apply plugin: 'com.github.dcendents.android-maven' - - android { - compileSdkVersion 25 - buildToolsVersion '25.0.2' - defaultConfig { - minSdkVersion 14 - targetSdkVersion 25 - } - compileOptions { - sourceCompatibility JavaVersion.VERSION_1_8 - targetCompatibility JavaVersion.VERSION_1_8 - } - - // Rename the aar correctly - libraryVariants.all { variant -> - variant.outputs.each { output -> - def outputFile = output.outputFile - if (outputFile != null && outputFile.name.endsWith('.aar')) { - def fileName = "${project.name}-${variant.baseName}-${version}.aar" - output.outputFile = new File(outputFile.parent, fileName) - } - } - } - - dependencies { - provided "jakarta.annotation:jakarta.annotation-api:$jakarta_annotation_version" - } - } - - afterEvaluate { - android.libraryVariants.all { variant -> - def task = project.tasks.create "jar${variant.name.capitalize()}", Jar - task.description = "Create jar artifact for ${variant.name}" - task.dependsOn variant.javaCompile - task.from variant.javaCompile.destinationDirectory - task.destinationDirectory = project.file("${project.buildDir}/outputs/jar") - task.archiveFileName = "${project.name}-${variant.baseName}-${version}.jar" - artifacts.add('archives', task); - } - } - - task sourcesJar(type: Jar) { - from android.sourceSets.main.java.srcDirs - classifier = 'sources' - } - - artifacts { - archives sourcesJar - } - -} else { - - apply plugin: 'java' - apply plugin: 'maven-publish' - - sourceCompatibility = JavaVersion.VERSION_1_7 - targetCompatibility = JavaVersion.VERSION_1_7 - - publishing { - publications { - maven(MavenPublication) { - artifactId = '{{artifactId}}' - from components.java - } - } - } - - task execute(type:JavaExec) { - main = System.getProperty('mainClass') - classpath = sourceSets.main.runtimeClasspath - } -} - -ext { - okhttp_version = "2.7.5" - oltu_version = "1.0.1" - retrofit_version = "1.9.0" - swagger_annotations_version = "1.5.21" - jakarta_annotation_version = "1.3.5" - junit_version = "4.13.2" - jodatime_version = "2.9.3" -} - -dependencies { - implementation "com.squareup.okhttp:okhttp:$okhttp_version" - implementation "com.google.code.findbugs:jsr305:3.0.2" - implementation "com.squareup.retrofit:retrofit:$retrofit_version" - implementation "io.swagger:swagger-annotations:$swagger_annotations_version" - implementation "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version" - implementation "joda-time:joda-time:$jodatime_version" - implementation "jakarta.annotation:jakarta.annotation-api:$jakarta_annotation_version" - testImplementation "junit:junit:$junit_version" -} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/build.sbt.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/build.sbt.mustache deleted file mode 100644 index 2cd243945a21..000000000000 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/build.sbt.mustache +++ /dev/null @@ -1,21 +0,0 @@ -lazy val root = (project in file(".")). - settings( - organization := "{{groupId}}", - name := "{{artifactId}}", - version := "{{artifactVersion}}", - scalaVersion := "2.11.4", - scalacOptions ++= Seq("-feature"), - javacOptions in compile ++= Seq("-Xlint:deprecation"), - publishArtifact in (Compile, packageDoc) := false, - resolvers += Resolver.mavenLocal, - libraryDependencies ++= Seq( - "com.squareup.okhttp" % "okhttp" % "2.7.5" % "compile", - "com.squareup.retrofit" % "retrofit" % "1.9.0" % "compile", - "io.swagger" % "swagger-annotations" % "1.5.21" % "compile", - "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", - "joda-time" % "joda-time" % "2.9.3" % "compile", - "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", - "junit" % "junit" % "4.13.2" % "test", - "com.novocode" % "junit-interface" % "0.10" % "test" - ) - ) diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/formParams.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/formParams.mustache deleted file mode 100644 index 851072b3f653..000000000000 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/formParams.mustache +++ /dev/null @@ -1 +0,0 @@ -{{#isFormParam}}{{^isFile}}{{#isMultipart}}@retrofit.http.Part{{/isMultipart}}{{^isMultipart}}@retrofit.http.Field{{/isMultipart}}("{{baseName}}") {{{dataType}}} {{paramName}}{{/isFile}}{{#isFile}}{{#isMultipart}}@retrofit.http.Part{{/isMultipart}}{{^isMultipart}}@retrofit.http.Field{{/isMultipart}}("{{baseName}}") TypedFile {{paramName}}{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/headerParams.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/headerParams.mustache deleted file mode 100644 index 5d6da4a94375..000000000000 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/headerParams.mustache +++ /dev/null @@ -1 +0,0 @@ -{{#isHeaderParam}}@retrofit.http.Header("{{baseName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/pathParams.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/pathParams.mustache deleted file mode 100644 index 7b8be8442e0d..000000000000 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/pathParams.mustache +++ /dev/null @@ -1 +0,0 @@ -{{#isPathParam}}@retrofit.http.Path("{{baseName}}") {{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/pom.mustache deleted file mode 100644 index b44c2fbd30fc..000000000000 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/pom.mustache +++ /dev/null @@ -1,293 +0,0 @@ - - 4.0.0 - {{groupId}} - {{artifactId}} - jar - {{artifactId}} - {{artifactVersion}} - {{artifactUrl}} - {{artifactDescription}} - - {{scmConnection}} - {{scmDeveloperConnection}} - {{scmUrl}} - -{{#parentOverridden}} - - {{{parentGroupId}}} - {{{parentArtifactId}}} - {{{parentVersion}}} - -{{/parentOverridden}} - - - - {{licenseName}} - {{licenseUrl}} - repo - - - - - - {{developerName}} - {{developerEmail}} - {{developerOrganization}} - {{developerOrganizationUrl}} - - - - - - - org.apache.maven.plugins - maven-enforcer-plugin - 3.0.0-M1 - - - enforce-maven - - enforce - - - - - 2.2.0 - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - 2.12 - - - - loggerPath - conf/log4j.properties - - - -Xms512m -Xmx1500m - methods - pertest - - - - maven-dependency-plugin - - - package - - copy-dependencies - - - ${project.build.directory}/lib - - - - - - - - org.apache.maven.plugins - maven-jar-plugin - 2.2 - - - - jar - test-jar - - - - - - - - - org.codehaus.mojo - build-helper-maven-plugin - 1.10 - - - add_sources - generate-sources - - add-source - - - - src/main/java - - - - - add_test_sources - generate-test-sources - - add-test-source - - - - src/test/java - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.6.1 - - 1.8 - 1.8 - - - - org.apache.maven.plugins - maven-javadoc-plugin - 3.3.2 - - none - 1.8 - - - - attach-javadocs - - jar - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.2.1 - - - attach-sources - - jar-no-fork - - - - - - - - - - sign-artifacts - - - - org.apache.maven.plugins - maven-gpg-plugin - 1.5 - - - sign-artifacts - verify - - sign - - - - - - - - - - - {{#swagger1AnnotationLibrary}} - - io.swagger - swagger-annotations - ${swagger-annotations-version} - - {{/swagger1AnnotationLibrary}} - {{#swagger2AnnotationLibrary}} - - io.swagger.core.v3 - swagger-annotations - ${swagger-annotations-version} - - {{/swagger2AnnotationLibrary}} - - - com.google.code.findbugs - jsr305 - 3.0.2 - - - com.squareup.retrofit - retrofit - ${retrofit-version} - - - org.apache.oltu.oauth2 - org.apache.oltu.oauth2.client - ${oltu-version} - - - com.squareup.okhttp - okhttp - ${okhttp-version} - - - joda-time - joda-time - ${jodatime-version} - - {{#parcelableModel}} - - - com.google.android - android - 4.1.1.4 - provided - - {{/parcelableModel}} - - jakarta.annotation - jakarta.annotation-api - ${jakarta-annotation-version} - provided - - - - junit - junit - ${junit-version} - test - - - - UTF-8 - {{#swagger1AnnotationLibrary}} - 1.6.6 - {{/swagger1AnnotationLibrary}} - {{#swagger2AnnotationLibrary}} - 2.2.15 - {{/swagger2AnnotationLibrary}} - 1.9.0 - 2.7.5 - 2.9.9 - 1.0.1 - {{#useJakartaEe}} - 2.1.1 - {{/useJakartaEe}} - {{^useJakartaEe}} - 1.3.5 - {{/useJakartaEe}} - 1.0.0 - 4.13.2 - - diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/queryParams.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/queryParams.mustache deleted file mode 100644 index 2a580ab34ec5..000000000000 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit/queryParams.mustache +++ /dev/null @@ -1 +0,0 @@ -{{#isQueryParam}}@retrofit.http.Query("{{baseName}}") {{#collectionFormat}}{{#isCollectionFormatMulti}}{{{dataType}}}{{/isCollectionFormatMulti}}{{^isCollectionFormatMulti}}{{{collectionFormat.toUpperCase}}}Params{{/isCollectionFormatMulti}}{{/collectionFormat}}{{^collectionFormat}}{{{dataType}}}{{/collectionFormat}} {{paramName}}{{/isQueryParam}} \ No newline at end of file