Open Source Repository

Home /jodd/jodd-3.3.2 | Repository Home



jodd/typeconverter/impl/BooleanConverter.java
// Copyright (c) 2003-2012, Jodd Team (jodd.org). All Rights Reserved.

package jodd.typeconverter.impl;

import jodd.typeconverter.TypeConversionException;
import jodd.typeconverter.TypeConverter;

import static jodd.util.StringPool.*;

/**
 * Converts given object to <code>Boolean</code>.
 * Conversion rules:
 <li><code>null</code> value is returned as <code>null</code>
 <li>object of destination type is simply casted
 <li>object is converted to string, trimmed. Then common boolean strings are matched:
 * "yes", "y", "true", "on", "1" for <code>true</code>; and opposite values
 * for <code>false</code>.
 */
public class BooleanConverter implements TypeConverter<Boolean> {

  public Boolean convert(Object value) {
    if (value == null) {
      return null;
    }

    if (value.getClass() == Boolean.class) {
      return (Booleanvalue;
    }

    String stringValue = value.toString().trim().toLowerCase();
    if (stringValue.equals(YES||
        stringValue.equals(Y||
        stringValue.equals(TRUE||
        stringValue.equals(ON||
        stringValue.equals(ONE)) {
      return Boolean.TRUE;
    }
    if (stringValue.equals(NO||
        stringValue.equals(N||
        stringValue.equals(FALSE||
        stringValue.equals(OFF||
        stringValue.equals(ZERO)) {
      return Boolean.FALSE;
    }

    throw new TypeConversionException(value);
  }

}