Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Kotlin][Client] new library support: Retrofit 2.x #4518

Merged
merged 30 commits into from
Dec 15, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
b88f465
Some clean code.
javils Nov 9, 2019
cd6bf93
Add support for retrofit2 in models and apis. Need work in ApiClient,…
javils Nov 9, 2019
63d3a25
Add ApiClient with retrofit2 support.
javils Nov 17, 2019
c419ca3
Remove unnecessary package.
javils Nov 17, 2019
bbe92d9
Add scripts to generate samples.
javils Nov 17, 2019
4d639d6
Generate sample of retrofit2
javils Nov 17, 2019
993ac5b
Merge branch 'master' into feature/kotlin/library/retrofit
javils Nov 17, 2019
ed0e0f0
Change toUpperCase to toUpperCase(Locale.ROOT) to fix compile.
javils Nov 17, 2019
07fd78f
Added GSON library when it's needed
javils Nov 17, 2019
a3b34b5
Fix typo.
javils Nov 30, 2019
f37bfbb
Add some missing common files.
javils Nov 30, 2019
818f249
Execute bin script.
javils Nov 30, 2019
f27b5dc
Merge branch 'master' into feature/kotlin/library/retrofit
javils Nov 30, 2019
6e4566f
Remove copy&paste error in script.
javils Dec 3, 2019
f81bbf3
Merge remote-tracking branch 'upstream/master' into feature/kotlin/li…
javils Dec 3, 2019
ce09949
[kotlin] update outdated files
4brunu Dec 3, 2019
e7f0140
Merge pull request #1 from 4brunu/feature/javils_retrofit
javils Dec 3, 2019
e192465
Merge remote-tracking branch 'upstream/master' into feature/kotlin/li…
javils Dec 6, 2019
39ac24b
Fix apis with no params.
javils Dec 10, 2019
3ace985
Add missing import in ApiClient
javils Dec 10, 2019
f3d2c22
Add support for CSV, SSV, TSV, PIPES, SPACES in retrofit 2 library.
javils Dec 10, 2019
930d767
Fix package name.
javils Dec 10, 2019
764cd51
Execute kotlin-client-retrofit2.sh script.
javils Dec 10, 2019
a60b39f
force rebuild.
javils Dec 11, 2019
705e097
execute script again.
javils Dec 11, 2019
bc78a38
Merge remote-tracking branch 'upstream/master' into feature/kotlin/li…
javils Dec 12, 2019
d2efbfc
Add missing imports from okhttp3.
javils Dec 14, 2019
3274aa0
Execute retrofit2 script.
javils Dec 14, 2019
a01609d
Merge remote-tracking branch 'upstream/master' into feature/kotlin/li…
javils Dec 14, 2019
3b31e91
Rerun script.
javils Dec 14, 2019
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions bin/kotlin-client-all.sh
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,4 @@
./bin/kotlin-client-string.sh
./bin/kotlin-client-threetenbp.sh
./bin/kotlin-client-nullable.sh
./bin/kotlin-client-retrofit2.sh
32 changes: 32 additions & 0 deletions bin/kotlin-client-retrofit2.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#!/bin/sh

SCRIPT="$0"
echo "# START SCRIPT: $SCRIPT"

while [ -h "$SCRIPT" ] ; do
ls=$(ls -ld "$SCRIPT")
link=$(expr "$ls" : '.*-> \(.*\)$')
if expr "$link" : '/.*' > /dev/null; then
SCRIPT="$link"
else
SCRIPT=$(dirname "$SCRIPT")/"$link"
fi
done

if [ ! -d "${APP_DIR}" ]; then
APP_DIR=$(dirname "$SCRIPT")/..
APP_DIR=$(cd "${APP_DIR}"; pwd)
fi

executable="./modules/openapi-generator-cli/target/openapi-generator-cli.jar"

if [ ! -f "$executable" ]
then
mvn -B clean package
fi

# if you've executed sbt assembly previously it will use that instead.
export JAVA_OPTS="${JAVA_OPTS} -Xmx1024M -DloggerPath=conf/log4j.properties"
ags="generate -t modules/openapi-generator/src/main/resources/kotlin-client -i modules/openapi-generator/src/test/resources/2_0/petstore.yaml -g kotlin --artifact-id kotlin-petstore-retrofit2 --library retrofit2 -o samples/client/petstore/kotlin-retrofit2 $@"

