Example usage for java.math BigDecimal ROUND_HALF_UP

List of usage examples for java.math BigDecimal ROUND_HALF_UP

Introduction

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

Prototype

int ROUND_HALF_UP

To view the source code for java.math BigDecimal ROUND_HALF_UP.

Click Source Link

Document

Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.

Usage

From source file:com.salesmanager.core.business.modules.integration.shipping.impl.UPSShippingQuote.java

@Override
public List<ShippingOption> getShippingQuotes(ShippingQuote shippingQuote, List<PackageDetails> packages,
        BigDecimal orderTotal, Delivery delivery, ShippingOrigin origin, MerchantStore store,
        IntegrationConfiguration configuration, IntegrationModule module,
        ShippingConfiguration shippingConfiguration, Locale locale) throws IntegrationException {

    Validate.notNull(configuration, "IntegrationConfiguration must not be null for USPS shipping module");

    if (StringUtils.isBlank(delivery.getPostalCode())) {
        return null;
    }/*from   ww  w  .ja v  a  2  s  .co m*/

    BigDecimal total = orderTotal;

    if (packages == null) {
        return null;
    }

    List<ShippingOption> options = null;

    // only applies to Canada and US
    Country country = delivery.getCountry();

    if (!(country.getIsoCode().equals("US") || country.getIsoCode().equals("CA"))) {
        return null;
        //throw new IntegrationException("UPS Not configured for shipping in country " + country.getIsoCode());
    }

    // supports en and fr
    String language = locale.getLanguage();
    if (!language.equals(Locale.FRENCH.getLanguage()) && !language.equals(Locale.ENGLISH.getLanguage())) {
        language = Locale.ENGLISH.getLanguage();
    }

    String pack = configuration.getIntegrationOptions().get("packages").get(0);
    Map<String, String> keys = configuration.getIntegrationKeys();

    String accessKey = keys.get("accessKey");
    String userId = keys.get("userId");
    String password = keys.get("password");

    String host = null;
    String protocol = null;
    String port = null;
    String url = null;

    StringBuilder xmlbuffer = new StringBuilder();
    HttpPost httppost = null;
    BufferedReader reader = null;

    try {
        String env = configuration.getEnvironment();

        Set<String> regions = module.getRegionsSet();
        if (!regions.contains(store.getCountry().getIsoCode())) {
            throw new IntegrationException("Can't use the service for store country code ");
        }

        Map<String, ModuleConfig> moduleConfigsMap = module.getModuleConfigs();
        for (String key : moduleConfigsMap.keySet()) {

            ModuleConfig moduleConfig = (ModuleConfig) moduleConfigsMap.get(key);
            if (moduleConfig.getEnv().equals(env)) {
                host = moduleConfig.getHost();
                protocol = moduleConfig.getScheme();
                port = moduleConfig.getPort();
                url = moduleConfig.getUri();
            }
        }

        StringBuilder xmlreqbuffer = new StringBuilder();
        xmlreqbuffer.append("<?xml version=\"1.0\"?>");
        xmlreqbuffer.append("<AccessRequest>");
        xmlreqbuffer.append("<AccessLicenseNumber>");
        xmlreqbuffer.append(accessKey);
        xmlreqbuffer.append("</AccessLicenseNumber>");
        xmlreqbuffer.append("<UserId>");
        xmlreqbuffer.append(userId);
        xmlreqbuffer.append("</UserId>");
        xmlreqbuffer.append("<Password>");
        xmlreqbuffer.append(password);
        xmlreqbuffer.append("</Password>");
        xmlreqbuffer.append("</AccessRequest>");

        String xmlhead = xmlreqbuffer.toString();

        String weightCode = store.getWeightunitcode();
        String measureCode = store.getSeizeunitcode();

        if (weightCode.equals("KG")) {
            weightCode = "KGS";
        } else {
            weightCode = "LBS";
        }

        String xml = "<?xml version=\"1.0\"?><RatingServiceSelectionRequest><Request><TransactionReference><CustomerContext>Shopizer</CustomerContext><XpciVersion>1.0001</XpciVersion></TransactionReference><RequestAction>Rate</RequestAction><RequestOption>Shop</RequestOption></Request>";
        StringBuffer xmldatabuffer = new StringBuffer();

        /**
         * <Shipment>
         * 
         * <Shipper> <Address> <City></City>
         * <StateProvinceCode>QC</StateProvinceCode>
         * <CountryCode>CA</CountryCode> <PostalCode></PostalCode>
         * </Address> </Shipper>
         * 
         * <ShipTo> <Address> <City>Redwood Shores</City>
         * <StateProvinceCode>CA</StateProvinceCode>
         * <CountryCode>US</CountryCode> <PostalCode></PostalCode>
         * <ResidentialAddressIndicator/> </Address> </ShipTo>
         * 
         * <Package> <PackagingType> <Code>21</Code> </PackagingType>
         * <PackageWeight> <UnitOfMeasurement> <Code>LBS</Code>
         * </UnitOfMeasurement> <Weight>1.1</Weight> </PackageWeight>
         * <PackageServiceOptions> <InsuredValue>
         * <CurrencyCode>CAD</CurrencyCode>
         * <MonetaryValue>100</MonetaryValue> </InsuredValue>
         * </PackageServiceOptions> </Package>
         * 
         * 
         * </Shipment>
         * 
         * <CustomerClassification> <Code>03</Code>
         * </CustomerClassification> </RatingServiceSelectionRequest>
         * **/

        /**Map countriesMap = (Map) RefCache.getAllcountriesmap(LanguageUtil
              .getLanguageNumberCode(locale.getLanguage()));
        Map zonesMap = (Map) RefCache.getAllZonesmap(LanguageUtil
              .getLanguageNumberCode(locale.getLanguage()));
                
        Country storeCountry = (Country) countriesMap.get(store
              .getCountry());
                
        Country customerCountry = (Country) countriesMap.get(customer
              .getCustomerCountryId());
                
        int sZone = -1;
        try {
           sZone = Integer.parseInt(store.getZone());
        } catch (Exception e) {
           // TODO: handle exception
        }
                
        Zone storeZone = (Zone) zonesMap.get(sZone);
        Zone customerZone = (Zone) zonesMap.get(customer
              .getCustomerZoneId());**/

        xmldatabuffer.append("<PickupType><Code>03</Code></PickupType>");
        // xmldatabuffer.append("<Description>Daily Pickup</Description>");
        xmldatabuffer.append("<Shipment><Shipper>");
        xmldatabuffer.append("<Address>");
        xmldatabuffer.append("<City>");
        xmldatabuffer.append(store.getStorecity());
        xmldatabuffer.append("</City>");
        // if(!StringUtils.isBlank(store.getStorestateprovince())) {
        if (store.getZone() != null) {
            xmldatabuffer.append("<StateProvinceCode>");
            xmldatabuffer.append(store.getZone().getCode());// zone code
            xmldatabuffer.append("</StateProvinceCode>");
        }
        xmldatabuffer.append("<CountryCode>");
        xmldatabuffer.append(store.getCountry().getIsoCode());
        xmldatabuffer.append("</CountryCode>");
        xmldatabuffer.append("<PostalCode>");
        xmldatabuffer.append(DataUtils.trimPostalCode(store.getStorepostalcode()));
        xmldatabuffer.append("</PostalCode></Address></Shipper>");

        // ship to
        xmldatabuffer.append("<ShipTo>");
        xmldatabuffer.append("<Address>");
        xmldatabuffer.append("<City>");
        xmldatabuffer.append(delivery.getCity());
        xmldatabuffer.append("</City>");
        // if(!StringUtils.isBlank(customer.getCustomerState())) {
        if (delivery.getZone() != null) {
            xmldatabuffer.append("<StateProvinceCode>");
            xmldatabuffer.append(delivery.getZone().getCode());// zone code
            xmldatabuffer.append("</StateProvinceCode>");
        }
        xmldatabuffer.append("<CountryCode>");
        xmldatabuffer.append(delivery.getCountry().getIsoCode());
        xmldatabuffer.append("</CountryCode>");
        xmldatabuffer.append("<PostalCode>");
        xmldatabuffer.append(DataUtils.trimPostalCode(delivery.getPostalCode()));
        xmldatabuffer.append("</PostalCode></Address></ShipTo>");
        // xmldatabuffer.append("<Service><Code>11</Code></Service>");//TODO service codes (next day ...)

        for (PackageDetails packageDetail : packages) {

            xmldatabuffer.append("<Package>");
            xmldatabuffer.append("<PackagingType>");
            xmldatabuffer.append("<Code>");
            xmldatabuffer.append(pack);
            xmldatabuffer.append("</Code>");
            xmldatabuffer.append("</PackagingType>");

            // weight
            xmldatabuffer.append("<PackageWeight>");
            xmldatabuffer.append("<UnitOfMeasurement>");
            xmldatabuffer.append("<Code>");
            xmldatabuffer.append(weightCode);
            xmldatabuffer.append("</Code>");
            xmldatabuffer.append("</UnitOfMeasurement>");
            xmldatabuffer.append("<Weight>");
            xmldatabuffer.append(
                    new BigDecimal(packageDetail.getShippingWeight()).setScale(1, BigDecimal.ROUND_HALF_UP));
            xmldatabuffer.append("</Weight>");
            xmldatabuffer.append("</PackageWeight>");

            // dimension
            xmldatabuffer.append("<Dimensions>");
            xmldatabuffer.append("<UnitOfMeasurement>");
            xmldatabuffer.append("<Code>");
            xmldatabuffer.append(measureCode);
            xmldatabuffer.append("</Code>");
            xmldatabuffer.append("</UnitOfMeasurement>");
            xmldatabuffer.append("<Length>");
            xmldatabuffer.append(
                    new BigDecimal(packageDetail.getShippingLength()).setScale(2, BigDecimal.ROUND_HALF_UP));
            xmldatabuffer.append("</Length>");
            xmldatabuffer.append("<Width>");
            xmldatabuffer.append(
                    new BigDecimal(packageDetail.getShippingWidth()).setScale(2, BigDecimal.ROUND_HALF_UP));
            xmldatabuffer.append("</Width>");
            xmldatabuffer.append("<Height>");
            xmldatabuffer.append(
                    new BigDecimal(packageDetail.getShippingHeight()).setScale(2, BigDecimal.ROUND_HALF_UP));
            xmldatabuffer.append("</Height>");
            xmldatabuffer.append("</Dimensions>");
            xmldatabuffer.append("</Package>");

        }

        xmldatabuffer.append("</Shipment>");
        xmldatabuffer.append("</RatingServiceSelectionRequest>");

        xmlbuffer.append(xmlhead).append(xml).append(xmldatabuffer.toString());

        LOGGER.debug("UPS QUOTE REQUEST " + xmlbuffer.toString());

        CloseableHttpClient httpclient = HttpClients.createDefault();
        //HttpClient client = new HttpClient();
        httppost = new HttpPost(protocol + "://" + host + ":" + port + url);

        StringEntity entity = new StringEntity(xmlbuffer.toString(), ContentType.APPLICATION_ATOM_XML);

        //RequestEntity entity = new StringRequestEntity(
        //      xmlbuffer.toString(), "text/plain", "UTF-8");
        httppost.setEntity(entity);

        // Create a custom response handler
        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {

            @Override
            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    LOGGER.error("Communication Error with ups quote " + status);
                    throw new ClientProtocolException("UPS quote communication error " + status);
                }
            }

        };

        String data = httpclient.execute(httppost, responseHandler);

        //int result = response.getStatusLine().getStatusCode();
        //int result = client.executeMethod(httppost);
        /*         if (result != 200) {
                    LOGGER.error("Communication Error with ups quote " + result + " "
          + protocol + "://" + host + ":" + port + url);
                    throw new Exception("UPS quote communication error " + result);
                 }*/

        LOGGER.debug("ups quote response " + data);

        UPSParsedElements parsed = new UPSParsedElements();

        Digester digester = new Digester();
        digester.push(parsed);
        digester.addCallMethod("RatingServiceSelectionResponse/Response/Error", "setErrorCode", 0);
        digester.addCallMethod("RatingServiceSelectionResponse/Response/ErrorDescriprion", "setError", 0);
        digester.addCallMethod("RatingServiceSelectionResponse/Response/ResponseStatusCode", "setStatusCode",
                0);
        digester.addCallMethod("RatingServiceSelectionResponse/Response/ResponseStatusDescription",
                "setStatusMessage", 0);
        digester.addCallMethod("RatingServiceSelectionResponse/Response/Error/ErrorDescription", "setError", 0);

        digester.addObjectCreate("RatingServiceSelectionResponse/RatedShipment", ShippingOption.class);
        // digester.addSetProperties(
        // "RatingServiceSelectionResponse/RatedShipment", "sequence",
        // "optionId" );
        digester.addCallMethod("RatingServiceSelectionResponse/RatedShipment/Service/Code", "setOptionId", 0);
        digester.addCallMethod("RatingServiceSelectionResponse/RatedShipment/TotalCharges/MonetaryValue",
                "setOptionPriceText", 0);
        //digester
        //      .addCallMethod(
        //            "RatingServiceSelectionResponse/RatedShipment/TotalCharges/CurrencyCode",
        //            "setCurrency", 0);
        digester.addCallMethod("RatingServiceSelectionResponse/RatedShipment/Service/Code", "setOptionCode", 0);
        digester.addCallMethod("RatingServiceSelectionResponse/RatedShipment/GuaranteedDaysToDelivery",
                "setEstimatedNumberOfDays", 0);
        digester.addSetNext("RatingServiceSelectionResponse/RatedShipment", "addOption");

        // <?xml
        // version="1.0"?><AddressValidationResponse><Response><TransactionReference><CustomerContext>SalesManager
        // Data</CustomerContext><XpciVersion>1.0</XpciVersion></TransactionReference><ResponseStatusCode>0</ResponseStatusCode><ResponseStatusDescription>Failure</ResponseStatusDescription><Error><ErrorSeverity>Hard</ErrorSeverity><ErrorCode>10002</ErrorCode><ErrorDescription>The
        // XML document is well formed but the document is not
        // valid</ErrorDescription><ErrorLocation><ErrorLocationElementName>AddressValidationRequest</ErrorLocationElementName></ErrorLocation></Error></Response></AddressValidationResponse>

        Reader xmlreader = new StringReader(data);

        digester.parse(xmlreader);

        if (!StringUtils.isBlank(parsed.getErrorCode())) {

            LOGGER.error(
                    "Can't process UPS statusCode=" + parsed.getErrorCode() + " message= " + parsed.getError());
            throw new IntegrationException(parsed.getError());
        }
        if (!StringUtils.isBlank(parsed.getStatusCode()) && !parsed.getStatusCode().equals("1")) {

            throw new IntegrationException(parsed.getError());
        }

        if (parsed.getOptions() == null || parsed.getOptions().size() == 0) {

            throw new IntegrationException("No shipping options available for the configuration");
        }

        /*String carrier = getShippingMethodDescription(locale);
        // cost is in CAD, need to do conversion
                
                
        boolean requiresCurrencyConversion = false; String storeCurrency
         = store.getCurrency();
        if(!storeCurrency.equals(Constants.CURRENCY_CODE_CAD)) {
         requiresCurrencyConversion = true; }
                 
                
        LabelUtil labelUtil = LabelUtil.getInstance();
        Map serviceMap = com.salesmanager.core.util.ShippingUtil
              .buildServiceMap("upsxml", locale);
                
        *//** Details on whit RT quote information to display **//*
                                                                  MerchantConfiguration rtdetails = config
                                                                  .getMerchantConfiguration(ShippingConstants.MODULE_SHIPPING_DISPLAY_REALTIME_QUOTES);
                                                                  int displayQuoteDeliveryTime = ShippingConstants.NO_DISPLAY_RT_QUOTE_TIME;
                                                                          
                                                                          
                                                                  if (rtdetails != null) {
                                                                          
                                                                  if (!StringUtils.isBlank(rtdetails.getConfigurationValue1())) {// display
                                                                  // or
                                                                  // not
                                                                  // quotes
                                                                  try {
                                                                  displayQuoteDeliveryTime = Integer.parseInt(rtdetails
                                                                  .getConfigurationValue1());
                                                                          
                                                                  } catch (Exception e) {
                                                                  log.error("Display quote is not an integer value ["
                                                                  + rtdetails.getConfigurationValue1() + "]");
                                                                  }
                                                                  }
                                                                  }*/

        List<ShippingOption> shippingOptions = parsed.getOptions();

        if (shippingOptions != null) {

            Map<String, String> details = module.getDetails();

            for (ShippingOption option : shippingOptions) {

                String name = details.get(option.getOptionCode());
                option.setOptionName(name);
                if (option.getOptionPrice() == null) {
                    String priceText = option.getOptionPriceText();
                    if (StringUtils.isBlank(priceText)) {
                        throw new IntegrationException("Price text is null for option " + name);
                    }

                    try {
                        BigDecimal price = new BigDecimal(priceText);
                        option.setOptionPrice(price);
                    } catch (Exception e) {
                        throw new IntegrationException("Can't convert to numeric price " + priceText);
                    }

                }

            }

        }

        /*         if (options != null) {
                
                    Map selectedintlservices = (Map) config
          .getConfiguration("service-global-upsxml");
                
                    Iterator i = options.iterator();
                    while (i.hasNext()) {
                       ShippingOption option = (ShippingOption) i.next();
                       // option.setCurrency(store.getCurrency());
                       StringBuffer description = new StringBuffer();
                
                       String code = option.getOptionCode();
                       option.setOptionCode(code);
                       // get description
                       String label = (String) serviceMap.get(code);
                       if (label == null) {
          log
                .warn("UPSXML cannot find description for service code "
                      + code);
                       }
                
                       option.setOptionName(label);
                
                       description.append(option.getOptionName());
                       if (displayQuoteDeliveryTime == ShippingConstants.DISPLAY_RT_QUOTE_TIME) {
          if (!StringUtils.isBlank(option
                .getEstimatedNumberOfDays())) {
             description.append(" (").append(
                   option.getEstimatedNumberOfDays()).append(
                   " ").append(
                   labelUtil.getText(locale,
                         "label.generic.days.lowercase"))
                   .append(")");
          }
                       }
                       option.setDescription(description.toString());
                
                       // get currency
                       if (!option.getCurrency().equals(store.getCurrency())) {
          option.setOptionPrice(CurrencyUtil.convertToCurrency(
                option.getOptionPrice(), option.getCurrency(),
                store.getCurrency()));
                       }
                
                       if (!selectedintlservices.containsKey(option
             .getOptionCode())) {
          if (returnColl == null) {
             returnColl = new ArrayList();
          }
          returnColl.add(option);
          // options.remove(option);
                       }
                
                    }
                
                    if (options.size() == 0) {
                       LogMerchantUtil
             .log(
                   store.getMerchantId(),
                   " none of the service code returned by UPS ["
                         + selectedintlservices
                               .keySet()
                               .toArray(
                                     new String[selectedintlservices
                                           .size()])
                         + "] for this shipping is in your selection list");
                    }
                 }*/

        return shippingOptions;

    } catch (Exception e1) {
        LOGGER.error("UPS quote error", e1);
        throw new IntegrationException(e1);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception ignore) {
            }
        }

        if (httppost != null) {
            httppost.releaseConnection();
        }
    }
}

