1 package org.codehaus.plexus.i18n;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 import java.util.ArrayList;
20 import java.util.Collections;
21 import java.util.Iterator;
22 import java.util.Locale;
23 import java.util.NoSuchElementException;
24 import java.util.StringTokenizer;
25
26
27
28
29
30
31
32
33
34
35 public class I18NTokenizer
36 implements Iterator
37 {
38
39
40
41
42 private static final String LOCALE_SEPARATOR = ",";
43
44
45
46
47 private static final char QUALITY_SEPARATOR = ';';
48
49
50
51
52
53 private static final Float DEFAULT_QUALITY = new Float(1.0f);
54
55
56
57
58 private ArrayList locales = new ArrayList(3);
59
60
61
62
63
64
65
66 public I18NTokenizer(String header)
67 {
68 StringTokenizer tok = new StringTokenizer(header, LOCALE_SEPARATOR);
69 while (tok.hasMoreTokens())
70 {
71 AcceptLanguage acceptLang = new AcceptLanguage();
72 String element = tok.nextToken().trim();
73 int index;
74
75
76
77 if ( (index = element.indexOf(QUALITY_SEPARATOR)) != -1 )
78 {
79 String q = element.substring(index);
80 element = element.substring(0, index);
81 if ( (index = q.indexOf('=')) != -1 )
82 {
83 try
84 {
85 acceptLang.quality =
86 Float.valueOf(q.substring(index + 1));
87 }
88 catch (NumberFormatException useDefault)
89 {
90 }
91 }
92 }
93
94 element = element.trim();
95
96
97
98 if ( (index = element.indexOf('-')) == -1 )
99 {
100
101 acceptLang.locale = new Locale(element, "");
102 }
103 else
104 {
105 acceptLang.locale = new Locale(element.substring(0, index),
106 element.substring(index + 1));
107 }
108
109 locales.add(acceptLang);
110 }
111
112
113 Collections.sort(locales, Collections.reverseOrder());
114 }
115
116
117
118
119 public boolean hasNext()
120 {
121 return !locales.isEmpty();
122 }
123
124
125
126
127
128
129
130
131 public Object next()
132 {
133 if (locales.isEmpty())
134 {
135 throw new NoSuchElementException();
136 }
137 return ((AcceptLanguage) locales.remove(0)).locale;
138 }
139
140
141
142
143 public final void remove()
144 {
145 throw new UnsupportedOperationException(getClass().getName() +
146 " does not support remove()");
147 }
148
149
150
151
152
153 private class AcceptLanguage implements Comparable
154 {
155
156
157
158 Locale locale;
159
160
161
162
163
164 Float quality = DEFAULT_QUALITY;
165
166 public final int compareTo(Object acceptLang)
167 {
168 return quality.compareTo( ((AcceptLanguage) acceptLang).quality );
169 }
170 }
171 }