| 1 | package be.nikiroo.utils.resources; |
| 2 | |
| 3 | import java.io.IOException; |
| 4 | import java.io.InputStream; |
| 5 | import java.io.InputStreamReader; |
| 6 | import java.net.URL; |
| 7 | import java.net.URLConnection; |
| 8 | import java.util.Locale; |
| 9 | import java.util.PropertyResourceBundle; |
| 10 | import java.util.ResourceBundle; |
| 11 | import java.util.ResourceBundle.Control; |
| 12 | |
| 13 | /** |
| 14 | * Fixed ResourceBundle.Control class. It will use UTF-8 for the files to load. |
| 15 | * |
| 16 | * Also support an option to first check into the given path before looking into |
| 17 | * the resources. |
| 18 | * |
| 19 | * @author niki |
| 20 | * |
| 21 | */ |
| 22 | class FixedResourceBundleControl extends Control { |
| 23 | @Override |
| 24 | public ResourceBundle newBundle(String baseName, Locale locale, |
| 25 | String format, ClassLoader loader, boolean reload) |
| 26 | throws IllegalAccessException, InstantiationException, IOException { |
| 27 | // The below is a copy of the default implementation. |
| 28 | String bundleName = toBundleName(baseName, locale); |
| 29 | String resourceName = toResourceName(bundleName, "properties"); |
| 30 | |
| 31 | ResourceBundle bundle = null; |
| 32 | InputStream stream = null; |
| 33 | if (reload) { |
| 34 | URL url = loader.getResource(resourceName); |
| 35 | if (url != null) { |
| 36 | URLConnection connection = url.openConnection(); |
| 37 | if (connection != null) { |
| 38 | connection.setUseCaches(false); |
| 39 | stream = connection.getInputStream(); |
| 40 | } |
| 41 | } |
| 42 | } else { |
| 43 | stream = loader.getResourceAsStream(resourceName); |
| 44 | } |
| 45 | |
| 46 | if (stream != null) { |
| 47 | try { |
| 48 | // This line is changed to make it to read properties files |
| 49 | // as UTF-8. |
| 50 | // How can someone use an archaic encoding such as ISO 8859-1 by |
| 51 | // *DEFAULT* is beyond me... |
| 52 | bundle = new PropertyResourceBundle(new InputStreamReader( |
| 53 | stream, "UTF-8")); |
| 54 | } finally { |
| 55 | stream.close(); |
| 56 | } |
| 57 | } |
| 58 | return bundle; |
| 59 | } |
| 60 | } |