Example usage for java.math BigDecimal intValueExact

List of usage examples for java.math BigDecimal intValueExact

Introduction

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

Prototype

public int intValueExact() 

Source Link

Document

Converts this BigDecimal to an int , checking for lost information.

Usage

From source file:Main.java

public static void main(String[] args) {

    BigDecimal bg1 = new BigDecimal("40");
    BigDecimal bg2 = new BigDecimal("4E+1");

    // assign the exact int value of bg1 and bg2 to i1,i2 respectively
    int i1 = bg1.intValueExact();
    int i2 = bg2.intValueExact();

    // print i1,i2 values
    System.out.println(i1);/*w  w  w . j  a  va 2 s. c o  m*/
    System.out.println(i2);
}

From source file:org.eel.kitchen.jsonschema.GsonProvider.java

private static JsonNode toNumberNode(final BigDecimal decimal) {
    try {// w ww .  j  a va2  s  .c  o  m
        return factory.numberNode(decimal.intValueExact());
    } catch (ArithmeticException ignored) {
        try {
            return factory.numberNode(decimal.longValueExact());
        } catch (ArithmeticException ignoredAgain) {
            return decimal.scale() == 0 ? factory.numberNode(decimal.toBigInteger())
                    : factory.numberNode(decimal);
        }
    }
}

From source file:org.kjots.json.content.io.simple.SimpleJsonReader.java

/**
 * Create the content handler.//from   w w w.ja va 2  s.  co  m
 *
 * @return The content handler.
 */
private ContentHandler createContentHandler() {
    return new ContentHandler() {
        @Override
        public void startJSON() {
            SimpleJsonReader.this.jsonContentHandler.startJson();
        }

        @Override
        public void endJSON() {
            SimpleJsonReader.this.jsonContentHandler.endJson();
        }

        @Override
        public boolean startObject() {
            SimpleJsonReader.this.jsonContentHandler.startObject();

            return true;
        }

        @Override
        public boolean endObject() {
            SimpleJsonReader.this.jsonContentHandler.endObject();

            return true;
        }

        @Override
        public boolean startObjectEntry(String key) {
            SimpleJsonReader.this.jsonContentHandler.memberName(key);

            return true;
        }

        @Override
        public boolean endObjectEntry() {
            return true;
        }

        @Override
        public boolean startArray() {
            SimpleJsonReader.this.jsonContentHandler.startArray();

            return true;
        }

        @Override
        public boolean endArray() {
            SimpleJsonReader.this.jsonContentHandler.endArray();

            return true;
        }

        @Override
        public boolean primitive(Object value) {
            if (value instanceof BigDecimal) {
                BigDecimal numericValue = (BigDecimal) value;

                // Attempt to coerce the value into an integer
                try {
                    value = Integer.valueOf(numericValue.intValueExact());
                } catch (ArithmeticException ae1) {
                    // Attempt to coerce the value into a long
                    try {
                        value = Long.valueOf(numericValue.longValueExact());
                    } catch (ArithmeticException ae2) {
                        // Attempt to coerce the value into a BigInteger
                        try {
                            value = numericValue.toBigIntegerExact();
                        } catch (ArithmeticException ae3) {
                            // Ignore this exception - value will remain a BigDecimal
                        }
                    }
                }
            }

            SimpleJsonReader.this.jsonContentHandler.primitive(value);

            return true;
        }
    };
}

From source file:org.ojai.json.impl.JsonStreamDocumentReader.java

@Override
public int getDecimalValueAsInt() {
    BigDecimal decimal = getDecimal();
    if (decimal != null) {
        return decimal.intValueExact();
    }/*from www  .  ja v a 2s. c o  m*/
    return 0;
}

From source file:org.openvpms.esci.adapter.map.invoice.InvoiceMapperImpl.java

/**
 * Returns the package size./* w w  w. ja  v  a2 s  . com*/
 *
 * @param line the invoice line
 * @param pkg  the expected package, or <tt>null</tt> if it is not known
 * @return the package size, or <tt>0</tt> if it is not known
 * @throws ESCIAdapterException if the package size is incorrectly specified
 */
