Skip to content

Commit

Permalink
Fix process pattern with date and date-time format.
Browse files Browse the repository at this point in the history
Fixed #1755
  • Loading branch information
altro3 committed Sep 5, 2024
1 parent a9ce3b8 commit 5d99c1d
Show file tree
Hide file tree
Showing 18 changed files with 227 additions and 87 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@
import static io.micronaut.openapi.generator.Utils.EXT_ANNOTATIONS_OPERATION;
import static io.micronaut.openapi.generator.Utils.EXT_ANNOTATIONS_SETTER;
import static io.micronaut.openapi.generator.Utils.addStrValueToEnum;
import static io.micronaut.openapi.generator.Utils.isDateType;
import static io.micronaut.openapi.generator.Utils.normalizeExtraAnnotations;
import static io.micronaut.openapi.generator.Utils.processGenericAnnotations;
import static org.openapitools.codegen.CodegenConstants.API_PACKAGE;
Expand Down Expand Up @@ -111,7 +112,7 @@ public abstract class AbstractMicronautJavaCodegen<T extends GeneratorOptionsBui
public static final String OPT_DATE_LIBRARY_OFFSET_DATETIME = "OFFSET_DATETIME";
public static final String OPT_DATE_LIBRARY_LOCAL_DATETIME = "LOCAL_DATETIME";
public static final String OPT_DATE_FORMAT = "dateFormat";
public static final String OPT_DATETIME_FORMAT = "datetimeFormat";
public static final String OPT_DATE_TIME_FORMAT = "dateTimeFormat";
public static final String OPT_REACTIVE = "reactive";
public static final String OPT_GENERATE_HTTP_RESPONSE_ALWAYS = "generateHttpResponseAlways";
public static final String OPT_GENERATE_HTTP_RESPONSE_WHERE_REQUIRED = "generateHttpResponseWhereRequired";
Expand Down Expand Up @@ -144,6 +145,8 @@ public abstract class AbstractMicronautJavaCodegen<T extends GeneratorOptionsBui
protected boolean generateHttpResponseAlways;
protected boolean generateHttpResponseWhereRequired = true;
protected String appName;
protected String dateFormat;
protected String dateTimeFormat;
protected String generateSwaggerAnnotations;
protected boolean generateOperationOnlyForFirstTag;
protected String serializationLibrary = SerializationLibraryKind.MICRONAUT_SERDE_JACKSON.name();
Expand Down Expand Up @@ -242,14 +245,14 @@ protected AbstractMicronautJavaCodegen() {
cliOptions.add(generateSwaggerAnnotationsOption);

cliOptions.add(new CliOption(OPT_DATE_FORMAT, "Specify the format pattern of date as a string"));
cliOptions.add(new CliOption(OPT_DATETIME_FORMAT, "Specify the format pattern of date-time as a string"));
cliOptions.add(new CliOption(OPT_DATE_TIME_FORMAT, "Specify the format pattern of date-time as a string"));

// Modify the DATE_LIBRARY option to only have supported values
cliOptions.stream()
.filter(o -> o.getOpt().equals(DATE_LIBRARY))
.findFirst()
.ifPresent(opt -> {
Map<String, String> valuesEnum = new HashMap<>();
var valuesEnum = new HashMap<String, String>();
valuesEnum.put(OPT_DATE_LIBRARY_OFFSET_DATETIME, opt.getEnum().get(OPT_DATE_LIBRARY_OFFSET_DATETIME));
valuesEnum.put(OPT_DATE_LIBRARY_LOCAL_DATETIME, opt.getEnum().get(OPT_DATE_LIBRARY_LOCAL_DATETIME));
opt.setEnum(valuesEnum);
Expand Down Expand Up @@ -448,6 +451,21 @@ public void processOpts() {
}
writePropertyBack(OPT_REACTIVE, reactive);

if (additionalProperties.containsKey(OPT_DATE_FORMAT)) {
dateFormat = (String) additionalProperties.get(OPT_DATE_FORMAT);
}
writePropertyBack(OPT_DATE_FORMAT, dateFormat);

if (additionalProperties.containsKey(OPT_DATE_TIME_FORMAT)) {
dateTimeFormat = (String) additionalProperties.get(OPT_DATE_TIME_FORMAT);
}
writePropertyBack(OPT_DATE_TIME_FORMAT, dateFormat);

if (additionalProperties.containsKey(OPT_GENERATE_HTTP_RESPONSE_ALWAYS)) {
generateHttpResponseAlways = convertPropertyToBoolean(OPT_GENERATE_HTTP_RESPONSE_ALWAYS);
}
writePropertyBack(OPT_GENERATE_HTTP_RESPONSE_ALWAYS, generateHttpResponseAlways);

if (additionalProperties.containsKey(OPT_GENERATE_HTTP_RESPONSE_ALWAYS)) {
generateHttpResponseAlways = convertPropertyToBoolean(OPT_GENERATE_HTTP_RESPONSE_ALWAYS);
}
Expand Down Expand Up @@ -837,18 +855,14 @@ private Pair<String, String> calcDefaultValues(String itemsDatatypeWithEnum, Str
} else if (ModelUtils.isStringSchema(schema)) {
if (schema.getDefault() != null) {
if (schema.getDefault() instanceof Date date) {
if ("java8".equals(getDateLibrary())) {
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
defaultValueInit = String.format(Locale.ROOT, "LocalDate.parse(\"%s\")", localDate.toString());
defaultValueStr = localDate.toString();
}
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
defaultValueInit = String.format(Locale.ROOT, "LocalDate.parse(\"%s\")", localDate.toString());
defaultValueStr = localDate.toString();
} else if (schema.getDefault() instanceof java.time.OffsetDateTime offsetDateTime) {
if ("java8".equals(getDateLibrary())) {
defaultValueInit = String.format(Locale.ROOT, "OffsetDateTime.parse(\"%s\", %s)",
offsetDateTime.atZoneSameInstant(ZoneId.systemDefault()),
"java.time.format.DateTimeFormatter.ISO_ZONED_DATE_TIME.withZone(java.time.ZoneId.systemDefault())");
defaultValueStr = offsetDateTime.toString();
}
defaultValueInit = String.format(Locale.ROOT, "OffsetDateTime.parse(\"%s\", %s)",
offsetDateTime.atZoneSameInstant(ZoneId.systemDefault()),
"java.time.format.DateTimeFormatter.ISO_ZONED_DATE_TIME.withZone(java.time.ZoneId.systemDefault())");
defaultValueStr = offsetDateTime.toString();
} else if (schema.getDefault() instanceof UUID) {
defaultValueInit = "UUID.fromString(\"" + schema.getDefault() + "\")";
defaultValueStr = schema.getDefault().toString();
Expand Down Expand Up @@ -1232,6 +1246,11 @@ public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List<Mo
if (useBeanValidation && !param.isContainer && param.isModel) {
param.vendorExtensions.put("withValid", true);
}
// check pattern property for date types: if set, need use this pattern as `@Format` annotation value
if (isDateType(param.dataType) && StringUtils.isNotEmpty(param.pattern)) {
param.vendorExtensions.put("formatPattern", param.pattern);
param.pattern = null;
}
}
if (op.returnProperty != null) {
processGenericAnnotations(op.returnProperty, useBeanValidation, isGenerateHardNullable(), false, false, false, false);
Expand Down Expand Up @@ -1679,6 +1698,11 @@ private void processProperty(CodegenProperty property, boolean isServer, Map<Str
)) {
property.vendorExtensions.put("withValid", true);
}
// check pattern property for date types: if set, need use this pattern as `@Format` annotation value
if (isDateType(property.dataType) && StringUtils.isNotEmpty(property.pattern)) {
property.vendorExtensions.put("formatPattern", property.pattern);
property.pattern = null;
}

processGenericAnnotations(property, useBeanValidation, isGenerateHardNullable(), false, false, false, false);

Expand Down Expand Up @@ -1961,6 +1985,16 @@ public void setGenerateSwaggerAnnotations(boolean generateSwaggerAnnotations) {
}
}

public void setDateFormat(String dateFormat) {
this.dateFormat = dateFormat;
additionalProperties.put(OPT_DATE_FORMAT, dateFormat);
}

public void setDateTimeFormat(String dateTimeFormat) {
this.dateTimeFormat = dateTimeFormat;
additionalProperties.put(OPT_DATE_TIME_FORMAT, dateTimeFormat);
}

@Override
public void postProcess() {
// disable output donation suggestion
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@
import static io.micronaut.openapi.generator.Utils.EXT_ANNOTATIONS_OPERATION;
import static io.micronaut.openapi.generator.Utils.EXT_ANNOTATIONS_SETTER;
import static io.micronaut.openapi.generator.Utils.addStrValueToEnum;
import static io.micronaut.openapi.generator.Utils.isDateType;
import static io.micronaut.openapi.generator.Utils.normalizeExtraAnnotations;
import static io.micronaut.openapi.generator.Utils.processGenericAnnotations;
import static org.openapitools.codegen.CodegenConstants.API_PACKAGE;
Expand Down Expand Up @@ -114,7 +115,7 @@ public abstract class AbstractMicronautKotlinCodegen<T extends GeneratorOptionsB
public static final String OPT_DATE_LIBRARY_OFFSET_DATETIME = "OFFSET_DATETIME";
public static final String OPT_DATE_LIBRARY_LOCAL_DATETIME = "LOCAL_DATETIME";
public static final String OPT_DATE_FORMAT = "dateFormat";
public static final String OPT_DATETIME_FORMAT = "datetimeFormat";
public static final String OPT_DATE_TIME_FORMAT = "dateTimeFormat";
public static final String OPT_REACTIVE = "reactive";
public static final String OPT_GENERATE_HTTP_RESPONSE_ALWAYS = "generateHttpResponseAlways";
public static final String OPT_GENERATE_HTTP_RESPONSE_WHERE_REQUIRED = "generateHttpResponseWhereRequired";
Expand Down Expand Up @@ -152,6 +153,8 @@ public abstract class AbstractMicronautKotlinCodegen<T extends GeneratorOptionsB
protected boolean implicitHeaders = false;
protected String implicitHeadersRegex;
protected String appName;
protected String dateFormat;
protected String dateTimeFormat;
protected String generateSwaggerAnnotations;
protected boolean generateOperationOnlyForFirstTag;
protected String serializationLibrary = SerializationLibraryKind.MICRONAUT_SERDE_JACKSON.name();
Expand Down Expand Up @@ -297,7 +300,7 @@ protected AbstractMicronautKotlinCodegen() {
cliOptions.add(generateSwaggerAnnotationsOption);

cliOptions.add(new CliOption(OPT_DATE_FORMAT, "Specify the format pattern of date as a string"));
cliOptions.add(new CliOption(OPT_DATETIME_FORMAT, "Specify the format pattern of date-time as a string"));
cliOptions.add(new CliOption(OPT_DATE_TIME_FORMAT, "Specify the format pattern of date-time as a string"));

// Modify the DATE_LIBRARY option to only have supported values
cliOptions.stream()
Expand Down Expand Up @@ -514,6 +517,15 @@ public void processOpts() {
}
writePropertyBack(OPT_REACTIVE, reactive);

if (additionalProperties.containsKey(OPT_DATE_FORMAT)) {
dateFormat = (String) additionalProperties.get(OPT_DATE_FORMAT);
}
writePropertyBack(OPT_DATE_FORMAT, dateFormat);
if (additionalProperties.containsKey(OPT_DATE_TIME_FORMAT)) {
dateTimeFormat = (String) additionalProperties.get(OPT_DATE_TIME_FORMAT);
}
writePropertyBack(OPT_DATE_TIME_FORMAT, dateTimeFormat);

if (additionalProperties.containsKey(OPT_GENERATE_HTTP_RESPONSE_ALWAYS)) {
generateHttpResponseAlways = convertPropertyToBoolean(OPT_GENERATE_HTTP_RESPONSE_ALWAYS);
}
Expand Down Expand Up @@ -961,6 +973,11 @@ public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List<Mo
|| (param.getIsArray() && param.getComplexType() != null && models.containsKey(param.getComplexType())))) {
param.vendorExtensions.put("withValid", true);
}
// check pattern property for date types: if set, need use this pattern as `@Format` annotation value
if (isDateType(param.dataType) && StringUtils.isNotEmpty(param.pattern)) {
param.vendorExtensions.put("formatPattern", param.pattern);
param.pattern = null;
}
}

if (op.returnProperty != null) {
Expand Down Expand Up @@ -1622,6 +1639,12 @@ private void processProperty(CodegenProperty property, boolean isServer, Codegen
property.vendorExtensions.put("withValid", true);
}

// check pattern property for date types: if set, need use this pattern as `@Format` annotation value
if (isDateType(property.dataType) && StringUtils.isNotEmpty(property.pattern)) {
property.vendorExtensions.put("formatPattern", property.pattern);
property.pattern = null;
}

processGenericAnnotations(property, useBeanValidation, false, property.isNullable || property.isDiscriminator,
property.required, property.isReadOnly, true);

Expand Down Expand Up @@ -2137,6 +2160,16 @@ public void setGenerateSwaggerAnnotations(boolean generateSwaggerAnnotations) {
}
}

public void setDateFormat(String dateFormat) {
this.dateFormat = dateFormat;
additionalProperties.put(OPT_DATE_FORMAT, dateFormat);
}

public void setDateTimeFormat(String dateTimeFormat) {
this.dateTimeFormat = dateTimeFormat;
additionalProperties.put(OPT_DATE_TIME_FORMAT, dateTimeFormat);
}

@Override
public void postProcess() {
// disable output donation suggestion
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,16 @@
*/
public final class Utils {

public static final List<String> DATE_TIME_TYPES = List.of(
"date",
"Date",
"DateTime",
"LocalDateTime",
"OffsetDateTime",
"ZonedDateTime",
"LocalDate",
"LocalTime"
);
public static final String DEFAULT_BODY_PARAM_NAME = "requestBody";
public static final String EXT_ANNOTATIONS_OPERATION = "x-operation-extra-annotation";
public static final String EXT_ANNOTATIONS_CLASS = "x-class-extra-annotation";
Expand All @@ -46,15 +56,15 @@ public static void processGenericAnnotations(CodegenParameter parameter, boolean
CodegenProperty items = parameter.isMap ? parameter.additionalProperties : parameter.items;
String datatypeWithEnum = parameter.datatypeWithEnum == null ? parameter.dataType : parameter.datatypeWithEnum;
processGenericAnnotations(parameter.dataType, datatypeWithEnum, parameter.isMap, parameter.containerTypeMapped,
items, parameter.vendorExtensions, useBeanValidation, isGenerateHardNullable, isNullable, isRequired, isReadonly, withNullablePostfix);
items, parameter.vendorExtensions, useBeanValidation, isGenerateHardNullable, isNullable, isRequired, isReadonly, withNullablePostfix);
}

public static void processGenericAnnotations(CodegenProperty property, boolean useBeanValidation, boolean isGenerateHardNullable,
boolean isNullable, boolean isRequired, boolean isReadonly, boolean withNullablePostfix) {
CodegenProperty items = property.isMap ? property.additionalProperties : property.items;
String datatypeWithEnum = property.datatypeWithEnum == null ? property.dataType : property.datatypeWithEnum;
processGenericAnnotations(property.dataType, datatypeWithEnum, property.isMap, property.containerTypeMapped,
items, property.vendorExtensions, useBeanValidation, isGenerateHardNullable, isNullable, isRequired, isReadonly, withNullablePostfix);
items, property.vendorExtensions, useBeanValidation, isGenerateHardNullable, isNullable, isRequired, isReadonly, withNullablePostfix);
}

public static void processGenericAnnotations(String dataType, String dataTypeWithEnum, boolean isMap, String containerType, CodegenProperty itemsProp, Map<String, Object> ext,
Expand Down Expand Up @@ -94,7 +104,7 @@ private static String genericAnnotations(CodegenProperty prop, boolean isGenerat
return result.toString();
}

if (StringUtils.isNotEmpty(prop.pattern)) {
if (StringUtils.isNotEmpty(prop.pattern) && !prop.isDate && !prop.isDateTime) {
if ("email".equals(type)) {
result.append("@Email(regexp = \"");
} else {
Expand Down Expand Up @@ -244,8 +254,8 @@ public static void addStrValueToEnum(List<Object> enumVars, boolean isNumeric) {
}
var upperValue = value.toUpperCase();
if (upperValue.endsWith("F")
|| upperValue.endsWith("L")
|| upperValue.endsWith("D")) {
|| upperValue.endsWith("L")
|| upperValue.endsWith("D")) {
value = value.substring(0, value.length() - 1);
}
if (!value.contains("\"")) {
Expand Down Expand Up @@ -302,4 +312,8 @@ private static List<String> normalizeExtraAnnotations(String prefix, Collection<
private static String normalizeExtraAnnotation(String prefix, String annotationStr) {
return prefix + (annotationStr.startsWith("@") ? annotationStr.substring(1) : annotationStr);
}

public static boolean isDateType(String type) {
return DATE_TIME_TYPES.contains(type);
}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
{{!
default type
}}{{^isDate}}{{^isDateTime}}{{{vendorExtensions.typeWithEnumWithGenericAnnotations}}}{{/isDateTime}}{{/isDate}}{{!
date-time
}}{{#isDateTime}}@Format("{{{datetimeFormat}}}") {{{vendorExtensions.typeWithEnumWithGenericAnnotations}}}{{/isDateTime}}{{!
date
}}{{#isDate}}@Format("{{{dateFormat}}}") {{{vendorExtensions.typeWithEnumWithGenericAnnotations}}}{{/isDate}}
{{^isDate}}{{^isDateTime}}{{{vendorExtensions.typeWithEnumWithGenericAnnotations}}}{{/isDateTime}}{{/isDate}}
{{#isDateTime}}{{#vendorExtensions.formatPattern}}@Format("{{{vendorExtensions.formatPattern}}}"){{/vendorExtensions.formatPattern}}{{^vendorExtensions.formatPattern}}{{#dateTimeFormat}}@Format("{{{dateTimeFormat}}}"){{/dateTimeFormat}}{{/vendorExtensions.formatPattern}} {{{dataType}}} {{/isDateTime}}
{{#isDate}}{{#vendorExtensions.formatPattern}}@Format("{{{vendorExtensions.formatPattern}}}"){{/vendorExtensions.formatPattern}}{{^vendorExtensions.formatPattern}}{{#dateFormat}}@Format("{{{dateFormat}}}"){{/dateFormat}}{{/vendorExtensions.formatPattern}} {{{dataType}}} {{/isDate}}
Loading

0 comments on commit 5d99c1d

Please sign in to comment.