format date in codegen (#20516)

This commit is contained in:
Zemke 2025-02-09 17:11:01 +01:00 committed by GitHub
parent af6be6adee
commit c2c161eb26
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 12 additions and 0 deletions

View File

@ -31,6 +31,7 @@ import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.oas.models.parameters.RequestBody;
import io.swagger.v3.oas.models.servers.Server;
import io.swagger.v3.parser.util.SchemaTypeUtil;
import java.text.SimpleDateFormat;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.io.FilenameUtils;
@ -71,6 +72,7 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
private final Logger LOGGER = LoggerFactory.getLogger(AbstractJavaCodegen.class);
private static final String ARTIFACT_VERSION_DEFAULT_VALUE = "1.0.0";
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd", Locale.ROOT);
public static final String DEFAULT_LIBRARY = "<default>";
public static final String DATE_LIBRARY = "dateLibrary";
@ -1638,6 +1640,9 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
@Override
public String toExampleValue(Schema p) {
if (p.getExample() != null) {
if (p.getExample() instanceof Date) {
return DATE_FORMAT.format(p.getExample());
}
return escapeText(p.getExample().toString());
} else {
return null;

View File

@ -965,4 +965,11 @@ public class AbstractJavaCodegenTest {
Assert.assertEquals(codegen.removeAnnotations("List<@Valid Pet>"), "List<Pet>");
}
@Test(description = "test generated example values for string properties")
public void testGeneratedExampleValues() {
final OpenAPI openAPI = FLATTENED_SPEC.get("3_0/spring/date-time-parameter-types-for-testing");
codegen.setOpenAPI(openAPI);
DateSchema dateSchema = (DateSchema) openAPI.getPaths().get("/thingy/{date}").getPost().getParameters().get(0).getSchema();
Assert.assertTrue(codegen.escapeQuotationMark(codegen.toExampleValue(dateSchema)).matches("2021-01-01"));
}
}