View Javadoc

1   /*
2    * Copyright 2004-2005, 2008 the original author or authors.
3    * 
4    * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5    * use this file except in compliance with the License. You may obtain a copy of
6    * 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, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations under
14   * the License.
15   */
16  package net.sf.morph.transform.converters;
17  
18  import java.math.BigDecimal;
19  import java.util.Locale;
20  
21  import net.sf.morph.transform.DecoratedConverter;
22  import net.sf.morph.transform.transformers.BaseTransformer;
23  import net.sf.morph.util.NumberUtils;
24  
25  /**
26   * Converts numbers to boolean values. Numbers equal to zero are converted to
27   * <code>false</code> and non-zero numbers will be converted to
28   * <code>true</code>.
29   * 
30   * @author Matt Sgarlata
31   * @since Dec 31, 2004
32   */
33  public class NumberToBooleanConverter extends BaseTransformer implements DecoratedConverter {
34  
35  	private static final Class[] DESTINATION_TYPES = { Boolean.class,
36  		boolean.class };
37  
38  	private static final Class[] SOURCE_TYPES = { Number.class };
39  
40  	/**
41  	 * {@inheritDoc}
42  	 */
43  	protected Object convertImpl(Class destinationClass, Object source,
44  		Locale locale) throws Exception {
45  
46  		BigDecimal bigDecimal = new BigDecimal(source.toString());
47  		// BigDecimal.equals() takes scale into account, so use compareTo()
48  		return bigDecimal.compareTo(NumberUtils.ZERO) == 0 ? Boolean.FALSE : Boolean.TRUE;
49  	}
50  
51  	/**
52  	 * {@inheritDoc}
53  	 */
54  	protected Class[] getSourceClassesImpl() throws Exception {
55  		return SOURCE_TYPES;
56  	}
57  
58  	/**
59  	 * {@inheritDoc}
60  	 */
61  	protected Class[] getDestinationClassesImpl() throws Exception {
62  		return DESTINATION_TYPES;
63  	}
64  
65  	/**
66  	 * {@inheritDoc}
67  	 */
68  	protected boolean isWrappingRuntimeExceptions() {
69  	    return true;
70      }
71  
72  }