Skip to content

Commit

Permalink
Refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
mercyblitz committed Apr 22, 2024
1 parent f2e839f commit dee457c
Show file tree
Hide file tree
Showing 5 changed files with 75 additions and 99 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,17 @@
import io.microsphere.collection.CollectionUtils;
import org.apache.commons.lang3.ArrayUtils;

import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import static io.microsphere.collection.MapUtils.isEmpty;
import static io.microsphere.text.FormatUtils.format;
import static java.util.Collections.emptyMap;
import static java.util.Collections.emptySet;
import static java.util.Collections.singleton;
import static java.util.Collections.unmodifiableSet;
import static java.util.Collections.unmodifiableMap;
import static java.util.Objects.requireNonNull;

/**
Expand All @@ -27,18 +25,16 @@
public abstract class AbstractResourceServiceMessageSource extends AbstractServiceMessageSource implements ResourceServiceMessageSource {

/**
* Message Resource name prefix
* The default prefix of of message resource name
*/
protected static final String RESOURCE_NAME_PREFIX = "i18n_messages_";
protected static final String DEFAULT_RESOURCE_NAME_PREFIX = "i18n_messages_";

/**
* Message Resource Name Suffix
* The default suffix of message resource name
*/
protected static final String RESOURCE_NAME_SUFFIX = ".properties";
protected static final String DEFAULT_RESOURCE_NAME_SUFFIX = ".properties";

private volatile Map<Locale, Map<String, String>> localizedMessages = emptyMap();

private volatile Set<String> initializedResources = emptySet();
private volatile Map<String, Map<String, String>> localizedResourceMessages = emptyMap();

