1 package org.apache.slide.projector.processor.resolver; 2 3 import java.util.ArrayList ; 4 import java.util.Collections ; 5 import java.util.List ; 6 import java.util.Locale ; 7 import java.util.StringTokenizer ; 8 9 import org.apache.slide.projector.Context; 10 import org.apache.slide.projector.descriptor.ParameterDescriptor; 11 import org.apache.slide.projector.descriptor.ResultEntryDescriptor; 12 import org.apache.slide.projector.descriptor.StringValueDescriptor; 13 import org.apache.slide.projector.i18n.DefaultMessage; 14 import org.apache.slide.projector.i18n.ParameterMessage; 15 import org.apache.slide.projector.processor.SimpleProcessor; 16 import org.apache.slide.projector.value.LocaleValue; 17 import org.apache.slide.projector.value.StringValue; 18 import org.apache.slide.projector.value.Value; 19 20 23 public class LocaleResolver extends SimpleProcessor { 24 private final static ParameterDescriptor parameterDescriptor = new ParameterDescriptor(INPUT, new ParameterMessage("localeResolver/locale"), new StringValueDescriptor(), new StringValue(Locale.getDefault().toString())); 25 private final static ResultEntryDescriptor resultEntryDescriptor = new ResultEntryDescriptor(SimpleProcessor.OUTPUT, new DefaultMessage("locale/result/output"), LocaleValue.CONTENT_TYPE, false); 26 27 public Value process(Value input, Context context) throws Exception { 28 List acceptedLanguages = new ArrayList (); 29 StringTokenizer tokenizer = new StringTokenizer (input.toString(), ","); 30 while ( tokenizer.hasMoreTokens() ) { 31 String localeToken = tokenizer.nextToken(); 32 double q = 1.0; 33 int qIndex = localeToken.indexOf(";q="); 34 if ( qIndex > 0 ) { 35 q = Double.parseDouble(localeToken.substring(qIndex+3)); 36 localeToken = localeToken.substring(0, qIndex); 37 } 38 acceptedLanguages.add(new AcceptedLanguage(q, new Locale (localeToken))); 40 } 41 Collections.sort(acceptedLanguages); 42 return new LocaleValue(((AcceptedLanguage)acceptedLanguages.get(0)).getLocale()); 43 } 44 45 public ParameterDescriptor getParameterDescriptor() { 46 return parameterDescriptor; 47 } 48 49 public ResultEntryDescriptor getResultEntryDescriptor() { 50 return resultEntryDescriptor; 51 } 52 53 class AcceptedLanguage implements Comparable { 54 double q; 55 Locale locale; 56 57 public AcceptedLanguage(double q, Locale locale) { 58 this.q = q; 59 this.locale = locale; 60 } 61 62 public Locale getLocale() { 63 return locale; 64 } 65 66 public double getQ() { 67 return q; 68 } 69 70 public int compareTo(Object a) { 71 if ( ((AcceptedLanguage)a).getQ() < q ) return -1; 72 if ( ((AcceptedLanguage)a).getQ() > q ) return 1; 73 return 0; 74 } 75 } 76 } | Popular Tags |