001: /*
002: * $Id: BigDecimalType.java,v 1.16 2005/12/22 09:02:31 ahimanikya Exp $
003: * =======================================================================
004: * Copyright (c) 2002-2005 Axion Development Team. All rights reserved.
005: *
006: * Redistribution and use in source and binary forms, with or without
007: * modification, are permitted provided that the following conditions
008: * are met:
009: *
010: * 1. Redistributions of source code must retain the above
011: * copyright notice, this list of conditions and the following
012: * disclaimer.
013: *
014: * 2. Redistributions in binary form must reproduce the above copyright
015: * notice, this list of conditions and the following disclaimer in
016: * the documentation and/or other materials provided with the
017: * distribution.
018: *
019: * 3. The names "Tigris", "Axion", nor the names of its contributors may
020: * not be used to endorse or promote products derived from this
021: * software without specific prior written permission.
022: *
023: * 4. Products derived from this software may not be called "Axion", nor
024: * may "Tigris" or "Axion" appear in their names without specific prior
025: * written permission.
026: *
027: * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
028: * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
029: * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
030: * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
031: * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
032: * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
033: * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
034: * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
035: * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
036: * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
037: * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
038: * =======================================================================
039: */
040:
041: package org.axiondb.types;
042:
043: import java.io.DataInput;
044: import java.io.DataOutput;
045: import java.io.IOException;
046: import java.math.BigDecimal;
047: import java.math.BigInteger;
048: import java.util.Comparator;
049:
050: import org.axiondb.AxionException;
051: import org.axiondb.DataType;
052:
053: /**
054: * A {@link DataType}representing an number value.
055: *
056: * @version $Revision: 1.16 $ $Date: 2005/12/22 09:02:31 $
057: * @author Chuck Burdick
058: * @author Rodney Waldhoff
059: * @author Ahimanikya Satapathy
060: * @author Jonathan Giron
061: */
062: public class BigDecimalType extends BaseNumberDataType implements
063: DataType.ExactNumeric {
064: public static final int ROUNDING_RULE = BigDecimal.ROUND_HALF_UP;
065:
066: public static final int DEFAULT_PRECISION = 22;
067: public static final int DEFAULT_SCALE = 0;
068: public static final int MAX_PRECISION = 38;
069:
070: public BigDecimalType() {
071: this (DEFAULT_PRECISION, 0);
072: }
073:
074: public BigDecimalType(int scale) {
075: this (DEFAULT_PRECISION, scale);
076: }
077:
078: public BigDecimalType(int precision, int scale) {
079: _precision = precision;
080: _scale = scale;
081: }
082:
083: public BigDecimalType(BigDecimal result) {
084: _scale = result.scale();
085:
086: int valueLength = result.toString().length();
087: valueLength -= (_scale != 0) ? 1 : 0; // account for decimal point if present
088: valueLength -= (result.signum() < 0) ? 1 : 0; // account for sign if present
089:
090: int unscaledPrecision = result.unscaledValue().abs().toString()
091: .length();
092: if (unscaledPrecision == _scale) {
093: _precision = _scale;
094: } else {
095: _precision = Math.max(valueLength, unscaledPrecision);
096: }
097: }
098:
099: public int getColumnDisplaySize() {
100: // # significant digits + decimal point (if any) + sign
101: return _precision + ((_scale == 0) ? 0 : 1) + 1;
102: }
103:
104: public int getPrecision() {
105: return _precision;
106: }
107:
108: public int getJdbcType() {
109: return java.sql.Types.NUMERIC;
110: }
111:
112: public String getPreferredValueClassName() {
113: return "java.math.BigDecimal";
114: }
115:
116: public int getScale() {
117: return _scale;
118: }
119:
120: public void setPrecision(int newPrecision) {
121: _precision = newPrecision;
122: }
123:
124: public void setScale(int newScale) {
125: _scale = newScale;
126: }
127:
128: /**
129: * Returns <code>"BigDecimal"</code>
130: *
131: * @return <code>"BigDecimal"</code>
132: */
133: public String toString() {
134: StringBuffer buf = new StringBuffer(25);
135: buf.append("numeric").append("(").append(_precision)
136: .append(",").append(_scale).append(")");
137: return buf.toString();
138: }
139:
140: public boolean accepts(Object value) {
141: if (value instanceof BigDecimal) {
142: return true;
143: } else {
144: return super .accepts(value);
145: }
146: }
147:
148: public boolean requiresRounding(BigDecimal value) {
149: return _scale >= 0 && value.scale() != _scale;
150: }
151:
152: /**
153: * Returns a <tt>BigDecimal</tt> converted from the given <i>value </i>, or throws
154: * {@link IllegalArgumentException}if the given <i>value </i> isn't
155: * {@link #accepts acceptable}.
156: */
157: public Object convert(Object value) throws AxionException {
158: if (value == null) {
159: return value;
160: }
161:
162: BigDecimal toreturn = null;
163: if (value instanceof BigDecimal) {
164: toreturn = (BigDecimal) (value);
165: } else if (value instanceof BigInteger) {
166: toreturn = new BigDecimal((BigInteger) value);
167: } else if (value instanceof Double || value instanceof Float) {
168: try {
169: toreturn = new BigDecimal(String.valueOf(value));
170: } catch (NumberFormatException e) {
171: throw new AxionException(22003);
172: }
173: } else if (value instanceof Number) {
174: toreturn = BigDecimal.valueOf(((Number) value).longValue());
175: } else if (value instanceof String) {
176: try {
177: toreturn = new BigDecimal(value.toString().trim());
178: } catch (NumberFormatException e) {
179: throw new AxionException(22018);
180: }
181: } else {
182: toreturn = (BigDecimal) (super .convert(value));
183: }
184:
185: if (null != toreturn) {
186: try {
187: if (requiresRounding(toreturn)) {
188: toreturn = toreturn.setScale(_scale, ROUNDING_RULE);
189: }
190: assertValueNotOutOfRange(toreturn);
191: } catch (ArithmeticException e) {
192: throw new AxionException("BigDecimal " + toreturn
193: + " has scale " + toreturn.scale()
194: + ", can't convert to scale " + _scale + ": "
195: + e.getMessage());
196: }
197: }
198: return toreturn;
199: }
200:
201: /**
202: * @see #write
203: */
204: public Object read(DataInput in) throws IOException {
205: String str = in.readUTF();
206: if (NULL_BIGDEC.equals(str)) {
207: return null;
208: }
209: BigInteger value = new BigInteger(str, TOSTRING_RADIX);
210: int scale = in.readInt();
211: return new BigDecimal(value, scale);
212: }
213:
214: /** <code>false</code> */
215: public boolean supportsSuccessor() {
216: return true;
217: }
218:
219: public Object successor(Object value)
220: throws IllegalArgumentException {
221: double v = ((BigDecimal) value).doubleValue();
222:
223: return new BigDecimal(v + 1);
224: }
225:
226: public void write(Object value, DataOutput out) throws IOException {
227: try {
228: BigDecimal towrite = (BigDecimal) (convert(value));
229: if (null == towrite) {
230: out.writeUTF(NULL_BIGDEC);
231: } else {
232: out.writeUTF(towrite.unscaledValue().toString(
233: TOSTRING_RADIX));
234: out.writeInt(towrite.scale());
235: }
236: } catch (AxionException e) {
237: throw new IOException(e.getMessage());
238: }
239: }
240:
241: public DataType makeNewInstance() {
242: return makeNewInstance(DEFAULT_PRECISION, 0);
243: }
244:
245: public int compare(Object a, Object b) {
246: BigDecimal bda = null;
247: try {
248: bda = (BigDecimal) convert(a);
249: } catch (AxionException e) {
250: throw new ClassCastException("cannot convert "
251: + a.toString() + " to BigDecimal for comparison");
252: }
253:
254: BigDecimal bdb = null;
255: try {
256: bdb = (BigDecimal) convert(b);
257: } catch (AxionException e) {
258: throw new ClassCastException("cannot convert "
259: + b.toString() + " to BigDecimal for comparison");
260: }
261:
262: return bda.compareTo(bdb);
263: }
264:
265: public DataType.ExactNumeric makeNewInstance(int newPrecision,
266: int newScale) {
267: return new BigDecimalType(newPrecision, newScale);
268: }
269:
270: protected Comparator getComparator() {
271: return this ;
272: }
273:
274: private int getPrecision(BigDecimal value) {
275: return value.unscaledValue().abs().toString().length();
276: }
277:
278: private void assertValueNotOutOfRange(BigDecimal value)
279: throws AxionException {
280: int wholeNumberPrecision = Math.max(0, getPrecision(value)
281: - value.scale());
282: if ((wholeNumberPrecision != 0)
283: && wholeNumberPrecision > (_precision - _scale)) {
284: throw new AxionException(22003);
285: }
286: }
287:
288: private int _precision = DEFAULT_PRECISION;
289: private int _scale = DEFAULT_SCALE;
290:
291: private static final String NULL_BIGDEC = " ";
292:
293: private static final int TOSTRING_RADIX = Character.MAX_RADIX;
294:
295: private static final long serialVersionUID = -8555010408278020956L;
296: }
|