java ${JAVA_OPTS} -jar ${executable} ${ags}
2 changes: 1 addition & 1 deletion docs/generators/kotlin.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,4 @@ sidebar_label: kotlin
|modelMutable|Create mutable models| |false|
|dateLibrary|Option. Date library to use|<dl><dt>**string**</dt><dd>String</dd><dt>**java8**</dt><dd>Java 8 native JSR310 (jvm only)</dd><dt>**threetenbp**</dt><dd>Threetenbp (jvm only)</dd><dl>|java8|
|collectionType|Option. Collection type to use|<dl><dt>**array**</dt><dd>kotlin.Array</dd><dt>**list**</dt><dd>kotlin.collections.List</dd><dl>|array|
|library|Library template (sub-template) to use|<dl><dt>**jvm-okhttp4**</dt><dd>[DEFAULT] Platform: Java Virtual Machine. HTTP client: OkHttp 4.2.0 (Android 5.0+ and Java 8+). JSON processing: Moshi 1.8.0.</dd><dt>**jvm-okhttp3**</dt><dd>Platform: Java Virtual Machine. HTTP client: OkHttp 3.12.4 (Android 2.3+ and Java 7+). JSON processing: Moshi 1.8.0.</dd><dt>**multiplatform**</dt><dd>Platform: Kotlin multiplatform. HTTP client: Ktor 1.2.4. JSON processing: Kotlinx Serialization: 0.12.0.</dd><dl>|jvm-okhttp4|
|library|Library template (sub-template) to use|<dl><dt>**jvm-okhttp4**</dt><dd>[DEFAULT] Platform: Java Virtual Machine. HTTP client: OkHttp 4.2.0 (Android 5.0+ and Java 8+). JSON processing: Moshi 1.8.0.</dd><dt>**jvm-okhttp3**</dt><dd>Platform: Java Virtual Machine. HTTP client: OkHttp 3.12.4 (Android 2.3+ and Java 7+). JSON processing: Moshi 1.8.0.</dd><dt>**retrofit2**</dt><dd>Platform: Java Virtual Machine. HTTP client: Retrofit 2.6.2.</dd><dt>**multiplatform**</dt><dd>Platform: Kotlin multiplatform. HTTP client: Ktor 1.2.4. JSON processing: Kotlinx Serialization: 0.12.0.</dd><dl>|jvm-okhttp4|

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ wrapper {

buildscript {
ext.kotlin_version = '1.3.61'
{{#retrofit2}}
ext.retrofitVersion = '2.6.2'
{{/retrofit2}}

repositories {
mavenCentral()
Expand Down Expand Up @@ -38,10 +41,10 @@ dependencies {
compile "com.squareup.moshi:moshi-kotlin:1.9.2"
{{/moshiCodeGen}}
compile "com.squareup.moshi:moshi-adapters:1.9.2"
{{#moshiCodeGen}}
{{#moshiCodeGen}}
compile "com.squareup.moshi:moshi:1.9.2"
kapt "com.squareup.moshi:moshi-kotlin-codegen:1.9.2"
{{/moshiCodeGen}}
{{/moshiCodeGen}}
{{/moshi}}
{{#gson}}
compile "com.google.code.gson:gson:2.8.6"
Expand All @@ -55,5 +58,15 @@ dependencies {
{{#threetenbp}}
compile "org.threeten:threetenbp:1.4.0"
{{/threetenbp}}
{{#retrofit2}}
compile "com.squareup.retrofit2:retrofit:$retrofitVersion"
{{#gson}}
compile "com.squareup.retrofit2:converter-gson:$retrofitVersion"
{{/gson}}
{{#moshi}}
compile "com.squareup.retrofit2:converter-moshi:$retrofitVersion"
{{/moshi}}
compile "com.squareup.retrofit2:converter-scalars:$retrofitVersion"
{{/retrofit2}}
testCompile "io.kotlintest:kotlintest-runner-junit5:3.1.0"
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
{{#jvm}}
{{^multiplatform}}
{{#gson}}
import com.google.gson.annotations.SerializedName
{{/gson}}
Expand All @@ -13,7 +13,7 @@ import android.os.Parcelable
import kotlinx.android.parcel.Parcelize

{{/parcelizeModels}}
{{/jvm}}
{{/multiplatform}}
{{#multiplatform}}
import kotlinx.serialization.*
import kotlinx.serialization.internal.CommonEnumSerializer
Expand Down Expand Up @@ -59,14 +59,14 @@ import java.io.Serializable
{{#nonPublicApi}}internal {{/nonPublicApi}}enum class {{{nameInCamelCase}}}(val value: {{#isListContainer}}{{{ nestedType }}}{{/isListContainer}}{{^isListContainer}}{{{dataType}}}{{/isListContainer}}){
{{#allowableValues}}
{{#enumVars}}
{{#jvm}}
{{^multiplatform}}
{{#moshi}}
@Json(name = {{{value}}}) {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}}
{{/moshi}}
{{#gson}}
@SerializedName(value={{{value}}}) {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}}
{{/gson}}
{{/jvm}}
{{/multiplatform}}
{{#multiplatform}}
{{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}}
{{/multiplatform}}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
{{#description}}
/* {{{description}}} */
{{/description}}
{{#jvm}}
{{^multiplatform}}
{{#moshi}}
@Json(name = "{{{vendorExtensions.x-base-name-literal}}}")
{{/moshi}}
{{#gson}}
@SerializedName("{{{vendorExtensions.x-base-name-literal}}}")
{{/gson}}
{{/jvm}}
{{/multiplatform}}
{{#multiplatform}}@SerialName(value = "{{{vendorExtensions.x-base-name-literal}}}") {{/multiplatform}}{{>modelMutable}} {{{name}}}: {{#isEnum}}{{#isListContainer}}{{#isList}}kotlin.collections.List{{/isList}}{{^isList}}kotlin.Array{{/isList}}<{{classname}}.{{{nameInCamelCase}}}>{{/isListContainer}}{{^isListContainer}}{{classname}}.{{{nameInCamelCase}}}{{/isListContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}? = {{#defaultvalue}}{{defaultvalue}}{{/defaultvalue}}{{^defaultvalue}}null{{/defaultvalue}}
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
{{#description}}
/* {{{description}}} */
{{/description}}
{{#jvm}}
{{^multiplatform}}
{{#moshi}}
@Json(name = "{{{vendorExtensions.x-base-name-literal}}}")
{{/moshi}}
{{#gson}}
@SerializedName("{{{vendorExtensions.x-base-name-literal}}}")
{{/gson}}
{{/jvm}}
{{/multiplatform}}
{{#multiplatform}}@SerialName(value = "{{{vendorExtensions.x-base-name-literal}}}") @Required {{/multiplatform}}{{>modelMutable}} {{{name}}}: {{#isEnum}}{{#isListContainer}}{{#isList}}kotlin.collections.List{{/isList}}{{^isList}}kotlin.Array{{/isList}}<{{classname}}.{{{nameInCamelCase}}}>{{/isListContainer}}{{^isListContainer}}{{classname}}.{{{nameInCamelCase}}}{{/isListContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{#isNullable}}?{{/isNullable}}
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
{{#jvm}}
{{^multiplatform}}
{{#gson}}
import com.google.gson.annotations.SerializedName
{{/gson}}
{{#moshi}}
import com.squareup.moshi.Json
{{/moshi}}
{{/jvm}}
{{/multiplatform}}
{{#multiplatform}}
import kotlinx.serialization.*
import kotlinx.serialization.internal.CommonEnumSerializer
Expand All @@ -19,14 +19,14 @@ import kotlinx.serialization.internal.CommonEnumSerializer
{{#nonPublicApi}}internal {{/nonPublicApi}}enum class {{classname}}(val value: {{{dataType}}}){

{{#allowableValues}}{{#enumVars}}
{{#jvm}}
{{^multiplatform}}
{{#moshi}}
@Json(name = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}})
{{/moshi}}
{{#gson}}
@SerializedName(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}})
{{/gson}}
{{/jvm}}
{{/multiplatform}}
{{#isListContainer}}
{{#isList}}
{{&name}}(listOf({{{value}}})){{^-last}},{{/-last}}{{#-last}};{{/-last}}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package {{apiPackage}}

import {{packageName}}.infrastructure.CollectionFormats.*
import retrofit2.http.*
import retrofit2.Call
import okhttp3.RequestBody
import okhttp3.ResponseBody
import okhttp3.MultipartBody

{{#imports}}import {{import}}
{{/imports}}

{{#operations}}
interface {{classname}} {
{{#operation}}
{{#isDeprecated}}
@Deprecated("This api was deprecated")
{{/isDeprecated}}
{{#formParams}}
{{#-first}}
{{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}
{{/-first}}
{{/formParams}}
{{^formParams}}
{{#prioritizedContentTypes}}
{{#-first}}
@Headers({
"Content-Type:{{{mediaType}}}"
})
{{/-first}}
{{/prioritizedContentTypes}}
{{/formParams}}
@{{httpMethod}}("{{{path}}}")
fun {{operationId}}({{^allParams}}){{/allParams}}{{#allParams}}{{>libraries/retrofit2/queryParams}}{{>libraries/retrofit2/pathParams}}{{>libraries/retrofit2/headerParams}}{{>libraries/retrofit2/bodyParams}}{{>libraries/retrofit2/formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}}){{/hasMore}}{{/allParams}}: Call<{{#isResponseFile}}ResponseBody{{/isResponseFile}}{{^isResponseFile}}{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Unit{{/returnType}}{{/isResponseFile}}>

{{/operation}}
}
{{/operations}}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{{#isBodyParam}}@Body {{paramName}}: {{{dataType}}}{{/isBodyParam}}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{{#isFormParam}}{{^isFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field{{/isMultipart}}("{{baseName}}") {{paramName}}: {{{dataType}}}{{/isFile}}{{#isFile}}{{#isMultipart}}@Part{{/isMultipart}}{{^isMultipart}}@Field("{{baseName}}"){{/isMultipart}} {{paramName}}: MultipartBody.Part {{/isFile}}{{/isFormParam}}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{{#isHeaderParam}}@Header("{{baseName}}") {{paramName}}: {{{dataType}}}{{/isHeaderParam}}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package {{packageName}}.infrastructure

import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.scalars.ScalarsConverterFactory
{{#gson}}
import retrofit2.converter.gson.GsonConverterFactory
{{/gson}}
{{#moshi}}
import retrofit2.converter.moshi.MoshiConverterFactory
{{/moshi}}

{{#nonPublicApi}}internal {{/nonPublicApi}}class ApiClient(
private var baseUrl: String = "{{{basePath}}}",
private var okHttpClient: OkHttpClient
) {
init {
normalizeBaseUrl()
}

val retrofitBuilder: Retrofit.Builder by lazy {

Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(ScalarsConverterFactory.create())
{{#gson}}
.addConverterFactory(GsonConverterFactory.create(Serializer.gson))
{{/gson}}
{{#moshi}}
.addConverterFactory(MoshiConverterFactory.create(Serializer.moshi))
{{/moshi}}
}

fun <S> createService(serviceClass: Class<S>): S {
return retrofitBuilder.client(okHttpClient).build().create(serviceClass)
}

private fun normalizeBaseUrl() {
if (!baseUrl.endsWith("/")) {
baseUrl += "/"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package {{packageName}}.infrastructure

{{#moshi}}
import com.squareup.moshi.FromJson
import com.squareup.moshi.ToJson
{{/moshi}}
{{#gson}}
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonWriter
import com.google.gson.stream.JsonToken.NULL
import java.io.IOException
{{/gson}}

{{#moshi}}
{{#nonPublicApi}}internal {{/nonPublicApi}}class ByteArrayAdapter {
@ToJson
fun toJson(data: ByteArray): String = String(data)

@FromJson
fun fromJson(data: String): ByteArray = data.toByteArray()
}
{{/moshi}}
{{#gson}}
{{#nonPublicApi}}internal {{/nonPublicApi}}class ByteArrayAdapter : TypeAdapter<ByteArray>() {
@Throws(IOException::class)
override fun write(out: JsonWriter?, value: ByteArray?) {
if (value == null) {
out?.nullValue()
} else {
out?.value(String(value))
}
}

@Throws(IOException::class)
override fun read(out: JsonReader?): ByteArray? {
out ?: return null

when (out.peek()) {
NULL -> {
out.nextNull()
return null
}
else -> {
return out.nextString().toByteArray()
}
}
}
}
{{/gson}}
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package {{packageName}}.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()
}
Loading