private int getPackageSize(UBLInvoiceLine line, Package pkg) {
    int result;
    BigDecimal packageSize = line.getPackSizeNumeric();
    int expectedSize = (pkg != null) ? pkg.getPackageSize() : 0;
    int invoiceSize;
    try {
        invoiceSize = packageSize.intValueExact();
    } catch (ArithmeticException exception) {
        ErrorContext context = new ErrorContext(line, "PackSizeNumeric");
        String intValue = Integer.toString(packageSize.intValue());
        throw new ESCIAdapterException(ESCIAdapterMessages.ublInvalidValue(context.getPath(), context.getType(),
                context.getID(), intValue, packageSize.toString()));
    }
    if (expectedSize != 0) {
        if (invoiceSize != 0 && invoiceSize != expectedSize) {
            log.warn("Different package size received for invoice. Expected package size=" + expectedSize
                    + ", invoiced package size=" + invoiceSize); // TODO - log context
        }
        result = expectedSize;
    } else {
        result = invoiceSize;
    }
    return result;
}

From source file:org.zuinnote.hadoop.office.format.common.converter.ExcelConverterSimpleSpreadSheetCellDAO.java

/**
 * Translate a data row according to the currently defined schema.
 * //ww  w.j a v a2  s  . c  om
 * @param dataRow cells containing data
 * @return an array of objects of primitive datatypes (boolean, int, byte, etc.)
 *         containing the data of datarow, null if dataRow does not fit into
 *         schema. Note: single elements can be null depending on the original
 *         Excel
 * 
 */
