Example usage for java.math BigDecimal doubleValue

List of usage examples for java.math BigDecimal doubleValue

Introduction

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

Prototype

@Override
public double doubleValue() 

Source Link

Document

Converts this BigDecimal to a double .

Usage

From source file:org.adempiere.webui.dashboard.CalendarWindow.java

private void syncModel() {
    Hashtable<String, BigDecimal> ht = new Hashtable<String, BigDecimal>();

    List<?> list = calendars.getModel().get(calendars.getBeginDate(), calendars.getEndDate(), null);
    int size = list.size();
    for (Iterator<?> it = list.iterator(); it.hasNext();) {
        String key = ((ADCalendarEvent) it.next()).getR_RequestType_ID() + "";

        if (!ht.containsKey(key))
            ht.put(key, BigDecimal.ONE);
        else {/*  ww w .j a va  2 s  .  c o  m*/
            BigDecimal value = ht.get(key);
            ht.put(key, value.add(BigDecimal.ONE));
        }
    }

    Hashtable<Object, String> htTypes = new Hashtable<Object, String>();
    for (int i = 0; i < lbxRequestTypes.getItemCount(); i++) {
        Listitem li = lbxRequestTypes.getItemAtIndex(i);
        if (li != null && li.getValue() != null)
            htTypes.put(li.getValue(), li.getLabel());
    }

    DefaultPieDataset pieDataset = new DefaultPieDataset();
    Enumeration<?> keys = ht.keys();
    while (keys.hasMoreElements()) {
        String key = (String) keys.nextElement();
        BigDecimal value = ht.get(key);
        String name = (String) htTypes.get(key);
        pieDataset.setValue(name == null ? "" : name,
                new Double(size > 0 ? value.doubleValue() / size * 100 : 0));
    }

    JFreeChart chart = ChartFactory.createPieChart3D(Msg.getMsg(Env.getCtx(), "EventsAnalysis"), pieDataset,
            true, true, true);
    PiePlot3D plot = (PiePlot3D) chart.getPlot();
    plot.setForegroundAlpha(0.5f);
    BufferedImage bi = chart.createBufferedImage(600, 250);
    try {
        byte[] bytes = EncoderUtil.encode(bi, ImageFormat.PNG, true);
        AImage image = new AImage("Pie Chart", bytes);
        myChart.setContent(image);
    } catch (IOException e) {
        e.printStackTrace();
    }
    htTypes = null;
    ht = null;
}

From source file:edu.ku.brc.specify.tasks.services.CollectingEventLocalityKMLGenerator.java

/**
 * Generates a KML chunk describing the given collecting event.
 *
 * @param ce the event/*w  w  w  .  ja va2s . co m*/
 * @param label the label for the event
 * @return the KML string
 */
protected void generatePlacemark(Element kmlDocument, final Locality loc, final String label) {
    if (loc == null || loc.getLatitude1() == null || loc.getLongitude1() == null) {
        return;
    }
    BigDecimal lat = loc.getLatitude1();
    BigDecimal lon = loc.getLongitude1();

    // TODO Finishing implementing this method with Geography

    //Geography  geo = loc.getGeography(); 

    // build the placemark
    Element placemark = kmlDocument.addElement("Placemark");
    placemark.addElement("styleUrl").addText("#custom");
    placemark.addElement("name").addText(label != null ? label : loc.getLocalityName());

    // build the fancy HTML popup description
    placemark.addElement("description").addCDATA(generateHtmlDesc(loc));

    GenericKMLGenerator.buildPointAndLookAt(placemark,
            new Pair<Double, Double>(lat.doubleValue(), lon.doubleValue()));
}

From source file:com.salesmanager.core.service.tax.TaxService.java

/**
 * Calculates tax on an OrderTotalSummary object (products applicable,
 * shipping...), creates and set the shopping cart lines. Returns the amount
 * with tax/* w  ww .j  a v a2 s .c o m*/
 * 
 * @param summary
 * @param amount
 * @param customer
 * @param merchantId
 * @return
 * @throws Exception
 */
