Statistics
| Revision:

gvsig-tools / org.gvsig.tools / library / trunk / org.gvsig.tools / org.gvsig.tools.lib / src / main / java / org / gvsig / tools / dataTypes / impl / coercion / CoerceToDecimal.java @ 2208

History | View | Annotate | Download (5.66 KB)

1
/**
2
 * gvSIG. Desktop Geographic Information System.
3
 *
4
 * Copyright (C) 2007-2013 gvSIG Association.
5
 *
6
 * This program is free software; you can redistribute it and/or modify it under
7
 * the terms of the GNU General Public License as published by the Free Software
8
 * Foundation; either version 2 of the License, or (at your option) any later
9
 * version.
10
 *
11
 * This program is distributed in the hope that it will be useful, but WITHOUT
12
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
13
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
14
 * details.
15
 *
16
 * You should have received a copy of the GNU General Public License along with
17
 * this program; if not, write to the Free Software Foundation, Inc., 51
18
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19
 *
20
 * For any additional information, do not hesitate to contact us at info AT
21
 * gvsig.com, or visit our website www.gvsig.com.
22
 */
23
package org.gvsig.tools.dataTypes.impl.coercion;
24

    
25
import java.math.BigDecimal;
26
import java.text.DecimalFormat;
27
import java.text.NumberFormat;
28
import java.text.ParsePosition;
29
import java.util.Date;
30
import java.util.Locale;
31
import org.apache.commons.lang3.StringUtils;
32
import org.gvsig.tools.dataTypes.AbstractCoercion;
33
import org.gvsig.tools.dataTypes.Coercion;
34

    
35
import org.gvsig.tools.dataTypes.CoercionException;
36
import org.gvsig.tools.dataTypes.DataTypeUtils;
37
import org.gvsig.tools.dataTypes.CoercionContext;
38
import org.gvsig.tools.dataTypes.CoercionContextLocale;
39
import org.gvsig.tools.dataTypes.CoercionContextDecimal;
40
import org.gvsig.tools.dataTypes.CoercionContextDecimalImpl;
41

    
42
@SuppressWarnings("UseSpecificCatch")
43
public class CoerceToDecimal extends AbstractCoercion {
44

    
45
  @Override
46
  public Object coerce(Object value) throws CoercionException {
47
    if (value == null || value instanceof BigDecimal) {
48
      return value;
49
    }
50
    return coerce(value, DataTypeUtils.coerceContextDefaultDecimal());
51
  }
52

    
53
  @Override
54
  public Object coerce(Object value, CoercionContext context) throws CoercionException {
55
    if (value == null ) {
56
      return value;
57
    }
58
    CoercionContextDecimal theContext;
59
    if (context instanceof CoercionContextDecimal) {
60
      theContext = (CoercionContextDecimal) context;
61
    } else {
62
      if (context instanceof CoercionContextLocale) {
63
        theContext = DataTypeUtils.coerceContextDecimal(((CoercionContextLocale) context).locale());
64
      } else {
65
        theContext = DataTypeUtils.coerceContextDefaultDecimal();
66
      }
67
    }
68
    BigDecimal num;
69
    try {
70
      if (value instanceof BigDecimal) {
71
        num = (BigDecimal) value;
72
        
73
      } else if (value instanceof Number) {
74
        num = new BigDecimal(((Number) value).doubleValue(), theContext.getMathContext());
75

    
76
      } else if (value instanceof Boolean) {
77
        num = new BigDecimal((boolean) value ? 1 : 0, theContext.getMathContext());
78
        
79
      } else if (value instanceof Date) {
80
        num = new BigDecimal(((Date) value).getTime(), theContext.getMathContext());
81

    
82
      } else {
83
        String s = value.toString().trim().toLowerCase();
84
        if (StringUtils.isBlank(s)) {
85
          return null;
86
        }
87
        if (s.startsWith("0x")) {
88
          num = new BigDecimal(Long.parseLong(s.substring(2), 16), theContext.getMathContext());
89

    
90
        } else {
91
          if (s.startsWith("+")) {
92
            s = s.substring(1);
93
          }
94
          ParsePosition p = new ParsePosition(0);
95
          DecimalFormat nf = (DecimalFormat) NumberFormat.getInstance(theContext.locale());
96
          nf.setParseBigDecimal(true);
97
          num = (BigDecimal) nf.parse(s, p);
98
          if (p.getErrorIndex() > 0 || p.getIndex() < s.length()) {
99
            throw new CoercionException("Can't coerce '" + s + "' to BigDecimal with locale " + theContext.locale().getLanguage() + "(error index " + p.getErrorIndex() + ", index " + p.getIndex() + ").");
100
          }
101
        }
102
      }
103
      if( theContext.hasScale() && num.scale()!=theContext.scale()) {
104
        // Ojo, que este set no es un set. Contruye un nuevo BigDecimal, no
105
        // modifica el existente.
106
        num = num.setScale(theContext.scale(), theContext.roundMode());
107
      }
108
      if( theContext.hasPrecision() && num.precision()>theContext.precision() ) {
109
        throw new ArithmeticException("Overflow");
110
      }
111
      return num;
112
    } catch (CoercionException e) {
113
      throw e;
114
    } catch (Exception e) {
115
      throw new CoercionException("Can't coerce '" + value.toString() + "' to BigDecimal with locale " + theContext.locale().getLanguage() + "'.", e);
116
    }
117
  }
118

    
119
  private static BigDecimal toBigDecimal(Object value, int precision, int scale) throws CoercionException {
120
      CoercionContextDecimalImpl context = new CoercionContextDecimalImpl(Locale.ENGLISH, precision, scale);
121
      Coercion c = new CoerceToDecimal();              
122
      BigDecimal x = (BigDecimal) c.coerce(value,context);
123
      return x;
124
  }
125
  
126
  public static void main(String[] args) throws CoercionException {
127
    BigDecimal n;
128

    
129
    n = toBigDecimal(1,6,3);
130
    System.out.println("BigDecimal(1,6,3): "+n+"("+n.precision()+","+n.scale()+")");
131

    
132
    n = toBigDecimal(10,6,3);
133
    System.out.println("BigDecimal(10,6,3): "+n+"("+n.precision()+","+n.scale()+")");
134

    
135
    n = toBigDecimal(12.345,6,3);
136
    System.out.println("BigDecimal(12.345,6,3): "+n+"("+n.precision()+","+n.scale()+")");
137

    
138
    n = toBigDecimal(-12.345,6,3);
139
    System.out.println("BigDecimal(-12.345,6,3): "+n+"("+n.precision()+","+n.scale()+")");
140

    
141
    n = toBigDecimal(12.3457,6,3);
142
    System.out.println("BigDecimal(12.3457,6,3): "+n+"("+n.precision()+","+n.scale()+")");
143

    
144
    n = toBigDecimal(120.3457,6,3);
145
    System.out.println("BigDecimal(120.3457,6,3): "+n+"("+n.precision()+","+n.scale()+")");
146
  }
147
}