01: /*
02: * Copyright (C) 2004 Joe Walnes.
03: * Copyright (C) 2006, 2007 XStream Committers.
04: * All rights reserved.
05: *
06: * The software in this package is published under the terms of the BSD
07: * style license a copy of which has been included with this distribution in
08: * the LICENSE.txt file.
09: *
10: * Created on 24. Julyl 2004 by Joe Walnes
11: */
12: package com.thoughtworks.xstream.converters.extended;
13:
14: import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;
15:
16: import java.util.Locale;
17:
18: /**
19: * Converts a java.util.Locale to a string.
20: *
21: * @author Jose A. Illescas
22: * @author Joe Walnes
23: */
24: public class LocaleConverter extends AbstractSingleValueConverter {
25:
26: public boolean canConvert(Class type) {
27: return type.equals(Locale.class);
28: }
29:
30: public Object fromString(String str) {
31: int[] underscorePositions = underscorePositions(str);
32: String language, country, variant;
33: if (underscorePositions[0] == -1) { // "language"
34: language = str;
35: country = "";
36: variant = "";
37: } else if (underscorePositions[1] == -1) { // "language_country"
38: language = str.substring(0, underscorePositions[0]);
39: country = str.substring(underscorePositions[0] + 1);
40: variant = "";
41: } else { // "language_country_variant"
42: language = str.substring(0, underscorePositions[0]);
43: country = str.substring(underscorePositions[0] + 1,
44: underscorePositions[1]);
45: variant = str.substring(underscorePositions[1] + 1);
46: }
47: return new Locale(language, country, variant);
48: }
49:
50: private int[] underscorePositions(String in) {
51: int[] result = new int[2];
52: for (int i = 0; i < result.length; i++) {
53: int last = i == 0 ? 0 : result[i - 1];
54: result[i] = in.indexOf('_', last + 1);
55: }
56: return result;
57: }
58:
59: }
|