@Transactional
public OrderTotalSummary calculateTax(OrderTotalSummary summary, Collection<OrderProduct> products,
        Customer customer, int merchantId, Locale locale, String currency) throws Exception {

    MerchantService mservice = (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService);
    MerchantStore store = mservice.getMerchantStore(merchantId);

    Map productsTax = new HashMap();

    //rounding definition
    BigDecimal totalTaxAmount = new BigDecimal(0);
    //totalTaxAmount.setScale(2, BigDecimal.ROUND_DOWN);

    // check if tax is applicable and build a map
    // of tax class - product
    if (products != null) {
        Iterator prodIt = products.iterator();
        while (prodIt.hasNext()) {
            OrderProduct prod = (OrderProduct) prodIt.next();
            if (prod.getTaxClassId() > -1) {

                BigDecimal groupBeforeTaxAmount = (BigDecimal) productsTax.get(prod.getTaxClassId());

                if (groupBeforeTaxAmount == null) {
                    groupBeforeTaxAmount = new BigDecimal("0");
                }

                BigDecimal finalPrice = prod.getFinalPrice();// unit price +
                // attribute
                // * qty
                // finalPrice = finalPrice.multiply(new
                // BigDecimal(prod.getProductQuantity()));

                groupBeforeTaxAmount = groupBeforeTaxAmount.add(finalPrice);

                // getPrices
                Set prices = prod.getPrices();
                // List prices = prod.getRelatedPrices();
                if (prices != null) {
                    Iterator ppriceIter = prices.iterator();
                    while (ppriceIter.hasNext()) {
                        OrderProductPrice pprice = (OrderProductPrice) ppriceIter.next();
                        if (!pprice.isDefaultPrice()) {// related price
                            // activation...
                            // PriceModule module =
                            // (PriceModule)SpringUtil.getBean(pprice.getProductPriceModuleName());
                            // if(module.isTaxApplicable()) {//related price
                            // becomes taxeable
                            // if(pprice.isProductHasTax()) {
                            // groupBeforeTaxAmount =
                            // groupBeforeTaxAmount.add(ProductUtil.determinePrice(pprice));

                            BigDecimal ppPrice = pprice.getProductPriceAmount();
                            ppPrice = ppPrice.multiply(new BigDecimal(prod.getProductQuantity()));

                            groupBeforeTaxAmount = groupBeforeTaxAmount.add(ppPrice);
                            // }
                        }
                    }
                }

                BigDecimal credits = prod.getApplicableCreditOneTimeCharge();
                groupBeforeTaxAmount = groupBeforeTaxAmount.subtract(credits);

                productsTax.put(prod.getTaxClassId(), groupBeforeTaxAmount);

            }
        }
    }

    if (productsTax.size() == 0) {
        return summary;
    }

    // determine if tax applies on billing or shipping address

    // get shipping & tax informations
    ConfigurationRequest request = new ConfigurationRequest(merchantId);
    ConfigurationResponse response = mservice.getConfiguration(request);

    String taxBasis = TaxConstants.SHIPPING_TAX_BASIS;

    // get tax basis
    MerchantConfiguration taxConf = response.getMerchantConfiguration(TaxConstants.MODULE_TAX_BASIS);
    if (taxConf != null && !StringUtils.isBlank(taxConf.getConfigurationValue())) {// tax
        // basis
        taxBasis = taxConf.getConfigurationValue();
    }

    // tax on shipping
    if (summary.getShippingTotal() != null && summary.getShippingTotal().floatValue() > 0) {
        MerchantConfiguration shippingTaxConf = response
                .getMerchantConfiguration(ShippingConstants.MODULE_SHIPPING_TAX_CLASS);
        if (shippingTaxConf != null && !StringUtils.isBlank(shippingTaxConf.getConfigurationValue())) {// tax on shipping

            long taxClass = Long.parseLong(shippingTaxConf.getConfigurationValue());
            BigDecimal groupSubTotal = (BigDecimal) productsTax.get(taxClass);
            if (groupSubTotal == null) {
                groupSubTotal = new BigDecimal("0");
                productsTax.put(taxClass, groupSubTotal);
            }
            groupSubTotal = groupSubTotal.add(summary.getShippingTotal());
            productsTax.put(taxClass, groupSubTotal);
        }
    }

    Map taxDescriptionsHolder = new TreeMap();

    Iterator taxMapIter = productsTax.keySet().iterator();
    while (taxMapIter.hasNext()) {// get each tax class

        long key = (Long) taxMapIter.next();
        // List taxClassGroup = (List)productsTax.get(key);

        int countryId = 0;

        Collection taxCollection = null;
        if (taxBasis.equals(TaxConstants.SHIPPING_TAX_BASIS)) {

            if (store.getCountry() != customer.getCustomerCountryId()) {
                return summary;
            }

            taxCollection = taxRateDao.findByCountryIdZoneIdAndClassId(customer.getCustomerCountryId(),
                    customer.getCustomerZoneId(), key, merchantId);
            countryId = customer.getCustomerCountryId();
        } else { // BILLING

            if (store.getCountry() != customer.getCustomerBillingCountryId()) {
                return summary;
            }

            taxCollection = taxRateDao.findByCountryIdZoneIdAndClassId(customer.getCustomerBillingCountryId(),
                    customer.getCustomerBillingZoneId(), key, merchantId);
            countryId = customer.getCustomerBillingCountryId();
        }

        if (taxCollection == null || taxCollection.size() == 0) {// no tax
            continue;
        }

        Map countries = RefCache.getCountriesMap();
        Country c = (Country) countries.get(countryId);

        if (c != null) {// tax adjustment rules
            TaxModule module = (TaxModule) SpringUtil.getBean(c.getCountryIsoCode2());
            if (module != null) {
                taxCollection = module.adjustTaxRate(taxCollection, store);
            }
        }

        //BigDecimal beforeTaxAmount = new BigDecimal("0");
        //beforeTaxAmount.setScale(2, BigDecimal.ROUND_HALF_UP);
        BigDecimal groupSubTotal = (BigDecimal) productsTax.get(key);

        //beforeTaxAmount = beforeTaxAmount.add(groupSubTotal);
        BigDecimal beforeTaxAmount = groupSubTotal;
        beforeTaxAmount.setScale(2, BigDecimal.ROUND_HALF_UP);

        // iterate through tax collection and calculate tax lines
        if (taxCollection != null) {

            Iterator i = taxCollection.iterator();
            while (i.hasNext()) {

                TaxRate trv = (TaxRate) i.next();
                // double value = ((trv.getTaxRate().doubleValue() *
                // beforeTaxAmount.doubleValue())/100)+beforeTaxAmount.doubleValue();
                double trDouble = trv.getTaxRate().doubleValue();

                // if piggy back, add tax to subtotal
                BigDecimal amount = beforeTaxAmount;
                if (trv.isPiggyback()) {
                    // add previous calculated tax on top of subtotal
                    amount = amount.add(totalTaxAmount);
                }

                // commented for piggyback
                // double beforeTaxDouble = beforeTaxAmount.doubleValue();
                double beforeTaxDouble = amount.doubleValue();

                double value = ((trDouble * beforeTaxDouble) / 100);

                BigDecimal nValue = BigDecimal.valueOf(value);

                //BigDecimal nValue = new BigDecimal(value);
                nValue.setScale(2, BigDecimal.ROUND_HALF_UP);

                //nValue = nValue.add(new BigDecimal(value));

                // commented for piggyback
                // beforeTaxAmount = beforeTaxAmount.add(nValue);

                //BigDecimal bdValue = nValue;
                String am = CurrencyUtil.getAmount(nValue, store.getCurrency());

                /** this one **/
                totalTaxAmount = totalTaxAmount.add(new BigDecimal(am));

                String name = LabelUtil.getInstance().getText(locale, "label.generic.tax");

                OrderTotalLine line = (OrderTotalLine) taxDescriptionsHolder
                        .get(trv.getZoneToGeoZone().getGeoZoneId());

                if (line == null) {
                    // tax description
                    line = new OrderTotalLine();
                    Set descriptionsSet = trv.getDescriptions();
                    if (descriptionsSet != null) {
                        Iterator li = descriptionsSet.iterator();
                        while (li.hasNext()) {
                            TaxRateDescription description = (TaxRateDescription) li.next();
                            if (description.getId().getLanguageId() == LanguageUtil
                                    .getLanguageNumberCode(locale.getLanguage())) {
                                name = description.getTaxDescription();
                                break;
                            }
                        }
                    }

                    line.setText(name);
                    line.setCost(nValue);
                    line.setCostFormated(CurrencyUtil.displayFormatedAmountWithCurrency(nValue, currency));
                    taxDescriptionsHolder.put(trv.getZoneToGeoZone().getGeoZoneId(), line);
                } else {// needs to re-use the same shopping cart line
                    BigDecimal cost = line.getCost();
                    cost = cost.add(nValue);
                    line.setCostFormated(CurrencyUtil.displayFormatedAmountWithCurrency(cost, currency));
                }

                // now set tax on producs
                Iterator prodIt = products.iterator();
                while (prodIt.hasNext()) {
                    OrderProduct prod = (OrderProduct) prodIt.next();
                    if (prod.getTaxClassId() == key) {
                        // calculate tax for this product
                        BigDecimal price = prod.getProductPrice();
                        BigDecimal productTax = prod.getProductTax();
                        if (productTax == null) {
                            productTax = new BigDecimal("0");
                        }
                        price = price.add(productTax);
                        double pTax = ((trDouble * price.doubleValue()) / 100);

                        prod.setProductTax(new BigDecimal(pTax));

                    }
                }

            } // end while

        }

        Iterator titer = taxDescriptionsHolder.keySet().iterator();
        while (titer.hasNext()) {
            long lineKey = (Long) titer.next();
            OrderTotalLine line = (OrderTotalLine) taxDescriptionsHolder.get(lineKey);
            summary.addTaxPrice(line);
        }

    }

    summary.setTaxTotal(totalTaxAmount);

    return summary;

}

