Example usage for java.math BigDecimal intValue

List of usage examples for java.math BigDecimal intValue

Introduction

In this page you can find the example usage for java.math BigDecimal intValue.

Prototype

@Override
public int intValue() 

Source Link

Document

Converts this BigDecimal to an int .

Usage

From source file:org.eclipse.smarthome.config.core.internal.ConfigMapper.java

private static Object objectConvert(Object value, Class<?> type) {
    Object result = value;/*from   ww  w.j  a v a  2  s . c  om*/
    // Handle the conversion case of BigDecimal to Float,Double,Long,Integer and the respective
    // primitive types
    String typeName = type.getSimpleName();
    if (value instanceof BigDecimal && !type.equals(BigDecimal.class)) {
        BigDecimal bdValue = (BigDecimal) value;
        if (type.equals(Float.class) || typeName.equals("float")) {
            result = bdValue.floatValue();
        } else if (type.equals(Double.class) || typeName.equals("double")) {
            result = bdValue.doubleValue();
        } else if (type.equals(Long.class) || typeName.equals("long")) {
            result = bdValue.longValue();
        } else if (type.equals(Integer.class) || typeName.equals("int")) {
            result = bdValue.intValue();
        }
    } else
    // Handle the conversion case of String to Float,Double,Long,Integer,BigDecimal,Boolean and the respective
    // primitive types
    if (value instanceof String && !type.equals(String.class)) {
        String bdValue = (String) value;
        if (type.equals(Float.class) || typeName.equals("float")) {
            result = Float.valueOf(bdValue);
        } else if (type.equals(Double.class) || typeName.equals("double")) {
            result = Double.valueOf(bdValue);
        } else if (type.equals(Long.class) || typeName.equals("long")) {
            result = Long.valueOf(bdValue);
        } else if (type.equals(BigDecimal.class)) {
            result = new BigDecimal(bdValue);
        } else if (type.equals(Integer.class) || typeName.equals("int")) {
            result = Integer.valueOf(bdValue);
        } else if (type.equals(Boolean.class) || typeName.equals("boolean")) {
            result = Boolean.valueOf(bdValue);
        } else if (type.isEnum()) {
            @SuppressWarnings({ "rawtypes", "unchecked" })
            final Class<? extends Enum> enumType = (Class<? extends Enum>) type;
            @SuppressWarnings({ "unchecked" })
            final Enum<?> enumvalue = Enum.valueOf(enumType, value.toString());
            result = enumvalue;
        } else if (Collection.class.isAssignableFrom(type)) {
            result = Collections.singletonList(value);
        }
    }
    return result;
}

From source file:be.dataminded.nifi.plugins.util.JdbcCommon.java

