View Javadoc

    1   /*
    2    * Copyright 2004-2009 the Seasar Foundation and the Others.
    3    *
    4    * Licensed under the Apache License, Version 2.0 (the "License");
    5    * you may not use this file except in compliance with the License.
    6    * You may obtain a copy of the License at
    7    *
    8    *     http://www.apache.org/licenses/LICENSE-2.0
    9    *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
    13   * either express or implied. See the License for the specific language
    14   * governing permissions and limitations under the License.
    15   */
    16  package org.seasar.cubby.converter.impl;
    17
    18  import org.seasar.cubby.converter.ConversionHelper;
    19
    20  /**
    21   * {@link Boolean}への変換を行うコンバータです。
    22   * <p>
    23   * 変換元オブジェクトの文字列表現が<code>yes</code>、<code>y</code>、<code>true</code>、
    24   * <code>on</code>、<code>1</code>なら<code>true</code>、 そうでなければ<code>false</code>
    25   * とします。
    26   * </p>
    27   *
    28   * @author baba
    29   */
    30  public class BooleanConverter extends AbstractConverter {
    31
    32  	/** <code>true</code>に評価する文字列の配列です。 */
    33  	private static final String[] TRUE_STRINGS = new String[] { "yes", "y",
    34  			"true", "on", "1", };
    35
    36  	/**
    37  	 * {@inheritDoc}
    38  	 */
    39  	public Class<?> getObjectType() {
    40  		return Boolean.class;
    41  	}
    42
    43  	/**
    44  	 * {@inheritDoc}
    45  	 */
    46  	public Object convertToObject(final Object value,
    47  			final Class<?> objectType, final ConversionHelper helper) {
    48  		if (value == null) {
    49  			return null;
    50  		}
    51  		return toBoolean(value.toString());
    52  	}
    53
    54  	/**
    55  	 * 文字列を{@link Boolean}に変換して返します。
    56  	 *
    57  	 * @param value
    58  	 *            変換元の文字列表現
    59  	 * @return 変換した結果の{@link Boolean}
    60  	 */
    61  	protected Object toBoolean(final String value) {
    62  		for (final String trueString : TRUE_STRINGS) {
    63  			if (trueString.equalsIgnoreCase(value)) {
    64  				return Boolean.TRUE;
    65  			}
    66  		}
    67  		return Boolean.FALSE;
    68  	}
    69
    70  	/**
    71  	 * {@inheritDoc}
    72  	 */
    73  	public String convertToString(final Object value,
    74  			final ConversionHelper helper) {
    75  		if (value == null) {
    76  			return null;
    77  		}
    78  		return value.toString();
    79  	}
    80
    81  }