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.github.totyumengr.minicubes.core.MiniCubeTest.java

@Test
public void test_6_1_merge() {

    FactTableBuilder builder = new FactTableBuilder().build("MiniCubeTest-merge")
            .addDimColumns(Arrays.asList(new String[] { "the_date", "tradeId", "productLineId", "postId" }))
            .addIndColumns(Arrays.asList(new String[] { "csm", "cash", "click", "shw" }));

    builder.addDimDatas(Integer.MAX_VALUE, Arrays.asList(new Integer[] { 20140607, 1, 1, 1 }));
    builder.addIndDatas(Integer.MAX_VALUE, Arrays.asList(new DoubleDouble[] { new DoubleDouble(123.123),
            new DoubleDouble(124.124), new DoubleDouble(123), new DoubleDouble(124) }));
    FactTable merge = builder.done();/*from ww w  . jav a2  s .c  o m*/
    // Do merge
    BigDecimal original = miniCube.sum("csm");
    miniCube.merge(new MiniCube(merge));

    Assert.assertEquals(
            original.add(new BigDecimal(123.123).setScale(Aggregations.IND_SCALE, BigDecimal.ROUND_HALF_UP)),
            miniCube.sum("csm"));

    Map<String, List<Integer>> filter = new HashMap<String, List<Integer>>(1);
    filter.put("the_date", Arrays.asList(new Integer[] { 20140606 }));
    miniCube.setParallelMode(false);
    Assert.assertEquals("138240687.91500000", miniCube.sum("csm", filter).toString());
}

From source file:org.efaps.esjp.accounting.transaction.TransInfo_Base.java

/**
 * Checks if is valid.//from  w  w  w .j a va 2  s.  c  o  m
 *
 * @return true, if is valid
 */
private boolean isValid() {
    BigDecimal amount = BigDecimal.ZERO;
    for (final PositionInfo pos : this.positions) {
        amount = amount.add(pos.getAmount().setScale(2, BigDecimal.ROUND_HALF_UP));
    }
    return amount.compareTo(BigDecimal.ZERO) == 0;
}

From source file:org.egov.ptis.service.es.CollectionIndexElasticSearchService.java

/**
 * Gives the consolidated collection for the dates and billing service
 * //from ww  w.  j av  a2  s. co m
 * @param fromDate
 * @param toDate
 * @param billingService
 * @return BigDecimal
 */
public BigDecimal getConsolidatedCollForYears(Date fromDate, Date toDate, String billingService) {
    BoolQueryBuilder boolQuery = QueryBuilders.boolQuery()
            .must(QueryBuilders.rangeQuery(RECEIPT_DATE).gte(DATEFORMATTER_YYYY_MM_DD.format(fromDate))
                    .lte(DATEFORMATTER_YYYY_MM_DD.format(toDate)).includeUpper(false))
            .mustNot(QueryBuilders.matchQuery(STATUS, CANCELLED));

    if (COLLECION_BILLING_SERVICE_WTMS.equalsIgnoreCase(billingService))
        boolQuery = boolQuery.must(QueryBuilders.matchQuery(BILLING_SERVICE, billingService));
    else
        boolQuery = boolQuery.must(QueryBuilders.boolQuery().filter(QueryBuilders.termsQuery(BILLING_SERVICE,
                Arrays.asList(COLLECION_BILLING_SERVICE_PT, COLLECION_BILLING_SERVICE_VLT))));

    SearchQuery searchQueryColl = new NativeSearchQueryBuilder().withIndices(COLLECTION_INDEX_NAME)
            .withQuery(boolQuery).addAggregation(AggregationBuilders.sum(COLLECTIONTOTAL).field(TOTAL_AMOUNT))
            .build();

    Aggregations collAggr = elasticsearchTemplate.query(searchQueryColl, new ResultsExtractor<Aggregations>() {
        @Override
        public Aggregations extract(SearchResponse response) {
            return response.getAggregations();
        }
    });

    Sum aggr = collAggr.get(COLLECTIONTOTAL);
    return BigDecimal.valueOf(aggr.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP);
}