public static long convertToAvroStream(final ResultSet rs, final OutputStream outStream, String recordName,
        ResultSetRowCallback callback, final int maxRows, boolean convertNames)
        throws SQLException, IOException {
    final Schema schema = createSchema(rs, recordName, convertNames);
    final GenericRecord rec = new GenericData.Record(schema);

    final DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<>(schema);
    try (final DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<>(datumWriter)) {
        dataFileWriter.create(schema, outStream);

        final ResultSetMetaData meta = rs.getMetaData();
        final int nrOfColumns = meta.getColumnCount();
        long nrOfRows = 0;
        while (rs.next()) {
            if (callback != null) {
                callback.processRow(rs);
            }/*www  .  j  a v a 2s . co m*/
            for (int i = 1; i <= nrOfColumns; i++) {
                final int javaSqlType = meta.getColumnType(i);

                // Need to handle CLOB and BLOB before getObject() is called, due to ResultSet's maximum portability statement
                if (javaSqlType == CLOB) {
                    Clob clob = rs.getClob(i);
                    if (clob != null) {
                        long numChars = clob.length();
                        char[] buffer = new char[(int) numChars];
                        InputStream is = clob.getAsciiStream();
                        int index = 0;
                        int c = is.read();
                        while (c > 0) {
                            buffer[index++] = (char) c;
                            c = is.read();
                        }
                        rec.put(i - 1, new String(buffer));
                        clob.free();
                    } else {
                        rec.put(i - 1, null);
                    }
                    continue;
                }

                if (javaSqlType == BLOB) {
                    Blob blob = rs.getBlob(i);
                    if (blob != null) {
                        long numChars = blob.length();
                        byte[] buffer = new byte[(int) numChars];
                        InputStream is = blob.getBinaryStream();
                        int index = 0;
                        int c = is.read();
                        while (c > 0) {
                            buffer[index++] = (byte) c;
                            c = is.read();
                        }
                        ByteBuffer bb = ByteBuffer.wrap(buffer);
                        rec.put(i - 1, bb);
                        blob.free();
                    } else {
                        rec.put(i - 1, null);
                    }
                    continue;
                }

                final Object value = rs.getObject(i);

                if (value == null) {
                    rec.put(i - 1, null);

                } else if (javaSqlType == BINARY || javaSqlType == VARBINARY || javaSqlType == LONGVARBINARY
                        || javaSqlType == ARRAY) {
                    // bytes requires little bit different handling
                    byte[] bytes = rs.getBytes(i);
                    ByteBuffer bb = ByteBuffer.wrap(bytes);
                    rec.put(i - 1, bb);

                } else if (value instanceof Byte) {
                    // tinyint(1) type is returned by JDBC driver as java.sql.Types.TINYINT
                    // But value is returned by JDBC as java.lang.Byte
                    // (at least H2 JDBC works this way)
                    // direct put to avro record results:
                    // org.apache.avro.AvroRuntimeException: Unknown datum type java.lang.Byte
                    rec.put(i - 1, ((Byte) value).intValue());
                } else if (value instanceof Short) {
                    //MS SQL returns TINYINT as a Java Short, which Avro doesn't understand.
                    rec.put(i - 1, ((Short) value).intValue());
                } else if (value instanceof BigDecimal) {
                    // Avro can't handle BigDecimal as a number - it will throw an AvroRuntimeException such as: "Unknown datum type: java.math.BigDecimal: 38"
                    try {
                        int scale = meta.getScale(i);
                        BigDecimal bigDecimal = ((BigDecimal) value);
                        if (scale == 0) {
                            if (meta.getPrecision(i) < 10) {
                                rec.put(i - 1, bigDecimal.intValue());
                            } else {
                                rec.put(i - 1, bigDecimal.longValue());
                            }
                        } else {
                            rec.put(i - 1, bigDecimal.doubleValue());
                        }
                    } catch (Exception e) {
                        rec.put(i - 1, value.toString());
                    }
                } else if (value instanceof BigInteger) {
                    // Check the precision of the BIGINT. Some databases allow arbitrary precision (> 19), but Avro won't handle that.
                    // It the SQL type is BIGINT and the precision is between 0 and 19 (inclusive); if so, the BigInteger is likely a
                    // long (and the schema says it will be), so try to get its value as a long.
                    // Otherwise, Avro can't handle BigInteger as a number - it will throw an AvroRuntimeException
                    // such as: "Unknown datum type: java.math.BigInteger: 38". In this case the schema is expecting a string.
                    if (javaSqlType == BIGINT) {
                        int precision = meta.getPrecision(i);
                        if (precision < 0 || precision > MAX_DIGITS_IN_BIGINT) {
                            rec.put(i - 1, value.toString());
                        } else {
                            try {
                                rec.put(i - 1, ((BigInteger) value).longValueExact());
                            } catch (ArithmeticException ae) {
                                // Since the value won't fit in a long, convert it to a string
                                rec.put(i - 1, value.toString());
                            }
                        }
                    } else {
                        rec.put(i - 1, value.toString());
                    }

                } else if (value instanceof Number || value instanceof Boolean) {
                    if (javaSqlType == BIGINT) {
                        int precision = meta.getPrecision(i);
                        if (precision < 0 || precision > MAX_DIGITS_IN_BIGINT) {
                            rec.put(i - 1, value.toString());
                        } else {
                            rec.put(i - 1, value);
                        }
                    } else {
                        rec.put(i - 1, value);
                    }

                } else {
                    // The different types that we support are numbers (int, long, double, float),
                    // as well as boolean values and Strings. Since Avro doesn't provide
                    // timestamp types, we want to convert those to Strings. So we will cast anything other
                    // than numbers or booleans to strings by using the toString() method.
                    rec.put(i - 1, value.toString());
                }
            }
            dataFileWriter.append(rec);
            nrOfRows += 1;

            if (maxRows > 0 && nrOfRows == maxRows)
                break;
        }

        return nrOfRows;
    }
}

