1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.text.lookup;
19
20 import java.util.MissingResourceException;
21 import java.util.ResourceBundle;
22
23
24
25
26
27
28
29
30
31
32
33
34
35 final class ResourceBundleStringLookup extends AbstractStringLookup {
36
37
38
39
40 static final ResourceBundleStringLookup INSTANCE = new ResourceBundleStringLookup();
41
42
43
44
45 private final String bundleName;
46
47
48
49
50 private ResourceBundleStringLookup() {
51 this(null);
52 }
53
54
55
56
57
58
59
60 ResourceBundleStringLookup(final String bundleName) {
61 this.bundleName = bundleName;
62 }
63
64 ResourceBundle getBundle(final String keyBundleName) {
65
66 return ResourceBundle.getBundle(keyBundleName);
67 }
68
69 String getString(final String keyBundleName, final String bundleKey) {
70 return getBundle(keyBundleName).getString(bundleKey);
71 }
72
73
74
75
76
77
78
79
80
81
82
83
84 @Override
85 public String lookup(final String key) {
86 if (key == null) {
87 return null;
88 }
89 final String[] keys = key.split(SPLIT_STR);
90 final int keyLen = keys.length;
91 final boolean anyBundle = bundleName == null;
92 if (anyBundle && keyLen != 2) {
93 throw IllegalArgumentExceptions
94 .format("Bad resource bundle key format [%s]; expected format is BundleName:KeyName.", key);
95 }
96 if (bundleName != null && keyLen != 1) {
97 throw IllegalArgumentExceptions.format("Bad resource bundle key format [%s]; expected format is KeyName.",
98 key);
99 }
100 final String keyBundleName = anyBundle ? keys[0] : bundleName;
101 final String bundleKey = anyBundle ? keys[1] : keys[0];
102 try {
103 return getString(keyBundleName, bundleKey);
104 } catch (final MissingResourceException e) {
105
106 return null;
107 } catch (final Exception e) {
108
109 throw IllegalArgumentExceptions.format(e, "Error looking up resource bundle [%s] and key [%s].",
110 keyBundleName, bundleKey);
111 }
112 }
113
114 @Override
115 public String toString() {
116 return super.toString() + " [bundleName=" + bundleName + "]";
117 }
118
119 }