Example usage for java.math BigDecimal valueOf

List of usage examples for java.math BigDecimal valueOf

Introduction

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

Prototype

public static BigDecimal valueOf(double val) 

Source Link

Document

Translates a double into a BigDecimal , using the double 's canonical string representation provided by the Double#toString(double) method.

Usage

From source file:com.dopecoin.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> requestExchangeRates(final URL url, float leafBtcConversion,
        final String userAgent, final String... fields) {
    final long start = System.currentTimeMillis();

    HttpURLConnection connection = null;
    Reader reader = null;//from   w  ww.j  a  v a2 s.com

    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.addRequestProperty("User-Agent", userAgent);
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024),
                    Constants.UTF_8);
            final StringBuilder content = new StringBuilder();
            Io.copy(reader, content);

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                if (!"timestamp".equals(currencyCode)) {
                    final JSONObject o = head.getJSONObject(currencyCode);

                    for (final String field : fields) {
                        final String rate = o.optString(field, null);

                        if (rate != null) {
                            try {
                                BigDecimal btcRate = new BigDecimal(GenericUtils.toNanoCoins(rate, 0));
                                BigInteger leafRate = btcRate.multiply(BigDecimal.valueOf(leafBtcConversion))
                                        .toBigInteger();

                                if (leafRate.signum() > 0) {
                                    rates.put(currencyCode,
                                            new ExchangeRate(currencyCode, leafRate, url.getHost()));
                                    break;
                                }
                            } catch (final ArithmeticException x) {
                                log.warn("problem fetching {} exchange rate from {}: {}",
                                        new Object[] { currencyCode, url, x.getMessage() });
                            }
                        }
                    }
                }
            }

            log.info("fetched exchange rates from {}, took {} ms", url, (System.currentTimeMillis() - start));

            return rates;
        } else {
            log.warn("http status {} when fetching {}", responseCode, url);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + url, x);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException x) {
                // swallow
            }
        }

        if (connection != null)
            connection.disconnect();
    }

    return null;
}

From source file:demo.config.PropertyConverter.java

/**
 * Convert the specified object into a BigDecimal.
 * /*from w ww.j  a  v  a2 s  . c  om*/
 * @param value
 *            the value to convert
 * @return the converted value
 * @throws ConversionException
 *             thrown if the value cannot be converted to a BigDecimal
 */
public static BigDecimal toBigDecimal(Object value) throws ConversionException {
    Number n = toNumber(value, BigDecimal.class);
    if (n instanceof BigDecimal) {
        return (BigDecimal) n;
    } else {
        return BigDecimal.valueOf(n.doubleValue());
    }
}

From source file:me.taylorkelly.mywarp.bukkit.BukkitSettings.java

/**
 * Creates a FeeBundle out of the given identifier and configuration-section.
 *
 * @param identifier the identifier// w  w w . j a  v a  2  s .c  o  m
 * @param values     the configuration-section that contains all values
 * @return a FeeBundle out of the given values
 */
private FeeBundle toFeeBundle(String identifier, ConfigurationSection values) {
    return new FeeBundle(identifier, BigDecimal.valueOf(values.getDouble("assets", 0)),
            BigDecimal.valueOf(values.getDouble("create", 0)),
            BigDecimal.valueOf(values.getDouble("createPrivate", 0)),
            BigDecimal.valueOf(values.getDouble("delete", 0)), BigDecimal.valueOf(values.getDouble("give", 0)),
            BigDecimal.valueOf(values.getDouble("help", 0)), BigDecimal.valueOf(values.getDouble("info", 0)),
            BigDecimal.valueOf(values.getDouble("invite", 0)), BigDecimal.valueOf(values.getDouble("list", 0)),
            BigDecimal.valueOf(values.getDouble("point", 0)),
            BigDecimal.valueOf(values.getDouble("private", 0)),
            BigDecimal.valueOf(values.getDouble("public", 0)),
            BigDecimal.valueOf(values.getDouble("uninvite", 0)),
            BigDecimal.valueOf(values.getDouble("update", 0)),
            BigDecimal.valueOf(values.getDouble("warpPlayer", 0)),
            BigDecimal.valueOf(values.getDouble("warpSignCreate", 0)),
            BigDecimal.valueOf(values.getDouble("warpSignUse", 0)),
            BigDecimal.valueOf(values.getDouble("warpTo", 0)),
            BigDecimal.valueOf(values.getDouble("welcome", 0)));
}

From source file:net.ceos.project.poi.annotated.core.CsvHandler.java