From source file:com.prowidesoftware.swift.utils.SwiftFormatUtils.java

/**
 * Return the number of decimals for the given number, which can be <code>null</code>, in which case this method returns zero.
 * /*from ww w. j  a v  a2 s.c o m*/
 * @return the number of decimal in the number or zero if there are none or the amount is <code>null</code>
 * @since 7.8
 */
public static int decimalsInAmount(final BigDecimal amount) {
    if (amount != null) {
        BigDecimal d = new BigDecimal(amount.toString());
        BigDecimal result = d.subtract(d.setScale(0, RoundingMode.FLOOR)).movePointRight(d.scale());
        if (result.intValue() != 0) {
            return result.toString().length();
        }
    }
    return 0;
}

From source file:com.github.jessemull.microflex.util.IntegerUtil.java

/**
 * Safely converts a number to an integer. Loss of precision may occur. Throws
 * an arithmetic exception upon overflow.
 * @param    Object    number to parse/*  www.j ava 2  s  . c o  m*/
 * @return             parsed number
 * @throws   ArithmeticException    on overflow
 */
public static int toInteger(Object obj) {

    /* Switch on class and convert to an int */

    String type = obj.getClass().getSimpleName();
    int parsed;

    switch (type) {

    case "Byte":
        Byte by = (Byte) obj;
        parsed = by.intValue();
        break;

    case "Short":
        Short sh = (Short) obj;
        parsed = sh.intValue();
        break;

    case "Integer":
        Integer in = (Integer) obj;
        parsed = in.intValue();
        break;

    case "Long":
        Long lo = (Long) obj;
        if (!OverFlowUtil.intOverflow(lo)) {
            throw new ArithmeticException("Overflow casting " + obj + " to an int.");
        }
        parsed = lo.intValue();
        break;

    case "Float":
        Float fl = (Float) obj;
        if (!OverFlowUtil.intOverflow(fl)) {
            throw new ArithmeticException("Overflow casting " + obj + " to an int.");
        }
        parsed = fl.intValue();
        break;

    case "BigInteger":
        BigInteger bi = (BigInteger) obj;
        if (!OverFlowUtil.intOverflow(bi)) {
            throw new ArithmeticException("Overflow casting " + obj + " to an int.");
        }
        parsed = bi.intValue();
        break;

    case "BigDecimal":
        BigDecimal bd = (BigDecimal) obj;
        if (!OverFlowUtil.intOverflow(bd)) {
            throw new ArithmeticException("Overflow casting " + obj + " to an int.");
        }
        parsed = bd.intValue();
        break;

    case "Double":
        Double db = (Double) obj;
        if (!OverFlowUtil.intOverflow(db)) {
            throw new ArithmeticException("Overflow casting " + obj + " to an int.");
        }
        parsed = db.intValue();
        break;

    default:
        throw new IllegalArgumentException(
                "Invalid type: " + type + "\nData values " + "must extend the abstract Number class.");

    }

    return parsed;
}

From source file:com.github.jessemull.microflex.util.IntegerUtil.java

/**
 * Safely converts a number to an integer. Loss of precision may occur. Throws
 * an arithmetic exception upon overflow.
 * @param    Number    number to parse/*from w  w w  . jav a2 s  .  c o  m*/
 * @return             parsed number
 * @throws   ArithmeticException    on overflow
 */
