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.io.InputStream;
21 import java.nio.file.Files;
22 import java.nio.file.Path;
23 import java.util.Properties;
24
25 import org.apache.commons.lang3.StringUtils;
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42 final class PropertiesStringLookup extends AbstractPathFencedLookup {
43
44
45
46
47 static final PropertiesStringLookup INSTANCE = new PropertiesStringLookup((Path[]) null);
48
49
50 static final String SEPARATOR = "::";
51
52
53
54
55 static String toPropertyKey(final String file, final String key) {
56 return AbstractStringLookup.toLookupKey(file, SEPARATOR, key);
57 }
58
59
60
61
62
63
64 PropertiesStringLookup(final Path... fences) {
65 super(fences);
66 }
67
68
69
70
71
72
73
74
75
76
77
78
79
80 @Override
81 public String lookup(final String key) {
82 if (key == null) {
83 return null;
84 }
85 final String[] keys = key.split(SEPARATOR);
86 final int keyLen = keys.length;
87 if (keyLen < 2) {
88 throw IllegalArgumentExceptions.format("Bad properties key format [%s]; expected format is %s.", key,
89 toPropertyKey("DocumentPath", "Key"));
90 }
91 final String documentPath = keys[0];
92 final String propertyKey = StringUtils.substringAfter(key, SEPARATOR);
93 try {
94 final Properties properties = new Properties();
95 try (InputStream inputStream = Files.newInputStream(getPath(documentPath))) {
96 properties.load(inputStream);
97 }
98 return properties.getProperty(propertyKey);
99 } catch (final Exception e) {
100 throw IllegalArgumentExceptions.format(e, "Error looking up properties [%s] and key [%s].", documentPath,
101 propertyKey);
102 }
103 }
104
105 }