public Object[] getDataAccordingToSchema(SpreadSheetCellDAO[] dataRow) {
    if (dataRow == null) {
        return new Object[this.schemaRow.size()];
    }
    if (dataRow.length > this.schemaRow.size()) {
        LOG.warn("Data row is larger than schema. Will return String for everything that is not specified. ");
    }
    List<Object> returnList = new ArrayList<>();
    for (int i = 0; i < this.schemaRow.size(); i++) { // fill up with schema rows
        returnList.add(null);
    }
    for (int i = 0; i < dataRow.length; i++) {
        SpreadSheetCellDAO currentCell = dataRow[i];

        if (currentCell != null) {
            // determine real position
            int j = new CellAddress(currentCell.getAddress()).getColumn();
            if (j >= returnList.size()) {
                // fill up
                for (int x = returnList.size(); x <= j; x++) {
                    returnList.add(null);
                }
            }
            GenericDataType applyDataType = null;
            if (j >= this.schemaRow.size()) {
                LOG.warn("No further schema row for column defined: " + String.valueOf(j)
                        + ". Will assume String.");
            } else {
                applyDataType = this.schemaRow.get(j);
            }
            if (applyDataType == null) {
                returnList.set(j, currentCell.getFormattedValue());
            } else if (applyDataType instanceof GenericStringDataType) {
                returnList.set(j, currentCell.getFormattedValue());
            } else if (applyDataType instanceof GenericBooleanDataType) {
                if (!"".equals(currentCell.getFormattedValue())) {
                    if (currentCell.getFormattedValue().equalsIgnoreCase("true")
                            || currentCell.getFormattedValue().equalsIgnoreCase("false")) {
                        returnList.set(j, Boolean.valueOf(currentCell.getFormattedValue()));
                    }
                }
            } else if (applyDataType instanceof GenericTimestampDataType) {
                if (!"".equals(currentCell.getFormattedValue())) {
                    boolean timestampFound = false;
                    if (this.dateTimeFormat != null) { // check first dateTimeFormat
                        Date theDate = this.dateTimeFormat.parse(currentCell.getFormattedValue(),
                                new ParsePosition(0));
                        if (theDate != null) {
                            returnList.set(j, new java.sql.Timestamp(theDate.getTime()));
                            timestampFound = true;
                        } else {
                            returnList.set(j, null);
                            LOG.warn(
                                    "Could not identify timestamp using Date.parse using provided dateTime format. Trying Timestamp.valueOf. Original value: "
                                            + currentCell.getFormattedValue());
                        }
                    }
                    if (!timestampFound) {
                        try {
                            returnList.set(j, java.sql.Timestamp.valueOf(currentCell.getFormattedValue()));
                            timestampFound = true;
                        } catch (IllegalArgumentException e) {
                            returnList.set(j, null);
                            LOG.warn(
                                    "Could not identify timestamp using TimeStamp.valueOf. Trying last resort Date parsing. Original value: "
                                            + currentCell.getFormattedValue());
                        }
                    }
                    if (!timestampFound) {
                        Date theDate = this.dateFormat.parse(currentCell.getFormattedValue(),
                                new ParsePosition(0));
                        if (theDate != null) {
                            returnList.set(j, new java.sql.Timestamp(theDate.getTime()));

                        } else {
                            returnList.set(j, null);
                            LOG.warn(
                                    "Could not identify timestamp using Date.parse using provided date format");
                        }
                    }

                }
            } else if (applyDataType instanceof GenericDateDataType) {
                if (!"".equals(currentCell.getFormattedValue())) {
                    Date theDate = this.dateFormat.parse(currentCell.getFormattedValue(), new ParsePosition(0));

                    if (theDate != null) {
                        returnList.set(j, theDate);

                    } else {
                        returnList.set(j, null);
                    }
                }
            }

            else if (applyDataType instanceof GenericNumericDataType) {
                if (!"".equals(currentCell.getFormattedValue())) {
                    BigDecimal bd = null;
                    try {
                        if (!"".equals(currentCell.getFormattedValue())) {
                            // check scientific notation
                            if (currentCell.getFormattedValue().toUpperCase().contains("E")) { // parse scientific notation
                                // remove any characters that could cause issues
                                String sanitizedCellContent = currentCell.getFormattedValue().replace(",", ".");
                                bd = new BigDecimal(sanitizedCellContent);
                            } else {
                                bd = (BigDecimal) this.decimalFormat.parse(currentCell.getFormattedValue());
                            }
                        }
                    } catch (ParseException p) {
                        LOG.warn(
                                "Could not parse decimal in spreadsheet cell, although type was detected as decimal");
                    }
                    if (bd != null) {
                        BigDecimal bdv = bd.stripTrailingZeros();
                        if (applyDataType instanceof GenericByteDataType) {
                            returnList.set(j, (byte) bdv.byteValueExact());
                        } else if (applyDataType instanceof GenericShortDataType) {
                            returnList.set(j, (short) bdv.shortValueExact());
                        } else if (applyDataType instanceof GenericIntegerDataType) {
                            returnList.set(j, (int) bdv.intValueExact());
                        } else if (applyDataType instanceof GenericLongDataType) {
                            returnList.set(j, (long) bdv.longValueExact());
                        } else if (applyDataType instanceof GenericDoubleDataType) {
                            returnList.set(j, (double) bdv.doubleValue());
                        } else if (applyDataType instanceof GenericFloatDataType) {
                            returnList.set(j, (float) bdv.floatValue());
                        } else if (applyDataType instanceof GenericBigDecimalDataType) {
                            returnList.set(j, bd);
                        } else {
                            returnList.set(j, null);
                        }
                    }
                }
            } else {
                returnList.set(j, null);
                LOG.warn("Could not convert object in spreadsheet cellrow. Did you add a new datatype?");
            }
        }
    }
    Object[] result = new Object[returnList.size()];
    returnList.toArray(result);
    return result;
}

From source file:org.zuinnote.hadoop.office.format.common.converter.ExcelConverterSimpleSpreadSheetCellDAO.java

/***
 * This provides another sample to infer schema in form of simple datatypes
 * (e.g. boolean, byte etc.). You might add as many sample as necessary to get a
 * precise schema./*from   w ww .  jav a 2 s. c  o m*/
 * 
 * @param dataRow
 */