From source file:org.meerkat.services.WebApp.java

/**
 * getLatencyAverage//w  w w . j  a  v a  2  s  . co m
 * 
 * @return Latency average
 */
private final double getAvailabilityAverage() {
    double availAvg = 0;
    PreparedStatement ps;
    ResultSet rs = null;
    try {
        ps = conn.prepareStatement(
                "SELECT AVG(AVAILABILITY) FROM MEERKAT.EVENTS WHERE APPNAME LIKE '" + this.name + "'");
        rs = ps.executeQuery();

        rs.next();
        availAvg = rs.getDouble(1);

        rs.close();
        ps.close();
        conn.commit();

    } catch (SQLException e) {
        log.error("Failed query average availability from application " + this.getName());
        log.error("", e);
    }

    BigDecimal bd = new BigDecimal(availAvg);
    bd = bd.setScale(2, BigDecimal.ROUND_DOWN);
    availAvg = bd.doubleValue();

    return availAvg;
}

From source file:org.meerkat.services.WebApp.java

/**
 * getAppLoadTimeAVG// w ww  .  j a va 2s .c  o  m
 * @return
 */
public double getAppLoadTimeAVG() {
    int decimalPlaces = 2;
    double loadTimeAVG = 0.0;
    PreparedStatement ps;
    ResultSet rs = null;
    try {
        ps = conn.prepareStatement(
                "SELECT AVG(LOADTIME) FROM MEERKAT.EVENTS WHERE APPNAME LIKE '" + this.name + "'");
        rs = ps.executeQuery();

        rs.next();
        loadTimeAVG = rs.getInt(1);

        rs.close();
        ps.close();
        conn.commit();

    } catch (SQLException e) {
        log.error("Failed query number of events from application " + this.getName());
        log.error("", e);
    }

    BigDecimal bd = new BigDecimal(loadTimeAVG);
    bd = bd.setScale(decimalPlaces, BigDecimal.ROUND_DOWN);
    loadTimeAVG = bd.doubleValue();

    return loadTimeAVG;
}

