KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > thoughtworks > xstream > converters > extended > LocaleConverter


1 package com.thoughtworks.xstream.converters.extended;
2
3 import com.thoughtworks.xstream.converters.basic.AbstractBasicConverter;
4
5 import java.util.Locale JavaDoc;
6
7 /**
8  * Converts a java.util.Locale to a string.
9  *
10  * @author Jose A. Illescas
11  * @author Joe Walnes
12  */

13 public class LocaleConverter extends AbstractBasicConverter {
14
15     public boolean canConvert(Class JavaDoc type) {
16         return type.equals(Locale JavaDoc.class);
17     }
18
19     protected Object JavaDoc fromString(String JavaDoc str) {
20         int[] underscorePositions = underscorePositions(str);
21         String JavaDoc language, country, variant;
22         if (underscorePositions[0] == -1) { // "language"
23
language = str;
24             country = "";
25             variant = "";
26         } else if (underscorePositions[1] == -1) { // "language_country"
27
language = str.substring(0, underscorePositions[0]);
28             country = str.substring(underscorePositions[0] + 1);
29             variant = "";
30         } else { // "language_country_variant"
31
language = str.substring(0, underscorePositions[0]);
32             country = str.substring(underscorePositions[0] + 1, underscorePositions[1]);
33             variant = str.substring(underscorePositions[1] + 1);
34         }
35         return new Locale JavaDoc(language, country, variant);
36     }
37
38     private int[] underscorePositions(String JavaDoc in) {
39         int[] result = new int[2];
40         for (int i = 0; i < result.length; i++) {
41             int last = i == 0 ? 0 : result[i - 1];
42             result[i] = in.indexOf('_', last + 1);
43         }
44         return result;
45     }
46
47 }
Popular Tags