01: /*
02: * Copyright (C) 2003, 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 26. September 2003 by Joe Walnes
11: */
12: package com.thoughtworks.xstream.converters.basic;
13:
14: /**
15: * Converts a boolean primitive or java.lang.Boolean wrapper to
16: * a String.
17: *
18: * @author Joe Walnes
19: * @author David Blevins
20: */
21: public class BooleanConverter extends AbstractSingleValueConverter {
22:
23: public static final BooleanConverter TRUE_FALSE = new BooleanConverter(
24: "true", "false", false);
25:
26: public static final BooleanConverter YES_NO = new BooleanConverter(
27: "yes", "no", false);
28:
29: public static final BooleanConverter BINARY = new BooleanConverter(
30: "1", "0", true);
31:
32: private final String positive;
33: private final String negative;
34: private final boolean caseSensitive;
35:
36: public BooleanConverter(final String positive,
37: final String negative, final boolean caseSensitive) {
38: this .positive = positive;
39: this .negative = negative;
40: this .caseSensitive = caseSensitive;
41: }
42:
43: public BooleanConverter() {
44: this ("true", "false", false);
45: }
46:
47: public boolean shouldConvert(final Class type, final Object value) {
48: return true;
49: }
50:
51: public boolean canConvert(final Class type) {
52: return type.equals(boolean.class) || type.equals(Boolean.class);
53: }
54:
55: public Object fromString(final String str) {
56: if (caseSensitive) {
57: return positive.equals(str) ? Boolean.TRUE : Boolean.FALSE;
58: } else {
59: return positive.equalsIgnoreCase(str) ? Boolean.TRUE
60: : Boolean.FALSE;
61: }
62: }
63:
64: public String toString(final Object obj) {
65: final Boolean value = (Boolean) obj;
66: return obj == null ? null : value.booleanValue() ? positive
67: : negative;
68: }
69: }
|