From source file:org.meerkat.services.WebApp.java

/**
 * getAvailabilityIndicator//  ww  w .  j  a  va2  s.co  m
 * @return    1 if last availability higher than availability average
 *          -1 if last avail. lower than avail. average
 *          0 if they are equal
 *          (No decimal plates considered)
 */
public double getAvailabilityIndicator() {
    double doubleAvailAverage = getAvailabilityAverage();
    BigDecimal bd = new BigDecimal(doubleAvailAverage);
    bd = bd.setScale(0, BigDecimal.ROUND_DOWN);
    double availAverage = bd.doubleValue();

    // get the value of last event
    double lastAvailability = 0;
    PreparedStatement ps;
    ResultSet rs = null;
    int maxId = embDB.getMaxIDofApp(this.getName());
    try {
        ps = conn.prepareStatement("SELECT ID, AVAILABILITY " + "FROM MEERKAT.EVENTS " + "WHERE APPNAME LIKE '"
                + this.getName() + "' " + "AND ID = " + maxId);

        rs = ps.executeQuery();

        while (rs.next()) {
            lastAvailability = rs.getDouble(2);
        }

        rs.close();
        ps.close();

    } catch (SQLException e) {
        log.error("Failed query average availability from application " + this.getName());
        log.error("", e);
    }

    BigDecimal bd1 = new BigDecimal(lastAvailability);
    bd1 = bd1.setScale(2, BigDecimal.ROUND_DOWN);
    lastAvailability = bd1.doubleValue();

    if (lastAvailability > availAverage) {
        return 1;
    } else if (lastAvailability < availAverage) {
        return -1;
    }

    return 0;
}

