Skip to content

Commit

Permalink
Fix discriminator override for kotlin
Browse files Browse the repository at this point in the history
  • Loading branch information
altro3 committed Nov 21, 2024
1 parent 4b657fd commit 95bc64b
Show file tree
Hide file tree
Showing 18 changed files with 139 additions and 88 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.media.StringSchema;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.parameters.RequestBody;
import io.swagger.v3.oas.models.responses.ApiResponse;
import io.swagger.v3.oas.models.servers.Server;
import org.apache.commons.lang3.StringUtils;
Expand Down Expand Up @@ -2102,7 +2103,7 @@ private void processVar(CodegenModel model, List<CodegenProperty> vars, List<Cod
copyVar = v.clone();
copyVar.isOverridden = true;
}
if (copyVar.isOverridden != null && copyVar.isOverridden) {
if (copyVar.isOverridden != null && copyVar.isOverridden && (!parentIsOneOfInterface || v.isDiscriminator)) {
copyVar.vendorExtensions.put("overridden", true);
}
requiredVarsWithoutDiscriminator.add(copyVar);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,24 +123,27 @@ public static void processGenericAnnotations(String dataType, String dataTypeWit
boolean useBeanValidation, boolean isGenerateHardNullable, boolean isNullable,
boolean isRequired, boolean isReadonly,
boolean withNullablePostfix) {
String genericAnnotations = null;
var typeWithGenericAnnotations = dataType;
var typeWithEnumWithGenericAnnotations = dataTypeWithEnum;
if (useBeanValidation && itemsProp != null && dataType.contains("<")) {
if (isMap) {
var genericAnnotations = genericAnnotations(itemsProp, isGenerateHardNullable);
genericAnnotations = genericAnnotations(itemsProp, isGenerateHardNullable);
processGenericAnnotations(itemsProp, useBeanValidation, isGenerateHardNullable, itemsProp.isNullable, itemsProp.required, itemsProp.isReadOnly, withNullablePostfix);
typeWithGenericAnnotations = "Map<String, " + genericAnnotations + itemsProp.vendorExtensions.get("typeWithGenericAnnotations") + ">";
typeWithEnumWithGenericAnnotations = "Map<String, " + genericAnnotations + itemsProp.vendorExtensions.get("typeWithEnumWithGenericAnnotations") + ">";
} else if (containerType != null) {
var genericAnnotations = genericAnnotations(itemsProp, isGenerateHardNullable);
genericAnnotations = genericAnnotations(itemsProp, isGenerateHardNullable);
processGenericAnnotations(itemsProp, useBeanValidation, isGenerateHardNullable, itemsProp.isNullable, itemsProp.required, itemsProp.isReadOnly, withNullablePostfix);
typeWithGenericAnnotations = containerType + "<" + genericAnnotations + itemsProp.vendorExtensions.get("typeWithGenericAnnotations") + ">";
typeWithEnumWithGenericAnnotations = containerType + "<" + genericAnnotations + itemsProp.vendorExtensions.get("typeWithEnumWithGenericAnnotations") + ">";
}
}

ext.put("typeWithGenericAnnotations", typeWithGenericAnnotations + (withNullablePostfix && (isNullable || isRequired && isReadonly) ? "?" : ""));
ext.put("typeWithEnumWithGenericAnnotations", typeWithEnumWithGenericAnnotations + (withNullablePostfix && (isNullable || isRequired && isReadonly) ? "?" : ""));
var isNullableType = withNullablePostfix && (isNullable || isRequired && isReadonly || (genericAnnotations != null && !genericAnnotations.contains("NotNull") && !isRequired));

ext.put("typeWithGenericAnnotations", typeWithGenericAnnotations + (isNullableType ? "?" : ""));
ext.put("typeWithEnumWithGenericAnnotations", typeWithEnumWithGenericAnnotations + (isNullableType ? "?" : ""));
}

private static String genericAnnotations(CodegenProperty prop, boolean isGenerateHardNullable) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4293,7 +4293,7 @@ public CodegenProperty fromProperty(String name, Schema p, boolean required, boo
property.defaultValueWithParam = toDefaultValueWithParam(name, p);

LOGGER.debug("debugging from property return: {}", property);
schemaCodegenPropertyCache.put(ns, property);
// schemaCodegenPropertyCache.put(ns, property);
return property;
}

Expand Down Expand Up @@ -6072,7 +6072,7 @@ protected void addVars(IJsonSchemaValidationProperties m, List<CodegenProperty>
} else {
final CodegenProperty cp;

if (cm != null && cm.allVars == vars && varsMap.keySet().contains(key)) {
if (cm != null && cm.allVars == vars && varsMap.containsKey(key)) {
// when updating allVars, reuse the codegen property from the child model if it's already present
// the goal is to avoid issues when the property is defined in both child, parent but the
// definition is not identical, e.g. required vs optional, integer vs string
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ interface {{classname}} {
{{{.}}}
{{/vendorExtensions.x-operation-extra-annotation}}
fun {{nickname}}({{#allParams}}
{{#formatSingleLine}}{{>client/params/queryParams}}{{>client/params/pathParams}}{{>client/params/headerParams}}{{>client/params/bodyParams}}{{>client/params/formParams}}{{>client/params/cookieParams}}{{^-last}},{{/-last}}{{/formatSingleLine}}
{{#formatSingleLine}}{{>client/params/queryParams}}{{>client/params/pathParams}}{{>client/params/headerParams}}{{>client/params/bodyParams}}{{>client/params/formParams}}{{>client/params/cookieParams}},{{/formatSingleLine}}
{{/allParams}}){{#returnType}}: {{{returnType}}}{{/returnType}}
{{/formatNoEmptyLines}}
{{/operation}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,5 +27,5 @@ annotation class Authorization(
/**
* The scopes for the oauth authorization.
*/
val scopes: Array<String> = []
val scopes: Array<String> = [],
)
Original file line number Diff line number Diff line change
Expand Up @@ -24,19 +24,20 @@ open class AuthorizationBinder : AnnotatedClientRequestBinder<Authorization> {
return Authorization::class.java
}

override fun bind(@NonNull context: MethodInvocationContext<Any, Any>,
@NonNull uriContext: ClientRequestUriContext,
@NonNull request: MutableHttpRequest<*>
override fun bind(
@NonNull context: MethodInvocationContext<Any, Any>,
@NonNull uriContext: ClientRequestUriContext,
@NonNull request: MutableHttpRequest<*>,
) {
val annotations: List<AnnotationValue<Authorization>> = context.annotationMetadata
.getAnnotationValuesByType(Authorization::class.java)
.getAnnotationValuesByType(Authorization::class.java)
if (annotations.isNotEmpty()) {
val authorizationNames = ArrayList<String>()
for (ann in annotations) {
ann.stringValue("value")
.filter{ s -> !s.isNullOrEmpty() }
.ifPresent { v -> authorizationNames.add(configurationName(v)) }
.filter{ s -> !s.isNullOrEmpty() }
.ifPresent { v -> authorizationNames.add(configurationName(v)) }
}
request.setAttribute(AUTHORIZATION_NAMES, authorizationNames)
}
Expand All @@ -47,6 +48,6 @@ open class AuthorizationBinder : AnnotatedClientRequestBinder<Authorization> {
}

companion object {
var AUTHORIZATION_NAMES = "micronaut.security.AUTHORIZATION_NAMES"
const val AUTHORIZATION_NAMES = "micronaut.security.AUTHORIZATION_NAMES"
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,15 @@ open class AuthorizationFilter(
init {
clientConfigurationByName = clientConfigurations
.filter { it.isEnabled }
.collect(Collectors.toMap({ it.name }, { it }))
tokenPropagatorByName = HashMap()
clientCredentialsClientByName = HashMap()
.filter { it.isEnabled }
.collect(Collectors.toMap({ it.name }, { it }))
tokenPropagatorByName = mutableMapOf()
clientCredentialsClientByName = mutableMapOf()
authorizationsByName = configurableAuthorizations
.collect(Collectors.toMap({ it.name }, { it }))
.collect(Collectors.toMap({ it.name }, { it }))
}

override fun doFilter(request: @NonNull MutableHttpRequest<*>, chain: @NonNull ClientFilterChain): Publisher<out HttpResponse<*>?> {
override fun doFilter(@NonNull request: MutableHttpRequest<*>, @NonNull chain: ClientFilterChain): Publisher<out HttpResponse<*>?> {
val names = request.getAttribute(AuthorizationBinder.AUTHORIZATION_NAMES, MutableList::class.java).orElse(null)
if (names.isNullOrEmpty()) {
return chain.proceed(request)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,5 @@ import {{javaxPackage}}.annotation.Generated
@Bindable
annotation class Authorizations(

val value: Array<Authorization>
val value: Array<Authorization>,
)
Original file line number Diff line number Diff line change
Expand Up @@ -15,31 +15,28 @@ import {{javaxPackage}}.annotation.Generated
{{>common/generatedAnnotation}}
{{/generatedAnnotation}}
@EachProperty("security.api-key-auth")
data class ApiKeyAuthConfiguration @ConfigurationInject
constructor(
@Parameter override val name: String,
@NonNull var location: AuthKeyLocation,
@NonNull var paramName: String,
@NonNull var apiKey: String
data class ApiKeyAuthConfiguration @ConfigurationInject constructor(
@Parameter
override val name: String,
@NonNull
var location: AuthKeyLocation,
@NonNull
var paramName: String,
@NonNull
var apiKey: String,
) : ConfigurableAuthorization {
override fun applyAuthorization(@NonNull request: MutableHttpRequest<*>) {
when (location) {
AuthKeyLocation.HEADER -> {
request.header(paramName, apiKey)
}
AuthKeyLocation.QUERY -> {
request.parameters.add(paramName, apiKey)
}
AuthKeyLocation.COOKIE -> {
request.cookie(Cookie.of(paramName, apiKey))
}
AuthKeyLocation.HEADER -> request.header(paramName, apiKey)
AuthKeyLocation.QUERY -> request.parameters.add(paramName, apiKey)
AuthKeyLocation.COOKIE -> request.cookie(Cookie.of(paramName, apiKey))
}
}

enum class AuthKeyLocation {
HEADER,
QUERY,
COOKIE
COOKIE,
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,12 @@ import {{javaxPackage}}.annotation.Generated
{{/generatedAnnotation}}
@EachProperty("security.basic-auth")
data class HttpBasicAuthConfiguration(
@Parameter override val name: String,
@NonNull var username: String,
@NonNull var password: String
@Parameter
override val name: String,
@NonNull
var username: String,
@NonNull
var password: String,
) : ConfigurableAuthorization {
override fun applyAuthorization(@NonNull request: MutableHttpRequest<*>) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{{#isBodyParam}}@Body {{>common/params/validation}}{{>client/params/type}}{{{paramName}}}: {{{vendorExtensions.typeWithEnumWithGenericAnnotations}}}{{/isBodyParam}}
{{#isBodyParam}}@Body {{>common/params/validation}}{{>client/params/type}}{{{paramName}}}: {{{vendorExtensions.typeWithEnumWithGenericAnnotations}}}{{#vendorExtensions.defaultValueInit}} = {{{.}}}{{/vendorExtensions.defaultValueInit}}{{^vendorExtensions.defaultValueInit}}{{#isNullable}} = null{{/isNullable}}{{^isNullable}}{{^required}} = null{{/required}}{{/isNullable}}{{/vendorExtensions.defaultValueInit}}{{/isBodyParam}}
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{{#isFormParam}}{{>common/params/validation}}{{>client/params/type}}{{{paramName}}}: {{{vendorExtensions.typeWithEnumWithGenericAnnotations}}}{{/isFormParam}}
{{#isFormParam}}{{>common/params/validation}}{{>client/params/type}}{{{paramName}}}: {{{vendorExtensions.typeWithEnumWithGenericAnnotations}}}{{#vendorExtensions.defaultValueInit}} = {{{.}}}{{/vendorExtensions.defaultValueInit}}{{^vendorExtensions.defaultValueInit}}{{#isNullable}} = null{{/isNullable}}{{^isNullable}}{{^required}} = null{{/required}}{{/isNullable}}{{/vendorExtensions.defaultValueInit}}{{/isFormParam}}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
{{>common/generatedAnnotation}}
{{/generatedAnnotation}}
{{>common/model/typeInfoAnnotation}}
interface {{classname}}{{#vendorExtensions.x-implements}}{{#-first}} : {{{.}}}{{/-first}}{{^-first}}, {{{.}}}{{/-first}}{{/vendorExtensions.x-implements}}{{/formatNoEmptyLines}}{{#discriminator}} {
{{/formatNoEmptyLines}}interface {{classname}}{{#vendorExtensions.x-implements}}{{#-first}} : {{{.}}}{{/-first}}{{^-first}}, {{{.}}}{{/-first}}{{/vendorExtensions.x-implements}}{{#discriminator}} {
val {{propertyName}}: {{propertyType}}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
{{#jackson}}
@JsonIgnoreProperties(
value = ["{{{discriminator.propertyBaseName}}}"], // ignore manually set {{{discriminator.propertyBaseName}}}, it will be automatically generated by Jackson during serialization
allowSetters = true // allows the {{{discriminator.propertyBaseName}}} to be set during deserialization
allowSetters = true, // allows the {{{discriminator.propertyBaseName}}} to be set during deserialization
)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "{{{discriminator.propertyBaseName}}}", visible = true)
{{#vendorExtensions.hasMappedModels}}
Expand All @@ -13,4 +13,4 @@
{{/vendorExtensions.hasMappedModels}}
{{/jackson}}
{{/discriminator.propertyBaseName}}
{{/discriminator}}
{{/discriminator}}
Original file line number Diff line number Diff line change
Expand Up @@ -53,20 +53,20 @@
{{#responses}}
ApiResponse(responseCode = "{{{code}}}", description = "{{{message}}}"{{#baseType}}, content = [
{{#produces}}
Content(mediaType = "{{{mediaType}}}", {{#isArray}}array = ArraySchema({{/isArray}}schema = Schema(implementation = {{{baseType}}}::class){{#isArray}}){{/isArray}}){{^-last}},{{/-last}}
Content(mediaType = "{{{mediaType}}}", {{#isArray}}array = ArraySchema({{/isArray}}schema = Schema(implementation = {{{baseType}}}::class){{#isArray}}){{/isArray}}),
{{/produces}}
]{{/baseType}}){{^-last}},{{/-last}}
]{{/baseType}}),
{{/responses}}
]{{#vendorExtensions.hasNotBodyParam}},
],{{#vendorExtensions.hasNotBodyParam}}
parameters = [
{{#vendorExtensions.swaggerParams}}
Parameter(name = "{{baseName}}"{{#isDeprecated}}, deprecated = true{{/isDeprecated}}{{#description}}, description = "{{{description}}}"{{/description}}{{#required}}, required = true{{/required}}, `in` = ParameterIn.{{#isCookieParam}}COOKIE{{/isCookieParam}}{{#isHeaderParam}}HEADER{{/isHeaderParam}}{{#isQueryParam}}QUERY{{/isQueryParam}}{{#isPathParam}}PATH{{/isPathParam}}){{^-last}},{{/-last}}
Parameter(name = "{{baseName}}"{{#isDeprecated}}, deprecated = true{{/isDeprecated}}{{#description}}, description = "{{{description}}}"{{/description}}{{#required}}, required = true{{/required}}, `in` = ParameterIn.{{#isCookieParam}}COOKIE{{/isCookieParam}}{{#isHeaderParam}}HEADER{{/isHeaderParam}}{{#isQueryParam}}QUERY{{/isQueryParam}}{{#isPathParam}}PATH{{/isPathParam}}),
{{/vendorExtensions.swaggerParams}}
]{{/vendorExtensions.hasNotBodyParam}}{{#hasAuthMethods}},
],{{/vendorExtensions.hasNotBodyParam}}{{#hasAuthMethods}}
security = [
{{#authMethods}}
SecurityRequirement(name = "{{name}}"{{#isOAuth}}{{#scopes.1}}, scopes = [{{#scopes}}"{{scope}}"{{^-last}}, {{/-last}}{{/scopes}}]{{/scopes.1}}{{/isOAuth}}){{^-last}},{{/-last}}
SecurityRequirement(name = "{{name}}"{{#isOAuth}}{{#scopes.1}}, scopes = [{{#scopes}}"{{scope}}"{{^-last}}, {{/-last}}{{/scopes}}]{{/scopes.1}}{{/isOAuth}}),
{{/authMethods}}
]{{/hasAuthMethods}}
],{{/hasAuthMethods}}
)
{{/generateSwagger2Annotations}}
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ interface {{classname}} {
{{#isDeprecated}}
@java.lang.Deprecated
{{/isDeprecated}}
{{{paramName}}}: {{#isEnum}}{{{vendorExtensions.typeWithEnumWithGenericAnnotations}}}{{/isEnum}}{{^isEnum}}{{{vendorExtensions.typeWithGenericAnnotations}}}{{/isEnum}}{{^-last}},{{/-last}}{{/formatSingleLine}}
{{{paramName}}}: {{#isEnum}}{{{vendorExtensions.typeWithEnumWithGenericAnnotations}}}{{/isEnum}}{{^isEnum}}{{{vendorExtensions.typeWithGenericAnnotations}}}{{/isEnum}},{{/formatSingleLine}}
{{/allParams}}){{#returnType}}: {{{returnType}}}{{/returnType}}
{{/formatNoEmptyLines}}

Expand Down
Loading

0 comments on commit 95bc64b

Please sign in to comment.