Skip to content

Add in Optional handling for SpringBoot POJOs #11384

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

Closed
wants to merge 33 commits into from
Closed
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
2d68708
Merge pull request #1 from OpenAPITools/master
welshm Jun 15, 2021
a3d03bb
Merge pull request #5 from OpenAPITools/master
welshm Jul 30, 2021
8c30649
Merge branch 'master' of github.com:OpenAPITools/openapi-generator
welshm Aug 23, 2021
6e1982a
Merge pull request #7 from OpenAPITools/master
welshm Nov 2, 2021
3455229
Merge branch 'master' of github.com:welshm/openapi-generator
welshm Nov 2, 2021
64028ca
Merge pull request #9 from OpenAPITools/master
welshm Dec 7, 2021
e87ace6
Merge pull request #13 from OpenAPITools/master
welshm Jan 22, 2022
a63b860
Add in `Optional` handling for SpringBoot POJOs
welshm Jan 23, 2022
faeb347
Try to add enum type to `DefaultCodegen`
welshm Jan 23, 2022
38872bb
Revert changes to `nullableDataType` and `optionalDataType`
welshm Jan 23, 2022
f9c22de
Simpligy mustache
welshm Jan 23, 2022
69c7202
Add `JsonIgnore` import
welshm Jan 23, 2022
a85cde9
Fix some maven artifact names
welshm Jan 23, 2022
b499f0f
t checkout spri Merge branch 'master' of github.com:OpenAPITools/open…
welshm Jan 31, 2022
57601a8
Merge branch 'master' into spring_oas3_nullability
welshm Jan 31, 2022
10cae3b
Fix spacing
welshm Jan 31, 2022
bdb64d6
Spaces not tabs
welshm Jan 31, 2022
f9eea2f
Merge branch 'master' into spring_oas3_nullability
welshm Feb 6, 2022
0b043ef
Update samples
welshm Feb 6, 2022
9103217
Merge branch 'master' into spring_oas3_nullability
welshm Feb 6, 2022
04bb679
Merge branch 'master' into spring_oas3_nullability
welshm Feb 17, 2022
98f38d7
Update to have `Optional` be first class data type instead of just for
welshm Feb 17, 2022
89f1a1e
Update for Optionals
welshm Feb 17, 2022
cd461bf
Update optionals
welshm Feb 17, 2022
58a2908
Newline remove
welshm Feb 17, 2022
b952636
Fix JDK8 module bean
welshm Feb 17, 2022
4e92c8e
Fix additional properties
welshm Feb 17, 2022
66d9eb2
Merge branch 'master' into spring_oas3_nullability
welshm Feb 17, 2022
6bbc3a8
Fix test xml to include JDK8 module
welshm Feb 18, 2022
e094a08
Merge branch 'master' into spring_oas3_nullability
welshm Feb 18, 2022
7cb3767
Fix default optoinal to `empty()` and add some datetime tests
welshm Feb 19, 2022
ad76d49
Cleanup and remove annotations from member variables for optionals
welshm Feb 19, 2022
ee9b290
Merge branch 'master' into spring_oas3_nullability
welshm Feb 19, 2022
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
12 changes: 12 additions & 0 deletions bin/configs/spring-boot-oas3-nullable-disabled.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
generatorName: spring
outputDir: samples/openapi3/server/petstore/springboot-nullable-disabled
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-nullable-required.yaml
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: This validates against 3_0

templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
groupId: org.openapitools.openapi3
documentationProvider: springdoc
artifactId: springboot-nullable-disabled
snapshotVersion: "true"
hideGenerationTimestamp: "true"
openApiNullable: "false"
useOptional: "true"
12 changes: 12 additions & 0 deletions bin/configs/spring-boot-oas3-nullable.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
generatorName: spring
outputDir: samples/openapi3/server/petstore/springboot-nullable
inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-with-nullable-required.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
groupId: org.openapitools.openapi3
documentationProvider: springdoc
artifactId: springboot-nullable
snapshotVersion: "true"
hideGenerationTimestamp: "true"
openApiNullable: "true"
useOptional: "true"
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ import java.util.Objects;
{{#openApiNullable}}
import org.openapitools.jackson.nullable.JsonNullable;
{{/openApiNullable}}
{{#useOptional}}
import com.fasterxml.jackson.annotation.JsonIgnore;
{{/useOptional}}
{{#serializableModel}}
import java.io.Serializable;
{{/serializableModel}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,14 +135,18 @@ public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}}{{^parent}}{{#ha
{{#useBeanValidation}}
{{>beanValidation}}
{{/useBeanValidation}}
{{#useOptional}}
// Rely on the @JsonProperty annotation on the variable and ignore the getter methods.
@JsonIgnore
{{/useOptional}}
{{#swagger2AnnotationLibrary}}
@Schema(name = "{{{baseName}}}", {{#isReadOnly}}accessMode = Schema.AccessMode.READ_ONLY, {{/isReadOnly}}{{#example}}example = "{{{.}}}", {{/example}}{{#description}}description = "{{{.}}}", {{/description}}required = {{{required}}})
{{/swagger2AnnotationLibrary}}
{{#swagger1AnnotationLibrary}}
@ApiModelProperty({{#example}}example = "{{{.}}}", {{/example}}{{#required}}required = {{required}}, {{/required}}{{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}value = "{{{description}}}")
{{/swagger1AnnotationLibrary}}
public {{>nullableDataType}} {{getter}}() {
return {{name}};
public {{#isNullable}}{{>nullableDataType}}{{/isNullable}}{{^isNullable}}{{#required}}{{>nullableDataType}}{{/required}}{{^required}}{{#isEnum}}{{#useOptional}}Optional<{{/useOptional}}{{{datatypeWithEnum}}}{{#useOptional}}>{{/useOptional}}{{/isEnum}}{{^isEnum}}{{>optionalDataType}}{{/isEnum}}{{/required}}{{/isNullable}} {{getter}}() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would prefer to use an include here. The code is difficult to read and hard to understand. Isn't it possible to use optionalDataType.mustache?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This comment seems old - but I need to fix the bean annotations anyway so this might change to an include

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Old, but still valid IMO

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved it's own include - I had trouble coming up with a good name so it's dataTypeDeclaration - which is kind of misleading because these are all data type declarations.

Open to suggestions of better names - and I'm taking a look at your wrapper type change now

return {{^isNullable}}{{#useOptional}}{{^required}}Optional.ofNullable({{/required}}{{/useOptional}}{{/isNullable}}{{name}}{{^isNullable}}{{#useOptional}}{{^required}}){{/required}}{{/useOptional}}{{/isNullable}};
}

{{#vendorExtensions.x-setter-extra-annotation}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -703,6 +703,7 @@ components:
status:
type: string
description: pet status in the store
nullable: true
enum:
- available
- pending
Expand Down
4 changes: 4 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1218,6 +1218,8 @@
<module>samples/openapi3/server/petstore/springboot</module>
<module>samples/server/petstore/springboot-beanvalidation</module>
<module>samples/server/petstore/springboot-useoptional</module>
<module>samples/openapi3/server/petstore/springboot-nullable</module>
<module>samples/openapi3/server/petstore/springboot-nullable-disabled</module>
<module>samples/openapi3/server/petstore/springboot-useoptional</module>
<module>samples/server/petstore/springboot-reactive</module>
<module>samples/openapi3/server/petstore/springboot-reactive</module>
Expand Down Expand Up @@ -1264,6 +1266,8 @@
<module>samples/server/petstore/springboot-beanvalidation</module>
<module>samples/server/petstore/springboot-useoptional</module>
<module>samples/openapi3/server/petstore/springboot-useoptional</module>
<module>samples/openapi3/server/petstore/springboot-nullable</module>
<module>samples/openapi3/server/petstore/springboot-nullable-disabled</module>
<module>samples/server/petstore/springboot-reactive</module>
<module>samples/openapi3/server/petstore/springboot-reactive</module>
<module>samples/server/petstore/springboot-implicitHeaders</module>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# OpenAPI Generator Ignore
# Generated by openapi-generator https://github.com/openapitools/openapi-generator

# Use this file to prevent files from being overwritten by the generator.
# The patterns follow closely to .gitignore or .dockerignore.

# As an example, the C# client generator defines ApiClient.cs.
# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
#ApiClient.cs

# You can match any string of characters against a directory, file or extension with a single asterisk (*):
#foo/*/qux
# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux

# You can recursively match patterns against a directory, file or extension with a double asterisk (**):
#foo/**/qux
# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux

# You can also negate patterns with an exclamation (!).
# For example, you can ignore all files in a docs folder with the file extension .md:
#docs/*.md
# Then explicitly reverse the ignore rule for a single file:
#!docs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
README.md
pom.xml
src/main/java/org/openapitools/OpenAPI2SpringBoot.java
src/main/java/org/openapitools/RFC3339DateFormat.java
src/main/java/org/openapitools/api/ApiUtil.java
src/main/java/org/openapitools/api/PetApi.java
src/main/java/org/openapitools/api/PetApiController.java
src/main/java/org/openapitools/api/StoreApi.java
src/main/java/org/openapitools/api/StoreApiController.java
src/main/java/org/openapitools/api/UserApi.java
src/main/java/org/openapitools/api/UserApiController.java
src/main/java/org/openapitools/configuration/HomeController.java
src/main/java/org/openapitools/model/Category.java
src/main/java/org/openapitools/model/ModelApiResponse.java
src/main/java/org/openapitools/model/Order.java
src/main/java/org/openapitools/model/Pet.java
src/main/java/org/openapitools/model/Tag.java
src/main/java/org/openapitools/model/User.java
src/main/resources/application.properties
src/main/resources/openapi.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
5.4.0-SNAPSHOT
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# OpenAPI generated server

Spring Boot Server


## Overview
This server was generated by the [OpenAPI Generator](https://openapi-generator.tech) project.
By using the [OpenAPI-Spec](https://openapis.org), you can easily generate a server stub.
This is an example of building a OpenAPI-enabled server in Java using the SpringBoot framework.

Start your server as a simple java application

You can view the api documentation in swagger-ui by pointing to
http://localhost:8080/

Change default port value in application.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.openapitools.openapi3</groupId>
<artifactId>springboot-nullable-disabled</artifactId>
<packaging>jar</packaging>
<name>springboot-nullable-disabled</name>
<version>1.0.0-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<springdoc.version>1.6.4</springdoc.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.2</version>
</parent>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
</dependency>
<!--SpringDoc dependencies -->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>${springdoc.version}</version>
</dependency>
<!-- @Nullable annotation -->
<dependency>
<groupId>com.google.code.findbugs</groupId>
<artifactId>jsr305</artifactId>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
<!-- Bean Validation API support -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
</dependencies>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package org.openapitools;

import com.fasterxml.jackson.databind.Module;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.ExitCodeGenerator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@SpringBootApplication
@ComponentScan(basePackages = {"org.openapitools", "org.openapitools.api" , "org.openapitools.configuration"})
public class OpenAPI2SpringBoot implements CommandLineRunner {

@Override
public void run(String... arg0) throws Exception {
if (arg0.length > 0 && arg0[0].equals("exitcode")) {
throw new ExitException();
}
}

public static void main(String[] args) throws Exception {
new SpringApplication(OpenAPI2SpringBoot.class).run(args);
}

static class ExitException extends RuntimeException implements ExitCodeGenerator {
private static final long serialVersionUID = 1L;

@Override
public int getExitCode() {
return 10;
}

}

@Bean
public WebMvcConfigurer webConfigurer() {
return new WebMvcConfigurer() {
/*@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("*")
.allowedHeaders("Content-Type");
}*/

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/swagger-ui/**").addResourceLocations("classpath:/META-INF/resources/webjars/swagger-ui/3.14.2/");
}
};
}


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package org.openapitools;

import com.fasterxml.jackson.databind.util.StdDateFormat;

import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.ParsePosition;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

public class RFC3339DateFormat extends DateFormat {
private static final long serialVersionUID = 1L;
private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC");

private final StdDateFormat fmt = new StdDateFormat()
.withTimeZone(TIMEZONE_Z)
.withColonInTimeZone(true);

public RFC3339DateFormat() {
this.calendar = new GregorianCalendar();
}

@Override
public Date parse(String source, ParsePosition pos) {
return fmt.parse(source, pos);
}

@Override
public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {
return fmt.format(date, toAppendTo, fieldPosition);
}

@Override
public Object clone() {
return this;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package org.openapitools.api;

import org.springframework.web.context.request.NativeWebRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ApiUtil {
public static void setExampleResponse(NativeWebRequest req, String contentType, String example) {
try {
HttpServletResponse res = req.getNativeResponse(HttpServletResponse.class);
res.setCharacterEncoding("UTF-8");
res.addHeader("Content-Type", contentType);
res.getWriter().print(example);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
Loading