From source file:org.meerkat.services.WebApp.java

/**
 * //from w w w.ja va  2 s. c  o m
 * getLatencyIndicator
 * @return    1 if last latency higher than latency average
 *          -1 if last latency lower than latency average
 *          0 if they are equal
 *          (No decimal plates considered)
 */
public double getLatencyIndicator() {
    double doubleLatencyAverage = getLatencyAverage();
    BigDecimal bd = new BigDecimal(doubleLatencyAverage);
    bd = bd.setScale(0, BigDecimal.ROUND_DOWN);
    double latencyAverage = bd.doubleValue();

    // get the value of last event
    double lastLatency = 0;
    PreparedStatement ps;
    ResultSet rs = null;
    int maxID = embDB.getMaxIDofApp(this.name);

    try {
        ps = conn.prepareStatement("SELECT ID, LATENCY " + "FROM MEERKAT.EVENTS " + "WHERE APPNAME LIKE '"
                + this.name + "' " + "AND ID = " + maxID);

        rs = ps.executeQuery();

        while (rs.next()) {
            lastLatency = rs.getDouble(2);
        }

        rs.close();
        ps.close();
        conn.commit();

    } catch (SQLException e) {
        log.error("Failed query average availability from application " + this.getName());
        log.error("", e);
    }

    BigDecimal bd1 = new BigDecimal(lastLatency);
    bd1 = bd1.setScale(2, BigDecimal.ROUND_DOWN);
    lastLatency = bd1.doubleValue();

    if (lastLatency > latencyAverage) {
        return 1;
    } else if (lastLatency < latencyAverage) {
        return -1;
    }

    return 0;
}

From source file:org.meerkat.services.WebApp.java

/**
 * getLoadTimeIndicator/* w w  w .  ja v a2s. co  m*/
 * @return    1 if last load time higher than load time average
 *          -1 if last load time lower than load time average
 *          0 if they are equal
 *          (No decimal plates considered)
 */
