View Javadoc

1   /*
2    * Copyright 2004-2010 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  
17  package org.seasar.cubby.converter.impl;
18  
19  import org.seasar.cubby.converter.ConversionHelper;
20  
21  /**
22   * {@link Boolean}への変換を行うコンバータです。
23   * <p>
24   * 変換元オブジェクトの文字列表現が<code>yes</code>、<code>y</code>、<code>true</code>、
25   * <code>on</code>、<code>1</code>なら<code>true</code>、 そうでなければ<code>false</code>
26   * とします。
27   * </p>
28   * 
29   * @author baba
30   */
31  public class BooleanConverter extends AbstractConverter {
32  
33  	/** <code>true</code>に評価する文字列の配列です。 */
34  	private static final String[] TRUE_STRINGS = new String[] { "yes", "y",
35  			"true", "on", "1", };
36  
37  	/**
38  	 * {@inheritDoc}
39  	 */
40  	public Class<?> getObjectType() {
41  		return Boolean.class;
42  	}
43  
44  	/**
45  	 * {@inheritDoc}
46  	 */
47  	public Object convertToObject(final Object value,
48  			final Class<?> objectType, final ConversionHelper helper) {
49  		if (value == null) {
50  			return null;
51  		}
52  		return toBoolean(value.toString());
53  	}
54  
55  	/**
56  	 * 文字列を{@link Boolean}に変換して返します。
57  	 * 
58  	 * @param value
59  	 *            変換元の文字列表現
60  	 * @return 変換した結果の{@link Boolean}
61  	 */
62  	protected Object toBoolean(final String value) {
63  		for (final String trueString : TRUE_STRINGS) {
64  			if (trueString.equalsIgnoreCase(value)) {
65  				return Boolean.TRUE;
66  			}
67  		}
68  		return Boolean.FALSE;
69  	}
70  
71  	/**
72  	 * {@inheritDoc}
73  	 */
74  	public String convertToString(final Object value,
75  			final ConversionHelper helper) {
76  		if (value == null) {
77  			return null;
78  		}
79  		return value.toString();
80  	}
81  
82  }