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