public double getLoadTimeIndicator() {
    double doubleLoadTimeAverage = getAppLoadTimeAVG();
    BigDecimal bd = new BigDecimal(doubleLoadTimeAverage);
    bd = bd.setScale(0, BigDecimal.ROUND_DOWN);
    double loadTimeAverage = bd.doubleValue();

    // get the value of last event
    double lastLoadTime = 0;
    PreparedStatement ps;
    ResultSet rs = null;
    int maxID = embDB.getMaxIDofApp(this.name);

    try {
        ps = conn.prepareStatement("SELECT ID, LOADTIME " + "FROM MEERKAT.EVENTS " + "WHERE APPNAME LIKE '"
                + this.name + "' " + "AND ID = " + maxID);

        rs = ps.executeQuery();

        while (rs.next()) {
            lastLoadTime = rs.getDouble(2);
        }

        rs.close();
        ps.close();
        conn.commit();

    } catch (SQLException e) {
        log.error("Failed query average load time from application " + this.getName());
        log.error("", e);
    }

    BigDecimal bd1 = new BigDecimal(lastLoadTime);
    bd1 = bd1.setScale(3, BigDecimal.ROUND_DOWN);
    lastLoadTime = bd1.doubleValue();

    if (lastLoadTime > loadTimeAverage) {
        return 1;
    } else if (lastLoadTime < loadTimeAverage) {
        return -1;
    }

    return 0;
}

From source file:edu.ku.brc.specify.tasks.services.CollectingEventLocalityKMLGenerator.java

/**
 * Generates a KML chunk describing the given collecting event.
 *
 * @param ce the event// w w w. j a v a 2 s. co m
 * @param label the label for the event
 * @return the KML string
 */
protected void generatePlacemark(Element kmlDocument, final CollectionObject colObj, final String label) {
    if (colObj == null || colObj.getCollectingEvent() == null
            || colObj.getCollectingEvent().getLocality() == null) {
        return;
    }

    CollectingEvent ce = colObj.getCollectingEvent();
    Locality loc = ce.getLocality();

    if (loc.getLatitude1() == null || loc.getLongitude1() == null) {
        return;
    }

    BigDecimal lat = loc.getLatitude1();
    BigDecimal lon = loc.getLongitude1();

    //DBTableInfo coti = DBTableIdMgr.getInstance().getInfoById(CollectionObject.getClassTableId());
    DBTableInfo ceti = DBTableIdMgr.getInstance().getInfoById(CollectingEvent.getClassTableId());

    StringBuilder title = new StringBuilder(colObj.getIdentityTitle());

    // build the placemark
    Element placemark = kmlDocument.addElement("Placemark");
    placemark.addElement("styleUrl").addText("#custom");
    placemark.addElement("name").addText(label != null ? label : title.toString());

    placemark.addElement("description").addCDATA(generateHtmlDesc(colObj));

    GenericKMLGenerator.buildPointAndLookAt(placemark,
            new Pair<Double, Double>(lat.doubleValue(), lon.doubleValue()));
}

From source file:net.samuelbjohnson.javadev.crosstopix.Joiner.java

public boolean join(Statement imslpStatement, Statement cpdlStatement, boolean fullOutput)
        throws NoSuchAlgorithmException, RepositoryException {
    BigDecimal distance = computeDistance(imslpStatement.getObject().stringValue(),
            cpdlStatement.getObject().stringValue());

    if (!fullOutput) {
        outputWriter.print(imslpStatement.getObject().stringValue().length() + ",");
        outputWriter.print(cpdlStatement.getObject().stringValue().length() + ",");
        outputWriter.println(distance);/*from   w  w w  .ja va 2s. com*/
        return true;
    }

    MessageDigest md5 = MessageDigest.getInstance("MD5");
    md5.update((imslpStatement.getObject().stringValue() + cpdlStatement.getObject().stringValue()
            + distance.toPlainString()).getBytes());
    BigInteger hashInt = new BigInteger(1, md5.digest());
    String md5Sum = hashInt.toString(16);

    Resource subject = valueFactory.createURI(subjectNamespace, md5Sum);
    URI predicateImslp = valueFactory.createURI(predicateNamespace, "comparable_1");
    URI predicateCpdl = valueFactory.createURI(predicateNamespace, "comparable_2");
    URI predicateDiff = valueFactory.createURI(predicateNamespace, "similarity");

    outputRepCon.add(subject, predicateImslp, imslpStatement.getSubject());
    outputRepCon.add(subject, predicateCpdl, cpdlStatement.getSubject());
    outputRepCon.add(subject, predicateDiff, valueFactory.createLiteral(distance.doubleValue()));

    outputRepCon.commit();

    return true;
}