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

Fix process pattern with date and date-time format. #1756

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
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 @@ -145,6 +146,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 @@ -243,14 +246,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 @@ -449,6 +452,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 @@ -838,18 +856,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 @@ -1241,6 +1255,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 @@ -1688,6 +1707,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 @@ -1972,6 +1996,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 @@ -83,6 +83,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 @@ -115,7 +116,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 @@ -154,6 +155,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 @@ -299,7 +302,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 @@ -516,6 +519,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 @@ -1000,6 +1012,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 @@ -1661,6 +1678,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 @@ -2178,6 +2201,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 @@ -38,6 +38,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 Down Expand Up @@ -143,7 +153,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 @@ -351,4 +361,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}}
Original file line number Diff line number Diff line change
Expand Up @@ -38,26 +38,46 @@
{{#jackson}}
{{^micronaut_serde_jackson}}
{{#isDateTime}}
{{#datetimeFormat}}
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "{{{datetimeFormat}}}")
{{/datetimeFormat}}
{{#vendorExtensions.formatPattern}}
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "{{{vendorExtensions.formatPattern}}}")
{{/vendorExtensions.formatPattern}}
{{^vendorExtensions.formatPattern}}
{{#dateTimeFormat}}
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "{{{dateTimeFormat}}}")
{{/dateTimeFormat}}
{{/vendorExtensions.formatPattern}}
{{/isDateTime}}
{{#isDate}}
{{#dateFormat}}
{{#vendorExtensions.formatPattern}}
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "{{{vendorExtensions.formatPattern}}}")
{{/vendorExtensions.formatPattern}}
{{^vendorExtensions.formatPattern}}
{{#dateFormat}}
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "{{{dateFormat}}}")
{{/dateFormat}}
{{/dateFormat}}
{{/vendorExtensions.formatPattern}}
{{/isDate}}
{{/micronaut_serde_jackson}}
{{/jackson}}
{{#micronaut_serde_jackson}}
{{#isDateTime}}
{{#datatimeFormat}}
@JsonFormat(pattern = "{{{datetimeFormat}}}")
{{/datatimeFormat}}
{{#vendorExtensions.formatPattern}}
@JsonFormat(pattern = "{{{vendorExtensions.formatPattern}}}")
{{/vendorExtensions.formatPattern}}
{{^vendorExtensions.formatPattern}}
{{#dateTimeFormat}}
@JsonFormat(pattern = "{{{dateTimeFormat}}}")
{{/dateTimeFormat}}
{{/vendorExtensions.formatPattern}}
{{/isDateTime}}
{{#isDate}}
{{#dateFormat}}
{{#vendorExtensions.formatPattern}}
@JsonFormat(pattern = "{{{vendorExtensions.formatPattern}}}")
{{/vendorExtensions.formatPattern}}
{{^vendorExtensions.formatPattern}}
{{#dateFormat}}
@JsonFormat(pattern = "{{{dateFormat}}}")
{{/dateFormat}}
{{/dateFormat}}
{{/vendorExtensions.formatPattern}}
{{/isDate}}
{{/micronaut_serde_jackson}}
Loading
Loading