public AbstractResourceServiceMessageSource(String source) {
super(source);
Expand All @@ -57,19 +53,12 @@ public void initializeResource(String resource) {

@Override
public void initializeResources(Iterable<String> resources) {
List<Locale> supportedLocales = getSupportedLocales();
assertSupportedLocales(supportedLocales);

// Copy the current messages and initialized resources
Map<Locale, Map<String, String>> localizedMessages = new HashMap<>(this.localizedMessages);
Set<String> initializedResources = new LinkedHashSet<>(this.initializedResources);

initializeResources(resources, supportedLocales, localizedMessages, initializedResources);

// Exchange the field
synchronized (this) {
this.localizedMessages = localizedMessages;
this.initializedResources = initializedResources;
// Copy the current messages and initialized resources
Map<String, Map<String, String>> localizedResourceMessages = new HashMap<>(this.localizedResourceMessages);
initializeResources(resources, localizedResourceMessages);
// Exchange the field
this.localizedResourceMessages = localizedResourceMessages;
}
}

Expand All @@ -91,43 +80,26 @@ protected String getInternalMessage(String code, String resolvedCode, Locale loc
Map<String, String> messages = getMessages(resolvedLocale);
String messagePattern = messages.get(resolvedCode);
if (messagePattern != null) {
message = formatMessage(messagePattern, args);
message = resolveMessage(messagePattern, args);
logMessage(code, resolvedCode, locale, resolvedLocale, args, messagePattern, message);
}
return message;
}

protected void logMessage(String code, String resolvedCode, Locale locale, Locale resolvedLocale, Object[] args,
String messagePattern, String message) {
if (logger.isDebugEnabled()) {
logger.debug("Source '{}' gets Message[code : '{}' , resolvedCode : '{}' , locale : '{}' , resolvedLocale : '{}', args : '{}' , pattern : '{}'] : '{}'",
source, code, resolvedCode, locale, resolvedLocale, ArrayUtils.toString(args), messagePattern, message);
}
}

@Override
public Set<String> getInitializeResources() {
return unmodifiableSet(initializedResources);
}

/**
* Initialization
*/
protected final void initialize() {
List<Locale> supportedLocales = getSupportedLocales();
assertSupportedLocales(supportedLocales);
Map<Locale, Map<String, String>> localizedMessages = new HashMap<>(supportedLocales.size());
Set<String> initializedResources = new LinkedHashSet<>();
Map<String, Map<String, String>> localizedResourceMessages = new HashMap<>(supportedLocales.size());
for (Locale resolveLocale : supportedLocales) {
String resource = getResource(resolveLocale);
initializeResource(resource, resolveLocale, localizedMessages, initializedResources);
initializeResource(resource, localizedResourceMessages);
}
// Exchange the field
synchronized (this) {
this.localizedMessages = localizedMessages;
this.initializedResources = initializedResources;
}
logger.debug("Source '{}' Initialization is completed , resources : {} , localizedMessages : {}", source, initializedResources, localizedMessages);
this.localizedResourceMessages = localizedResourceMessages;
logger.debug("Source '{}' Initialization is completed , localizedResourceMessages : {}", source, localizedResourceMessages);
}

private void assertSupportedLocales(List<Locale> supportedLocales) {
Expand All @@ -137,10 +109,8 @@ private void assertSupportedLocales(List<Locale> supportedLocales) {
}

protected final void clearAllMessages() {
this.localizedMessages.clear();
this.initializedResources.clear();
this.localizedMessages = null;
this.initializedResources = null;
this.localizedResourceMessages.clear();
this.localizedResourceMessages = null;
}

private void validateMessages(Map<String, String> messages, String resourceName) {
Expand All @@ -159,60 +129,68 @@ private void validateMessageCodePrefix(String code, String resourceName) {
}

private String getResource(Locale locale) {
String resourceName = getResourceName(locale);
String resourceName = buildResourceName(locale);
return getResource(resourceName);
}

private String getResourceName(Locale locale) {
return RESOURCE_NAME_PREFIX + locale + RESOURCE_NAME_SUFFIX;
protected String buildResourceName(Locale locale) {
return DEFAULT_RESOURCE_NAME_PREFIX + locale + DEFAULT_RESOURCE_NAME_SUFFIX;
}

protected abstract String getResource(String resourceName);

protected abstract Map<String, String> loadMessages(Locale locale, String resource);
protected abstract Map<String, String> loadMessages(String resource);

@Nullable
public final Map<String, String> getMessages(Locale locale) {
return localizedMessages.getOrDefault(locale, emptyMap());
String resource = getResource(locale);
return localizedResourceMessages.get(resource);
}

@Override
public String toString() {
final StringBuilder sb = new StringBuilder(getClass().getSimpleName())
.append("{source='").append(source).append('\'')
.append(", initializedResources=").append(initializedResources)
.append(", defaultLocale=").append(getDefaultLocale())
.append(", supportedLocales=").append(getSupportedLocales())
.append(", localizedMessages=").append(localizedMessages)
.append('}');
return sb.toString();
private void initializeResources(Iterable<String> resources, Map<String, Map<String, String>> localizedResourceMessages) {
for (String resource : resources) {
initializeResource(resource, localizedResourceMessages);
}
}

private void initializeResources(Iterable<String> resources, List<Locale> supportedLocales,
Map<Locale, Map<String, String>> localizedMessages, Set<String> initializedResources) {

for (Locale locale : supportedLocales) {
initializeResources(resources, locale, localizedMessages, initializedResources);
private void initializeResource(String resource, Map<String, Map<String, String>> localizedResourceMessages) {
Map<String, String> messages = loadMessages(resource);
if (messages == null) {
logger.debug("Source '{}' Locale resource ['{}'] messages was not found", source, resource);
return;
}

logger.debug("Source '{}' loads the resource['{}'] messages : {}", source, resource, messages);
validateMessages(messages, resource);
// Override the localized message if present
localizedResourceMessages.put(resource, messages);
}

private void initializeResources(Iterable<String> resources, Locale locale, Map<Locale, Map<String, String>> localizedMessages,
Set<String> initializedResources) {
for (String resource : resources) {
initializeResource(resource, locale, localizedMessages, initializedResources);
protected void logMessage(String code, String resolvedCode, Locale locale, Locale resolvedLocale, Object[] args,
String messagePattern, String message) {
if (logger.isDebugEnabled()) {
logger.debug("Source '{}' gets Message[code : '{}' , resolvedCode : '{}' , locale : '{}' , resolvedLocale : '{}', args : '{}' , pattern : '{}'] : '{}'",
source, code, resolvedCode, locale, resolvedLocale, ArrayUtils.toString(args), messagePattern, message);
}
}

private void initializeResource(String resource, Locale locale, Map<Locale, Map<String, String>> localizedMessages,
Set<String> initializedResources) {
Map<String, String> messages = loadMessages(locale, resource);
validateMessages(messages, resource);
if (!isEmpty(messages)) {
logger.debug("Source '{}' loads the Locale '{}' resource['{}'] messages : {}", source, locale, resource, messages);
} else {
logger.debug("Source '{}' Locale '{}' resource not found['{}'] messages", source, locale, resource);
}
initializedResources.add(resource);
// Override the localized message if present
localizedMessages.put(locale, messages);
public Map<String, Map<String, String>> getLocalizedResourceMessages() {
return unmodifiableMap(this.localizedResourceMessages);
}

@Override
public Set<String> getInitializeResources() {
return localizedResourceMessages.keySet();
}

@Override
public String toString() {
final StringBuilder sb = new StringBuilder(getClass().getSimpleName())
.append("{source='").append(source).append('\'')
.append(", defaultLocale=").append(getDefaultLocale())
.append(", supportedLocales=").append(getSupportedLocales())
.append(", localizedResourceMessages=").append(localizedResourceMessages)
.append('}');
return sb.toString();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -173,8 +173,8 @@ protected static List<Locale> resolveDerivedLocales(Locale locale) {
}


protected String formatMessage(String message, Object... args) {
// Using slf4j format, future subclasses may re-implement formatting
protected String resolveMessage(String message, Object... args) {
// Using FormatUtils#format, future subclasses may re-implement formatting
return format(message, args);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;

import static io.microsphere.text.FormatUtils.format;

Expand All @@ -33,7 +32,7 @@ protected String getResource(String resourceName) {
}

@Override
protected List<Reader> loadAllPropertiesResources(Locale locale, String resource) throws IOException {
protected List<Reader> loadAllPropertiesResources(String resource) throws IOException {
ClassLoader classLoader = getClass().getClassLoader();
Enumeration<URL> resources = classLoader.getResources(resource);
List<Reader> propertiesResources = new LinkedList<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,15 @@

import java.io.IOException;
import java.io.Reader;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;

import static io.microsphere.collection.CollectionUtils.isEmpty;
import static io.microsphere.text.FormatUtils.format;
import static java.util.Collections.emptyMap;
import static java.util.Collections.unmodifiableMap;

/**
* {@link Properties} Resource {@link ServiceMessageSource} Class
Expand All @@ -28,22 +27,22 @@ public PropertiesResourceServiceMessageSource(String source) {
}

@Override
protected final Map<String, String> loadMessages(Locale locale, String resource) {
protected final Map<String, String> loadMessages(String resource) {
Map<String, String> messages = emptyMap();
try {
Properties properties = loadAllProperties(locale, resource);
Properties properties = loadAllProperties(resource);
if (!MapUtils.isEmpty(properties)) {
messages = new HashMap<>(properties.size());
messages.putAll((Map) properties);
}
} catch (IOException e) {
throw new RuntimeException(format("Source '{}' Messages Properties Resource[locale : {}, name : {}] loading is failed", source, locale, resource), e);
throw new RuntimeException(format("Source '{}' Messages Properties Resource[name : {}] loading is failed", source, resource), e);
}
return Collections.unmodifiableMap(messages);
return unmodifiableMap(messages);
}

private Properties loadAllProperties(Locale locale, String resource) throws IOException {
List<Reader> propertiesResources = loadAllPropertiesResources(locale, resource);
private Properties loadAllProperties(String resource) throws IOException {
List<Reader> propertiesResources = loadAllPropertiesResources(resource);
logger.debug("Source '{}' loads {} Properties Resources['{}']", source, propertiesResources.size(), resource);
if (isEmpty(propertiesResources)) {
return null;
Expand All @@ -60,5 +59,5 @@ private Properties loadAllProperties(Locale locale, String resource) throws IOEx

protected abstract String getResource(String resourceName);

protected abstract List<Reader> loadAllPropertiesResources(Locale locale, String resource) throws IOException;
protected abstract List<Reader> loadAllPropertiesResources(String resource) throws IOException;
}
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ protected Locale getInternalLocale() {
}

@Override
protected List<Reader> loadAllPropertiesResources(Locale locale, String resource) throws IOException {
protected List<Reader> loadAllPropertiesResources(String resource) throws IOException {
String propertyName = resource;
String propertiesContent = environment.getProperty(propertyName);
return hasText(propertiesContent) ? asList(new StringReader(propertiesContent)) : emptyList();
Expand Down

0 comments on commit dee457c

Please sign in to comment.