mirror of
https://github.com/OpenAPITools/openapi-generator.git
synced 2025-12-03 00:43:46 +00:00
Merge remote-tracking branch 'origin/master' into 6.0.x
This commit is contained in:
@@ -10,7 +10,7 @@ settings.gradle
|
||||
src/main/kotlin/org/openapitools/client/apis/EnumApi.kt
|
||||
src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt
|
||||
src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt
|
||||
src/main/kotlin/org/openapitools/client/infrastructure/ApiInfrastructureResponse.kt
|
||||
src/main/kotlin/org/openapitools/client/infrastructure/ApiResponse.kt
|
||||
src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt
|
||||
src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt
|
||||
src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
/**
|
||||
* OpenAPI Petstore
|
||||
* Test for issue 4062
|
||||
*
|
||||
* 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.apis
|
||||
|
||||
import org.openapitools.client.models.PetEnum
|
||||
|
||||
import org.openapitools.client.infrastructure.ApiClient
|
||||
import org.openapitools.client.infrastructure.ClientException
|
||||
import org.openapitools.client.infrastructure.ClientError
|
||||
import org.openapitools.client.infrastructure.ServerException
|
||||
import org.openapitools.client.infrastructure.ServerError
|
||||
import org.openapitools.client.infrastructure.MultiValueMap
|
||||
import org.openapitools.client.infrastructure.RequestConfig
|
||||
import org.openapitools.client.infrastructure.RequestMethod
|
||||
import org.openapitools.client.infrastructure.ResponseType
|
||||
import org.openapitools.client.infrastructure.Success
|
||||
import org.openapitools.client.infrastructure.toMultiValue
|
||||
|
||||
class EnumApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) {
|
||||
companion object {
|
||||
@JvmStatic
|
||||
val defaultBasePath: String by lazy {
|
||||
System.getProperties().getProperty("org.openapitools.client.baseUrl", "http://petstore.swagger.io/v2")
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get enums
|
||||
*
|
||||
* @return PetEnum
|
||||
* @throws UnsupportedOperationException If the API returns an informational or redirection response
|
||||
* @throws ClientException If the API returns a client error response
|
||||
* @throws ServerException If the API returns a server error response
|
||||
*/
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
|
||||
fun getEnum() : PetEnum {
|
||||
val localVariableConfig = getEnumRequestConfig()
|
||||
|
||||
val localVarResponse = request<PetEnum>(
|
||||
localVariableConfig
|
||||
)
|
||||
|
||||
return when (localVarResponse.responseType) {
|
||||
ResponseType.Success -> (localVarResponse as Success<*>).data as PetEnum
|
||||
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
|
||||
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
|
||||
ResponseType.ClientError -> {
|
||||
val localVarError = localVarResponse as ClientError<*>
|
||||
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
|
||||
}
|
||||
ResponseType.ServerError -> {
|
||||
val localVarError = localVarResponse as ServerError<*>
|
||||
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* To obtain the request config of the operation getEnum
|
||||
*
|
||||
* @return RequestConfig
|
||||
*/
|
||||
fun getEnumRequestConfig() : RequestConfig {
|
||||
val localVariableBody: kotlin.Any? = null
|
||||
val localVariableQuery: MultiValueMap = mutableMapOf()
|
||||
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
|
||||
|
||||
val localVariableConfig = RequestConfig(
|
||||
method = RequestMethod.GET,
|
||||
path = "/enum",
|
||||
query = localVariableQuery,
|
||||
headers = localVariableHeaders,
|
||||
body = localVariableBody
|
||||
)
|
||||
|
||||
return localVariableConfig
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package org.openapitools.client.infrastructure
|
||||
|
||||
typealias MultiValueMap = MutableMap<String,List<String>>
|
||||
|
||||
fun collectionDelimiter(collectionFormat: String) = when(collectionFormat) {
|
||||
"csv" -> ","
|
||||
"tsv" -> "\t"
|
||||
"pipe" -> "|"
|
||||
"space" -> " "
|
||||
else -> ""
|
||||
}
|
||||
|
||||
val defaultMultiValueConverter: (item: Any?) -> String = { item -> "$item" }
|
||||
|
||||
fun <T : Any?> toMultiValue(items: Array<T>, collectionFormat: String, map: (item: T) -> String = defaultMultiValueConverter)
|
||||
= toMultiValue(items.asIterable(), collectionFormat, map)
|
||||
|
||||
fun <T : Any?> toMultiValue(items: Iterable<T>, collectionFormat: String, map: (item: T) -> String = defaultMultiValueConverter): List<String> {
|
||||
return when(collectionFormat) {
|
||||
"multi" -> items.map(map)
|
||||
else -> listOf(items.joinToString(separator = collectionDelimiter(collectionFormat), transform = map))
|
||||
}
|
||||
}
|
||||
@@ -1,232 +0,0 @@
|
||||
package org.openapitools.client.infrastructure
|
||||
|
||||
import okhttp3.Credentials
|
||||
import okhttp3.OkHttpClient
|
||||
import okhttp3.RequestBody
|
||||
import okhttp3.RequestBody.Companion.asRequestBody
|
||||
import okhttp3.RequestBody.Companion.toRequestBody
|
||||
import okhttp3.FormBody
|
||||
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
|
||||
import okhttp3.ResponseBody
|
||||
import okhttp3.MediaType.Companion.toMediaTypeOrNull
|
||||
import okhttp3.Request
|
||||
import okhttp3.Headers
|
||||
import okhttp3.MultipartBody
|
||||
import java.io.File
|
||||
import java.net.URLConnection
|
||||
import java.util.Date
|
||||
import java.time.LocalDate
|
||||
import java.time.LocalDateTime
|
||||
import java.time.LocalTime
|
||||
import java.time.OffsetDateTime
|
||||
import java.time.OffsetTime
|
||||
|
||||
open class ApiClient(val baseUrl: String) {
|
||||
companion object {
|
||||
protected const val ContentType = "Content-Type"
|
||||
protected const val Accept = "Accept"
|
||||
protected const val Authorization = "Authorization"
|
||||
protected const val JsonMediaType = "application/json"
|
||||
protected const val FormDataMediaType = "multipart/form-data"
|
||||
protected const val FormUrlEncMediaType = "application/x-www-form-urlencoded"
|
||||
protected const val XmlMediaType = "application/xml"
|
||||
|
||||
val apiKey: MutableMap<String, String> = mutableMapOf()
|
||||
val apiKeyPrefix: MutableMap<String, String> = mutableMapOf()
|
||||
var username: String? = null
|
||||
var password: String? = null
|
||||
var accessToken: String? = null
|
||||
|
||||
@JvmStatic
|
||||
val client: OkHttpClient by lazy {
|
||||
builder.build()
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
val builder: OkHttpClient.Builder = OkHttpClient.Builder()
|
||||
}
|
||||
|
||||
/**
|
||||
* Guess Content-Type header from the given file (defaults to "application/octet-stream").
|
||||
*
|
||||
* @param file The given file
|
||||
* @return The guessed Content-Type
|
||||
*/
|
||||
protected fun guessContentTypeFromFile(file: File): String {
|
||||
val contentType = URLConnection.guessContentTypeFromName(file.name)
|
||||
return contentType ?: "application/octet-stream"
|
||||
}
|
||||
|
||||
protected inline fun <reified T> requestBody(content: T, mediaType: String = JsonMediaType): RequestBody =
|
||||
when {
|
||||
content is File -> content.asRequestBody(
|
||||
mediaType.toMediaTypeOrNull()
|
||||
)
|
||||
mediaType == FormDataMediaType -> {
|
||||
MultipartBody.Builder()
|
||||
.setType(MultipartBody.FORM)
|
||||
.apply {
|
||||
// content's type *must* be Map<String, Any?>
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
(content as Map<String, Any?>).forEach { (key, value) ->
|
||||
if (value is File) {
|
||||
val partHeaders = Headers.headersOf(
|
||||
"Content-Disposition",
|
||||
"form-data; name=\"$key\"; filename=\"${value.name}\""
|
||||
)
|
||||
val fileMediaType = guessContentTypeFromFile(value).toMediaTypeOrNull()
|
||||
addPart(partHeaders, value.asRequestBody(fileMediaType))
|
||||
} else {
|
||||
val partHeaders = Headers.headersOf(
|
||||
"Content-Disposition",
|
||||
"form-data; name=\"$key\""
|
||||
)
|
||||
addPart(
|
||||
partHeaders,
|
||||
parameterToString(value).toRequestBody(null)
|
||||
)
|
||||
}
|
||||
}
|
||||
}.build()
|
||||
}
|
||||
mediaType == FormUrlEncMediaType -> {
|
||||
FormBody.Builder().apply {
|
||||
// content's type *must* be Map<String, Any?>
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
(content as Map<String, Any?>).forEach { (key, value) ->
|
||||
add(key, parameterToString(value))
|
||||
}
|
||||
}.build()
|
||||
}
|
||||
mediaType == JsonMediaType -> Serializer.moshi.adapter(T::class.java).toJson(content).toRequestBody(
|
||||
mediaType.toMediaTypeOrNull()
|
||||
)
|
||||
mediaType == XmlMediaType -> throw UnsupportedOperationException("xml not currently supported.")
|
||||
// TODO: this should be extended with other serializers
|
||||
else -> throw UnsupportedOperationException("requestBody currently only supports JSON body and File body.")
|
||||
}
|
||||
|
||||
protected inline fun <reified T: Any?> responseBody(body: ResponseBody?, mediaType: String? = JsonMediaType): T? {
|
||||
if(body == null) {
|
||||
return null
|
||||
}
|
||||
val bodyContent = body.string()
|
||||
if (bodyContent.isEmpty()) {
|
||||
return null
|
||||
}
|
||||
return when(mediaType) {
|
||||
JsonMediaType -> Serializer.moshi.adapter(T::class.java).fromJson(bodyContent)
|
||||
else -> throw UnsupportedOperationException("responseBody currently only supports JSON body.")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
protected inline fun <reified T: Any?> request(requestConfig: RequestConfig): ApiInfrastructureResponse<T?> {
|
||||
val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.")
|
||||
|
||||
val url = httpUrl.newBuilder()
|
||||
.addPathSegments(requestConfig.path.trimStart('/'))
|
||||
.apply {
|
||||
requestConfig.query.forEach { query ->
|
||||
query.value.forEach { queryValue ->
|
||||
addQueryParameter(query.key, queryValue)
|
||||
}
|
||||
}
|
||||
}.build()
|
||||
|
||||
// take content-type/accept from spec or set to default (application/json) if not defined
|
||||
if (requestConfig.headers[ContentType].isNullOrEmpty()) {
|
||||
requestConfig.headers[ContentType] = JsonMediaType
|
||||
}
|
||||
if (requestConfig.headers[Accept].isNullOrEmpty()) {
|
||||
requestConfig.headers[Accept] = JsonMediaType
|
||||
}
|
||||
val headers = requestConfig.headers
|
||||
|
||||
if(headers[ContentType] ?: "" == "") {
|
||||
throw kotlin.IllegalStateException("Missing Content-Type header. This is required.")
|
||||
}
|
||||
|
||||
if(headers[Accept] ?: "" == "") {
|
||||
throw kotlin.IllegalStateException("Missing Accept header. This is required.")
|
||||
}
|
||||
|
||||
// TODO: support multiple contentType options here.
|
||||
val contentType = (headers[ContentType] as String).substringBefore(";").toLowerCase()
|
||||
|
||||
val request = when (requestConfig.method) {
|
||||
RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType))
|
||||
RequestMethod.GET -> Request.Builder().url(url)
|
||||
RequestMethod.HEAD -> Request.Builder().url(url).head()
|
||||
RequestMethod.PATCH -> Request.Builder().url(url).patch(requestBody(requestConfig.body, contentType))
|
||||
RequestMethod.PUT -> Request.Builder().url(url).put(requestBody(requestConfig.body, contentType))
|
||||
RequestMethod.POST -> Request.Builder().url(url).post(requestBody(requestConfig.body, contentType))
|
||||
RequestMethod.OPTIONS -> Request.Builder().url(url).method("OPTIONS", null)
|
||||
}.apply {
|
||||
headers.forEach { header -> addHeader(header.key, header.value) }
|
||||
}.build()
|
||||
|
||||
val response = client.newCall(request).execute()
|
||||
val accept = response.header(ContentType)?.substringBefore(";")?.toLowerCase()
|
||||
|
||||
// TODO: handle specific mapping types. e.g. Map<int, Class<?>>
|
||||
when {
|
||||
response.isRedirect -> return Redirection(
|
||||
response.code,
|
||||
response.headers.toMultimap()
|
||||
)
|
||||
response.isInformational -> return Informational(
|
||||
response.message,
|
||||
response.code,
|
||||
response.headers.toMultimap()
|
||||
)
|
||||
response.isSuccessful -> return Success(
|
||||
responseBody(response.body, accept),
|
||||
response.code,
|
||||
response.headers.toMultimap()
|
||||
)
|
||||
response.isClientError -> return ClientError(
|
||||
response.message,
|
||||
response.body?.string(),
|
||||
response.code,
|
||||
response.headers.toMultimap()
|
||||
)
|
||||
else -> return ServerError(
|
||||
response.message,
|
||||
response.body?.string(),
|
||||
response.code,
|
||||
response.headers.toMultimap()
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
protected fun parameterToString(value: Any?): String {
|
||||
when (value) {
|
||||
null -> {
|
||||
return ""
|
||||
}
|
||||
is Array<*> -> {
|
||||
return toMultiValue(value, "csv").toString()
|
||||
}
|
||||
is Iterable<*> -> {
|
||||
return toMultiValue(value, "csv").toString()
|
||||
}
|
||||
is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date -> {
|
||||
return parseDateToQueryString<Any>(value)
|
||||
}
|
||||
else -> {
|
||||
return value.toString()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
protected inline fun <reified T: Any> parseDateToQueryString(value : T): String {
|
||||
/*
|
||||
.replace("\"", "") converts the json object string to an actual string for the query parameter.
|
||||
The moshi or gson adapter allows a more generic solution instead of trying to use a native
|
||||
formatter. It also easily allows to provide a simple way to define a custom date format pattern
|
||||
inside a gson/moshi adapter.
|
||||
*/
|
||||
return Serializer.moshi.adapter(T::class.java).toJson(value).replace("\"", "")
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
package org.openapitools.client.infrastructure
|
||||
|
||||
enum class ResponseType {
|
||||
Success, Informational, Redirection, ClientError, ServerError
|
||||
}
|
||||
|
||||
interface Response
|
||||
|
||||
abstract class ApiInfrastructureResponse<T>(val responseType: ResponseType): Response {
|
||||
abstract val statusCode: Int
|
||||
abstract val headers: Map<String,List<String>>
|
||||
}
|
||||
|
||||
class Success<T>(
|
||||
val data: T,
|
||||
override val statusCode: Int = -1,
|
||||
override val headers: Map<String, List<String>> = mapOf()
|
||||
): ApiInfrastructureResponse<T>(ResponseType.Success)
|
||||
|
||||
class Informational<T>(
|
||||
val statusText: String,
|
||||
override val statusCode: Int = -1,
|
||||
override val headers: Map<String, List<String>> = mapOf()
|
||||
) : ApiInfrastructureResponse<T>(ResponseType.Informational)
|
||||
|
||||
class Redirection<T>(
|
||||
override val statusCode: Int = -1,
|
||||
override val headers: Map<String, List<String>> = mapOf()
|
||||
) : ApiInfrastructureResponse<T>(ResponseType.Redirection)
|
||||
|
||||
class ClientError<T>(
|
||||
val message: String? = null,
|
||||
val body: Any? = null,
|
||||
override val statusCode: Int = -1,
|
||||
override val headers: Map<String, List<String>> = mapOf()
|
||||
) : ApiInfrastructureResponse<T>(ResponseType.ClientError)
|
||||
|
||||
class ServerError<T>(
|
||||
val message: String? = null,
|
||||
val body: Any? = null,
|
||||
override val statusCode: Int = -1,
|
||||
override val headers: Map<String, List<String>>
|
||||
): ApiInfrastructureResponse<T>(ResponseType.ServerError)
|
||||
@@ -1,29 +0,0 @@
|
||||
package org.openapitools.client.infrastructure
|
||||
|
||||
import kotlin.properties.ReadWriteProperty
|
||||
import kotlin.reflect.KProperty
|
||||
|
||||
object ApplicationDelegates {
|
||||
/**
|
||||
* Provides a property delegate, allowing the property to be set once and only once.
|
||||
*
|
||||
* If unset (no default value), a get on the property will throw [IllegalStateException].
|
||||
*/
|
||||
fun <T> setOnce(defaultValue: T? = null) : ReadWriteProperty<Any?, T> = SetOnce(defaultValue)
|
||||
|
||||
private class SetOnce<T>(defaultValue: T? = null) : ReadWriteProperty<Any?, T> {
|
||||
private var isSet = false
|
||||
private var value: T? = defaultValue
|
||||
|
||||
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
|
||||
return value ?: throw IllegalStateException("${property.name} not initialized")
|
||||
}
|
||||
|
||||
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) = synchronized(this) {
|
||||
if (!isSet) {
|
||||
this.value = value
|
||||
isSet = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
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()
|
||||
}
|
||||
@@ -1,18 +0,0 @@
|
||||
@file:Suppress("unused")
|
||||
package org.openapitools.client.infrastructure
|
||||
|
||||
import java.lang.RuntimeException
|
||||
|
||||
open class ClientException(message: kotlin.String? = null, val statusCode: Int = -1, val response: Response? = null) : RuntimeException(message) {
|
||||
|
||||
companion object {
|
||||
private const val serialVersionUID: Long = 123L
|
||||
}
|
||||
}
|
||||
|
||||
open class ServerException(message: kotlin.String? = null, val statusCode: Int = -1, val response: Response? = null) : RuntimeException(message) {
|
||||
|
||||
companion object {
|
||||
private const val serialVersionUID: Long = 456L
|
||||
}
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
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)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
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)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
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)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package org.openapitools.client.infrastructure
|
||||
|
||||
/**
|
||||
* Defines a config object for a given request.
|
||||
* NOTE: This object doesn't include 'body' because it
|
||||
* allows for caching of the constructed object
|
||||
* for many request definitions.
|
||||
* NOTE: Headers is a Map<String,String> because rfc2616 defines
|
||||
* multi-valued headers as csv-only.
|
||||
*/
|
||||
data class RequestConfig(
|
||||
val method: RequestMethod,
|
||||
val path: String,
|
||||
val headers: MutableMap<String, String> = mutableMapOf(),
|
||||
val query: MutableMap<String, List<String>> = mutableMapOf(),
|
||||
val body: kotlin.Any? = null
|
||||
)
|
||||
@@ -1,8 +0,0 @@
|
||||
package org.openapitools.client.infrastructure
|
||||
|
||||
/**
|
||||
* Provides enumerated HTTP verbs
|
||||
*/
|
||||
enum class RequestMethod {
|
||||
GET, DELETE, HEAD, OPTIONS, PATCH, POST, PUT
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
package org.openapitools.client.infrastructure
|
||||
|
||||
import okhttp3.Response
|
||||
|
||||
/**
|
||||
* Provides an extension to evaluation whether the response is a 1xx code
|
||||
*/
|
||||
val Response.isInformational : Boolean get() = this.code in 100..199
|
||||
|
||||
/**
|
||||
* Provides an extension to evaluation whether the response is a 3xx code
|
||||
*/
|
||||
@Suppress("EXTENSION_SHADOWED_BY_MEMBER")
|
||||
val Response.isRedirect : Boolean get() = this.code in 300..399
|
||||
|
||||
/**
|
||||
* Provides an extension to evaluation whether the response is a 4xx code
|
||||
*/
|
||||
val Response.isClientError : Boolean get() = this.code in 400..499
|
||||
|
||||
/**
|
||||
* Provides an extension to evaluation whether the response is a 5xx (Standard) through 999 (non-standard) code
|
||||
*/
|
||||
val Response.isServerError : Boolean get() = this.code in 500..999
|
||||
@@ -1,21 +0,0 @@
|
||||
package org.openapitools.client.infrastructure
|
||||
|
||||
import com.squareup.moshi.Moshi
|
||||
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
|
||||
import java.util.Date
|
||||
|
||||
object Serializer {
|
||||
@JvmStatic
|
||||
val moshiBuilder: Moshi.Builder = Moshi.Builder()
|
||||
.add(OffsetDateTimeAdapter())
|
||||
.add(LocalDateTimeAdapter())
|
||||
.add(LocalDateAdapter())
|
||||
.add(UUIDAdapter())
|
||||
.add(ByteArrayAdapter())
|
||||
.add(KotlinJsonAdapterFactory())
|
||||
|
||||
@JvmStatic
|
||||
val moshi: Moshi by lazy {
|
||||
moshiBuilder.build()
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
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)
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
/**
|
||||
* OpenAPI Petstore
|
||||
* Test for issue 4062
|
||||
*
|
||||
* 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 enum with complex-ish naming
|
||||
* Values: MY_FIRST_VALUE,MY_SECOND_VALUE
|
||||
*/
|
||||
|
||||
enum class PetEnum(val value: kotlin.String){
|
||||
|
||||
|
||||
@Json(name = "myFirstValue")
|
||||
MY_FIRST_VALUE("myFirstValue"),
|
||||
|
||||
|
||||
@Json(name = "MY_SECOND_VALUE")
|
||||
MY_SECOND_VALUE("MY_SECOND_VALUE");
|
||||
|
||||
|
||||
|
||||
/**
|
||||
This override toString avoids using the enum var name and uses the actual api value instead.
|
||||
In cases the var name and value are different, the client would send incorrect enums to the server.
|
||||
**/
|
||||
override fun toString(): String {
|
||||
return value
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -20,10 +20,14 @@
|
||||
|
||||
package org.openapitools.client.apis
|
||||
|
||||
import java.io.IOException
|
||||
|
||||
import org.openapitools.client.models.PetEnum
|
||||
|
||||
import com.squareup.moshi.Json
|
||||
|
||||
import org.openapitools.client.infrastructure.ApiClient
|
||||
import org.openapitools.client.infrastructure.ApiInfrastructureResponse
|
||||
import org.openapitools.client.infrastructure.ApiResponse
|
||||
import org.openapitools.client.infrastructure.ClientException
|
||||
import org.openapitools.client.infrastructure.ClientError
|
||||
import org.openapitools.client.infrastructure.ServerException
|
||||
@@ -47,12 +51,14 @@ class EnumApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) {
|
||||
* Get enums
|
||||
*
|
||||
* @return PetEnum
|
||||
* @throws IllegalStateException If the request is not correctly configured
|
||||
* @throws IOException Rethrows the OkHttp execute method exception
|
||||
* @throws UnsupportedOperationException If the API returns an informational or redirection response
|
||||
* @throws ClientException If the API returns a client error response
|
||||
* @throws ServerException If the API returns a server error response
|
||||
*/
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
|
||||
@Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class)
|
||||
fun getEnum() : PetEnum {
|
||||
val localVarResponse = getEnumWithHttpInfo()
|
||||
|
||||
@@ -74,14 +80,13 @@ class EnumApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) {
|
||||
/**
|
||||
* Get enums
|
||||
*
|
||||
* @return ApiInfrastructureResponse<PetEnum?>
|
||||
* @throws UnsupportedOperationException If the API returns an informational or redirection response
|
||||
* @throws ClientException If the API returns a client error response
|
||||
* @throws ServerException If the API returns a server error response
|
||||
* @return ApiResponse<PetEnum?>
|
||||
* @throws IllegalStateException If the request is not correctly configured
|
||||
* @throws IOException Rethrows the OkHttp execute method exception
|
||||
*/
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
@Throws(UnsupportedOperationException::class, ClientException::class, ServerException::class)
|
||||
fun getEnumWithHttpInfo() : ApiInfrastructureResponse<PetEnum?> {
|
||||
@Throws(IllegalStateException::class, IOException::class)
|
||||
fun getEnumWithHttpInfo() : ApiResponse<PetEnum?> {
|
||||
val localVariableConfig = getEnumRequestConfig()
|
||||
|
||||
return request<Unit, PetEnum>(
|
||||
@@ -98,6 +103,7 @@ class EnumApi(basePath: kotlin.String = defaultBasePath) : ApiClient(basePath) {
|
||||
val localVariableBody = null
|
||||
val localVariableQuery: MultiValueMap = mutableMapOf()
|
||||
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
|
||||
localVariableHeaders["Accept"] = "application/json"
|
||||
|
||||
return RequestConfig(
|
||||
method = RequestMethod.GET,
|
||||
|
||||
@@ -25,7 +25,6 @@ import java.time.LocalDateTime
|
||||
import java.time.LocalTime
|
||||
import java.time.OffsetDateTime
|
||||
import java.time.OffsetTime
|
||||
import java.util.Date
|
||||
import java.util.Locale
|
||||
import com.squareup.moshi.adapter
|
||||
|
||||
@@ -105,7 +104,7 @@ open class ApiClient(val baseUrl: String) {
|
||||
}
|
||||
}.build()
|
||||
}
|
||||
mediaType == JsonMediaType -> {
|
||||
mediaType.startsWith("application/") && mediaType.endsWith("json") ->
|
||||
if (content == null) {
|
||||
EMPTY_REQUEST
|
||||
} else {
|
||||
@@ -114,7 +113,6 @@ open class ApiClient(val baseUrl: String) {
|
||||
mediaType.toMediaTypeOrNull()
|
||||
)
|
||||
}
|
||||
}
|
||||
mediaType == XmlMediaType -> throw UnsupportedOperationException("xml not currently supported.")
|
||||
// TODO: this should be extended with other serializers
|
||||
else -> throw UnsupportedOperationException("requestBody currently only supports JSON body and File body.")
|
||||
@@ -138,14 +136,15 @@ open class ApiClient(val baseUrl: String) {
|
||||
out.close()
|
||||
return f as T
|
||||
}
|
||||
return when(mediaType) {
|
||||
JsonMediaType -> Serializer.moshi.adapter<T>().fromJson(bodyContent)
|
||||
return when {
|
||||
mediaType==null || (mediaType.startsWith("application/") && mediaType.endsWith("json")) ->
|
||||
Serializer.moshi.adapter<T>().fromJson(bodyContent)
|
||||
else -> throw UnsupportedOperationException("responseBody currently only supports JSON body.")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
protected inline fun <reified I, reified T: Any?> request(requestConfig: RequestConfig<I>): ApiInfrastructureResponse<T?> {
|
||||
protected inline fun <reified I, reified T: Any?> request(requestConfig: RequestConfig<I>): ApiResponse<T?> {
|
||||
val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.")
|
||||
|
||||
val url = httpUrl.newBuilder()
|
||||
@@ -167,11 +166,11 @@ open class ApiClient(val baseUrl: String) {
|
||||
}
|
||||
val headers = requestConfig.headers
|
||||
|
||||
if(headers[ContentType] ?: "" == "") {
|
||||
if(headers[ContentType].isNullOrEmpty()) {
|
||||
throw kotlin.IllegalStateException("Missing Content-Type header. This is required.")
|
||||
}
|
||||
|
||||
if(headers[Accept] ?: "" == "") {
|
||||
if(headers[Accept].isNullOrEmpty()) {
|
||||
throw kotlin.IllegalStateException("Missing Accept header. This is required.")
|
||||
}
|
||||
|
||||
@@ -229,7 +228,7 @@ open class ApiClient(val baseUrl: String) {
|
||||
null -> ""
|
||||
is Array<*> -> toMultiValue(value, "csv").toString()
|
||||
is Iterable<*> -> toMultiValue(value, "csv").toString()
|
||||
is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime, is Date ->
|
||||
is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime ->
|
||||
parseDateToQueryString(value)
|
||||
else -> value.toString()
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ enum class ResponseType {
|
||||
|
||||
interface Response
|
||||
|
||||
abstract class ApiInfrastructureResponse<T>(val responseType: ResponseType): Response {
|
||||
abstract class ApiResponse<T>(val responseType: ResponseType): Response {
|
||||
abstract val statusCode: Int
|
||||
abstract val headers: Map<String,List<String>>
|
||||
}
|
||||
@@ -15,29 +15,29 @@ class Success<T>(
|
||||
val data: T,
|
||||
override val statusCode: Int = -1,
|
||||
override val headers: Map<String, List<String>> = mapOf()
|
||||
): ApiInfrastructureResponse<T>(ResponseType.Success)
|
||||
): ApiResponse<T>(ResponseType.Success)
|
||||
|
||||
class Informational<T>(
|
||||
val statusText: String,
|
||||
override val statusCode: Int = -1,
|
||||
override val headers: Map<String, List<String>> = mapOf()
|
||||
) : ApiInfrastructureResponse<T>(ResponseType.Informational)
|
||||
) : ApiResponse<T>(ResponseType.Informational)
|
||||
|
||||
class Redirection<T>(
|
||||
override val statusCode: Int = -1,
|
||||
override val headers: Map<String, List<String>> = mapOf()
|
||||
) : ApiInfrastructureResponse<T>(ResponseType.Redirection)
|
||||
) : ApiResponse<T>(ResponseType.Redirection)
|
||||
|
||||
class ClientError<T>(
|
||||
val message: String? = null,
|
||||
val body: Any? = null,
|
||||
override val statusCode: Int = -1,
|
||||
override val headers: Map<String, List<String>> = mapOf()
|
||||
) : ApiInfrastructureResponse<T>(ResponseType.ClientError)
|
||||
) : ApiResponse<T>(ResponseType.ClientError)
|
||||
|
||||
class ServerError<T>(
|
||||
val message: String? = null,
|
||||
val body: Any? = null,
|
||||
override val statusCode: Int = -1,
|
||||
override val headers: Map<String, List<String>>
|
||||
): ApiInfrastructureResponse<T>(ResponseType.ServerError)
|
||||
): ApiResponse<T>(ResponseType.ServerError)
|
||||
@@ -1,29 +0,0 @@
|
||||
package org.openapitools.client.infrastructure
|
||||
|
||||
import kotlin.properties.ReadWriteProperty
|
||||
import kotlin.reflect.KProperty
|
||||
|
||||
object ApplicationDelegates {
|
||||
/**
|
||||
* Provides a property delegate, allowing the property to be set once and only once.
|
||||
*
|
||||
* If unset (no default value), a get on the property will throw [IllegalStateException].
|
||||
*/
|
||||
fun <T> setOnce(defaultValue: T? = null) : ReadWriteProperty<Any?, T> = SetOnce(defaultValue)
|
||||
|
||||
private class SetOnce<T>(defaultValue: T? = null) : ReadWriteProperty<Any?, T> {
|
||||
private var isSet = false
|
||||
private var value: T? = defaultValue
|
||||
|
||||
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
|
||||
return value ?: throw IllegalStateException("${property.name} not initialized")
|
||||
}
|
||||
|
||||
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) = synchronized(this) {
|
||||
if (!isSet) {
|
||||
this.value = value
|
||||
isSet = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user