public static int toInteger(Number number) {

    /* Switch on class and convert to an int */

    String type = number.getClass().getSimpleName();
    int parsed;

    switch (type) {

    case "Byte":
        Byte by = (Byte) number;
        parsed = by.intValue();
        break;

    case "Short":
        Short sh = (Short) number;
        parsed = sh.intValue();
        break;

    case "Integer":
        Integer in = (Integer) number;
        parsed = in.intValue();
        break;

    case "Long":
        Long lo = (Long) number;
        if (!OverFlowUtil.intOverflow(lo)) {
            throw new ArithmeticException("Overflow casting " + number + " to an int.");
        }
        parsed = lo.intValue();
        break;

    case "Float":
        Float fl = (Float) number;
        if (!OverFlowUtil.intOverflow(fl)) {
            throw new ArithmeticException("Overflow casting " + number + " to an int.");
        }
        parsed = fl.intValue();
        break;

    case "BigInteger":
        BigInteger bi = (BigInteger) number;
        if (!OverFlowUtil.intOverflow(bi)) {
            throw new ArithmeticException("Overflow casting " + number + " to an int.");
        }
        parsed = bi.intValue();
        break;

    case "BigDecimal":
        BigDecimal bd = (BigDecimal) number;
        if (!OverFlowUtil.intOverflow(bd)) {
            throw new ArithmeticException("Overflow casting " + number + " to an int.");
        }
        parsed = bd.intValue();
        break;

    case "Double":
        Double db = (Double) number;
        if (!OverFlowUtil.intOverflow(db)) {
            throw new ArithmeticException("Overflow casting " + number + " to an int.");
        }
        parsed = db.intValue();
        break;

    default:
        throw new IllegalArgumentException(
                "Invalid type: " + type + "\nData values " + "must extend the abstract Number class.");

    }

    return parsed;
}

From source file:com.moneychanger.core.helper.bitcoin.BitcoinClient.java

protected static double roundToTwoDecimals(double amount) {
    BigDecimal amountTimes100 = new BigDecimal(amount * 100.0D + 0.5D);
    BigDecimal roundedAmountTimes100 = new BigDecimal(amountTimes100.intValue());
    BigDecimal roundedAmount = roundedAmountTimes100.divide(new BigDecimal(100.0D));

    return roundedAmount.doubleValue();
}

From source file:ru.paradoxs.bitcoin.client.BitcoinClient.java

/**
 * Rounds a double to the nearest two decimals, rounding UP.
 * Not proud of this code, but it works.
 */// w w  w . j av  a 2  s .  c  o m
protected static BigDecimal roundToTwoDecimals(BigDecimal amount) {
    BigDecimal amountTimes100 = amount.multiply(new BigDecimal(100)).add(new BigDecimal("0.5"));
    BigDecimal roundedAmountTimes100 = new BigDecimal(amountTimes100.intValue());
    BigDecimal roundedAmount = roundedAmountTimes100.divide(new BigDecimal(100.0));

    return roundedAmount;
}

From source file:eionet.cr.util.Util.java

/**
 * Algorithm calculates the estimated number of hashes.
 *
 * @param minHash//  w ww.  ja  v  a2  s  .  c  o  m
 * @param maxHash
 * @return
 */
public static int calculateHashesCount(long minHash, long maxHash) {

    BigDecimal minValue = new BigDecimal(Long.MIN_VALUE);
    BigDecimal maxValue = new BigDecimal(Long.MAX_VALUE);
    BigDecimal lowKey = new BigDecimal(minHash);
    BigDecimal highKey = new BigDecimal(maxHash);
    BigDecimal distance = maxValue.subtract(highKey).add(lowKey).subtract(minValue);
    BigDecimal hitCount = new BigDecimal(2).pow(64).divide(distance, 0, BigDecimal.ROUND_HALF_UP);

    return hitCount.intValue();
}

From source file:org.bitcoin.client.BitcoinClient.java

/**
 * Rounds a double to the nearest dwo decimals, rounding UP.
 * Not proud of this code, but it works.
 *//*w  w  w . j ava2 s .  com*/
protected static double roundToTwoDecimals(double amount) {
    BigDecimal amountTimes100 = new BigDecimal(amount * 100 + 0.5);
    BigDecimal roundedAmountTimes100 = new BigDecimal(amountTimes100.intValue());
    BigDecimal roundedAmount = roundedAmountTimes100.divide(new BigDecimal(100.0));

    return roundedAmount.doubleValue();
}