From source file:org.egov.adtax.service.AdvertisementPermitDetailService.java

private void roundOfAllTaxAmount(final AdvertisementPermitDetail advertisementPermitDetail) {
    if (advertisementPermitDetail.getEncroachmentFee() != null)
        advertisementPermitDetail.setEncroachmentFee(
                advertisementPermitDetail.getEncroachmentFee().setScale(2, BigDecimal.ROUND_HALF_UP));

    if (advertisementPermitDetail.getTaxAmount() != null)
        advertisementPermitDetail//from  w w w. j a  va  2 s  . com
                .setTaxAmount(advertisementPermitDetail.getTaxAmount().setScale(2, BigDecimal.ROUND_HALF_UP));

    if (advertisementPermitDetail.getAdvertisement().getPendingTax() != null)
        advertisementPermitDetail.getAdvertisement().setPendingTax(advertisementPermitDetail.getAdvertisement()
                .getPendingTax().setScale(2, BigDecimal.ROUND_HALF_UP));
}

From source file:org.kuali.kfs.fp.document.service.impl.BudgetAdjustmentLaborBenefitsServiceImpl.java

/**
 * Given a budget adjustment accounting line, generates appropriate fringe benefit lines for the line
 *
 * @param line a line to generate fringe benefit lines for
 * @return a List of BudgetAdjustmentAccountingLines to add to the document as fringe benefit lines
 *//*www.  j  a  va  2 s.c  o  m*/
