All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.restup.bind.converter.StringToBooleanConverter Maven / Gradle / Ivy

There is a newer version: 0.0.5
Show newest version
package com.github.restup.bind.converter;

import java.util.HashSet;
import java.util.Set;
import static org.apache.commons.lang3.StringUtils.*;

public class StringToBooleanConverter {

    private static final Set trueValues;
    private static final Set falseValues;

    static {
        trueValues = new HashSet(6);
        trueValues.add("true");
        trueValues.add("on");
        trueValues.add("yes");
        trueValues.add("1");
        trueValues.add("t");
        trueValues.add("y");

        falseValues = new HashSet(6);
        falseValues.add("false");
        falseValues.add("off");
        falseValues.add("no");
        falseValues.add("0");
        falseValues.add("n");
        falseValues.add("f");
    }


    public static boolean isTrue(Object value) {
        if (value instanceof Boolean) {
            return (Boolean) value;
        }
        if (value instanceof String) {
            return trueValues.contains(((String) value).toLowerCase());
        }
        return false;
    }

    public static Boolean toBoolean(String from) {
        if (from != null) {
            String value = from.trim();
            if (isNotEmpty(from)) {
                value = value.toLowerCase();
                if (trueValues.contains(value)) {
                    return Boolean.TRUE;
                } else if (falseValues.contains(value)) {
                    return Boolean.FALSE;
                }
            }
        }
        throw new IllegalArgumentException(from + " is not a valid boolean value");
    }

    private StringToBooleanConverter() {
        super();        
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy