1 /*
2  * Copyright (C) 2003, 2004 Joe Walnes.
3  * Copyright (C) 2006, 2007, 2014, 2018 XStream Committers.
4  * All rights reserved.
5  *
6  * The software in this package is published under the terms of the BSD
7  * style license a copy of which has been included with this distribution in
8  * the LICENSE.txt file.
9  * 
10  * Created on 26. September 2003 by Joe Walnes
11  */

12 package com.thoughtworks.xstream.converters.basic;
13
14
15 /**
16  * Converts a boolean primitive or java.lang.Boolean wrapper to
17  * a String.
18  *
19  * @author Joe Walnes
20  * @author David Blevins
21  */

22 public class BooleanConverter extends AbstractSingleValueConverter {
23
24     public static final BooleanConverter TRUE_FALSE = new BooleanConverter("true""false"false);
25     public static final BooleanConverter YES_NO = new BooleanConverter("yes""no"false);
26     public static final BooleanConverter BINARY = new BooleanConverter("1""0"true);
27
28     private final String positive;
29     private final String negative;
30     private final boolean caseSensitive;
31
32     public BooleanConverter(final String positive, final String negative, final boolean caseSensitive) {
33         this.positive = positive;
34         this.negative = negative;
35         this.caseSensitive = caseSensitive;
36     }
37
38     public BooleanConverter() {
39         this("true""false"false);
40     }
41
42     /**
43      * @deprecated As of 1.4.8 use {@link #canConvert(Class)}
44      */

45     public boolean shouldConvert(final Class type, final Object value) {
46         return true;
47     }
48
49     public boolean canConvert(final Class type) {
50         return type == boolean.class || type == Boolean.class;
51     }
52
53     public Object fromString(final String str) {
54         if (caseSensitive) {
55             return positive.equals(str) ? Boolean.TRUE : Boolean.FALSE;
56         } else {
57             return positive.equalsIgnoreCase(str) ? Boolean.TRUE : Boolean.FALSE;
58         }
59     }
60
61     public String toString(final Object obj) {
62         final Boolean value = (Boolean) obj;
63         return obj == null ? null : value.booleanValue() ? positive : negative;
64     }
65 }
66