Skip to content

Commit

Permalink
Merge pull request #1894 from altro3/refactor-kotlin-pojos
Browse files Browse the repository at this point in the history
Refactor generating kotlin pojos
  • Loading branch information
altro3 authored Dec 18, 2024
2 parents e13384d + 2758c5e commit 15c0dec
Show file tree
Hide file tree
Showing 26 changed files with 652 additions and 268 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -735,6 +735,11 @@ public String toModelTestFilename(String name) {
@Override
public CodegenParameter fromParameter(Parameter p, Set<String> imports) {
var parameter = super.fromParameter(p, imports);

if (parameter.isPathParam && !parameter.required) {
parameter.required = true;
}

checkPrimitives(parameter, unaliasSchema(p.getSchema()));
// if name is escaped
var realName = parameter.paramName;
Expand Down

Large diffs are not rendered by default.

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 Expand Up @@ -438,6 +441,9 @@ private static List<String> normalizeExtraAnnotations(String prefix, Collection<
}

private static String normalizeExtraAnnotation(String prefix, String annotationStr) {
if (annotationStr.startsWith(prefix)) {
return annotationStr;
}
return prefix + (annotationStr.startsWith("@") ? annotationStr.substring(1) : annotationStr);
}

Expand Down

Large diffs are not rendered by default.

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 @@ -13,7 +13,7 @@
{{#isContainer}}
// Is a container wrapped = {{isXmlWrapped}}
{{#items}}
// items.name = {{name}} items.baseName = {{baseName}} items.xmlName = {{xmlName}} items.xmlNamespace = {{xmlNamespace}}
// items.name = {{{name}}} items.baseName = {{baseName}} items.xmlName = {{xmlName}} items.xmlNamespace = {{xmlNamespace}}
// items.example = {{example}} items.type = {{dataType}}
@{{{vendorExtensions.fieldAnnPrefix}}}XmlElement({{#xmlNamespace}}namespace = "{{xmlNamespace}}", {{/xmlNamespace}}name = "{{#xmlName}}{{xmlName}}{{/xmlName}}{{^xmlName}}{{baseName}}{{/xmlName}}")
{{/items}}
Expand Down
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 @@ -45,7 +45,7 @@
{{/vendorExtensions.x-class-extra-annotation}}
{{/formatNoEmptyLines}}
{{!Declare the class with extends and implements}}
{{#nonPublicApi}}internal {{/nonPublicApi}}{{#hasChildren}}open {{/hasChildren}}{{^hasChildren}}{{#hasVars}}data {{/hasVars}}{{/hasChildren}}class {{classname}}{{#hasVars}}({{/hasVars}}
{{#nonPublicApi}}internal {{/nonPublicApi}}{{#hasChildren}}open {{/hasChildren}}{{vendorExtensions.dataClass}}class {{classname}}{{#hasVars}}({{/hasVars}}
{{#vendorExtensions.requiredVarsWithoutDiscriminator}}

{{#formatNoEmptyLines}}
Expand All @@ -66,34 +66,9 @@
{{/deprecated}}
{{/description}}
{{>common/model/field_annotations}}
{{#vendorExtensions.overridden}}override {{/vendorExtensions.overridden}}{{^vendorExtensions.overridden}}{{#hasChildren}}open {{/hasChildren}}{{/vendorExtensions.overridden}}var {{{name}}}: {{{vendorExtensions.typeWithEnumWithGenericAnnotations}}}{{#vendorExtensions.defaultValueInit}} = {{{.}}}{{/vendorExtensions.defaultValueInit}}{{^vendorExtensions.defaultValueInit}}{{#isNullable}} = null{{/isNullable}}{{/vendorExtensions.defaultValueInit}},
{{^vendorExtensions.isParentVar}}{{#vendorExtensions.overridden}}override {{/vendorExtensions.overridden}}{{^vendorExtensions.overridden}}{{#hasChildren}}open {{/hasChildren}}{{/vendorExtensions.overridden}}var {{/vendorExtensions.isParentVar}}{{{name}}}: {{{vendorExtensions.typeWithEnumWithGenericAnnotations}}}{{#vendorExtensions.defaultValueInit}} = {{{.}}}{{/vendorExtensions.defaultValueInit}}{{^vendorExtensions.defaultValueInit}}{{#isNullable}} = null{{/isNullable}}{{/vendorExtensions.defaultValueInit}},
{{/formatNoEmptyLines}}
{{/vendorExtensions.requiredVarsWithoutDiscriminator}}
{{#vendorExtensions.withInheritance}}
{{#vendorExtensions.optionalVars}}

{{#formatNoEmptyLines}}
{{#description}}
/**
* {{description}}
{{#deprecated}}
*
* @deprecated{{#vendorExtensions.x-deprecated-message}} {{{.}}}{{/vendorExtensions.x-deprecated-message}}
{{/deprecated}}
*/
{{/description}}
{{^description}}
{{#deprecated}}
/**
* @deprecated{{#vendorExtensions.x-deprecated-message}} {{{.}}}{{/vendorExtensions.x-deprecated-message}}
*/
{{/deprecated}}
{{/description}}
{{>common/model/field_annotations}}
{{#vendorExtensions.overridden}}override {{/vendorExtensions.overridden}}{{^vendorExtensions.overridden}}{{#vendorExtensions.hasChildren}}open {{/vendorExtensions.hasChildren}}{{/vendorExtensions.overridden}}var {{{name}}}: {{{vendorExtensions.typeWithEnumWithGenericAnnotations}}} = {{#vendorExtensions.defaultValueInit}}{{{.}}}{{/vendorExtensions.defaultValueInit}}{{^vendorExtensions.defaultValueInit}}null{{/vendorExtensions.defaultValueInit}},
{{/formatNoEmptyLines}}
{{/vendorExtensions.optionalVars}}
{{/vendorExtensions.withInheritance}}
{{#hasVars}}){{/hasVars}}{{#parent}} : {{{parent}}}({{#vendorExtensions.requiredParentVarsWithoutDiscriminator}}{{{name}}}{{^-last}}, {{/-last}}{{/vendorExtensions.requiredParentVarsWithoutDiscriminator}}){{/parent}}{{#vendorExtensions.x-implements}}{{#parent}}, {{/parent}}{{^parent}}: {{/parent}}{{^-first}}, {{/-first}}{{{.}}}{{/vendorExtensions.x-implements}} {{openbrace}}

{{#vendorExtensions.withInheritance}}
Expand All @@ -117,7 +92,7 @@
}

override fun hashCode(): Int =
Objects.hash({{#vars}}{{^isByteArray}}{{name}}{{/isByteArray}}{{#isByteArray}}Arrays.hashCode({{name}}){{/isByteArray}}{{^-last}}, {{/-last}}{{/vars}}{{#parent}}{{#vendorExtensions.hasOwnVars}}, {{/vendorExtensions.hasOwnVars}}super.hashCode(){{/parent}})
Objects.hash({{#vars}}{{^isByteArray}}{{{name}}}{{/isByteArray}}{{#isByteArray}}Arrays.hashCode({{{name}}}){{/isByteArray}}{{^-last}}, {{/-last}}{{/vars}}{{#parent}}{{#vendorExtensions.hasOwnVars}}, {{/vendorExtensions.hasOwnVars}}super.hashCode(){{/parent}})

override fun toString(): String =
{{#hasVars}}
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}}
Loading

0 comments on commit 15c0dec

Please sign in to comment.