1 package org.apache.turbine.services.localization; 2 3 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 33 public class LocaleTokenizer 34 implements Iterator 35 { 36 40 private static final String LOCALE_SEPARATOR = ","; 41 42 45 private static final char QUALITY_SEPARATOR = ';'; 46 47 51 private static final Float DEFAULT_QUALITY = new Float (1.0f); 52 53 56 private ArrayList locales = new ArrayList (3); 57 58 64 public LocaleTokenizer(String header) 65 { 66 StringTokenizer tok = new StringTokenizer (header, LOCALE_SEPARATOR); 67 while (tok.hasMoreTokens()) 68 { 69 AcceptLanguage acceptLang = new AcceptLanguage(); 70 String element = tok.nextToken().trim(); 71 int index; 72 73 if ((index = element.indexOf(QUALITY_SEPARATOR)) != -1) 76 { 77 String q = element.substring(index); 78 element = element.substring(0, index); 79 if ((index = q.indexOf('=')) != -1) 80 { 81 try 82 { 83 acceptLang.quality = 84 Float.valueOf(q.substring(index + 1)); 85 } 86 catch (NumberFormatException useDefault) 87 { 88 } 89 } 90 } 91 92 element = element.trim(); 93 94 if ((index = element.indexOf('-')) == -1) 97 { 98 acceptLang.locale = new Locale (element, ""); 100 } 101 else 102 { 103 acceptLang.locale = new Locale (element.substring(0, index), 104 element.substring(index + 1)); 105 } 106 107 locales.add(acceptLang); 108 } 109 110 Collections.sort(locales, Collections.reverseOrder()); 112 } 113 114 117 public boolean hasNext() 118 { 119 return !locales.isEmpty(); 120 } 121 122 129 public Object next() 130 { 131 if (locales.isEmpty()) 132 { 133 throw new NoSuchElementException (); 134 } 135 return ((AcceptLanguage) locales.remove(0)).locale; 136 } 137 138 141 public final void remove() 142 { 143 throw new UnsupportedOperationException (getClass().getName() + 144 " does not support remove()"); 145 } 146 147 151 private class AcceptLanguage implements Comparable 152 { 153 156 Locale locale; 157 158 162 Float quality = DEFAULT_QUALITY; 163 164 public final int compareTo(Object acceptLang) 165 { 166 return quality.compareTo(((AcceptLanguage) acceptLang).quality); 167 } 168 } 169 } 170 | Popular Tags |