protected List<BudgetAdjustmentAccountingLine> generateBenefitLines(Integer fiscalYear,
        BudgetAdjustmentAccountingLine line, BudgetAdjustmentDocument document) {
    List<BudgetAdjustmentAccountingLine> fringeLines = new ArrayList<BudgetAdjustmentAccountingLine>();
    try {
        Collection<LaborLedgerPositionObjectBenefit> objectBenefits = SpringContext
                .getBean(LaborModuleService.class).retrieveActiveLaborPositionObjectBenefits(fiscalYear,
                        line.getChartOfAccountsCode(), line.getFinancialObjectCode());
        if (objectBenefits != null) {
            for (LaborLedgerPositionObjectBenefit fringeBenefitInformation : objectBenefits) {
                // now create and set properties for the benefit line
                BudgetAdjustmentAccountingLine benefitLine = null;
                if (line.isSourceAccountingLine()) {
                    benefitLine = (BudgetAdjustmentAccountingLine) document.getSourceAccountingLineClass()
                            .newInstance();
                } else {
                    benefitLine = (BudgetAdjustmentAccountingLine) document.getTargetAccountingLineClass()
                            .newInstance();
                }

                // create a map to use in the lookup of the account
                Map<String, Object> fieldValues = new HashMap<String, Object>();
                fieldValues.put("chartOfAccountsCode", line.getChartOfAccountsCode());
                fieldValues.put("accountNumber", line.getAccountNumber());
                // use the budget adjustment accounting line to get the account number that will then be used to lookup the
                // labor benefit rate category code
                Account lookupAccount = businessObjectService.findByPrimaryKey(Account.class, fieldValues);
                LaborLedgerBenefitsCalculation benefitsCalculation = null;
                String laborBenefitsRateCategoryCode = "";
                // make sure the parameter exists
                if (SpringContext.getBean(ParameterService.class).parameterExists(Account.class,
                        KFSParameterKeyConstants.LdParameterConstants.DEFAULT_BENEFIT_RATE_CATEGORY_CODE)) {
                    laborBenefitsRateCategoryCode = SpringContext.getBean(ParameterService.class)
                            .getParameterValueAsString(Account.class,
                                    KFSParameterKeyConstants.LdParameterConstants.DEFAULT_BENEFIT_RATE_CATEGORY_CODE);
                } else {
                    laborBenefitsRateCategoryCode = "";
                }
                // make sure the system parameter exists
                if (SpringContext.getBean(ParameterService.class).parameterExists(
                        KfsParameterConstants.FINANCIAL_SYSTEM_ALL.class,
                        KFSParameterKeyConstants.LdParameterConstants.ENABLE_FRINGE_BENEFIT_CALC_BY_BENEFIT_RATE_CATEGORY_IND)) {
                    // check the system param to see if the labor benefit rate category should be filled in
                    String sysParam = SpringContext.getBean(ParameterService.class).getParameterValueAsString(
                            KfsParameterConstants.FINANCIAL_SYSTEM_ALL.class,
                            KFSParameterKeyConstants.LdParameterConstants.ENABLE_FRINGE_BENEFIT_CALC_BY_BENEFIT_RATE_CATEGORY_IND);
                    LOG.debug("sysParam: " + sysParam);
                    // if sysParam == Y then Labor Benefit Rate Category should be used in the search
                    if (sysParam.equalsIgnoreCase("Y")) {

                        if (StringUtils.isBlank(line.getSubAccount().getSubAccountNumber())) {
                            laborBenefitsRateCategoryCode = lookupAccount.getLaborBenefitRateCategoryCode();
                        } else {
                            laborBenefitsRateCategoryCode = SpringContext.getBean(LaborModuleService.class)
                                    .getBenefitRateCategoryCode(line.getChartOfAccountsCode(),
                                            line.getAccountNumber(),
                                            line.getSubAccount().getSubAccountNumber());
                        }

                        // make sure laborBenefitsRateCategoryCode isn't null
                        if (ObjectUtils.isNull(laborBenefitsRateCategoryCode)) {
                            // make sure the parameter exists
                            if (SpringContext.getBean(ParameterService.class).parameterExists(Account.class,
                                    KFSParameterKeyConstants.LdParameterConstants.DEFAULT_BENEFIT_RATE_CATEGORY_CODE)) {
                                laborBenefitsRateCategoryCode = SpringContext.getBean(ParameterService.class)
                                        .getParameterValueAsString(Account.class,
                                                KFSParameterKeyConstants.LdParameterConstants.DEFAULT_BENEFIT_RATE_CATEGORY_CODE);
                            } else {
                                laborBenefitsRateCategoryCode = "";
                            }
                        }

                    }
                }

                String beneCalc = "{" + fringeBenefitInformation.getUniversityFiscalYear() + ","
                        + fringeBenefitInformation.getChartOfAccountsCode() + ","
                        + fringeBenefitInformation.getFinancialObjectBenefitsTypeCode() + ","
                        + laborBenefitsRateCategoryCode + "}";
                LOG.info("Looking for a benefits calculation for " + beneCalc);
                // get the benefits calculation taking the laborBenefitRateCategoryCode into account
                benefitsCalculation = fringeBenefitInformation
                        .getLaborLedgerBenefitsCalculation(laborBenefitsRateCategoryCode);

                if (benefitsCalculation != null) {
                    LOG.info("Found benefits calculation for " + beneCalc);
                } else {
                    LOG.info("Couldn't locate a benefits calculation for " + beneCalc);
                }
                if ((benefitsCalculation != null) && benefitsCalculation.isActive()) {
                    benefitLine.copyFrom(line);
                    benefitLine
                            .setFinancialObjectCode(benefitsCalculation.getPositionFringeBenefitObjectCode());
                    benefitLine.refreshNonUpdateableReferences();
                    LaborModuleService laborModuleService = SpringContext.getBean(LaborModuleService.class);
                    if (ObjectUtils.isNotNull(laborModuleService.getCostSharingSourceAccountNumber())) {
                        benefitLine.setAccountNumber(laborModuleService.getCostSharingSourceAccountNumber());
                        benefitLine
                                .setSubAccountNumber(laborModuleService.getCostSharingSourceSubAccountNumber());
                        benefitLine.setChartOfAccountsCode(
                                laborModuleService.getCostSharingSourceChartOfAccountsCode());
                    }

                    benefitLine.refreshNonUpdateableReferences();

                    // convert whole percentage to decimal value (5% to .0500, 18.66% to 0.1866)
                    BigDecimal fringeBenefitPercent = formatPercentageForMultiplication(
                            benefitsCalculation.getPositionFringeBenefitPercent());
                    // compute the benefit current amount with all decimals and then round it to the closest integer by setting the
                    // scale to 0 and using the round half up rounding mode: exp. 1200*0.1866 = 223.92 -> rounded to 224
                    BigDecimal benefitCurrentAmount = line.getCurrentBudgetAdjustmentAmount().bigDecimalValue()
                            .multiply(fringeBenefitPercent);
                    benefitCurrentAmount = benefitCurrentAmount.setScale(2, BigDecimal.ROUND_HALF_UP);
                    benefitLine.setCurrentBudgetAdjustmentAmount(new KualiDecimal(benefitCurrentAmount));

                    KualiInteger benefitBaseAmount = line.getBaseBudgetAdjustmentAmount()
                            .multiply(fringeBenefitPercent);
                    benefitLine.setBaseBudgetAdjustmentAmount(benefitBaseAmount);

                    // clear monthly lines per KULEDOCS-1606
                    benefitLine.clearFinancialDocumentMonthLineAmounts();

                    // set flag on line so we know it was a generated benefit line and can clear it out later if needed
                    benefitLine.setFringeBenefitIndicator(true);

                    fringeLines.add(benefitLine);
                }
            }
        }
    } catch (InstantiationException ie) {
        // it's doubtful this catch block or the catch block below are ever accessible, as accounting lines should already have
        // been generated
        // for the document. But we can still make it somebody else's problem
        throw new RuntimeException(ie);
    } catch (IllegalAccessException iae) {
        // with some luck we'll pass the buck now sez some other dev "This sucks!" Get your Runtime on!
        // but really...we'll never make it this far. I promise.
        throw new RuntimeException(iae);
    }

    return fringeLines;
}