public void updateSpreadSheetCellRowToInferSchemaInformation(SpreadSheetCellDAO[] dataRow) {
    // check size of cell based on address
    // if necessary add more to schemaRow

    for (SpreadSheetCellDAO currentSpreadSheetCellDAO : dataRow) {
        boolean dataTypeFound = false;
        if (currentSpreadSheetCellDAO != null) {
            // add potential column to list
            int j = new CellAddress(currentSpreadSheetCellDAO.getAddress()).getColumn();
            if (j >= this.schemaRow.size()) {
                // fill up
                for (int x = this.schemaRow.size(); x <= j; x++) {
                    this.schemaRow.add(null);
                }
            }
            // check if boolean data type
            if ((currentSpreadSheetCellDAO.getFormattedValue() != null)
                    && (!"".equals(currentSpreadSheetCellDAO.getFormattedValue()))) { // skip null value
                String currentCellValue = currentSpreadSheetCellDAO.getFormattedValue();
                // check if boolean
                if (("TRUE".equals(currentCellValue)) || ("FALSE".equals(currentCellValue))) {
                    dataTypeFound = true;
                    if (this.schemaRow.get(j) != null) { // check if previous assumption was boolean

                        if (!(this.schemaRow.get(j) instanceof GenericBooleanDataType)) {
                            // if not then the type needs to be set to string
                            this.schemaRow.set(j, new GenericStringDataType());
                        }
                        // if yes then nothing todo (already boolean)
                    } else { // we face this the first time
                        this.schemaRow.set(j, new GenericBooleanDataType());
                    }
                }
                // check if timestamp using provided format
                if (!dataTypeFound) {
                    if (this.dateTimeFormat != null) { // only if a format is specified
                        Date theDate = this.dateTimeFormat.parse(currentCellValue, new ParsePosition(0));
                        if (theDate != null) { // we found indeed a date time

                            dataTypeFound = true;
                            if (this.schemaRow.get(j) != null) { // check if previous assumption was date

                                if (!(this.schemaRow.get(j) instanceof GenericTimestampDataType)) {
                                    // if not then the type needs to be set to string
                                    this.schemaRow.set(j, new GenericStringDataType());
                                }
                            } else { // we face this the first time
                                this.schemaRow.set(j, new GenericTimestampDataType());

                            }

                        }
                    }
                }
                // check for timestamp using java.sql.Timestamp
                if (!dataTypeFound) {

                    try {
                        java.sql.Timestamp ts = java.sql.Timestamp.valueOf(currentCellValue);
                        dataTypeFound = true;
                        this.schemaRow.set(j, new GenericTimestampDataType());
                    } catch (IllegalArgumentException e) {
                        LOG.warn(
                                "Could not identify timestamp using TimeStamp.valueOf. Trying last resort Date parsing....");
                    }
                }
                // check if date data type
                if (!dataTypeFound) {

                    Date theDate = this.dateFormat.parse(currentCellValue, new ParsePosition(0));
                    if (theDate != null) { // we have indeed a date

                        dataTypeFound = true;
                        if (this.schemaRow.get(j) != null) { // check if previous assumption was date

                            if (!(this.schemaRow.get(j) instanceof GenericDateDataType)) {
                                // if not then the type needs to be set to string
                                this.schemaRow.set(j, new GenericStringDataType());
                            }

                        } else { // we face this the first time
                            this.schemaRow.set(j, new GenericDateDataType());
                            // check if it has a time component

                        }
                    }
                }
                // check if BigDecimal

                BigDecimal bd = (BigDecimal) this.decimalFormat.parse(currentCellValue, new ParsePosition(0));
                if ((!dataTypeFound) && (bd != null)) {
                    BigDecimal bdv = bd.stripTrailingZeros();

                    dataTypeFound = true;

                    if (this.schemaRow.get(j) != null) { // check if previous assumption was a number

                        // check if we need to upgrade to decimal
                        if ((bdv.scale() > 0) && (this.schemaRow.get(j) instanceof GenericNumericDataType)) {
                            // upgrade to decimal, if necessary
                            if (!(this.schemaRow.get(j) instanceof GenericBigDecimalDataType)) {
                                this.schemaRow.set(j,
                                        new GenericBigDecimalDataType(bdv.precision(), bdv.scale()));
                            } else {
                                if ((bdv.scale() > ((GenericBigDecimalDataType) this.schemaRow.get(j))
                                        .getScale())
                                        && (bdv.precision() > ((GenericBigDecimalDataType) this.schemaRow
                                                .get(j)).getPrecision())) {
                                    this.schemaRow.set(j,
                                            new GenericBigDecimalDataType(bdv.precision(), bdv.scale()));
                                } else if (bdv.scale() > ((GenericBigDecimalDataType) this.schemaRow.get(j))
                                        .getScale()) {
                                    // upgrade scale
                                    GenericBigDecimalDataType gbd = ((GenericBigDecimalDataType) this.schemaRow
                                            .get(j));
                                    gbd.setScale(bdv.scale());
                                    this.schemaRow.set(j, gbd);
                                } else if (bdv.precision() > ((GenericBigDecimalDataType) this.schemaRow.get(j))
                                        .getPrecision()) {
                                    // upgrade precision
                                    // new precision is needed to extend to max scale
                                    GenericBigDecimalDataType gbd = ((GenericBigDecimalDataType) this.schemaRow
                                            .get(j));
                                    int newpre = bdv.precision() + (gbd.getScale() - bdv.scale());
                                    gbd.setPrecision(newpre);
                                    this.schemaRow.set(j, gbd);
                                }
                            }
                        } else { // check if we need to upgrade one of the integer types
                            // if current is byte
                            boolean isByte = false;
                            boolean isShort = false;
                            boolean isInt = false;
                            boolean isLong = true;
                            try {
                                bdv.longValueExact();
                                isLong = true;
                                bdv.intValueExact();
                                isInt = true;
                                bdv.shortValueExact();
                                isShort = true;
                                bdv.byteValueExact();
                                isByte = true;
                            } catch (Exception e) {
                                LOG.debug("Possible data types: Long: " + isLong + " Int: " + isInt + " Short: "
                                        + isShort + " Byte: " + isByte);
                            }
                            // if it was Numeric before we can ignore testing the byte case, here just for
                            // completeness
                            if ((isByte) && ((this.schemaRow.get(j) instanceof GenericByteDataType)
                                    || (this.schemaRow.get(j) instanceof GenericShortDataType)
                                    || (this.schemaRow.get(j) instanceof GenericIntegerDataType)
                                    || (this.schemaRow.get(j) instanceof GenericLongDataType))) {
                                // if it was Byte before we can ignore testing the byte case, here just for
                                // completeness
                            } else if ((isShort) && ((this.schemaRow.get(j) instanceof GenericByteDataType))) {
                                // upgrade to short
                                this.schemaRow.set(j, new GenericShortDataType());
                            } else if ((isInt) && ((this.schemaRow.get(j) instanceof GenericShortDataType)
                                    || (this.schemaRow.get(j) instanceof GenericByteDataType))) {
                                // upgrade to integer
                                this.schemaRow.set(j, new GenericIntegerDataType());
                            } else if ((!isByte) && (!isShort) && (!isInt)
                                    && !((this.schemaRow.get(j) instanceof GenericLongDataType))) {
                                // upgrade to long
                                this.schemaRow.set(j, new GenericLongDataType());
                            }

                        }

                    } else {
                        // we face it for the first time
                        // determine value type
                        if (bdv.scale() > 0) {
                            this.schemaRow.set(j, new GenericBigDecimalDataType(bdv.precision(), bdv.scale()));
                        } else {
                            boolean isByte = false;
                            boolean isShort = false;
                            boolean isInt = false;
                            boolean isLong = true;
                            try {
                                bdv.longValueExact();
                                isLong = true;
                                bdv.intValueExact();
                                isInt = true;
                                bdv.shortValueExact();
                                isShort = true;
                                bdv.byteValueExact();
                                isByte = true;
                            } catch (Exception e) {
                                LOG.debug("Possible data types: Long: " + isLong + " Int: " + isInt + " Short: "
                                        + isShort + " Byte: " + isByte);
                            }
                            if (isByte) {
                                this.schemaRow.set(j, new GenericByteDataType());
                            } else if (isShort) {
                                this.schemaRow.set(j, new GenericShortDataType());
                            } else if (isInt) {
                                this.schemaRow.set(j, new GenericIntegerDataType());
                            } else if (isLong) {
                                this.schemaRow.set(j, new GenericLongDataType());
                            }
                        }
                    }
                }
                if (!dataTypeFound) {
                    // otherwise string
                    if (!(this.schemaRow.get(j) instanceof GenericStringDataType)) {
                        this.schemaRow.set(j, new GenericStringDataType());
                    }

                }

            } else {
                // ignore null values
            }
        }
    }
}