All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.springframework.context.support.ResourceBundleMessageSourceCustom Maven / Gradle / Ivy

package org.springframework.context.support;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Locale;

import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.SystemPropertyUtils;

public class ResourceBundleMessageSourceCustom extends ResourceBundleMessageSource {
  private static final ResourcePatternResolver RESOURCE_PATTERN_RESOLVER = ResourcePatternUtils.getResourcePatternResolver(new DefaultResourceLoader());
  private static final String USER_HOME = SystemPropertyUtils.resolvePlaceholders("${user.home}");

  public ResourceBundleMessageSourceCustom(String packageName) {
    setUseCodeAsDefaultMessage(true);
    String locationPattern = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + ClassUtils.convertClassNameToResourcePath('/' + packageName + '/') + "**" + ".properties";
    for (Resource resource : getResources(locationPattern)) {
      String filename = (filename = resource.getFilename()).substring(0, filename.length() - ".properties".length());
      if (isBasename(filename)) {
        addBasenames(packageName + '.' + filename);
      }
    }
  }

  public ResourceBundleMessageSourceCustom(File directory) {
    setUseCodeAsDefaultMessage(true);
    if (directory.exists() && directory.isDirectory()) {
      String locationPattern = directory.toURI() + "**" + ".properties";
      for (Resource resource : getResources(locationPattern)) {
        String filename = (filename = resource.getFilename()).substring(0, filename.length() - ".properties".length());
        if (isBasename(filename)) {
          addBasenames(directory.toURI().toString() + '/' + filename);
        }
      }
    }
  }

  private boolean isBasename(String filename) {
    if (filename == null) {
      return false;
    }
    for (Locale locale : Locale.getAvailableLocales()) {
      if (!locale.equals(Locale.ROOT) && filename.endsWith('_' + locale.toString())) {
        return false;
      }
    }
    return true;
  }

  private Resource[] getResources(String locationPattern) {
    Assert.notNull(locationPattern, "'locationPattern' must not be null");
    locationPattern = locationPattern.replaceFirst("^~", Paths.get(USER_HOME).toFile().toURI().toString());
    try {
      return RESOURCE_PATTERN_RESOLVER.getResources(locationPattern);
    }
    catch (IOException e) {
      throw new IllegalStateException(e);
    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy