Skip to content

Provide option to set allowed locales #2836 #2875

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

Merged
merged 2 commits into from
Jan 25, 2025
Merged
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
@@ -346,7 +346,7 @@ protected OpenAPI getOpenApi(Locale locale) {
this.reentrantLock.lock();
try {
final OpenAPI openAPI;
final Locale finalLocale = locale == null ? Locale.getDefault() : locale;
final Locale finalLocale = selectLocale(locale);
if (openAPIService.getCachedOpenAPI(finalLocale) == null || springDocConfigProperties.isCacheDisabled()) {
Instant start = Instant.now();
openAPI = openAPIService.build(finalLocale);
@@ -422,6 +422,20 @@ protected OpenAPI getOpenApi(Locale locale) {
}
}

private Locale selectLocale(Locale inputLocale) {
List<String> allowedLocales = springDocConfigProperties.getAllowedLocales();
if (!CollectionUtils.isEmpty(allowedLocales)) {
Locale bestMatchingAllowedLocale = Locale.lookup(
Locale.LanguageRange.parse(inputLocale.toLanguageTag()),
allowedLocales.stream().map(Locale::forLanguageTag).collect(Collectors.toList())
);

return bestMatchingAllowedLocale == null ? Locale.forLanguageTag(allowedLocales.get(0)) : bestMatchingAllowedLocale;
}

return inputLocale == null ? Locale.getDefault() : inputLocale;
}

/**
* Indents are removed for properties that are mainly used as “explanations” using Open API.
*
@@ -1361,7 +1375,7 @@ else if (existingOperation != null) {
* @param locale the locale
*/
protected void initOpenAPIBuilder(Locale locale) {
locale = locale == null ? Locale.getDefault() : locale;
locale = selectLocale(locale);
if (openAPIService.getCachedOpenAPI(locale) != null && springDocConfigProperties.isCacheDisabled()) {
openAPIService = openAPIBuilderObjectFactory.getObject();
}
Original file line number Diff line number Diff line change
@@ -184,6 +184,11 @@ public class SpringDocConfigProperties {
*/
private boolean useManagementPort;

/**
* Allowed locales for i18n.
*/
private List<String> allowedLocales;

/**
* The Disable i18n.
*/
@@ -985,6 +990,24 @@ public void setWriterWithDefaultPrettyPrinter(boolean writerWithDefaultPrettyPri
this.writerWithDefaultPrettyPrinter = writerWithDefaultPrettyPrinter;
}

/**
* List of allowed locales for i18n.
*
* @return the allowed locales
*/
public List<String> getAllowedLocales() {
return allowedLocales;
}

/**
* Sets allowed locales for i18n.
*
* @param allowedLocales the allowed locales
*/
public void setAllowedLocales(List<String> allowedLocales) {
this.allowedLocales = allowedLocales;
}

/**
* Is disable i 18 n boolean.
*
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
*
* *
* * *
* * * *
* * * * * Copyright 2019-2024 the original author or authors.
* * * * *
* * * * * Licensed under the Apache License, Version 2.0 (the "License");
* * * * * you may not use this file except in compliance with the License.
* * * * * You may obtain a copy of the License at
* * * * *
* * * * * https://www.apache.org/licenses/LICENSE-2.0
* * * * *
* * * * * Unless required by applicable law or agreed to in writing, software
* * * * * distributed under the License is distributed on an "AS IS" BASIS,
* * * * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * * * * See the License for the specific language governing permissions and
* * * * * limitations under the License.
* * * *
* * *
* *
*
*/

package test.org.springdoc.api.v30.app238;

import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;

import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Tag(name = "greeting", description = "test")
public class HelloLocaleController {

@GetMapping("/persons")
public void persons(@Valid @NotBlank String name) {
}

@GetMapping("/test")
public HttpEntity<String> demo2() {
return null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/*
*
* *
* * *
* * * *
* * * * * Copyright 2019-2024 the original author or authors.
* * * * *
* * * * * Licensed under the Apache License, Version 2.0 (the "License");
* * * * * you may not use this file except in compliance with the License.
* * * * * You may obtain a copy of the License at
* * * * *
* * * * * https://www.apache.org/licenses/LICENSE-2.0
* * * * *
* * * * * Unless required by applicable law or agreed to in writing, software
* * * * * distributed under the License is distributed on an "AS IS" BASIS,
* * * * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * * * * See the License for the specific language governing permissions and
* * * * * limitations under the License.
* * * *
* * *
* *
*
*/

package test.org.springdoc.api.v30.app238;

import java.util.Locale;

import org.junit.jupiter.api.Test;
import org.springdoc.core.customizers.OpenApiLocaleCustomizer;
import org.springdoc.core.utils.Constants;
import test.org.springdoc.api.v30.AbstractSpringDocV30Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.http.HttpHeaders;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.web.servlet.MvcResult;

import static org.hamcrest.Matchers.is;
import static org.skyscreamer.jsonassert.JSONAssert.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@TestPropertySource(properties = "springdoc.allowed-locales=en-US,fr-CA")
public class SpringDocApp238Test extends AbstractSpringDocV30Test {

@Test
@Override
public void testApp() throws Exception {
testApp(Locale.US);
testApp(Locale.CANADA_FRENCH);
// resolves to en-US as Chinese locale is not allowed in properties
testApp(Locale.SIMPLIFIED_CHINESE);
}

private void testApp(Locale locale) throws Exception {
className = getClass().getSimpleName();
String testNumber = className.replaceAll("[^0-9]", "");
MvcResult mockMvcResult =
mockMvc.perform(get(Constants.DEFAULT_API_DOCS_URL).locale(locale).header(HttpHeaders.ACCEPT_LANGUAGE, locale.toLanguageTag())).andExpect(status().isOk())
.andExpect(jsonPath("$.openapi", is("3.0.1"))).andReturn();
String result = mockMvcResult.getResponse().getContentAsString();
String expected = getContent("results/3.0.1/app" + testNumber + "-" + locale.toLanguageTag() + ".json");
assertEquals(expected, result, true);
}

@SpringBootApplication
static class SpringDocTestApp {

@Autowired
ResourceBundleMessageSource resourceBundleMessageSource;

@Bean
public OpenApiLocaleCustomizer openApiLocaleCustomizer() {
return (openAPI, locale)
-> openAPI.getInfo().title(resourceBundleMessageSource.getMessage("test", null, locale));
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
*
* *
* * *
* * * *
* * * * * Copyright 2019-2024 the original author or authors.
* * * * *
* * * * * Licensed under the Apache License, Version 2.0 (the "License");
* * * * * you may not use this file except in compliance with the License.
* * * * * You may obtain a copy of the License at
* * * * *
* * * * * https://www.apache.org/licenses/LICENSE-2.0
* * * * *
* * * * * Unless required by applicable law or agreed to in writing, software
* * * * * distributed under the License is distributed on an "AS IS" BASIS,
* * * * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * * * * See the License for the specific language governing permissions and
* * * * * limitations under the License.
* * * *
* * *
* *
*
*/

package test.org.springdoc.api.v31.app238;

import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;

import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Tag(name = "greeting", description = "test")
public class HelloLocaleController {

@GetMapping("/persons")
public void persons(@Valid @NotBlank String name) {
}

@GetMapping("/test")
public HttpEntity<String> demo2() {
return null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
/*
*
* *
* * *
* * * *
* * * * * Copyright 2019-2024 the original author or authors.
* * * * *
* * * * * Licensed under the Apache License, Version 2.0 (the "License");
* * * * * you may not use this file except in compliance with the License.
* * * * * You may obtain a copy of the License at
* * * * *
* * * * * https://www.apache.org/licenses/LICENSE-2.0
* * * * *
* * * * * Unless required by applicable law or agreed to in writing, software
* * * * * distributed under the License is distributed on an "AS IS" BASIS,
* * * * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * * * * See the License for the specific language governing permissions and
* * * * * limitations under the License.
* * * *
* * *
* *
*
*/

package test.org.springdoc.api.v31.app238;

import java.util.Locale;

import org.junit.jupiter.api.Test;
import org.springdoc.core.customizers.OpenApiLocaleCustomizer;
import org.springdoc.core.utils.Constants;
import test.org.springdoc.api.v31.AbstractSpringDocTest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.http.HttpHeaders;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.web.servlet.MvcResult;

import static org.hamcrest.Matchers.is;
import static org.skyscreamer.jsonassert.JSONAssert.assertEquals;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@TestPropertySource(properties = "springdoc.allowed-locales=en-US,fr-CA")
public class SpringDocApp238Test extends AbstractSpringDocTest {

@Test
@Override
public void testApp() throws Exception {
testApp(Locale.US);
testApp(Locale.CANADA_FRENCH);
// resolves to en-US as Chinese locale is not allowed in properties
testApp(Locale.SIMPLIFIED_CHINESE);
}

private void testApp(Locale locale) throws Exception {
className = getClass().getSimpleName();
String testNumber = className.replaceAll("[^0-9]", "");
MvcResult mockMvcResult =
mockMvc.perform(get(Constants.DEFAULT_API_DOCS_URL).locale(locale).header(HttpHeaders.ACCEPT_LANGUAGE, locale.toLanguageTag())).andExpect(status().isOk())
.andExpect(jsonPath("$.openapi", is("3.1.0"))).andReturn();
String result = mockMvcResult.getResponse().getContentAsString();
String expected = getContent("results/3.1.0/app" + testNumber + "-" + locale.toLanguageTag() + ".json");
assertEquals(expected, result, true);
}

@SpringBootApplication
static class SpringDocTestApp {

@Autowired
ResourceBundleMessageSource resourceBundleMessageSource;

@Bean
public OpenApiLocaleCustomizer openApiLocaleCustomizer() {
return (openAPI, locale)
-> openAPI.getInfo().title(resourceBundleMessageSource.getMessage("test", null, locale));
}

}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
test=This is a test message[ZH]
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
{
"openapi": "3.0.1",
"info": {
"title": "This is a test message",
"version": "v0"
},
"servers": [
{
"url": "http://localhost",
"description": "Generated server url"
}
],
"tags": [
{
"name": "Hello! Welcome to our website!",
"description": "This is a test message"
}
],
"paths": {
"/test": {
"get": {
"tags": [
"Hello! Welcome to our website!"
],
"operationId": "demo2",
"responses": {
"200": {
"description": "OK",
"content": {
"*/*": {
"schema": {
"type": "string"
}
}
}
}
}
}
},
"/persons": {
"get": {
"tags": [
"Hello! Welcome to our website!"
],
"operationId": "persons",
"parameters": [
{
"name": "name",
"in": "query",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "OK"
}
}
}
}
},
"components": {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
{
"openapi": "3.0.1",
"info": {
"title": "This is a test message[FR]",
"version": "v0"
},
"servers": [
{
"url": "http://localhost",
"description": "Generated server url"
}
],
"tags": [
{
"name": "Hello! Welcome to our website![FR]",
"description": "This is a test message[FR]"
}
],
"paths": {
"/test": {
"get": {
"tags": [
"Hello! Welcome to our website![FR]"
],
"operationId": "demo2",
"responses": {
"200": {
"description": "OK",
"content": {
"*/*": {
"schema": {
"type": "string"
}
}
}
}
}
}
},
"/persons": {
"get": {
"tags": [
"Hello! Welcome to our website![FR]"
],
"operationId": "persons",
"parameters": [
{
"name": "name",
"in": "query",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "OK"
}
}
}
}
},
"components": {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
{
"openapi": "3.0.1",
"info": {
"title": "This is a test message",
"version": "v0"
},
"servers": [
{
"url": "http://localhost",
"description": "Generated server url"
}
],
"tags": [
{
"name": "Hello! Welcome to our website!",
"description": "This is a test message"
}
],
"paths": {
"/test": {
"get": {
"tags": [
"Hello! Welcome to our website!"
],
"operationId": "demo2",
"responses": {
"200": {
"description": "OK",
"content": {
"*/*": {
"schema": {
"type": "string"
}
}
}
}
}
}
},
"/persons": {
"get": {
"tags": [
"Hello! Welcome to our website!"
],
"operationId": "persons",
"parameters": [
{
"name": "name",
"in": "query",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "OK"
}
}
}
}
},
"components": {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
{
"openapi": "3.1.0",
"info": {
"title": "This is a test message",
"version": "v0"
},
"servers": [
{
"url": "http://localhost",
"description": "Generated server url"
}
],
"tags": [
{
"name": "Hello! Welcome to our website!",
"description": "This is a test message"
}
],
"paths": {
"/test": {
"get": {
"tags": [
"Hello! Welcome to our website!"
],
"operationId": "demo2",
"responses": {
"200": {
"description": "OK",
"content": {
"*/*": {
"schema": {
"type": "string"
}
}
}
}
}
}
},
"/persons": {
"get": {
"tags": [
"Hello! Welcome to our website!"
],
"operationId": "persons",
"parameters": [
{
"name": "name",
"in": "query",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "OK"
}
}
}
}
},
"components": {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
{
"openapi": "3.1.0",
"info": {
"title": "This is a test message[FR]",
"version": "v0"
},
"servers": [
{
"url": "http://localhost",
"description": "Generated server url"
}
],
"tags": [
{
"name": "Hello! Welcome to our website![FR]",
"description": "This is a test message[FR]"
}
],
"paths": {
"/test": {
"get": {
"tags": [
"Hello! Welcome to our website![FR]"
],
"operationId": "demo2",
"responses": {
"200": {
"description": "OK",
"content": {
"*/*": {
"schema": {
"type": "string"
}
}
}
}
}
}
},
"/persons": {
"get": {
"tags": [
"Hello! Welcome to our website![FR]"
],
"operationId": "persons",
"parameters": [
{
"name": "name",
"in": "query",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "OK"
}
}
}
}
},
"components": {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
{
"openapi": "3.1.0",
"info": {
"title": "This is a test message",
"version": "v0"
},
"servers": [
{
"url": "http://localhost",
"description": "Generated server url"
}
],
"tags": [
{
"name": "Hello! Welcome to our website!",
"description": "This is a test message"
}
],
"paths": {
"/test": {
"get": {
"tags": [
"Hello! Welcome to our website!"
],
"operationId": "demo2",
"responses": {
"200": {
"description": "OK",
"content": {
"*/*": {
"schema": {
"type": "string"
}
}
}
}
}
}
},
"/persons": {
"get": {
"tags": [
"Hello! Welcome to our website!"
],
"operationId": "persons",
"parameters": [
{
"name": "name",
"in": "query",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "OK"
}
}
}
}
},
"components": {}
}