1
2
3
4
5
6
7
8
9
10
11
12 package org.hyphenType.util.resourcebundles;
13
14 import java.io.IOException;
15 import java.io.InputStream;
16 import java.io.InputStreamReader;
17 import java.net.URL;
18 import java.net.URLConnection;
19 import java.security.AccessController;
20 import java.security.PrivilegedActionException;
21 import java.security.PrivilegedExceptionAction;
22 import java.util.Locale;
23 import java.util.PropertyResourceBundle;
24 import java.util.ResourceBundle;
25 import java.util.ResourceBundle.Control;
26
27
28
29
30 public class GenericEncodingControl extends Control {
31
32
33
34
35 private String encodingName;
36
37
38
39
40
41
42 public GenericEncodingControl(final String encodingName) {
43 this.encodingName = encodingName;
44 }
45
46 @SuppressWarnings("unchecked")
47 @Override
48 public final ResourceBundle newBundle(final String baseName, final Locale locale, final String format, final ClassLoader loader, final boolean reload) throws IllegalAccessException, InstantiationException, IOException {
49 String bundleName = toBundleName(baseName, locale);
50 ResourceBundle bundle = null;
51 if (format.equals("java.class")) {
52 try {
53 Class<? extends ResourceBundle> bundleClass = (Class<? extends ResourceBundle>) loader.loadClass(bundleName);
54
55
56
57 if (ResourceBundle.class.isAssignableFrom(bundleClass)) {
58 bundle = bundleClass.newInstance();
59 } else {
60 throw new ClassCastException(bundleClass.getName() + " cannot be cast to ResourceBundle");
61 }
62 } catch (ClassNotFoundException e) {
63
64 }
65 } else if (format.equals("java.properties")) {
66
67 final String resourceName = toResourceName(bundleName, "properties");
68 final ClassLoader classLoader = loader;
69 final boolean reloadFlag = reload;
70 InputStream stream = null;
71 try {
72 stream = AccessController.doPrivileged(new PrivilegedExceptionAction<InputStream>() {
73 public InputStream run() throws IOException {
74 InputStream is = null;
75 if (reloadFlag) {
76 URL url = classLoader.getResource(resourceName);
77 if (url != null) {
78 URLConnection connection = url.openConnection();
79 if (connection != null) {
80
81
82
83 connection.setUseCaches(false);
84 is = connection.getInputStream();
85 }
86 }
87 } else {
88 is = classLoader.getResourceAsStream(resourceName);
89 }
90 return is;
91 }
92 });
93 } catch (PrivilegedActionException e) {
94 throw (IOException) e.getException();
95 }
96 if (stream != null) {
97 try {
98 bundle = new PropertyResourceBundle(new InputStreamReader(stream, encodingName));
99 } finally {
100 stream.close();
101 }
102 }
103 } else {
104 throw new IllegalArgumentException("unknown format: " + format);
105 }
106
107 return bundle;
108 }
109 }