Skip to content

Add bean validation annotations for the method parameters which are treated as headers #10555

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

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
10 changes: 10 additions & 0 deletions bin/configs/spring-mvc-headers-validation-with-optional.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
generatorName: spring
outputDir: samples/server/petstore/spring-mvc-headers-validation-with-optional
inputSpec: modules/openapi-generator/src/test/resources/3_0/headers-validation.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
java8: true
performBeanValidation: "true"
useOptional: true
hideGenerationTimestamp: "true"
artifactId: spring-mvc-headers-validation
10 changes: 10 additions & 0 deletions bin/configs/spring-mvc-headers-validation-without-optional.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
generatorName: spring
outputDir: samples/server/petstore/spring-mvc-headers-validation-without-optional
inputSpec: modules/openapi-generator/src/test/resources/3_0/headers-validation.yaml
templateDir: modules/openapi-generator/src/main/resources/JavaSpring
additionalProperties:
java8: true
performBeanValidation: "true"
useOptional: false
hideGenerationTimestamp: "true"
artifactId: spring-mvc-headers-validation
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{{#isHeaderParam}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{#values}}{{{.}}}{{^-last}}, {{/-last}}{{#-last}}{{/-last}}{{/values}}"{{/allowableValues}}{{^isContainer}}{{#defaultValue}}, defaultValue = "{{{.}}}"{{/defaultValue}}{{/isContainer}}) @RequestHeader(value = "{{baseName}}", required = {{#required}}true{{/required}}{{^required}}false{{/required}}) {{>optionalDataType}} {{paramName}}{{/isHeaderParam}}
{{#isHeaderParam}}{{#useBeanValidation}}{{#useOptional}}{{#required}}{{>beanValidationCore}}{{/required}}{{/useOptional}}{{^useOptional}}{{>beanValidationCore}}{{/useOptional}}{{/useBeanValidation}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{#values}}{{{.}}}{{^-last}}, {{/-last}}{{#-last}}{{/-last}}{{/values}}"{{/allowableValues}}{{^isContainer}}{{#defaultValue}}, defaultValue = "{{{.}}}"{{/defaultValue}}{{/isContainer}}) @RequestHeader(value = "{{baseName}}", required = {{#required}}true{{/required}}{{^required}}false{{/required}}) {{>optionalDataType}} {{paramName}}{{/isHeaderParam}}
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
openapi: 3.0.1
info:
title: Test for Issue 7125
description: desc
version: 1.0.0
tags:
- name: verify-headers-validation
description: verify headers validation
paths:
/test-headers-validation:
get:
tags:
- verify-headers-validation
summary: test headers validation
description: desc
operationId: headersValidationTest
parameters:
- name: requiredStringWithMinLength
in: header
required: true
schema:
type: string
minLength: 32
- name: requiredStringWithMaxLength
in: header
required: true
schema:
type: string
maxLength: 32
- name: requiredStringWithLength
in: header
required: true
schema:
type: string
minLength: 32
maxLength: 32
- name: requiredStringWithPattern
in: header
required: true
schema:
type: string
pattern: ^([0-9a-fA-F]{32})$
- name: optionalStringWithMinLength
in: header
required: false
schema:
type: string
minLength: 32
- name: optionalStringWithMaxLength
in: header
required: false
schema:
type: string
maxLength: 32
- name: optionalStringWithLength
in: header
required: false
schema:
type: string
minLength: 32
maxLength: 32
- name: optionalStringWithPattern
in: header
required: false
schema:
type: string
pattern: ^([0-9a-fA-F]{32})$
responses:
200:
description: default response
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,10 @@
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/TestHeadersValidationApi.java
src/main/java/org/openapitools/api/TestHeadersValidationApiController.java
src/main/java/org/openapitools/configuration/HomeController.java
src/main/java/org/openapitools/configuration/OpenAPIDocumentationConfig.java
src/main/resources/application.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
5.3.0-SNAPSHOT
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# 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.

The underlying library integrating OpenAPI to SpringBoot is [springfox](https://github.com/springfox/springfox)

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,78 @@
<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</groupId>
<artifactId>spring-mvc-headers-validation</artifactId>
<packaging>jar</packaging>
<name>spring-mvc-headers-validation</name>
<version>1.0.0</version>
<properties>
<java.version>1.8</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
<springfox-version>2.9.2</springfox-version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.3.RELEASE</version>
</parent>
<build>
<sourceDirectory>src/main/java</sourceDirectory>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</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>
<!--SpringFox dependencies -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${springfox-version}</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${springfox-version}</version>
</dependency>
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
<dependency>
<groupId>org.openapitools</groupId>
<artifactId>jackson-databind-nullable</artifactId>
<version>0.2.1</version>
</dependency>
<!-- Bean Validation API support -->
<dependency>
<groupId>jakarta.validation</groupId>
<artifactId>jakarta.validation-api</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,57 @@
package org.openapitools;

import com.fasterxml.jackson.databind.Module;
import org.openapitools.jackson.nullable.JsonNullableModule;
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.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");
}*/
};
}

@Bean
public Module jsonNullableModule() {
return new JsonNullableModule();
}

}
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