1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package de.smartics.properties.spi.core.context;
17
18 import java.util.ArrayList;
19 import java.util.Collections;
20 import java.util.Comparator;
21 import java.util.HashSet;
22 import java.util.List;
23 import java.util.Locale;
24 import java.util.Set;
25
26 import org.apache.commons.io.FilenameUtils;
27 import org.apache.commons.lang.LocaleUtils;
28
29 import de.smartics.properties.api.core.domain.ConfigException;
30 import de.smartics.properties.api.core.domain.PropertiesContext;
31 import de.smartics.util.lang.ClassPathContext;
32 import de.smartics.util.util.GenericServiceFactory;
33
34
35
36
37 final class LocaleFinder
38 {
39
40
41
42
43
44
45
46 private static final ClassPathListing CLASS_PATH_LISTING;
47
48
49
50
51
52
53 private static final Comparator<Locale> COMPARATOR = new Comparator<Locale>()
54 {
55 @Override
56 public int compare(final Locale o1, final Locale o2)
57 {
58 return o1.toString().compareTo(o2.toString());
59 }
60 };
61
62
63
64 static
65 {
66 ClassPathListing service = null;
67 try
68 {
69 service =
70 new GenericServiceFactory<ClassPathListing>(ClassPathListing.class)
71 .create();
72 }
73 catch (final IllegalStateException e)
74 {
75 service = new JarAndFileClassPathListing();
76 }
77
78 CLASS_PATH_LISTING = service;
79 }
80
81
82
83
84
85
86 LocaleFinder()
87 {
88 }
89
90
91
92
93
94
95
96
97
98
99
100 List<Locale> find(final String systemId, final ClassPathContext context)
101 throws ConfigException
102 {
103 final Set<Locale> locales = new HashSet<Locale>();
104 locales.add(new Locale(""));
105
106 final List<String> listing =
107 CLASS_PATH_LISTING.list(context,
108 PropertiesContext.META_INF_PROPERTY_SET_REPORT);
109
110 for (final String path : listing)
111 {
112 final Locale locale = calcLocale(path);
113 if (locale != null)
114 {
115 locales.add(locale);
116 }
117 }
118
119 final List<Locale> list = new ArrayList<Locale>(locales);
120 Collections.sort(list, COMPARATOR);
121 return list;
122 }
123
124 Locale calcLocale(final String urlString)
125 {
126 final String fileName = FilenameUtils.getBaseName(urlString);
127 final int urlStringLength = urlString.length();
128 int separatorIndex = fileName.indexOf('_');
129 Locale locale = null;
130
131 while (separatorIndex != -1)
132 {
133 final String localeString = fileName.substring(separatorIndex + 1);
134 locale = constructLocale(localeString);
135 separatorIndex =
136 locale != null || separatorIndex + 1 >= urlStringLength ? -1
137 : fileName.indexOf('_', separatorIndex + 1);
138 }
139 return locale;
140 }
141
142 private Locale constructLocale(final String localeString)
143 {
144 try
145 {
146 final Locale locale = LocaleUtils.toLocale(localeString);
147 return locale;
148 }
149 catch (final IllegalArgumentException e)
150 {
151 return null;
152 }
153 }
154
155
156
157 }