mirror of
https://github.com/OpenAPITools/openapi-generator.git
synced 2025-12-09 17:26:09 +00:00
Merge remote-tracking branch 'origin/master' into 5.1.x
This commit is contained in:
@@ -0,0 +1,124 @@
|
||||
package org.openapitools.client.apis
|
||||
|
||||
import org.openapitools.client.infrastructure.CollectionFormats.*
|
||||
import retrofit2.http.*
|
||||
import retrofit2.Call
|
||||
import okhttp3.RequestBody
|
||||
|
||||
import org.openapitools.client.models.ApiResponse
|
||||
import org.openapitools.client.models.Pet
|
||||
|
||||
import okhttp3.MultipartBody
|
||||
|
||||
interface PetApi {
|
||||
/**
|
||||
* Add a new pet to the store
|
||||
*
|
||||
* Responses:
|
||||
* - 405: Invalid input
|
||||
*
|
||||
* @param body Pet object that needs to be added to the store
|
||||
* @return [Call]<[Unit]>
|
||||
*/
|
||||
@POST("pet")
|
||||
fun addPet(@Body body: Pet): Call<Unit>
|
||||
|
||||
/**
|
||||
* Deletes a pet
|
||||
*
|
||||
* Responses:
|
||||
* - 400: Invalid pet value
|
||||
*
|
||||
* @param petId Pet id to delete
|
||||
* @param apiKey (optional)
|
||||
* @return [Call]<[Unit]>
|
||||
*/
|
||||
@DELETE("pet/{petId}")
|
||||
fun deletePet(@Path("petId") petId: kotlin.Long, @Header("api_key") apiKey: kotlin.String): Call<Unit>
|
||||
|
||||
/**
|
||||
* Finds Pets by status
|
||||
* Multiple status values can be provided with comma separated strings
|
||||
* Responses:
|
||||
* - 200: successful operation
|
||||
* - 400: Invalid status value
|
||||
*
|
||||
* @param status Status values that need to be considered for filter
|
||||
* @return [Call]<[kotlin.collections.List<Pet>]>
|
||||
*/
|
||||
@GET("pet/findByStatus")
|
||||
fun findPetsByStatus(@Query("status") status: CSVParams): Call<kotlin.collections.List<Pet>>
|
||||
|
||||
/**
|
||||
* Finds Pets by tags
|
||||
* Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.
|
||||
* Responses:
|
||||
* - 200: successful operation
|
||||
* - 400: Invalid tag value
|
||||
*
|
||||
* @param tags Tags to filter by
|
||||
* @return [Call]<[kotlin.collections.List<Pet>]>
|
||||
*/
|
||||
@Deprecated("This api was deprecated")
|
||||
@GET("pet/findByTags")
|
||||
fun findPetsByTags(@Query("tags") tags: CSVParams): Call<kotlin.collections.List<Pet>>
|
||||
|
||||
/**
|
||||
* Find pet by ID
|
||||
* Returns a single pet
|
||||
* Responses:
|
||||
* - 200: successful operation
|
||||
* - 400: Invalid ID supplied
|
||||
* - 404: Pet not found
|
||||
*
|
||||
* @param petId ID of pet to return
|
||||
* @return [Call]<[Pet]>
|
||||
*/
|
||||
@GET("pet/{petId}")
|
||||
fun getPetById(@Path("petId") petId: kotlin.Long): Call<Pet>
|
||||
|
||||
/**
|
||||
* Update an existing pet
|
||||
*
|
||||
* Responses:
|
||||
* - 400: Invalid ID supplied
|
||||
* - 404: Pet not found
|
||||
* - 405: Validation exception
|
||||
*
|
||||
* @param body Pet object that needs to be added to the store
|
||||
* @return [Call]<[Unit]>
|
||||
*/
|
||||
@PUT("pet")
|
||||
fun updatePet(@Body body: Pet): Call<Unit>
|
||||
|
||||
/**
|
||||
* Updates a pet in the store with form data
|
||||
*
|
||||
* Responses:
|
||||
* - 405: Invalid input
|
||||
*
|
||||
* @param petId ID of pet that needs to be updated
|
||||
* @param name Updated name of the pet (optional)
|
||||
* @param status Updated status of the pet (optional)
|
||||
* @return [Call]<[Unit]>
|
||||
*/
|
||||
@FormUrlEncoded
|
||||
@POST("pet/{petId}")
|
||||
fun updatePetWithForm(@Path("petId") petId: kotlin.Long, @Field("name") name: kotlin.String, @Field("status") status: kotlin.String): Call<Unit>
|
||||
|
||||
/**
|
||||
* uploads an image
|
||||
*
|
||||
* Responses:
|
||||
* - 200: successful operation
|
||||
*
|
||||
* @param petId ID of pet to update
|
||||
* @param additionalMetadata Additional data to pass to server (optional)
|
||||
* @param file file to upload (optional)
|
||||
* @return [Call]<[ApiResponse]>
|
||||
*/
|
||||
@Multipart
|
||||
@POST("pet/{petId}/uploadImage")
|
||||
fun uploadFile(@Path("petId") petId: kotlin.Long, @Part("additionalMetadata") additionalMetadata: kotlin.String, @Part file: MultipartBody.Part): Call<ApiResponse>
|
||||
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package org.openapitools.client.apis
|
||||
|
||||
import org.openapitools.client.infrastructure.CollectionFormats.*
|
||||
import retrofit2.http.*
|
||||
import retrofit2.Call
|
||||
import okhttp3.RequestBody
|
||||
|
||||
import org.openapitools.client.models.Order
|
||||
|
||||
interface StoreApi {
|
||||
/**
|
||||
* Delete purchase order by ID
|
||||
* For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
|
||||
* Responses:
|
||||
* - 400: Invalid ID supplied
|
||||
* - 404: Order not found
|
||||
*
|
||||
* @param orderId ID of the order that needs to be deleted
|
||||
* @return [Call]<[Unit]>
|
||||
*/
|
||||
@DELETE("store/order/{orderId}")
|
||||
fun deleteOrder(@Path("orderId") orderId: kotlin.String): Call<Unit>
|
||||
|
||||
/**
|
||||
* Returns pet inventories by status
|
||||
* Returns a map of status codes to quantities
|
||||
* Responses:
|
||||
* - 200: successful operation
|
||||
*
|
||||
* @return [Call]<[kotlin.collections.Map<kotlin.String, kotlin.Int>]>
|
||||
*/
|
||||
@GET("store/inventory")
|
||||
fun getInventory(): Call<kotlin.collections.Map<kotlin.String, kotlin.Int>>
|
||||
|
||||
/**
|
||||
* Find purchase order by ID
|
||||
* For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions
|
||||
* Responses:
|
||||
* - 200: successful operation
|
||||
* - 400: Invalid ID supplied
|
||||
* - 404: Order not found
|
||||
*
|
||||
* @param orderId ID of pet that needs to be fetched
|
||||
* @return [Call]<[Order]>
|
||||
*/
|
||||
@GET("store/order/{orderId}")
|
||||
fun getOrderById(@Path("orderId") orderId: kotlin.Long): Call<Order>
|
||||
|
||||
/**
|
||||
* Place an order for a pet
|
||||
*
|
||||
* Responses:
|
||||
* - 200: successful operation
|
||||
* - 400: Invalid Order
|
||||
*
|
||||
* @param body order placed for purchasing the pet
|
||||
* @return [Call]<[Order]>
|
||||
*/
|
||||
@POST("store/order")
|
||||
fun placeOrder(@Body body: Order): Call<Order>
|
||||
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package org.openapitools.client.apis
|
||||
|
||||
import org.openapitools.client.infrastructure.CollectionFormats.*
|
||||
import retrofit2.http.*
|
||||
import retrofit2.Call
|
||||
import okhttp3.RequestBody
|
||||
|
||||
import org.openapitools.client.models.User
|
||||
|
||||
interface UserApi {
|
||||
/**
|
||||
* Create user
|
||||
* This can only be done by the logged in user.
|
||||
* Responses:
|
||||
* - 0: successful operation
|
||||
*
|
||||
* @param body Created user object
|
||||
* @return [Call]<[Unit]>
|
||||
*/
|
||||
@POST("user")
|
||||
fun createUser(@Body body: User): Call<Unit>
|
||||
|
||||
/**
|
||||
* Creates list of users with given input array
|
||||
*
|
||||
* Responses:
|
||||
* - 0: successful operation
|
||||
*
|
||||
* @param body List of user object
|
||||
* @return [Call]<[Unit]>
|
||||
*/
|
||||
@POST("user/createWithArray")
|
||||
fun createUsersWithArrayInput(@Body body: kotlin.collections.List<User>): Call<Unit>
|
||||
|
||||
/**
|
||||
* Creates list of users with given input array
|
||||
*
|
||||
* Responses:
|
||||
* - 0: successful operation
|
||||
*
|
||||
* @param body List of user object
|
||||
* @return [Call]<[Unit]>
|
||||
*/
|
||||
@POST("user/createWithList")
|
||||
fun createUsersWithListInput(@Body body: kotlin.collections.List<User>): Call<Unit>
|
||||
|
||||
/**
|
||||
* Delete user
|
||||
* This can only be done by the logged in user.
|
||||
* Responses:
|
||||
* - 400: Invalid username supplied
|
||||
* - 404: User not found
|
||||
*
|
||||
* @param username The name that needs to be deleted
|
||||
* @return [Call]<[Unit]>
|
||||
*/
|
||||
@DELETE("user/{username}")
|
||||
fun deleteUser(@Path("username") username: kotlin.String): Call<Unit>
|
||||
|
||||
/**
|
||||
* Get user by user name
|
||||
*
|
||||
* Responses:
|
||||
* - 200: successful operation
|
||||
* - 400: Invalid username supplied
|
||||
* - 404: User not found
|
||||
*
|
||||
* @param username The name that needs to be fetched. Use user1 for testing.
|
||||
* @return [Call]<[User]>
|
||||
*/
|
||||
@GET("user/{username}")
|
||||
fun getUserByName(@Path("username") username: kotlin.String): Call<User>
|
||||
|
||||
/**
|
||||
* Logs user into the system
|
||||
*
|
||||
* Responses:
|
||||
* - 200: successful operation
|
||||
* - 400: Invalid username/password supplied
|
||||
*
|
||||
* @param username The user name for login
|
||||
* @param password The password for login in clear text
|
||||
* @return [Call]<[kotlin.String]>
|
||||
*/
|
||||
@GET("user/login")
|
||||
fun loginUser(@Query("username") username: kotlin.String, @Query("password") password: kotlin.String): Call<kotlin.String>
|
||||
|
||||
/**
|
||||
* Logs out current logged in user session
|
||||
*
|
||||
* Responses:
|
||||
* - 0: successful operation
|
||||
*
|
||||
* @return [Call]<[Unit]>
|
||||
*/
|
||||
@GET("user/logout")
|
||||
fun logoutUser(): Call<Unit>
|
||||
|
||||
/**
|
||||
* Updated user
|
||||
* This can only be done by the logged in user.
|
||||
* Responses:
|
||||
* - 400: Invalid user supplied
|
||||
* - 404: User not found
|
||||
*
|
||||
* @param username name that need to be deleted
|
||||
* @param body Updated user object
|
||||
* @return [Call]<[Unit]>
|
||||
*/
|
||||
@PUT("user/{username}")
|
||||
fun updateUser(@Path("username") username: kotlin.String, @Body body: User): Call<Unit>
|
||||
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package org.openapitools.client.auth
|
||||
|
||||
import java.io.IOException
|
||||
import java.net.URI
|
||||
import java.net.URISyntaxException
|
||||
|
||||
import okhttp3.Interceptor
|
||||
import okhttp3.Response
|
||||
|
||||
class ApiKeyAuth(
|
||||
private val location: String = "",
|
||||
private val paramName: String = "",
|
||||
private var apiKey: String = ""
|
||||
) : Interceptor {
|
||||
|
||||
@Throws(IOException::class)
|
||||
override fun intercept(chain: Interceptor.Chain): Response {
|
||||
var request = chain.request()
|
||||
|
||||
if ("query" == location) {
|
||||
var newQuery = request.url.toUri().query
|
||||
val paramValue = "$paramName=$apiKey"
|
||||
if (newQuery == null) {
|
||||
newQuery = paramValue
|
||||
} else {
|
||||
newQuery += "&$paramValue"
|
||||
}
|
||||
|
||||
val newUri: URI
|
||||
try {
|
||||
val oldUri = request.url.toUri()
|
||||
newUri = URI(oldUri.scheme, oldUri.authority,
|
||||
oldUri.path, newQuery, oldUri.fragment)
|
||||
} catch (e: URISyntaxException) {
|
||||
throw IOException(e)
|
||||
}
|
||||
|
||||
request = request.newBuilder().url(newUri.toURL()).build()
|
||||
} else if ("header" == location) {
|
||||
request = request.newBuilder()
|
||||
.addHeader(paramName, apiKey)
|
||||
.build()
|
||||
} else if ("cookie" == location) {
|
||||
request = request.newBuilder()
|
||||
.addHeader("Cookie", "$paramName=$apiKey")
|
||||
.build()
|
||||
}
|
||||
return chain.proceed(request)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package org.openapitools.client.auth
|
||||
|
||||
import java.net.HttpURLConnection.HTTP_UNAUTHORIZED
|
||||
import java.net.HttpURLConnection.HTTP_FORBIDDEN
|
||||
|
||||
import java.io.IOException
|
||||
|
||||
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.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 okhttp3.Interceptor
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.Response
|
||||
|
||||
class OAuth(
|
||||
client: OkHttpClient,
|
||||
var tokenRequestBuilder: TokenRequestBuilder
|
||||
) : Interceptor {
|
||||
|
||||
interface AccessTokenListener {
|
||||
fun notify(token: BasicOAuthToken)
|
||||
}
|
||||
|
||||
private var oauthClient: OAuthClient = OAuthClient(OAuthOkHttpClient(client))
|
||||
|
||||
@Volatile
|
||||
private var accessToken: String? = null
|
||||
var authenticationRequestBuilder: AuthenticationRequestBuilder? = null
|
||||
private var accessTokenListener: AccessTokenListener? = null
|
||||
|
||||
constructor(
|
||||
requestBuilder: TokenRequestBuilder
|
||||
) : this(
|
||||
OkHttpClient(),
|
||||
requestBuilder
|
||||
)
|
||||
|
||||
constructor(
|
||||
flow: OAuthFlow,
|
||||
authorizationUrl: String,
|
||||
tokenUrl: String,
|
||||
scopes: String
|
||||
) : this(
|
||||
OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes)
|
||||
) {
|
||||
setFlow(flow);
|
||||
authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl);
|
||||
}
|
||||
|
||||
fun setFlow(flow: OAuthFlow) {
|
||||
when (flow) {
|
||||
OAuthFlow.accessCode, OAuthFlow.implicit ->
|
||||
tokenRequestBuilder.setGrantType(GrantType.AUTHORIZATION_CODE)
|
||||
OAuthFlow.password ->
|
||||
tokenRequestBuilder.setGrantType(GrantType.PASSWORD)
|
||||
OAuthFlow.application ->
|
||||
tokenRequestBuilder.setGrantType(GrantType.CLIENT_CREDENTIALS)
|
||||
}
|
||||
}
|
||||
|
||||
@Throws(IOException::class)
|
||||
override fun intercept(chain: Interceptor.Chain): Response {
|
||||
return retryingIntercept(chain, true)
|
||||
}
|
||||
|
||||
@Throws(IOException::class)
|
||||
private fun retryingIntercept(chain: Interceptor.Chain, updateTokenAndRetryOnAuthorizationFailure: Boolean): Response {
|
||||
var 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
|
||||
val oAuthRequest: OAuthClientRequest
|
||||
if (accessToken == null) {
|
||||
updateAccessToken(null)
|
||||
}
|
||||
|
||||
if (accessToken != null) {
|
||||
// Build the request
|
||||
val rb = request.newBuilder()
|
||||
|
||||
val requestAccessToken = accessToken
|
||||
try {
|
||||
oAuthRequest = OAuthBearerClientRequest(request.url.toString())
|
||||
.setAccessToken(requestAccessToken)
|
||||
.buildHeaderMessage()
|
||||
} catch (e: OAuthSystemException) {
|
||||
throw IOException(e)
|
||||
}
|
||||
|
||||
oAuthRequest.headers.entries.forEach { header ->
|
||||
rb.addHeader(header.key, header.value)
|
||||
}
|
||||
rb.url(oAuthRequest.locationUri)
|
||||
|
||||
//Execute the request
|
||||
val 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.code == HTTP_UNAUTHORIZED || response.code == HTTP_FORBIDDEN) && updateTokenAndRetryOnAuthorizationFailure) {
|
||||
try {
|
||||
if (updateAccessToken(requestAccessToken)) {
|
||||
response.body?.close()
|
||||
return retryingIntercept(chain, false)
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
response.body?.close()
|
||||
throw e
|
||||
}
|
||||
}
|
||||
return response
|
||||
} else {
|
||||
return chain.proceed(chain.request())
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the access token has been updated
|
||||
*/
|
||||
@Throws(IOException::class)
|
||||
@Synchronized
|
||||
fun updateAccessToken(requestAccessToken: String?): Boolean {
|
||||
if (accessToken == null || accessToken.equals(requestAccessToken)) {
|
||||
return try {
|
||||
val accessTokenResponse = oauthClient.accessToken(this.tokenRequestBuilder.buildBodyMessage())
|
||||
if (accessTokenResponse != null && accessTokenResponse.accessToken != null) {
|
||||
accessToken = accessTokenResponse.accessToken
|
||||
accessTokenListener?.notify(accessTokenResponse.oAuthToken as BasicOAuthToken)
|
||||
!accessToken.equals(requestAccessToken)
|
||||
} else {
|
||||
false
|
||||
}
|
||||
} catch (e: OAuthSystemException) {
|
||||
throw IOException(e)
|
||||
} catch (e: OAuthProblemException) {
|
||||
throw IOException(e)
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package org.openapitools.client.auth
|
||||
|
||||
enum class OAuthFlow {
|
||||
accessCode, implicit, password, application
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package org.openapitools.client.auth
|
||||
|
||||
import java.io.IOException
|
||||
|
||||
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 okhttp3.OkHttpClient
|
||||
import okhttp3.Request
|
||||
import okhttp3.MediaType.Companion.toMediaTypeOrNull
|
||||
import okhttp3.RequestBody
|
||||
|
||||
|
||||
class OAuthOkHttpClient(
|
||||
private var client: OkHttpClient
|
||||
) : HttpClient {
|
||||
|
||||
constructor() : this(OkHttpClient())
|
||||
|
||||
@Throws(OAuthSystemException::class, OAuthProblemException::class)
|
||||
override fun <T : OAuthClientResponse?> execute(
|
||||
request: OAuthClientRequest,
|
||||
headers: Map<String, String>?,
|
||||
requestMethod: String,
|
||||
responseClass: Class<T>?): T {
|
||||
|
||||
var mediaType = "application/json".toMediaTypeOrNull()
|
||||
val requestBuilder = Request.Builder().url(request.locationUri)
|
||||
|
||||
headers?.forEach { entry ->
|
||||
if (entry.key.equals("Content-Type", true)) {
|
||||
mediaType = entry.value.toMediaTypeOrNull()
|
||||
} else {
|
||||
requestBuilder.addHeader(entry.key, entry.value)
|
||||
}
|
||||
}
|
||||
|
||||
val body: RequestBody? = if (request.body != null) RequestBody.create(mediaType, request.body) else null
|
||||
requestBuilder.method(requestMethod, body)
|
||||
|
||||
try {
|
||||
val response = client.newCall(requestBuilder.build()).execute()
|
||||
return OAuthClientResponseFactory.createCustomResponse(
|
||||
response.body?.string(),
|
||||
response.body?.contentType()?.toString(),
|
||||
response.code,
|
||||
responseClass)
|
||||
} catch (e: IOException) {
|
||||
throw OAuthSystemException(e)
|
||||
}
|
||||
}
|
||||
|
||||
override fun shutdown() {
|
||||
// Nothing to do here
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
package org.openapitools.client.infrastructure
|
||||
|
||||
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder
|
||||
import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder
|
||||
import org.openapitools.client.auth.ApiKeyAuth
|
||||
import org.openapitools.client.auth.OAuth
|
||||
import org.openapitools.client.auth.OAuth.AccessTokenListener
|
||||
import org.openapitools.client.auth.OAuthFlow
|
||||
|
||||
import okhttp3.Interceptor
|
||||
import okhttp3.OkHttpClient
|
||||
import retrofit2.Retrofit
|
||||
import okhttp3.logging.HttpLoggingInterceptor
|
||||
import retrofit2.converter.scalars.ScalarsConverterFactory
|
||||
import com.squareup.moshi.Moshi
|
||||
import retrofit2.converter.moshi.MoshiConverterFactory
|
||||
|
||||
class ApiClient(
|
||||
private var baseUrl: String = defaultBasePath,
|
||||
private val okHttpClientBuilder: OkHttpClient.Builder? = null,
|
||||
private val serializerBuilder: Moshi.Builder = Serializer.moshiBuilder,
|
||||
private val okHttpClient : OkHttpClient? = null
|
||||
) {
|
||||
private val apiAuthorizations = mutableMapOf<String, Interceptor>()
|
||||
var logger: ((String) -> Unit)? = null
|
||||
|
||||
private val retrofitBuilder: Retrofit.Builder by lazy {
|
||||
Retrofit.Builder()
|
||||
.baseUrl(baseUrl)
|
||||
.addConverterFactory(ScalarsConverterFactory.create())
|
||||
.addConverterFactory(MoshiConverterFactory.create(serializerBuilder.build()))
|
||||
}
|
||||
|
||||
private val clientBuilder: OkHttpClient.Builder by lazy {
|
||||
okHttpClientBuilder ?: defaultClientBuilder
|
||||
}
|
||||
|
||||
private val defaultClientBuilder: OkHttpClient.Builder by lazy {
|
||||
OkHttpClient()
|
||||
.newBuilder()
|
||||
.addInterceptor(HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger {
|
||||
override fun log(message: String) {
|
||||
logger?.invoke(message)
|
||||
}
|
||||
}).apply {
|
||||
level = HttpLoggingInterceptor.Level.BODY
|
||||
})
|
||||
}
|
||||
|
||||
init {
|
||||
normalizeBaseUrl()
|
||||
}
|
||||
|
||||
constructor(
|
||||
baseUrl: String = defaultBasePath,
|
||||
okHttpClientBuilder: OkHttpClient.Builder? = null,
|
||||
serializerBuilder: Moshi.Builder = Serializer.moshiBuilder,
|
||||
authNames: Array<String>
|
||||
) : this(baseUrl, okHttpClientBuilder, serializerBuilder) {
|
||||
authNames.forEach { authName ->
|
||||
val auth = when (authName) {
|
||||
"api_key" -> ApiKeyAuth("header", "api_key")"petstore_auth" -> OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets")
|
||||
else -> throw RuntimeException("auth name $authName not found in available auth names")
|
||||
}
|
||||
addAuthorization(authName, auth);
|
||||
}
|
||||
}
|
||||
|
||||
constructor(
|
||||
baseUrl: String = defaultBasePath,
|
||||
okHttpClientBuilder: OkHttpClient.Builder? = null,
|
||||
serializerBuilder: Moshi.Builder = Serializer.moshiBuilder,
|
||||
authName: String,
|
||||
clientId: String,
|
||||
secret: String,
|
||||
username: String,
|
||||
password: String
|
||||
) : this(baseUrl, okHttpClientBuilder, serializerBuilder, arrayOf(authName)) {
|
||||
getTokenEndPoint()
|
||||
?.setClientId(clientId)
|
||||
?.setClientSecret(secret)
|
||||
?.setUsername(username)
|
||||
?.setPassword(password)
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one)
|
||||
* @return Token request builder
|
||||
*/
|
||||
fun getTokenEndPoint(): TokenRequestBuilder? {
|
||||
var result: TokenRequestBuilder? = null
|
||||
apiAuthorizations.values.runOnFirst<Interceptor, OAuth> {
|
||||
result = tokenRequestBuilder
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one)
|
||||
* @return Authentication request builder
|
||||
*/
|
||||
fun getAuthorizationEndPoint(): AuthenticationRequestBuilder? {
|
||||
var result: AuthenticationRequestBuilder? = null
|
||||
apiAuthorizations.values.runOnFirst<Interceptor, OAuth> {
|
||||
result = authenticationRequestBuilder
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* @return ApiClient
|
||||
*/
|
||||
fun setAccessToken(accessToken: String): ApiClient {
|
||||
apiAuthorizations.values.runOnFirst<Interceptor, OAuth> {
|
||||
setAccessToken(accessToken)
|
||||
}
|
||||
return this
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to configure the oauth accessCode/implicit flow parameters
|
||||
* @param clientId Client ID
|
||||
* @param clientSecret Client secret
|
||||
* @param redirectURI Redirect URI
|
||||
* @return ApiClient
|
||||
*/
|
||||
fun configureAuthorizationFlow(clientId: String, clientSecret: String, redirectURI: String): ApiClient {
|
||||
apiAuthorizations.values.runOnFirst<Interceptor, OAuth> {
|
||||
tokenRequestBuilder
|
||||
.setClientId(clientId)
|
||||
.setClientSecret(clientSecret)
|
||||
.setRedirectURI(redirectURI)
|
||||
authenticationRequestBuilder
|
||||
?.setClientId(clientId)
|
||||
?.setRedirectURI(redirectURI)
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configures a listener which is notified when a new access token is received.
|
||||
* @param accessTokenListener Access token listener
|
||||
* @return ApiClient
|
||||
*/
|
||||
fun registerAccessTokenListener(accessTokenListener: AccessTokenListener): ApiClient {
|
||||
apiAuthorizations.values.runOnFirst<Interceptor, OAuth> {
|
||||
registerAccessTokenListener(accessTokenListener)
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds an authorization to be used by the client
|
||||
* @param authName Authentication name
|
||||
* @param authorization Authorization interceptor
|
||||
* @return ApiClient
|
||||
*/
|
||||
fun addAuthorization(authName: String, authorization: Interceptor): ApiClient {
|
||||
if (apiAuthorizations.containsKey(authName)) {
|
||||
throw RuntimeException("auth name $authName already in api authorizations")
|
||||
}
|
||||
apiAuthorizations[authName] = authorization
|
||||
clientBuilder.addInterceptor(authorization)
|
||||
return this
|
||||
}
|
||||
|
||||
fun setLogger(logger: (String) -> Unit): ApiClient {
|
||||
this.logger = logger
|
||||
return this
|
||||
}
|
||||
|
||||
fun <S> createService(serviceClass: Class<S>): S {
|
||||
var usedClient: OkHttpClient? = null
|
||||
this.okHttpClient?.let { usedClient = it } ?: run {usedClient = clientBuilder.build()}
|
||||
return retrofitBuilder.client(usedClient).build().create(serviceClass)
|
||||
}
|
||||
|
||||
private fun normalizeBaseUrl() {
|
||||
if (!baseUrl.endsWith("/")) {
|
||||
baseUrl += "/"
|
||||
}
|
||||
}
|
||||
|
||||
private inline fun <T, reified U> Iterable<T>.runOnFirst(callback: U.() -> Unit) {
|
||||
for (element in this) {
|
||||
if (element is U) {
|
||||
callback.invoke(element)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
@JvmStatic
|
||||
val defaultBasePath: String by lazy {
|
||||
System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package org.openapitools.client.infrastructure
|
||||
|
||||
import com.squareup.moshi.FromJson
|
||||
import com.squareup.moshi.ToJson
|
||||
|
||||
class ByteArrayAdapter {
|
||||
@ToJson
|
||||
fun toJson(data: ByteArray): String = String(data)
|
||||
|
||||
@FromJson
|
||||
fun fromJson(data: String): ByteArray = data.toByteArray()
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package org.openapitools.client.infrastructure
|
||||
|
||||
class CollectionFormats {
|
||||
|
||||
open class CSVParams {
|
||||
|
||||
var params: List<String>
|
||||
|
||||
constructor(params: List<String>) {
|
||||
this.params = params
|
||||
}
|
||||
|
||||
constructor(vararg params: String) {
|
||||
this.params = listOf(*params)
|
||||
}
|
||||
|
||||
override fun toString(): String {
|
||||
return params.joinToString(",")
|
||||
}
|
||||
}
|
||||
|
||||
open class SSVParams : CSVParams {
|
||||
|
||||
constructor(params: List<String>) : super(params)
|
||||
|
||||
constructor(vararg params: String) : super(*params)
|
||||
|
||||
override fun toString(): String {
|
||||
return params.joinToString(" ")
|
||||
}
|
||||
}
|
||||
|
||||
class TSVParams : CSVParams {
|
||||
|
||||
constructor(params: List<String>) : super(params)
|
||||
|
||||
constructor(vararg params: String) : super(*params)
|
||||
|
||||
override fun toString(): String {
|
||||
return params.joinToString("\t")
|
||||
}
|
||||
}
|
||||
|
||||
class PIPESParams : CSVParams {
|
||||
|
||||
constructor(params: List<String>) : super(params)
|
||||
|
||||
constructor(vararg params: String) : super(*params)
|
||||
|
||||
override fun toString(): String {
|
||||
return params.joinToString("|")
|
||||
}
|
||||
}
|
||||
|
||||
class SPACEParams : SSVParams()
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package org.openapitools.client.infrastructure
|
||||
|
||||
import com.squareup.moshi.FromJson
|
||||
import com.squareup.moshi.ToJson
|
||||
import java.time.LocalDate
|
||||
import java.time.format.DateTimeFormatter
|
||||
|
||||
class LocalDateAdapter {
|
||||
@ToJson
|
||||
fun toJson(value: LocalDate): String {
|
||||
return DateTimeFormatter.ISO_LOCAL_DATE.format(value)
|
||||
}
|
||||
|
||||
@FromJson
|
||||
fun fromJson(value: String): LocalDate {
|
||||
return LocalDate.parse(value, DateTimeFormatter.ISO_LOCAL_DATE)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package org.openapitools.client.infrastructure
|
||||
|
||||
import com.squareup.moshi.FromJson
|
||||
import com.squareup.moshi.ToJson
|
||||
import java.time.LocalDateTime
|
||||
import java.time.format.DateTimeFormatter
|
||||
|
||||
class LocalDateTimeAdapter {
|
||||
@ToJson
|
||||
fun toJson(value: LocalDateTime): String {
|
||||
return DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(value)
|
||||
}
|
||||
|
||||
@FromJson
|
||||
fun fromJson(value: String): LocalDateTime {
|
||||
return LocalDateTime.parse(value, DateTimeFormatter.ISO_LOCAL_DATE_TIME)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package org.openapitools.client.infrastructure
|
||||
|
||||
import com.squareup.moshi.FromJson
|
||||
import com.squareup.moshi.ToJson
|
||||
import java.time.OffsetDateTime
|
||||
import java.time.format.DateTimeFormatter
|
||||
|
||||
class OffsetDateTimeAdapter {
|
||||
@ToJson
|
||||
fun toJson(value: OffsetDateTime): String {
|
||||
return DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(value)
|
||||
}
|
||||
|
||||
@FromJson
|
||||
fun fromJson(value: String): OffsetDateTime {
|
||||
return OffsetDateTime.parse(value, DateTimeFormatter.ISO_OFFSET_DATE_TIME)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package org.openapitools.client.infrastructure
|
||||
|
||||
import com.squareup.moshi.JsonDataException
|
||||
import com.squareup.moshi.Moshi
|
||||
import retrofit2.Response
|
||||
|
||||
@Throws(JsonDataException::class)
|
||||
inline fun <reified T> Response<*>.getErrorResponse(serializerBuilder: Moshi.Builder = Serializer.moshiBuilder): T? {
|
||||
val serializer = serializerBuilder.build()
|
||||
val parser = serializer.adapter(T::class.java)
|
||||
val response = errorBody()?.string()
|
||||
if(response != null) {
|
||||
return parser.fromJson(response)
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package org.openapitools.client.infrastructure
|
||||
|
||||
import com.squareup.moshi.Moshi
|
||||
import com.squareup.moshi.adapters.Rfc3339DateJsonAdapter
|
||||
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
|
||||
import java.util.Date
|
||||
|
||||
object Serializer {
|
||||
@JvmStatic
|
||||
val moshiBuilder: Moshi.Builder = Moshi.Builder()
|
||||
.add(Date::class.java, Rfc3339DateJsonAdapter().nullSafe())
|
||||
.add(OffsetDateTimeAdapter())
|
||||
.add(LocalDateTimeAdapter())
|
||||
.add(LocalDateAdapter())
|
||||
.add(UUIDAdapter())
|
||||
.add(ByteArrayAdapter())
|
||||
.add(KotlinJsonAdapterFactory())
|
||||
|
||||
@JvmStatic
|
||||
val moshi: Moshi by lazy {
|
||||
moshiBuilder.build()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package org.openapitools.client.infrastructure
|
||||
|
||||
import com.squareup.moshi.FromJson
|
||||
import com.squareup.moshi.ToJson
|
||||
import java.util.UUID
|
||||
|
||||
class UUIDAdapter {
|
||||
@ToJson
|
||||
fun toJson(uuid: UUID) = uuid.toString()
|
||||
|
||||
@FromJson
|
||||
fun fromJson(s: String) = UUID.fromString(s)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* OpenAPI Petstore
|
||||
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
|
||||
*
|
||||
* The version of the OpenAPI document: 1.0.0
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
package org.openapitools.client.models
|
||||
|
||||
|
||||
import com.squareup.moshi.Json
|
||||
|
||||
/**
|
||||
* Describes the result of uploading an image resource
|
||||
* @param code
|
||||
* @param type
|
||||
* @param message
|
||||
*/
|
||||
|
||||
data class ApiResponse (
|
||||
@Json(name = "code")
|
||||
val code: kotlin.Int? = null,
|
||||
@Json(name = "type")
|
||||
val type: kotlin.String? = null,
|
||||
@Json(name = "message")
|
||||
val message: kotlin.String? = null
|
||||
)
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* OpenAPI Petstore
|
||||
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
|
||||
*
|
||||
* The version of the OpenAPI document: 1.0.0
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
package org.openapitools.client.models
|
||||
|
||||
|
||||
import com.squareup.moshi.Json
|
||||
|
||||
/**
|
||||
* A category for a pet
|
||||
* @param id
|
||||
* @param name
|
||||
*/
|
||||
|
||||
data class Category (
|
||||
@Json(name = "id")
|
||||
val id: kotlin.Long? = null,
|
||||
@Json(name = "name")
|
||||
val name: kotlin.String? = null
|
||||
)
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* OpenAPI Petstore
|
||||
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
|
||||
*
|
||||
* The version of the OpenAPI document: 1.0.0
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
package org.openapitools.client.models
|
||||
|
||||
|
||||
import com.squareup.moshi.Json
|
||||
|
||||
/**
|
||||
* An order for a pets from the pet store
|
||||
* @param id
|
||||
* @param petId
|
||||
* @param quantity
|
||||
* @param shipDate
|
||||
* @param status Order Status
|
||||
* @param complete
|
||||
*/
|
||||
|
||||
data class Order (
|
||||
@Json(name = "id")
|
||||
val id: kotlin.Long? = null,
|
||||
@Json(name = "petId")
|
||||
val petId: kotlin.Long? = null,
|
||||
@Json(name = "quantity")
|
||||
val quantity: kotlin.Int? = null,
|
||||
@Json(name = "shipDate")
|
||||
val shipDate: java.time.OffsetDateTime? = null,
|
||||
/* Order Status */
|
||||
@Json(name = "status")
|
||||
val status: Order.Status? = null,
|
||||
@Json(name = "complete")
|
||||
val complete: kotlin.Boolean? = null
|
||||
) {
|
||||
|
||||
/**
|
||||
* Order Status
|
||||
* Values: placed,approved,delivered
|
||||
*/
|
||||
|
||||
enum class Status(val value: kotlin.String){
|
||||
@Json(name = "placed") placed("placed"),
|
||||
@Json(name = "approved") approved("approved"),
|
||||
@Json(name = "delivered") delivered("delivered");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* OpenAPI Petstore
|
||||
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
|
||||
*
|
||||
* The version of the OpenAPI document: 1.0.0
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
package org.openapitools.client.models
|
||||
|
||||
import org.openapitools.client.models.Category
|
||||
import org.openapitools.client.models.Tag
|
||||
|
||||
import com.squareup.moshi.Json
|
||||
|
||||
/**
|
||||
* A pet for sale in the pet store
|
||||
* @param name
|
||||
* @param photoUrls
|
||||
* @param id
|
||||
* @param category
|
||||
* @param tags
|
||||
* @param status pet status in the store
|
||||
*/
|
||||
|
||||
data class Pet (
|
||||
@Json(name = "name")
|
||||
val name: kotlin.String,
|
||||
@Json(name = "photoUrls")
|
||||
val photoUrls: kotlin.collections.List<kotlin.String>,
|
||||
@Json(name = "id")
|
||||
val id: kotlin.Long? = null,
|
||||
@Json(name = "category")
|
||||
val category: Category? = null,
|
||||
@Json(name = "tags")
|
||||
val tags: kotlin.collections.List<Tag>? = null,
|
||||
/* pet status in the store */
|
||||
@Json(name = "status")
|
||||
val status: Pet.Status? = null
|
||||
) {
|
||||
|
||||
/**
|
||||
* pet status in the store
|
||||
* Values: available,pending,sold
|
||||
*/
|
||||
|
||||
enum class Status(val value: kotlin.String){
|
||||
@Json(name = "available") available("available"),
|
||||
@Json(name = "pending") pending("pending"),
|
||||
@Json(name = "sold") sold("sold");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* OpenAPI Petstore
|
||||
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
|
||||
*
|
||||
* The version of the OpenAPI document: 1.0.0
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
package org.openapitools.client.models
|
||||
|
||||
|
||||
import com.squareup.moshi.Json
|
||||
|
||||
/**
|
||||
* A tag for a pet
|
||||
* @param id
|
||||
* @param name
|
||||
*/
|
||||
|
||||
data class Tag (
|
||||
@Json(name = "id")
|
||||
val id: kotlin.Long? = null,
|
||||
@Json(name = "name")
|
||||
val name: kotlin.String? = null
|
||||
)
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* OpenAPI Petstore
|
||||
* This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.
|
||||
*
|
||||
* The version of the OpenAPI document: 1.0.0
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
package org.openapitools.client.models
|
||||
|
||||
|
||||
import com.squareup.moshi.Json
|
||||
|
||||
/**
|
||||
* A User who is purchasing from the pet store
|
||||
* @param id
|
||||
* @param username
|
||||
* @param firstName
|
||||
* @param lastName
|
||||
* @param email
|
||||
* @param password
|
||||
* @param phone
|
||||
* @param userStatus User Status
|
||||
*/
|
||||
|
||||
data class User (
|
||||
@Json(name = "id")
|
||||
val id: kotlin.Long? = null,
|
||||
@Json(name = "username")
|
||||
val username: kotlin.String? = null,
|
||||
@Json(name = "firstName")
|
||||
val firstName: kotlin.String? = null,
|
||||
@Json(name = "lastName")
|
||||
val lastName: kotlin.String? = null,
|
||||
@Json(name = "email")
|
||||
val email: kotlin.String? = null,
|
||||
@Json(name = "password")
|
||||
val password: kotlin.String? = null,
|
||||
@Json(name = "phone")
|
||||
val phone: kotlin.String? = null,
|
||||
/* User Status */
|
||||
@Json(name = "userStatus")
|
||||
val userStatus: kotlin.Int? = null
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user