Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.cantaa.util.resource;
  
  import java.net.URL;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
 
Handles loading resource-strings from a bundle

Usage:


     provider = new BundleProvider("BundleName");
     String value = provider.getString("key", "parameter");
 

Author(s):
Hans Lesmeister
 
 public class BundleProvider {
     private static final Logger log = LoggerFactory.getLogger(BundleProvider.class);
 
     private static final ResourceBundle.Control control = new MyBundleControl();
     private static final List<StringCONTROL_FORMATS = Arrays.asList("properties.xml");
 
     private final Set<StringbundleNames = new HashSet<String>();
     private final Map<StringURLClassLoaderbundleLoaders = new HashMap<StringURLClassLoader>();
     private LocaleProvider localeProvider;

    
Constructor for backwards compatibility

Deprecated:
Use constructor BundleProvider(LocaleProvider, String[]) instead
Parameters:
bundleName
localeProvider
 
     public BundleProvider(String bundleNameLocaleProvider localeProvider) {
         this(localeProviderbundleName);
     }
 
     public BundleProvider(String bundleName) {
         this(nullbundleName);
     }
 
     public BundleProvider(LocaleProvider localeProviderString... bundleNames) {
         super();
         Reject.ifNull(bundleNames"bundleNames is null");
         Reject.ifTrue(bundleNames.length == 0, "bundleNames is empty");
 
         this. = localeProvider;
         for (String bundleName : bundleNames) {
             this..add(bundleName);
         }
     }
 
     public void addBundleLoader(String bundleNameURLClassLoader bundleLoader) {
         Reject.ifNull(bundleName"bundleName is null");
         Reject.ifNull(bundleLoader"bundleLoader is null");
 
         .add(bundleName);
         .put(bundleNamebundleLoader);
     }
 
     public String getString(String keyObject... objects) {
         return getString(nullkeyobjects);
     }
 
     public void setLocaleProvider(LocaleProvider localeProvider) {
         this. = localeProvider;
     }

    
Get a localized resource string from the Bundle

Parameters:
locale The locale to use. If null then locale from the locale provider is used or the current default locale is used
key Key of the string in the bundle
objects Optional array of values to feed MessageFormat for placeholders in the resource strings
Returns:
The value that was retrieved from the bundle. If the key could not be found then no exception is thrown. Instead, the key itself is returned
 
     public String getString(Locale localeString keyObject... objects) {
         Locale usedLocale = determineLocale(locale);
 
        String value = key;
        for (String bundleName : ) {
            URLClassLoader bundleLoader = .get(bundleName);
            ResourceBundle rb;
            if (bundleLoader == null) {
                rb = ResourceBundle.getBundle(bundleNameusedLocale);
            } else {
                rb = ResourceBundle.getBundle(bundleNameusedLocalebundleLoader);
            }
            if (rb.containsKey(key)) {
                value = rb.getString(key);
                break;
            }
        }
        if ((value != null) && (objects != null) && (objects.length != 0)) {
            final MessageFormat format = new MessageFormat(valueusedLocale);
            value = format.format(objects);
        }
        return value;
    }

    
Determine a locale to use

Parameters:
locale
Returns:
the applied locale or, if null, the locale provided by the locale provider or, if null, the default locale
    private Locale determineLocale(Locale locale) {
        if (locale != null) {
            return locale;
        }
        if ( == null) {
            return Locale.getDefault();
        }
        Locale usedLocale = .getLocale();
        if (usedLocale == null) {
            return Locale.getDefault();
        }
        return usedLocale;
    }
    private static class MyBundleControl extends ResourceBundle.Control {
        public List<StringgetFormats(String baseName) {
            if (baseName == null) {
                throw new NullPointerException();
            }
            return ;
        }
        public ResourceBundle newBundle(String baseName,
                                        Locale locale,
                                        String format,
                                        ClassLoader loader,
                                        boolean reload)
                throws IllegalAccessException,
                       InstantiationException,
                       IOException
        {
            if (baseName == null || locale == null
                || format == null || loader == null) {
                throw new NullPointerException();
            }
            ResourceBundle bundle = null;
            if (format.equals("properties.xml")) {
                String bundleName = toBundleName(baseNamelocale);
                String resourceName = toResourceName(bundleNameformat);
                .debug("bundleName to load: {}, resourceName to load {}"bundleNameresourceName);
                InputStream stream = null;
                if (reload) {
                    .debug("Reloading the resource");
                    URL url = loader.getResource(resourceName);
                    if (url != null) {
                        URLConnection connection = url.openConnection();
                        if (connection != null) {
                            // Disable caches to get fresh data for
                            // reloading.
                            connection.setUseCaches(false);
                            stream = connection.getInputStream();
                        }
                    }
                }
                else {
                    .debug("About to load the resource");
                    stream = loader.getResourceAsStream(resourceName);
                }
                if (stream != null) {
                    .debug("Loading the resource");
                    BufferedInputStream bis = new BufferedInputStream(stream);
                    try {
                        bundle = new XMLResourceBundle(bis);
                        .debug("Resource is loaded successfully");
                    }
                    finally {
                        bis.close();
                    }
                }
            }
            return bundle;
        }
    }
    private static class XMLResourceBundle extends ResourceBundle {
        private Properties props;
        XMLResourceBundle(InputStream streamthrows IOException {
             = new Properties();
            .loadFromXML(stream);
        }
        protected Object handleGetObject(String key) {
            return .getProperty(key);
        }
        @SuppressWarnings("unchecked")
        public Enumeration<StringgetKeys() {
            return (Enumeration<String>) .propertyNames();
        }
    }
New to GrepCode? Check out our FAQ X