From source file:model.experiments.tuningRuns.CompetitiveAveragingGridSearch.java

/**
 * Round to certain number of decimals// w w  w .j ava 2 s .  c  om
 *
 * @param d
 * @param decimalPlace
 * @return
 */
public static float round(float d, int decimalPlace) {
    BigDecimal bd = new BigDecimal(Float.toString(d));
    bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
    return bd.floatValue();
}

From source file:org.egov.wtms.service.es.WaterChargeCollectionDocService.java

/**
 * Returns total demand from WaterCharge index, based on input filters
 *
 * @param collectionDetailsRequest//from ww  w .  j av  a2  s . c o m
 * @return
 */
public BigDecimal getTotalDemandBasedOnInputFilters(
        final WaterChargeDashBoardRequest collectionDetailsRequest) {
    final BoolQueryBuilder boolQuery = prepareWhereClause(collectionDetailsRequest, null);
    final SearchQuery searchQueryColl = new NativeSearchQueryBuilder()
            .withIndices(WaterTaxConstants.WATER_TAX_INDEX_NAME).withQuery(boolQuery)
            .addAggregation(AggregationBuilders.sum(WaterTaxConstants.WATERCHARGETOTALDEMAND)
                    .field(WaterTaxConstants.WATERCHARGETOTALDEMAND))
            .build();

    final Aggregations collAggr = elasticsearchTemplate.query(searchQueryColl,
            response -> response.getAggregations());

    final Sum aggr = collAggr.get(WaterTaxConstants.WATERCHARGETOTALDEMAND);
    return BigDecimal.valueOf(aggr.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP);
}

From source file:com.salesmanager.core.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 {

    if (StringUtils.isBlank(delivery.getPostalCode())) {
        return null;
    }//from www.  j a  v a2  s.c o 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();
    PostMethod 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());

        String data = "";

        HttpClient client = new HttpClient();
        httppost = new PostMethod(protocol + "://" + host + ":" + port + url);
        RequestEntity entity = new StringRequestEntity(xmlbuffer.toString(), "text/plain", "UTF-8");
        httppost.setRequestEntity(entity);

        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);
        }
        data = httppost.getResponseBodyAsString();
        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:org.devgateway.ocds.web.rest.controller.CorruptionRiskDashboardIndicatorsStatsController.java