From source file:org.apache.tajo.master.Repartitioner.java

public static QueryUnit[] createRangePartitionedTasks(SubQuery subQuery, SubQuery childSubQuery, int maxNum)
        throws InternalException {
    ExecutionBlock execBlock = subQuery.getBlock();
    TableStat stat = childSubQuery.getTableStat();
    if (stat.getNumRows() == 0) {
        return new QueryUnit[0];
    }/*from   www .jav  a2  s. co m*/

    ScanNode scan = execBlock.getScanNodes()[0];
    Path tablePath;
    tablePath = subQuery.getContext().getStorageManager().getTablePath(scan.getTableId());

    StoreTableNode store = (StoreTableNode) childSubQuery.getBlock().getPlan();
    SortNode sort = (SortNode) store.getSubNode();
    SortSpec[] sortSpecs = sort.getSortKeys();
    Schema sortSchema = PlannerUtil.sortSpecsToSchema(sort.getSortKeys());

    // calculate the number of maximum query ranges
    TupleRange mergedRange = TupleUtil.columnStatToRange(sort.getOutSchema(), sortSchema,
            stat.getColumnStats());
    RangePartitionAlgorithm partitioner = new UniformRangePartition(sortSchema, mergedRange);
    BigDecimal card = partitioner.getTotalCardinality();

    // if the number of the range cardinality is less than the desired number of tasks,
    // we set the the number of tasks to the number of range cardinality.
    int determinedTaskNum;
    if (card.compareTo(new BigDecimal(maxNum)) < 0) {
        LOG.info("The range cardinality (" + card + ") is less then the desired number of tasks (" + maxNum
                + ")");
        determinedTaskNum = card.intValue();
    } else {
        determinedTaskNum = maxNum;
    }

    LOG.info("Try to divide " + mergedRange + " into " + determinedTaskNum + " sub ranges (total units: "
            + determinedTaskNum + ")");
    TupleRange[] ranges = partitioner.partition(determinedTaskNum);

    Fragment dummyFragment = new Fragment(scan.getTableId(), tablePath,
            CatalogUtil.newTableMeta(scan.getInSchema(), StoreType.CSV), 0, 0, null);

    List<String> basicFetchURIs = new ArrayList<String>();

    SubQuery child = childSubQuery.getContext().getSubQuery(subQuery.getBlock().getChildBlock(scan).getId());
    for (QueryUnit qu : child.getQueryUnits()) {
        for (IntermediateEntry p : qu.getIntermediateData()) {
            String uri = createBasicFetchUri(p.getPullHost(), p.getPullPort(), childSubQuery.getId(), p.taskId,
                    p.attemptId);
            basicFetchURIs.add(uri);
        }
    }

    boolean ascendingFirstKey = sortSpecs[0].isAscending();
    SortedMap<TupleRange, Set<URI>> map;
    if (ascendingFirstKey) {
        map = new TreeMap<TupleRange, Set<URI>>();
    } else {
        map = new TreeMap<TupleRange, Set<URI>>(new TupleRange.DescendingTupleRangeComparator());
    }

    Set<URI> uris;
    try {
        for (int i = 0; i < ranges.length; i++) {
            uris = new HashSet<URI>();
            for (String uri : basicFetchURIs) {
                String rangeParam = TupleUtil.rangeToQuery(sortSchema, ranges[i], ascendingFirstKey,
                        ascendingFirstKey ? i == (ranges.length - 1) : i == 0);
                URI finalUri = URI.create(uri + "&" + rangeParam);
                uris.add(finalUri);
            }
            map.put(ranges[i], uris);
        }

    } catch (UnsupportedEncodingException e) {
        LOG.error(e);
    }

    QueryUnit[] tasks = createEmptyNonLeafTasks(subQuery, determinedTaskNum, dummyFragment);
    assignPartitionByRoundRobin(map, scan.getTableId(), tasks);
    return tasks;
}