From source file:com.ah.be.common.PresenceUtil.java

public static String convertValue(double bandWidth) {
    String vonvertBandWidth = "";
    bandWidth = new BigDecimal(bandWidth / 1024).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
    vonvertBandWidth = bandWidth + " KB";
    if (bandWidth > 1024) {
        bandWidth = new BigDecimal(bandWidth / 1024).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        vonvertBandWidth = bandWidth + " MB";
    } else if (bandWidth > 1024) {
        bandWidth = new BigDecimal(bandWidth / 1024).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        vonvertBandWidth = bandWidth + " GB";
    }/*from   ww w  .j a v  a  2s .c  o m*/
    return vonvertBandWidth;
}

From source file:com.example.photoremark.MainActivity.java

public double roundDouble(double value, int weishu) {
    BigDecimal bg = new BigDecimal(value);
    double newValue = bg.setScale(weishu, BigDecimal.ROUND_HALF_UP).doubleValue();
    return newValue;
}

From source file:jp.terasoluna.fw.web.taglib.DecimalTag.java

/**
 * ^O]Jn?\bh?B//from  ww  w.jav a  2s  .  c om
 *
 * @return ???w?B? <code>SKIP_BODY</code>
 * @throws JspException JSPO
 */
@Override
public int doStartTag() throws JspException {

    Object value = this.value;
    if (value == null) {
        // bean???Av?beanbNAbv
        // ???A^?[
        if (ignore) {
            if (TagUtil.lookup(pageContext, name, scope) == null) {
                return SKIP_BODY; // ?o
            }
        }

        // v?v?peBlbNAbv
        value = TagUtil.lookup(pageContext, name, property, scope);
        if (value == null) {
            return SKIP_BODY; // ?o
        }
    }

    // v?peBlString^xBigDecimal
    BigDecimal bd = null;
    if (value instanceof String) {
        String trimed = StringUtil.rtrim((String) value);
        if ("".equals(trimed)) {
            return SKIP_BODY; //  ?o
        }
        bd = new BigDecimal(trimed);
    } else if (value instanceof BigDecimal) {
        bd = (BigDecimal) value;
    } else {
        return SKIP_BODY; // ?o
    }

    // ??_?w??
    if (scale >= 0) {
        // round???[h?s?i???l?j
        if (round != null) {
            if ("ROUND_FLOOR".equalsIgnoreCase(round)) {
                bd = bd.setScale(scale, BigDecimal.ROUND_FLOOR);
            } else if ("ROUND_CEILING".equalsIgnoreCase(round)) {
                bd = bd.setScale(scale, BigDecimal.ROUND_CEILING);
            } else if ("ROUND_HALF_UP".equalsIgnoreCase(round)) {
                bd = bd.setScale(scale, BigDecimal.ROUND_HALF_UP);
            } else {
                log.error("Please set a rounding mode");
                throw new IllegalArgumentException("Please set a rounding mode");
            }
        } else {
            bd = bd.setScale(scale, BigDecimal.ROUND_HALF_UP);
        }
    }

    // tH?[}bg
    DecimalFormat df = new DecimalFormat(pattern);
    String output = df.format(bd);

    if (id != null) {
        // idw?AXNveBO?p
        // y?[WXR?[vZbg?B
        pageContext.setAttribute(id, output);
    } else {
        // idw?Av?peBlC^vg
        // ?BK?tB^?B
        if (filter) {
            TagUtil.write(pageContext, TagUtil.filter(output));
        } else {
            TagUtil.write(pageContext, output);
        }
    }

    return SKIP_BODY;
}

From source file:org.kalypso.ui.wizards.results.ResultSldHelper.java

/**
 * sets the parameters for the colormap of an isoline
 *//*  w  w w .java  2 s . com*/
private static void configureLineSymbolizer(final SurfaceLineSymbolizer symbolizer, final BigDecimal minValue,
        final BigDecimal maxValue) throws FilterEvaluationException {
    final LineColorMap templateColorMap = symbolizer.getColorMap();
    final LineColorMap newColorMap = new LineColorMap_Impl();

    // retrieve stuff from template-entries
    final LineColorMapEntry fromEntry = templateColorMap.findEntry("from", null); //$NON-NLS-1$
    final LineColorMapEntry toEntry = templateColorMap.findEntry("to", null); //$NON-NLS-1$
    final LineColorMapEntry fatEntry = templateColorMap.findEntry("fat", null); //$NON-NLS-1$

    final Color fromColor = fromEntry.getStroke().getStroke(null);
    final Color toColor = toEntry.getStroke().getStroke(null);
    final double opacity = fromEntry.getStroke().getOpacity(null);

    final double normalWidth = fromEntry.getStroke().getWidth(null);
    final double fatWidth = fatEntry.getStroke().getWidth(null);

    // defines which isolines are drawn with a fat line
    final double fatValue = fatEntry.getQuantity(null);
    // TODO: get setep / scale from quantity
    // get rounded values below min and above max (rounded by first decimal)
    // as a first try we will generate isolines using class steps of 0.1
    // later, the classes will be done by using user defined class steps.
    // for that we fill an array of calculated (later user defined values) from max to min
    final BigDecimal minDecimal = minValue.setScale(1, BigDecimal.ROUND_FLOOR);
    final BigDecimal maxDecimal = maxValue.setScale(1, BigDecimal.ROUND_CEILING);

    final BigDecimal stepWidth = new BigDecimal(0.1).setScale(1, BigDecimal.ROUND_HALF_UP);
    final int numOfClasses = (maxDecimal.subtract(minDecimal).divide(stepWidth)).intValue() + 1;

    for (int currentClass = 0; currentClass < numOfClasses; currentClass++) {
        final double currentValue = minDecimal.doubleValue() + currentClass * stepWidth.doubleValue();

        Color lineColor;
        if (fromColor == toColor)
            lineColor = fromColor;
        else
            lineColor = interpolateColor(fromColor, toColor, currentClass, numOfClasses);

        final double strokeWidth;
        if (currentValue % fatValue == 0)
            strokeWidth = fatWidth;
        else
            strokeWidth = normalWidth;

        final Stroke stroke = StyleFactory.createStroke(lineColor, strokeWidth, opacity);

        final ParameterValueType label = StyleFactory.createParameterValueType("Isolinie " + currentClass); //$NON-NLS-1$
        final ParameterValueType quantity = StyleFactory.createParameterValueType(currentValue);

        final LineColorMapEntry colorMapEntry = new LineColorMapEntry_Impl(stroke, label, quantity);
        newColorMap.addColorMapClass(colorMapEntry);
    }

    symbolizer.setColorMap(newColorMap);
}