@ApiOperation(value = "Percent of total projects flagged (denominator is total projects)")
@RequestMapping(value = "/api/percentTotalProjectsFlaggedByYear", method = { RequestMethod.POST,
        RequestMethod.GET }, produces = "application/json")
public List<DBObject> percentTotalProjectsFlaggedByYear(final YearFilterPagingRequest filter) {

    //get the total projects flagged by year
    List<DBObject> totalFlaggedProjects = totalFlaggedProjectsByIndicatorTypeByYear(filter);

    //denominator total projects eligible by year
    List<DBObject> totalProjectsByYear = totalProjectsByYear(filter);

    totalFlaggedProjects.forEach(e -> {
        findByYearAndTypeAndMonth(totalProjectsByYear, (Integer) e.get(Keys.YEAR), null,
                (Integer) e.get(Keys.MONTH)).forEach(f -> {
                    e.put(Keys.PROJECT_COUNT, f.get(Keys.PROJECT_COUNT));
                    e.put(Keys.PERCENT,/*from  w  ww  .j  a  v  a  2s  .  c om*/
                            (BigDecimal.valueOf((Integer) e.get(Keys.FLAGGED_PROJECT_COUNT))
                                    .setScale(BIGDECIMAL_SCALE)
                                    .divide(BigDecimal.valueOf((Integer) f.get(Keys.PROJECT_COUNT)),
                                            BigDecimal.ROUND_HALF_UP)
                                    .multiply(ONE_HUNDRED)));
                });
    });

    return totalFlaggedProjects;
}

From source file:org.egov.adtax.service.AdvertisementDemandService.java

/**
 * @param demand//from w  ww .  ja va 2  s.  co m
 * @param penaltyCalculationDate
 * @return Penalty Amount and PendingAmount
 */
public Map<String, BigDecimal> checkPedingAmountByDemand(final AdvertisementPermitDetail advPermitDetail) {

    final Map<String, BigDecimal> demandFeeType = new LinkedHashMap<>();

    BigDecimal penaltyAmt = BigDecimal.ZERO;
    BigDecimal pendingAmount = BigDecimal.ZERO;
    BigDecimal additionalTaxAmount = BigDecimal.ZERO;
    /**
     * Assumption: We are calculating penalty for total pending amount. If penalty is part of demand, then also we are
     * considering that amount for penalty calculation.
     */
    if (advPermitDetail != null && advPermitDetail.getAdvertisement() != null
            && advPermitDetail.getAdvertisement().getDemandId() != null) {
        for (final EgDemandDetails demandDtl : advPermitDetail.getAdvertisement().getDemandId()
                .getEgDemandDetails())
            if (demandDtl.getAmount().subtract(demandDtl.getAmtCollected()).compareTo(BigDecimal.ZERO) > 0)
                pendingAmount = pendingAmount.add(demandDtl.getAmount().subtract(demandDtl.getAmtCollected()));
        penaltyAmt = advertisementPenaltyCalculator.calculatePenalty(advPermitDetail);
        additionalTaxAmount = advertisementAdditionalTaxCalculator
                .getTotalAdditionalTaxesByPassingAdvertisementPermit(advPermitDetail);
    }
    demandFeeType.put(AdvertisementTaxConstants.PENALTYAMOUNT,
            penaltyAmt.setScale(0, BigDecimal.ROUND_HALF_UP));
    demandFeeType.put(AdvertisementTaxConstants.ADDITIONALTAXAMOUNT,
            additionalTaxAmount.setScale(0, BigDecimal.ROUND_HALF_UP));
    demandFeeType.put(AdvertisementTaxConstants.PENDINGDEMANDAMOUNT,
            pendingAmount.setScale(0, BigDecimal.ROUND_HALF_UP));

    return demandFeeType;

}