/**
 * Apply a BigDecimal value to the object.
 * //www .ja v a2 s .c o  m
 * @param o
 *            the object
 * @param field
 *            the field
 * @param values
 *            the array with the content at one line
 * @param idx
 *            the index of the field
 * @throws ConverterException
 *             the conversion exception type
 */
protected static void bigDecimalReader(final Object o, final Field field, final String[] values, final int idx)
        throws ConverterException {
    String dBdValue = values[idx];
    if (dBdValue != null) {
        try {
            field.set(o, BigDecimal.valueOf(Double.valueOf(dBdValue)));
        } catch (IllegalArgumentException | IllegalAccessException e) {
            throw new ConverterException(ExceptionMessage.CONVERTER_BIGDECIMAL.getMessage(), e);
        }
    }
}

From source file:pe.gob.mef.gescon.web.ui.EntidadMB.java

public void save(ActionEvent event) {
    try {/*from  w w w .  ja v a  2 s . c  o m*/
        if (CollectionUtils.isEmpty(this.getListaEntidad())) {
            this.setListaEntidad(Collections.EMPTY_LIST);
        }
        Entidad entidad = new Entidad();
        entidad.setVnombre(this.getNombre());
        entidad.setVcodigoentidad(this.getCodigo());
        entidad.setVdescripcion(this.getDescripcion());
        if (!errorValidation(entidad)) {
            LoginMB loginMB = (LoginMB) JSFUtils.getSessionAttribute("loginMB");
            User user = loginMB.getUser();
            EntidadService service = (EntidadService) ServiceFinder.findBean("EntidadService");
            entidad.setNentidadid(service.getNextPK());
            entidad.setVnombre(StringUtils.upperCase(this.getNombre().trim()));
            entidad.setVcodigoentidad(this.getCodigo());
            entidad.setVdescripcion(StringUtils.capitalize(this.getDescripcion().trim()));
            entidad.setNactivo(BigDecimal.ONE);
            entidad.setDfechacreacion(new Date());
            entidad.setVusuariocreacion(user.getVlogin());
            entidad.setVdepartamento(this.getDepartamento());
            entidad.setVprovincia(this.getProvincia());
            entidad.setVdistrito(this.getDistrito());
            entidad.setVdepartamento(this.getDepartamento());
            entidad.setNtipoid(BigDecimal.valueOf(Long.parseLong(this.getTipoentidad())));
            service.saveOrUpdate(entidad);
            this.setListaEntidad(service.getEntidades());
            this.cleanAttributes();
            RequestContext.getCurrentInstance().execute("PF('newDialog').hide();");
        }
    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.dm.estore.core.config.impl.InitDataLoaderImpl.java

private BigDecimal parseSafeDouble(final String value) {
    if (!StringUtils.isEmpty(value)) {
        try {/*from  w  w  w.  j  a  va  2 s . co  m*/
            return BigDecimal.valueOf(Double.parseDouble(value));
        } catch (Exception e) {
            // do nothing
        }
    }

    return BigDecimal.ZERO;
}

From source file:net.sourceforge.fenixedu.domain.residence.StudentsPerformanceReport.java

private void addInformation(final Spreadsheet spreadsheet, final Student student) {
    StudentCurricularPlan studentCurricularPlan = getStudentCurricularPlan(student, getExecutionSemester());

    final Row row = spreadsheet.addRow();
    row.setCell(student.getNumber());//  ww w . j av  a 2  s .co m
    row.setCell(student.getPerson().getName());
    row.setCell(studentCurricularPlan.getDegreeType().getFilteredName());
    row.setCell(studentCurricularPlan.getName());
    row.setCell(studentCurricularPlan.getRegistration().getCycleType(getExecutionSemester().getExecutionYear())
            .getDescription());
    row.setCell(getApprovedECTS(student).toPlainString());
    row.setCell(getEnrolledECTS(student).toPlainString());
    row.setCell(getApprovedGradeValuesSum(student));
    row.setCell(getNumberOfApprovedCourses(student));
    row.setCell(getA(student).toPlainString());
    row.setCell(getB(student).toPlainString());
    row.setCell(getA(student).add(getB(student)).multiply(BigDecimal.valueOf(100)).intValue());

}

From source file:es.juntadeandalucia.panelGestion.negocio.vo.TaskVO.java

private void processShapeFile() throws Throwable {
    Table table = taskEntity.getTable();
    Integer srid = Utils.getSRID(table.getEpsg());

    String schemaTableName = TableUtils.getSchemaTable(table);

    BigDecimal totalFeatures = BigDecimal.valueOf(fileProcessor.getNumEntries());
    int saveLine = 0;
    while (taskEntity.getState().getStatus() != Status.FINISHED) {
        insertShapeFeature(schemaTableName, fileColumns, srid);
        updateShapeProgress(totalFeatures);
        // save the task state every 'LINES_TO_SAVE' lines processed
        if (saveLine == PanelSettings.taskLinesToSave) {
            saveTask();//from w w  w  .  j  av a  2  s  .  c  o m
            saveLine = 0;
        }
        saveLine++;
    }
}

From source file:de.hybris.platform.configurablebundleservices.bundle.impl.FindBundlePricingWithCurrentPriceFactoryStrategyTest.java

@Test(expected = IllegalArgumentException.class)
public void testOneTimeChargePriceNoPlan() {
    given(childCart.getBillingTime()).willReturn(oneTimeChargeBillingEvent);
    given(priceRule.getBillingEvent()).willReturn(oneTimeChargeBillingEvent);
    given(priceRule.getPrice()).willReturn(BigDecimal.valueOf(RULE_HIGH_PRICE.doubleValue()));
    given(oneTimeChargeEntry.getPrice()).willReturn(ONE_TIME_CHARGE_PLAN_PRICE);
    given(childEntry.getBasePrice()).willReturn(BASE_PRICE);
    given(oneTimeChargeEntry.getId()).willReturn("oneTimeChargeEntry");
    given(priceRule.getId()).willReturn("priceRule");

    final List<DiscountValue> discountValues = Lists.newArrayList();
    bundlePriceFactory.reduceOneTimePrice(null, priceRule, discountValues, currency, childEntry);

    assertTrue(discountValues.isEmpty());
}

From source file:ca.sqlpower.matchmaker.munge.AddressCorrectionMungeStep.java

/**
 * Uses the user validated values stored in the from the result table where
 * available. Otherwise, if no value is available, it will default to the
 * auto-corrected value./*from w  w w. ja  v  a2s  .  co  m*/
 * 
 * @return
 * @throws Exception
 *             Any Exceptions will get passed along to the SPSwingWorker
 *             running this process.
 */
private Boolean doCallWriteBackCorrectedAddresses() throws Exception {
    logger.debug("Running with user validated addresses as output");

    SQLIndex uniqueKey = getProject().getSourceTableIndex();

    List<Object> uniqueKeyValues = new ArrayList<Object>();

    for (Column col : uniqueKey.getChildren(Column.class)) {
        MungeStepOutput output = inputStep.getOutputByName(col.getName());
        if (output == null) {
            throw new IllegalStateException("Input step is missing unique key column '" + col.getName() + "'");
        }
        uniqueKeyValues.add(output.getData());
    }

    AddressResult result = pool.findAddress(uniqueKeyValues);

    if (result != null && result.getOutputAddress() != null &&
    /*!result.getOutputAddress().isEmptyAddress() && */
            result.isValid()) {
        Address address = result.getOutputAddress();

        MungeStepOutput addressLine2MSO = getMSOInputs().get(1);
        String addressLine2 = (addressLine2MSO != null) ? (String) addressLine2MSO.getData() : null;
        MungeStepOutput countryMSO = getMSOInputs().get(4);
        String country = (countryMSO != null) ? (String) countryMSO.getData() : null;

        logger.debug("Found an output address:\n" + address);
        List<MungeStepOutput> outputs = getChildren(MungeStepOutput.class);
        outputs.get(0).setData(address.getAddress());
        outputs.get(1).setData(addressLine2);
        outputs.get(2).setData(address.getSuite());
        outputs.get(3).setData(
                address.getStreetNumber() != null ? BigDecimal.valueOf(address.getStreetNumber()) : null);
        outputs.get(4).setData(address.getStreetNumberSuffix());
        outputs.get(5).setData(address.getStreet());
        outputs.get(6).setData(address.getStreetType());
        outputs.get(7).setData(address.getStreetDirection());
        outputs.get(8).setData(address.getMunicipality());
        outputs.get(9).setData(address.getProvince());
        outputs.get(10).setData(country);
        outputs.get(11).setData(address.getPostalCode());
        outputs.get(12).setData(result.isValid());
        addressCorrected = true;
        pool.markAddressForDeletion(uniqueKeyValues);
    } else {
        addressCorrected = false;
    }

    return Boolean.TRUE;
}