From source file:com.icebreak.p2p.trade.impl.TradeServiceImpl.java

@Transactional(rollbackFor = Exception.class, value = "transactionManager")
@Override/*w w w  . j av  a  2  s  . c  om*/
public RepayOrder gotoYJFRepay(long repayUserId, long demandId, long repayPlanId) throws Exception {

    List<UserBaseInfoDO> repayUsers = userBaseInfoManager.queryByType(null, String.valueOf(repayUserId));
    UserBaseInfoDO repayUser = null;
    if (ListUtil.isNotEmpty(repayUsers)) {
        repayUser = repayUsers.get(0);
        if (!"normal".equals(repayUser.getState())) {
            logger.error("?userId{}", repayUserId);
            throw new Exception("user state error");
        }
    } else {
        logger.error("?userId{}", repayUserId);
        throw new Exception("can not find repay user");
    }

    Trade trade = tradeDao.getByDemandId(demandId);
    LoanDemandDO loan = loanDemandManager.queryLoanDemandByDemandId(trade.getDemandId());

    RepayPlanInfo repayPlanInfo = null;

    if (DivisionWayEnum.SIT_WAY.code().equals(loan.getRepayDivisionWay())) {
        RepayPlanQueryOrder repayPlanQueryOrder = new RepayPlanQueryOrder();
        repayPlanQueryOrder.setRepayDivisionWay(DivisionWayEnum.SIT_WAY.code());
        repayPlanQueryOrder.setPageSize(999999);
        repayPlanQueryOrder.setPageNumber(1);
        repayPlanQueryOrder.setTradeId(trade.getId());
        repayPlanQueryOrder.setPeriodNo(1);
        QueryBaseBatchResult<RepayPlanInfo> result = repayPlanService.queryRepayPlanInfo(repayPlanQueryOrder);
        if (ListUtil.isNotEmpty(result.getPageList())) {
            repayPlanInfo = result.getPageList().get(0);
            repayPlanId = repayPlanInfo.getRepayPlanId(); // ?id
        }
    } else {
        if (repayPlanId == 0) {
            throw new RuntimeException(
                    "??repayPlanId=" + repayPlanId + "id?0");
        }
    }

    // ??
    Money availableBalance = null;

    YzzUserAccountQueryResponse accountResult = apiTool.queryUserAccount(repayUser.getAccountId());

    if (accountResult.success()) {
        availableBalance = new Money(accountResult.getAvailableBalance());
    } else {
        throw new Exception("??");
    }

    RepayPlanDO repayPlan = repayPlanDAO.findById(repayPlanId);

    if (StringUtil.equalsIgnoreCase("PS", repayPlan.getStatus())
            || StringUtil.equalsIgnoreCase("AS", repayPlan.getStatus())) {
        throw new Exception("?");
    }

    if (StringUtil.isBlank(repayPlan.getCreateRepayNo())) {
        // 
        RepayTradeOrder order = new RepayTradeOrder();
        order.setPayerUserId(repayUser.getAccountId());
        order.setTradeAmount(repayPlanInfo.getAmount());
        order.setTradeMemo(repayPlanInfo.getNote());
        order.setTradeName(repayPlanInfo.getTradeName() + "");
        RepayTradeResult result = repayService.createRepayTrade(order, this.getOpenApiContext());
        if (!result.isSuccess()) {
            return null;
        }

        repayPlan.setCreateRepayNo(result.getTradeNo());

        repayPlan.setStatus(RepayPlanStatusEnum.APPLY.getCode());
        try {
            repayPlanDAO.update(repayPlan);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    long repayAmount = 0;
    double repayCutAmount = 0;
    // ?
    double repayDivisionAmount = 0;
    // ??,??
    if (DivisionWayEnum.SIT_WAY.code().equals(loan.getRepayDivisionWay())) {
        // 
        long divisionTemplateLoanBaseId = loan.getDivisionTemplateId();
        DivisionTemplateLoanDO divisionTemplateLoan = divisionTemplateLoanService
                .getByBaseId(divisionTemplateLoanBaseId);
        List<DivsionRuleRole> repayRolelist = divisionService
                .getRuleRole(String.valueOf(divisionTemplateLoan.getRepayTemplateId()));
        double payInterest = 0;
        if (repayRolelist != null && repayRolelist.size() > 0) {
            for (DivsionRuleRole druleRole : repayRolelist) {
                if (DivisionPhaseEnum.REPAY_PHASE.code().equals(druleRole.getPhase())) {
                    BigDecimal bg = new BigDecimal(getDaysRuleRate(druleRole.getRule(), trade));
                    repayCutAmount += Math.round(
                            trade.getLoanedAmount() * bg.setScale(10, BigDecimal.ROUND_HALF_UP).doubleValue());
                    payInterest += bg.setScale(10, BigDecimal.ROUND_HALF_UP).doubleValue();

                    if (druleRole.getRoleId() != SysUserRoleEnum.INVESTOR.getValue()) {
                        repayDivisionAmount += Math.round(trade.getLoanedAmount()
                                * bg.setScale(10, BigDecimal.ROUND_HALF_UP).doubleValue());
                    }
                }
            }
        }
        repayAmount = trade.getLoanedAmount() + (long) repayCutAmount;
        if (availableBalance.getCent() < repayAmount) {
            logger.info("??---id" + repayUser.getUserId());
            return null;
        }
    }

    String repayYjfUserId = tradeDetailDao.getYjfUserNameByUserId(repayUserId);

    logger.info("repayUserId :" + repayUserId + " " + repayYjfUserId + " " + repayUser.getAccountId());

    long tradeId = trade.getId();

    RepayOrder repayOrder = new RepayOrder();

    // ??,??
    if (DivisionWayEnum.SIT_WAY.code().equals(loan.getRepayDivisionWay())) {

        // ?
        List<TransferTrade> investTradeList = transferTradeDao.getPhaseTransferTrades(tradeId,
                DivisionPhaseEnum.ORIGINAL_PHASE.code(), TradeDetailStatusEnum.PS.code(), //???
                new String[] { SysUserRoleEnum.INVESTOR.getRoleCode() });

        // ?
        List<TransferTrade> investDevisionList = transferTradeDao.getPhaseTransferTrades(tradeId,
                DivisionPhaseEnum.REPAY_PHASE.getCode(), null, //???
                new String[] { SysUserRoleEnum.INVESTOR.getRoleCode() });

        // 
        List<TransferTrade> divisionList = divisionService.queryRepayDivision(tradeId);

        List<RepaySubOrder> subOrders = new ArrayList<RepaySubOrder>();
        for (int i = 0; i < investTradeList.size(); i++) {
            TransferTrade tt = investTradeList.get(i);
            RepaySubOrder subOrder = new RepaySubOrder();
            Money transferAmount = Money.cent(tt.getAmount());

            TransferTrade td = this.getRepayDetail(investDevisionList, investTradeList.get(i));
            if (null == td) {
                transferAmount.addTo(Money.cent(0l));
            } else {
                transferAmount.addTo(Money.cent(td.getAmount()));
            }

            subOrder.setTransferAmount(transferAmount.toString());
            subOrder.setMemo("");
            subOrder.setOrderNo(BusinessNumberUtil.gainOutBizNoNumber());
            subOrder.setPayeeUserId(tt.getYjfUserName());
            subOrder.setTradeName("");
            subOrders.add(subOrder);
        }

        repayOrder.setPayerUserId(repayUser.getAccountId());
        repayOrder.setOrderNo(BusinessNumberUtil.gainOutBizNoNumber());
        repayOrder.setRefTradeNo(trade.getCode());
        //
        if (repayDivisionAmount > 0) {
            RepaySubOrder shardOrder = new RepaySubOrder();
            shardOrder.setMemo("");
            shardOrder.setOrderNo(BusinessNumberUtil.gainOutBizNoNumber());
            shardOrder.setPayeeUserId(Constants.EXCHANGE_ACCOUNT);
            shardOrder.setTradeName("");
            shardOrder.setTransferAmount(Money.cent((long) repayDivisionAmount).toString());
            repayOrder.setShardOrder(shardOrder);
        }
        repayOrder.setSubOrders(subOrders);
        repayOrder.setTradeNo(repayPlan.getCreateRepayNo());
    }
    //?
    repayPlan.setRepayNo(repayOrder.getOrderNo());
    repayPlan.setStatus(RepayPlanStatusEnum.APPLY.getCode());
    repayPlanDAO.update(repayPlan);

    return repayOrder;
}

From source file:org.adempiere.webui.apps.graph.WGraph.java

private void renderTable(Component parent) {
    Div div = new Div();
    appendChild(div);/*from w  w  w  .j a v  a 2 s  .  com*/
    div.setSclass("pa-content");
    parent.appendChild(div);

    Table table = new Table();
    table.setSclass("pa-dataGrid");
    div.appendChild(table);
    Tr tr = new Tr();
    table.appendChild(tr);
    Td td = new Td();
    td.setSclass("pa-label");
    tr.appendChild(td);
    Text text = new Text("Target");
    td.appendChild(text);
    td = new Td();
    td.setDynamicProperty("colspan", "2");
    td.setSclass("pa-tdcontent");
    tr.appendChild(td);
    text = new Text(
            builder.getMGoal().getMeasureTarget().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
    td.appendChild(text);

    tr = new Tr();
    table.appendChild(tr);
    td = new Td();
    td.setSclass("pa-label");
    tr.appendChild(td);
    text = new Text("Actual");
    td.appendChild(text);
    td = new Td();
    td.setDynamicProperty("colspan", "2");
    td.setSclass("pa-tdcontent");
    tr.appendChild(td);
    text = new Text(
            builder.getMGoal().getMeasureActual().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
    td.appendChild(text);

    GraphColumn[] bList = getGraphColumnList();

    tr = new Tr();
    table.appendChild(tr);
    td = new Td();
    tr.appendChild(td);
    td.setDynamicProperty("rowspan", bList.length);
    td.setSclass("pa-label");
    td.setDynamicProperty("valign", "top");
    text = new Text(builder.getMGoal().getXAxisText());
    td.appendChild(text);

    for (int k = 0; k < bList.length; k++) {
        GraphColumn bgc = bList[k];
        if (k > 0) {
            tr = new Tr();
            table.appendChild(tr);
        }

        td = new Td();
        td.setSclass("pa-tdlabel");
        tr.appendChild(td);
        text = new Text(bgc.getLabel());
        td.appendChild(text);
        td = new Td();
        td.setSclass("pa-tdvalue");
        tr.appendChild(td);
        BigDecimal value = new BigDecimal(bgc.getValue());
        if (bgc.getMQuery(builder.getMGoal()) != null) {
            A a = new A();
            a.setSclass("pa-hrefNode");
            td.appendChild(a);
            a.setId(ZOOM_KEY + k);
            a.addEventListener(Events.ON_CLICK, new EventListener() {
                public void onEvent(Event event) throws Exception {
                    Component comp = event.getTarget();
                    String id = comp.getId();
                    if (id.startsWith(ZOOM_KEY)) {
                        String ss = id.substring(ZOOM_KEY.length());
                        int index = Integer.parseInt(String.valueOf(ss));
                        GraphColumn[] colList = getGraphColumnList();
                        if ((index >= 0) && (index < colList.length))
                            AEnv.zoom(colList[index].getMQuery(builder.getMGoal()));
                    }
                }

            });
            a.setDynamicProperty("href", "javascript:;");
            text = new Text(value.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
            a.appendChild(text);

        } else {
            text = new Text(value.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString());
        }
    }
    tr = new Tr();
    table.appendChild(tr);
    td = new Td();
    td.setDynamicProperty("colspan", "3");
    tr.appendChild(td);
    text = new Text(builder.getMGoal().getDescription());
    td.appendChild(text);
    Br br = new Br();
    td.appendChild(br);
    text = new Text(stripHtml(builder.getMGoal().getColorSchema().getDescription(), true));
    td.appendChild(text);
}

From source file:Armadillo.Analytics.Base.Precision.java

/**
 * Rounds the given value to the specified number of decimal places.
 * The value is rounded using the {@link BigDecimal#ROUND_HALF_UP} method.
 *
 * @param x Value to round.//  w w  w  .  jav  a2 s  . co m
 * @param scale Number of digits to the right of the decimal point.
 * @return the rounded value.
 * @since 1.1 (previously in {@code MathUtils}, moved as of version 3.0)
 */
public static float round(float x, int scale) {
    return round(x, scale, BigDecimal.ROUND_HALF_UP);
}

From source file:hr.diskobolos.service.impl.EvaluationAnswerServiceImpl.java

private Float getQuestionnairePercentage(List<EvaluationAnswer> evaluationAnswers, Long numberOfQuestion,
        List<EvaluationQuestionnaireDefEnum> questionnaireDef) {
    Long numberOfAnsweredQuestions = evaluationAnswers.stream()
            .filter(e -> questionnaireDef.contains(e.getAnswer().getEvaluationQuestionDef().getQuestion()))
            .collect(Collectors.counting());
    Float questionnairePercentage = ((float) numberOfAnsweredQuestions / numberOfQuestion) * 100;
    return new BigDecimal(Float.toString(questionnairePercentage)).setScale(2, BigDecimal.ROUND_HALF_UP)
            .floatValue();//from   w w w  .j a v a2s  .  c  o  m
}

From source file:com.salesmanager.core.util.ProductUtil.java

public static String formatHTMLProductPrice(Locale locale, String currency, Product view,
        boolean showDiscountDate, boolean shortDiscountFormat) {

    if (currency == null) {
        log.error("Currency is null ...");
        return "-N/A-";
    }//from   w w  w  . ja  va 2 s  . co  m

    int decimalPlace = 2;

    String prefix = "";
    String suffix = "";

    Map currenciesmap = RefCache.getCurrenciesListWithCodes();
    Currency c = (Currency) currenciesmap.get(currency);

    // regular price
    BigDecimal bdprodprice = view.getProductPrice();

    Date dt = new Date();

    // discount price
    java.util.Date spdate = null;
    java.util.Date spenddate = null;
    BigDecimal bddiscountprice = null;
    Special special = view.getSpecial();
    if (special != null) {
        spdate = special.getSpecialDateAvailable();
        spenddate = special.getExpiresDate();
        if (spdate.before(new Date(dt.getTime())) && spenddate.after(new Date(dt.getTime()))) {
            bddiscountprice = special.getSpecialNewProductPrice();
        }
    }

    // all other prices
    Set prices = view.getPrices();
    if (prices != null) {
        Iterator pit = prices.iterator();
        while (pit.hasNext()) {
            ProductPrice pprice = (ProductPrice) pit.next();
            if (pprice.isDefaultPrice()) {
                pprice.setLocale(locale);
                suffix = pprice.getPriceSuffix();
                bddiscountprice = null;
                spdate = null;
                spenddate = null;
                bdprodprice = pprice.getProductPriceAmount();
                ProductPriceSpecial ppspecial = pprice.getSpecial();
                if (ppspecial != null) {
                    if (ppspecial.getProductPriceSpecialStartDate() != null
                            && ppspecial.getProductPriceSpecialEndDate() != null) {
                        spdate = ppspecial.getProductPriceSpecialStartDate();
                        spenddate = ppspecial.getProductPriceSpecialEndDate();
                    }
                    bddiscountprice = ppspecial.getProductPriceSpecialAmount();
                }
                break;
            }
        }
    }

    double fprodprice = 0;
    ;
    if (bdprodprice != null) {
        fprodprice = bdprodprice.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP).doubleValue();
    }

    // regular price String
    String regularprice = CurrencyUtil.displayFormatedCssAmountWithCurrency(bdprodprice, currency);

    // discount price String
    String discountprice = null;
    String savediscount = null;

    if (bddiscountprice != null && (spdate != null && spdate.before(new Date(dt.getTime()))
            && spenddate.after(new Date(dt.getTime())))) {

        double fdiscountprice = bddiscountprice.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP).doubleValue();

        discountprice = CurrencyUtil.displayFormatedAmountWithCurrency(bddiscountprice, currency);

        double arith = fdiscountprice / fprodprice;
        double fsdiscount = 100 - arith * 100;

        Float percentagediscount = new Float(fsdiscount);

        savediscount = String.valueOf(percentagediscount.intValue());

    }

    StringBuffer p = new StringBuffer();
    p.append("<div class='product-price'>");
    if (discountprice == null) {
        p.append("<div class='product-price-price' style='width:50%;float:left;'>");
        p.append(regularprice);
        if (!StringUtils.isBlank(suffix)) {
            p.append(suffix).append(" ");
        }
        p.append("</div>");
        p.append("<div class='product-line'>&nbsp;</div>");
    } else {
        p.append("<div style='width:50%;float:left;'>");
        p.append("<strike>").append(regularprice);
        if (!StringUtils.isBlank(suffix)) {
            p.append(suffix).append(" ");
        }
        p.append("</strike>");
        p.append("</div>");
        p.append("<div style='width:50%;float:right;'>");
        p.append("<font color='red'>").append(discountprice);
        if (!StringUtils.isBlank(suffix)) {
            p.append(suffix).append(" ");
        }
        p.append("</font>");
        if (!shortDiscountFormat) {
            p.append("<br>").append("<font color='red' style='font-size:75%;'>")
                    .append(LabelUtil.getInstance().getText(locale, "label.generic.save")).append(": ")
                    .append(savediscount)
                    .append(LabelUtil.getInstance().getText(locale, "label.generic.percentsign")).append(" ")
                    .append(LabelUtil.getInstance().getText(locale, "label.generic.off")).append("</font>");
        }

        if (showDiscountDate && spenddate != null) {
            p.append("<br>").append(" <font style='font-size:65%;'>")
                    .append(LabelUtil.getInstance().getText(locale, "label.generic.until")).append("&nbsp;")
                    .append(DateUtil.formatDate(spenddate)).append("</font>");
        }

        p.append("</div>").toString();
    }
    p.append("</div>");
    return p.toString();

}