Skip to content

Commit

Permalink
feat: adds LocalizedMessageSource (#6870)
Browse files Browse the repository at this point in the history
Co-authored-by: Tim Yates <tim.yates@gmail.com>
  • Loading branch information
sdelamo and timyates authored Feb 16, 2022
1 parent 1f4e2a0 commit 07b0efe
Show file tree
Hide file tree
Showing 28 changed files with 608 additions and 35 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package io.micronaut.http.server.netty.util

import io.micronaut.context.ApplicationContext
import io.micronaut.context.LocalizedMessageSource
import io.micronaut.context.MessageSource
import io.micronaut.context.annotation.Factory
import io.micronaut.context.annotation.Requires
import io.micronaut.context.i18n.ResourceBundleMessageSource
import io.micronaut.http.HttpHeaders
import io.micronaut.http.HttpRequest
import io.micronaut.http.MediaType
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import io.micronaut.http.annotation.Produces
import io.micronaut.http.client.BlockingHttpClient
import io.micronaut.http.client.HttpClient
import io.micronaut.runtime.server.EmbeddedServer
import jakarta.inject.Singleton
import spock.lang.AutoCleanup
import spock.lang.Shared
import spock.lang.Specification

class HttpLocalizedMessageSourceSpec extends Specification {

@Shared
@AutoCleanup
EmbeddedServer embeddedServer = ApplicationContext.run(EmbeddedServer, [
'spec.name': 'HttpLocalizedMessageSourceSpec',
])

@Shared
@AutoCleanup
HttpClient httpClient = embeddedServer.applicationContext.createBean(HttpClient, embeddedServer.URL)

@Shared
@AutoCleanup
BlockingHttpClient client = httpClient.toBlocking()

void "depending on the resolved locale default messages.properties or default messages_es.properties are used"() {
expect:
"Hello Welcome Sergio Good Bye" == client.retrieve(HttpRequest.GET('/i18n').header(HttpHeaders.ACCEPT_LANGUAGE, "en"))
"Hola Bienvenido Sergio Good Bye" == client.retrieve(HttpRequest.GET('/i18n').header(HttpHeaders.ACCEPT_LANGUAGE, "es"))
"Hello Welcome Sergio Good Bye" == client.retrieve(HttpRequest.GET('/i18n/default').header(HttpHeaders.ACCEPT_LANGUAGE, "en"))
"Hola Bienvenido Sergio Good Bye" == client.retrieve(HttpRequest.GET('/i18n/default').header(HttpHeaders.ACCEPT_LANGUAGE, "es"))
}

@Requires(property = "spec.name", value = "HttpLocalizedMessageSourceSpec")
@Factory
static class MessageSourceFactory {
@Singleton
MessageSource createMessageSource() {
return new ResourceBundleMessageSource("i18n.messages");
}
}

@Requires(property = "spec.name", value = "HttpLocalizedMessageSourceSpec")
@Controller("/i18n")
static class LocalizedMessageSourceController {
private final LocalizedMessageSource localizedMessageSource;

LocalizedMessageSourceController(LocalizedMessageSource localizedMessageSource) {
this.localizedMessageSource = localizedMessageSource
}

@Get
@Produces(MediaType.TEXT_PLAIN)
String message() {
return localizedMessageSource.getMessage("hello").get() + " " +
localizedMessageSource.getMessage("welcome.name", "Sergio").get() + " " +
localizedMessageSource.getMessageOrDefault("bye", "Good Bye")
}

@Get("/default")
@Produces(MediaType.TEXT_PLAIN)
String messageOrDefault() {
return localizedMessageSource.getMessageOrDefault("hello", "Foo") + " " +
localizedMessageSource.getMessageOrDefault("welcome.name", "Foo", "Sergio") + " " +
localizedMessageSource.getMessageOrDefault("bye", "Good Bye", ["foo": "bar"])
}
}
}
2 changes: 2 additions & 0 deletions http-server-netty/src/test/resources/i18n/messages.properties
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
hello=Hello
welcome.name=Welcome {0}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
hello=Hola
welcome.name=Bienvenido {0}
4 changes: 1 addition & 3 deletions http-server/build.gradle
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@


internalSanityChecks {
expectedServiceCount.put('io.micronaut.inject.BeanDefinitionReference', 30)
expectedServiceCount.put('io.micronaut.inject.BeanDefinitionReference', 32)
expectedServiceCount.put('io.micronaut.inject.BeanConfiguration', 1)
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* Copyright 2017-2022 original 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 io.micronaut.http.server.util.locale;

import io.micronaut.context.AbstractLocalizedMessageSource;
import io.micronaut.context.MessageSource;
import io.micronaut.core.annotation.NonNull;
import io.micronaut.core.util.LocaleResolver;
import io.micronaut.http.HttpRequest;
import io.micronaut.runtime.http.scope.RequestAware;
import io.micronaut.runtime.http.scope.RequestScope;
import java.util.Locale;

/**
* A {@link RequestScope} which uses the current {@link HttpRequest} to resolve the locale and hence return the localized messages.
* @author Sergio del Amo
* @since 3.4.0
*/
@RequestScope
public class HttpLocalizedMessageSource extends AbstractLocalizedMessageSource<HttpRequest<?>> implements RequestAware {
private Locale locale;

/**
* @param localeResolver The locale resolver
* @param messageSource The message source
*/
public HttpLocalizedMessageSource(LocaleResolver<HttpRequest<?>> localeResolver, MessageSource messageSource) {
super(localeResolver, messageSource);
}

@Override
@NonNull
protected Locale getLocale() {
if (locale == null) {
throw new IllegalStateException("RequestAware::setRequest should have set the locale");
}
return locale;
}

@Override
public void setRequest(HttpRequest<?> request) {
this.locale = resolveLocale(request);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package io.micronaut.http.server.util.locale

import spock.lang.Specification

class HttpLocalizedMessageSourceIllegalStateExceptionSpec extends Specification {

void "if locale is null an exception is thrown"() {
when:
new HttpLocalizedMessageSource(null, null).getLocale()

then:
thrown(IllegalStateException)

}
}
6 changes: 0 additions & 6 deletions http/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,6 @@ internalSanityChecks {
expectedServiceCount.put('io.micronaut.inject.BeanDefinitionReference', 21)
}


internalSanityChecks {
expectedServiceCount.put('io.micronaut.inject.BeanDefinitionReference', 21)
expectedServiceCount.put('io.micronaut.core.beans.BeanIntrospectionReference', 4)
}

dependencies {
annotationProcessor project(":inject-java")
annotationProcessor project(":graal")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
/*
* Copyright 2017-2022 original 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 io.micronaut.context;

import io.micronaut.core.annotation.NonNull;
import io.micronaut.core.util.LocaleResolver;

import java.util.Locale;
import java.util.Map;
import java.util.Optional;

/**
* Abstract class which implements {@link LocalizedMessageSource} and leverages {@link LocaleResolver} API.
* @author Sergio del Amo
* @since 3.4.0
* @param <T> The context object which will be used to resolve the locale
*/
public abstract class AbstractLocalizedMessageSource<T> implements LocalizedMessageSource {
private final LocaleResolver<T> localeResolver;
private final MessageSource messageSource;

/**
*
* @param localeResolver The locale resolver
* @param messageSource The message source
*/
public AbstractLocalizedMessageSource(LocaleResolver<T> localeResolver,
MessageSource messageSource) {
this.localeResolver = localeResolver;
this.messageSource = messageSource;
}

/**
*
* @return The resolved locale;
*/
@NonNull
protected abstract Locale getLocale();

/**
* Resolve a message for the given code and variables for the messages.
* @param code The code
* @param variables to be used to interpolate the message
* @return A message if present
*/
@Override
@NonNull
public Optional<String> getMessage(@NonNull String code, Object... variables) {
return messageSource.getMessage(code, getLocale(), variables);
}

/**
* Resolve a message for the given code and variables for the messages.
* @param code The code
* @param variables to be used to interpolate the message
* @return A message if present
*/
@Override
@NonNull
public Optional<String> getMessage(@NonNull String code, Map<String, Object> variables) {
return messageSource.getMessage(code, getLocale(), variables);
}

@Override
@NonNull
public Optional<String> getMessage(@NonNull String code) {
return messageSource.getMessage(code, getLocale());
}

/**
* @param localeResolutionContext The context object which will be used to resolve the locale
* @return The resolved locale;
*/
@NonNull
protected Locale resolveLocale(T localeResolutionContext) {
return localeResolver.resolveOrDefault(localeResolutionContext);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/*
* Copyright 2017-2022 original 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 io.micronaut.context;

import io.micronaut.core.annotation.NonNull;

import java.util.Map;
import java.util.Optional;

/**
* Retrieve messages for the resolved locale.
* @author Sergio del Amo
* @since 3.4.0
*/
public interface LocalizedMessageSource {
/**
* Resolve a message for the given code.
* @param code The code
* @return A message if present
*/
@NonNull Optional<String> getMessage(@NonNull String code);

/**
* Resolve a message for the given code and variables for the messages.
* @param code The code
* @param variables to be used to interpolate the message
* @return A message if present
*/
@NonNull Optional<String> getMessage(@NonNull String code, Object... variables);

/**
* Resolve a message for the given code and variables for the messages.
* @param code The code
* @param variables to be used to interpolate the message
* @return A message if present
*/
@NonNull Optional<String> getMessage(@NonNull String code, Map<String, Object> variables);

/**
* Resolve a message for the given code. If the message is not present then default message is returned.
* @param code The code
* @param defaultMessage The default message to use if no other message is found
* @return A message if present. If the message is not present then default message supplied is returned.
*/
default @NonNull String getMessageOrDefault(@NonNull String code, @NonNull String defaultMessage) {
return getMessage(code).orElse(defaultMessage);
}

/**
* Resolve a message for the given code. If the message is not present then default message is returned.
* @param code The code
* @param defaultMessage The default message to use if no other message is found
* @param variables to be used to interpolate the message
* @return A message if present. If the message is not present then default message supplied is returned.
*/
default @NonNull String getMessageOrDefault(@NonNull String code, @NonNull String defaultMessage, Object... variables) {
return getMessage(code, variables).orElse(defaultMessage);
}

/**
* Resolve a message for the given code. If the message is not present then default message is returned.
* @param code The code
* @param defaultMessage The default message to use if no other message is found
* @param variables to be used to interpolate the message
* @return A message if present. If the message is not present then default message supplied is returned.
*/
default @NonNull String getMessageOrDefault(@NonNull String code, @NonNull String defaultMessage, Map<String, Object> variables) {
return getMessage(code, variables).orElse(defaultMessage);
}
}
Loading

0 comments on commit 07b0efe

Please sign in to comment.