1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package net.sf.ezmorph.object;
18
19 import java.math.BigDecimal;
20 import java.math.BigInteger;
21
22 import net.sf.ezmorph.MorphException;
23
24 import org.apache.commons.lang.builder.EqualsBuilder;
25 import org.apache.commons.lang.builder.HashCodeBuilder;
26
27
28
29
30
31
32 public final class BigDecimalMorpher extends AbstractObjectMorpher
33 {
34 private BigDecimal defaultValue;
35
36 public BigDecimalMorpher()
37 {
38 super();
39 }
40
41
42
43
44 public BigDecimalMorpher( BigDecimal defaultValue )
45 {
46 super( true );
47 this.defaultValue = defaultValue;
48 }
49
50 public boolean equals( Object obj )
51 {
52 if( this == obj ){
53 return true;
54 }
55 if( obj == null ){
56 return false;
57 }
58
59 if( !(obj instanceof BigDecimalMorpher) ){
60 return false;
61 }
62
63 BigDecimalMorpher other = (BigDecimalMorpher) obj;
64 EqualsBuilder builder = new EqualsBuilder();
65 if( isUseDefault() && other.isUseDefault() ){
66 builder.append( getDefaultValue(), other.getDefaultValue() );
67 return builder.isEquals();
68 }else if( !isUseDefault() && !other.isUseDefault() ){
69 return builder.isEquals();
70 }else{
71 return false;
72 }
73 }
74
75
76
77
78 public BigDecimal getDefaultValue()
79 {
80 return defaultValue;
81 }
82
83 public int hashCode()
84 {
85 HashCodeBuilder builder = new HashCodeBuilder();
86 if( isUseDefault() ){
87 builder.append( getDefaultValue() );
88 }
89 return builder.toHashCode();
90 }
91
92 public Object morph( Object value )
93 {
94 if( value instanceof BigDecimal ){
95 return value;
96 }
97
98 if( value == null ){
99 if( isUseDefault() ){
100 return defaultValue;
101 }else{
102 return (BigDecimal) null;
103 }
104 }
105
106 if( value instanceof Number ){
107 if( value instanceof Float ){
108 Float f = ((Float) value);
109 if( f.isInfinite() || f.isNaN() ){
110 throw new MorphException( "BigDecimal can not be infinite or NaN" );
111 }
112 }else if( value instanceof Double ){
113 Double d = ((Double) value);
114 if( d.isInfinite() || d.isNaN() ){
115 throw new MorphException( "BigDecimal can not be infinite or NaN" );
116 }
117 }else if( value instanceof BigInteger ){
118 return new BigDecimal( (BigInteger) value );
119 }
120
121 return new BigDecimal( ((Number) value).doubleValue() );
122 }else{
123 try{
124 String str = String.valueOf( value )
125 .trim();
126 if( str.length() == 0 || str.equalsIgnoreCase( "null" ) ){
127 return (BigDecimal) null;
128 }else{
129 return new BigDecimal( str );
130 }
131 }
132 catch( NumberFormatException nfe ){
133 if( isUseDefault() ){
134 return defaultValue;
135 }else{
136 throw new MorphException( nfe );
137 }
138 }
139 }
140 }
141
142 public Class morphsTo()
143 {
144 return BigDecimal.class;
145 }
146 }