Fix 2 TODO items:
[jvcard.git] / src / be / nikiroo / jvcard / resources / FixedResourceBundleControl.java
1 package be.nikiroo.jvcard.resources;
2
3 import java.io.File;
4 import java.io.FileInputStream;
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.InputStreamReader;
8 import java.net.URL;
9 import java.net.URLConnection;
10 import java.util.Locale;
11 import java.util.PropertyResourceBundle;
12 import java.util.ResourceBundle;
13 import java.util.ResourceBundle.Control;
14
15 /**
16 * Fixed ResourceBundle.Control class. It will use UTF-8 for the files to load.
17 *
18 * Also support an option to first check into the given path before looking into
19 * the resources.
20 *
21 * @author niki
22 *
23 */
24 class FixedResourceBundleControl extends Control {
25 private String outsideWorld = null;
26
27 /**
28 * Create a new {@link FixedResourceBundleControl}.
29 *
30 * @param outsideWorld
31 * NULL if you are only interested into the resources, a path to
32 * first check into it before looking at the actual resources
33 */
34 public FixedResourceBundleControl(String outsideWorld) {
35 this.outsideWorld = outsideWorld;
36 }
37
38 @Override
39 public ResourceBundle newBundle(String baseName, Locale locale,
40 String format, ClassLoader loader, boolean reload)
41 throws IllegalAccessException, InstantiationException, IOException {
42 // The below is a copy of the default implementation.
43 String bundleName = toBundleName(baseName, locale);
44 String resourceName = toResourceName(bundleName, "properties");
45
46 ResourceBundle bundle = null;
47 InputStream stream = null;
48 if (reload) {
49 URL url = loader.getResource(resourceName);
50 if (url != null) {
51 URLConnection connection = url.openConnection();
52 if (connection != null) {
53 connection.setUseCaches(false);
54 stream = connection.getInputStream();
55 }
56 }
57 } else {
58 // New code to support outside resources:
59 if (outsideWorld != null) {
60 String pkg = this.getClass().getPackage().getName();
61 pkg = pkg.replaceAll("\\.", File.separator) + File.separator;
62
63 if (resourceName.startsWith(pkg)) {
64 try {
65 String file = outsideWorld + File.separator
66 + resourceName.substring(pkg.length());
67 stream = new FileInputStream(file);
68 } catch (Exception e) {
69 // file not in priority directory,
70 // fallback to default resource
71 }
72 }
73 }
74
75 if (stream == null)
76 stream = loader.getResourceAsStream(resourceName);
77 //
78 }
79 if (stream != null) {
80 try {
81 // This line is changed to make it to read properties files
82 // as UTF-8.
83 // How can someone use an archaic encoding such as ISO 8859-1 by
84 // *DEFAULT* is beyond me...
85 bundle = new PropertyResourceBundle(new InputStreamReader(
86 stream, "UTF-8"));
87 } finally {
88 stream.close();
89 }
90 }
91 return bundle;
92 }
93 }