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:org.egov.ptis.client.util.PropertyTaxUtil.java

/**
 * API returns the percentage of tax difference between GIS survey tax and application tax Current second half taxes, exluding
 * UAC penalty will be considered for the comparison
 * @param propertyImpl/*from  www. j a v a 2  s .c o m*/
 * @return BigDecimal
 */
public BigDecimal getTaxDifferenceForGIS(PropertyImpl propertyImpl) {
    BigDecimal taxDiffPerc = BigDecimal.ZERO;
    BigDecimal gisHalfYrTax = BigDecimal.ZERO;
    BigDecimal applHalfYrTax = BigDecimal.ZERO;
    Map<String, Installment> currYearInstMap = getInstallmentsForCurrYear(new Date());
    PropertyImpl gisProperty = (PropertyImpl) propertyDAO
            .getLatestGISPropertyForBasicProperty(propertyImpl.getBasicProperty());
    if (gisProperty != null) {
        Ptdemand gisPtdemand = gisProperty.getPtDemandSet().iterator().next();
        if (gisPtdemand != null) {
            for (EgDemandDetails demandDetails : gisPtdemand.getEgDemandDetails()) {
                if (gisPtdemand.getEgInstallmentMaster().getFromDate()
                        .equals(demandDetails.getInstallmentStartDate())
                        && !PropertyTaxConstants.DEMANDRSN_CODE_UNAUTHORIZED_PENALTY.equalsIgnoreCase(
                                demandDetails.getEgDemandReason().getEgDemandReasonMaster().getCode()))
                    gisHalfYrTax = gisHalfYrTax.add(demandDetails.getAmount());
            }
        }
    }
    Ptdemand ptdemand = propertyImpl.getPtDemandSet().iterator().next();
    if (ptdemand != null) {
        for (EgDemandDetails demandDetails : ptdemand.getEgDemandDetails()) {
            if (currYearInstMap.get(CURRENTYEAR_SECOND_HALF).getFromDate()
                    .equals(demandDetails.getInstallmentStartDate())
                    && !PropertyTaxConstants.DEMANDRSN_CODE_UNAUTHORIZED_PENALTY.equalsIgnoreCase(
                            demandDetails.getEgDemandReason().getEgDemandReasonMaster().getCode()))
                applHalfYrTax = applHalfYrTax.add(demandDetails.getAmount());
        }
    }
    if (gisHalfYrTax.compareTo(BigDecimal.ZERO) > 0)
        taxDiffPerc = ((gisHalfYrTax.subtract(applHalfYrTax)).multiply(BIGDECIMAL_100)).divide(gisHalfYrTax,
                BigDecimal.ROUND_HALF_UP);

    if (gisProperty != null)
        gisProperty.setSurveyVariance(taxDiffPerc);
    return taxDiffPerc;
}

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

private void prepareReceiptDetailListFromMap(final WaterChargeDashBoardRequest collectionDetailsRequest,
        final List<WaterChargeDashBoardResponse> receiptDataList, final String aggregationField,
        final Map<String, BigDecimal> currDayCollMap, final Map<String, BigDecimal> lytdCollMap,
        final Map.Entry<String, BigDecimal> entry) {
    String name;/*  w ww.  j a  va2 s.  c  om*/
    BigDecimal variance;
    final WaterChargeDashBoardResponse receiptData = new WaterChargeDashBoardResponse();
    name = entry.getKey();
    if (WaterTaxConstants.REGIONNAMEAGGREGATIONFIELD.equals(aggregationField))
        receiptData.setRegionName(name);
    else if (WaterTaxConstants.DISTRICTNAMEAGGREGATIONFIELD.equals(aggregationField)) {
        receiptData.setRegionName(collectionDetailsRequest.getRegionName());
        receiptData.setDistrictName(name);
    } else if (WaterTaxConstants.CITYNAMEAGGREGATIONFIELD.equals(aggregationField)) {
        receiptData.setUlbName(name);
        receiptData.setDistrictName(collectionDetailsRequest.getDistrictName());
        receiptData.setUlbGrade(collectionDetailsRequest.getUlbGrade());
    } else if (WaterTaxConstants.CITYGRADEAGGREGATIONFIELD.equals(aggregationField))
        receiptData.setUlbGrade(name);
    else if (WaterTaxConstants.REVENUEWARDAGGREGATIONFIELD.equals(aggregationField))
        receiptData.setWardName(name);

    receiptData.setCurrentYearTillDateColl(entry.getValue());
    receiptData.setCurrDayColl(
            currDayCollMap.get(name) == null ? BigDecimal.valueOf(0) : currDayCollMap.get(name));
    receiptData.setLastYearTillDateColl(
            lytdCollMap.get(name) == null ? BigDecimal.valueOf(0) : lytdCollMap.get(name));
    if (receiptData.getLastYearTillDateColl().compareTo(BigDecimal.ZERO) == 0)
        variance = WaterTaxConstants.BIGDECIMAL_100;
    else
        variance = receiptData.getCurrentYearTillDateColl().subtract(receiptData.getLastYearTillDateColl())
                .multiply(WaterTaxConstants.BIGDECIMAL_100)
                .divide(receiptData.getLastYearTillDateColl(), 1, BigDecimal.ROUND_HALF_UP);
    receiptData.setLastYearVar(variance);
    receiptDataList.add(receiptData);
}

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

public Map<String, BigDecimal> getCollectionAndDemandCountResults(
        final WaterChargeDashBoardRequest collectionDetailsRequest, final Date fromDate, final Date toDate,
        final String indexName, final String fieldName, final String aggregationField) {
    BoolQueryBuilder boolQuery = prepareWhereClause(collectionDetailsRequest, indexName);
    if (indexName.equals(WaterTaxConstants.COLLECTION_INDEX_NAME))
        boolQuery = boolQuery/*from  ww  w  .  ja  va 2s  .com*/
                .filter(QueryBuilders.rangeQuery(RECEIPT_DATEINDEX)
                        .gte(WaterTaxConstants.DATEFORMATTER_YYYY_MM_DD.format(fromDate))
                        .lte(WaterTaxConstants.DATEFORMATTER_YYYY_MM_DD.format(toDate)).includeUpper(false))
                .mustNot(QueryBuilders.matchQuery(STATUS, CANCELLED));

    final AggregationBuilder aggregation = AggregationBuilders.terms(BY_CITY).field(aggregationField).size(120)
            .subAggregation(AggregationBuilders.count("total_count").field(fieldName));

    final SearchQuery searchQueryColl = new NativeSearchQueryBuilder().withIndices(indexName)
            .withQuery(boolQuery).addAggregation(aggregation).build();

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

    final StringTerms cityAggr = collAggr.get(BY_CITY);
    final Map<String, BigDecimal> cytdCollMap = new HashMap<>();
    for (final Terms.Bucket entry : cityAggr.getBuckets()) {
        final ValueCount aggr = entry.getAggregations().get("total_count");
        cytdCollMap.put(String.valueOf(entry.getKey()),
                BigDecimal.valueOf(aggr.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
    }
    return cytdCollMap;
}

From source file:com.lp.server.fertigung.ejbfac.FertigungFacBean.java

public LossollmaterialDto updateLossollmaterial(LossollmaterialDto lossollmaterialDto,
        TheClientDto theClientDto) throws EJBExceptionLP {
    Integer iId = lossollmaterialDto.getIId();
    LosDto losDto = losFindByPrimaryKey(lossollmaterialDto.getLosIId());
    if (losDto.getStatusCNr().equals(FertigungFac.STATUS_ERLEDIGT)) {
        throw new EJBExceptionLP(EJBExceptionLP.FEHLER_FERTIGUNG_DAS_LOS_IST_BEREITS_ERLEDIGT, "");
    }//from w  w  w .  ja  v a  2s .c om
    if (losDto.getStatusCNr().equals(FertigungFac.STATUS_STORNIERT)) {
        throw new EJBExceptionLP(EJBExceptionLP.FEHLER_FERTIGUNG_DAS_LOS_IST_STORNIERT, "");
    }
    try {
        Lossollmaterial lossollmaterial = em.find(Lossollmaterial.class, iId);

        if (!lossollmaterial.getArtikelIId().equals(lossollmaterialDto.getArtikelIId())) {
            // Wenn Update auf Artikel, dann Position loeschen und neu
            // anlegen
            removeLossollmaterial(lossollmaterialDto, theClientDto);

            lossollmaterialDto = createLossollmaterial(lossollmaterialDto, theClientDto);

            lossollmaterial = em.find(Lossollmaterial.class, lossollmaterialDto.getIId());

        }

        if (lossollmaterial == null) {
            throw new EJBExceptionLP(EJBExceptionLP.FEHLER_BEIM_UPDATE, "");
        }

        if (getMandantFac().hatZusatzfunktionberechtigung(MandantFac.ZUSATZFUNKTION_GERAETESERIENNUMMERN,
                theClientDto)) {
            if (losDto.getStuecklisteIId() != null) {

                // PJ 16622

                Artikel artikel = em.find(Artikel.class, lossollmaterialDto.getArtikelIId());
                if (Helper.short2boolean(artikel.getBSeriennrtragend())) {

                    BigDecimal ssg = lossollmaterialDto.getNMenge().divide(losDto.getNLosgroesse(), 4,
                            BigDecimal.ROUND_HALF_UP);

                    if (ssg.doubleValue() != 1) {
                        throw new EJBExceptionLP(
                                EJBExceptionLP.FEHLER_POSITIONSMENGE_EINES_SNR_ARTIKELS_MUSS_1_SEIN_WENN_GERAETESNR,
                                new Exception(
                                        "FEHLER_POSITIONSMENGE_EINES_SNR_ARTIKELS_MUSS_1_SEIN_WENN_GERAETESNR"));

                    }

                }

            }
        }
        lossollmaterialDto.setTAendern(new Timestamp(System.currentTimeMillis()));
        lossollmaterialDto.setPersonalIIdAendern(theClientDto.getIDPersonal());
        setLossollmaterialFromLossollmaterialDto(lossollmaterial, lossollmaterialDto, theClientDto);
        // angelegt -> reservierung updaten
        if (losDto.getStatusCNr().equals(FertigungFac.STATUS_ANGELEGT)) {
            ArtikelDto artikelDto = getArtikelFac().artikelFindByPrimaryKey(lossollmaterial.getArtikelIId(),
                    theClientDto);
            java.sql.Date dTermin;
            if (lossollmaterial.getNMenge().compareTo(new BigDecimal(0)) > 0) {
                // Positive Reservierung: produktionsstart
                dTermin = losDto.getTProduktionsbeginn();
            } else {
                // Negative Reservierung: produktionsende
                dTermin = losDto.getTProduktionsende();
            }
            updateReservierung(artikelDto, lossollmaterialDto.getIId(), lossollmaterialDto.getNMenge(),
                    new java.sql.Timestamp(dTermin.getTime()));
        }
        // ausgegeben -> fehlmenge aktualisieren
        else {
            getFehlmengeFac().aktualisiereFehlmenge(LocaleFac.BELEGART_LOS, lossollmaterialDto.getIId(), false,
                    theClientDto);
        }
        return lossollmaterialDto;
        // }
        // catch (FinderException ex) {
        // throw new EJBExceptionLP(EJBExceptionLP.FEHLER_BEIM_UPDATE, ex);
    } catch (RemoteException ex) {
        throwEJBExceptionLPRespectOld(ex);
        return null;
    }
}

From source file:org.apache.ofbiz.shipment.thirdparty.usps.UspsServices.java

public static Map<String, Object> uspsPriorityMailInternationalLabel(DispatchContext dctx,
        Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    String shipmentGatewayConfigId = (String) context.get("shipmentGatewayConfigId");
    String resource = (String) context.get("configProps");
    GenericValue shipmentRouteSegment = (GenericValue) context.get("shipmentRouteSegment");
    Locale locale = (Locale) context.get("locale");

    // Start the document
    Document requestDocument;/* w w  w . j a v  a2  s.  c om*/
    boolean certify = false;
    String test = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "test", resource,
            "shipment.usps.test");
    if (!"Y".equalsIgnoreCase(test)) {
        requestDocument = createUspsRequestDocument("PriorityMailIntlRequest", false, delegator,
                shipmentGatewayConfigId, resource);
    } else {
        requestDocument = createUspsRequestDocument("PriorityMailIntlCertifyRequest", false, delegator,
                shipmentGatewayConfigId, resource);
        certify = true;
    }
    Element rootElement = requestDocument.getDocumentElement();

    // Retrieve from/to address and package details
    GenericValue originAddress = null;
    GenericValue originTelecomNumber = null;
    GenericValue destinationAddress = null;
    GenericValue destinationProvince = null;
    GenericValue destinationCountry = null;
    GenericValue destinationTelecomNumber = null;
    List<GenericValue> shipmentPackageRouteSegs = null;
    try {
        originAddress = shipmentRouteSegment.getRelatedOne("OriginPostalAddress", false);
        originTelecomNumber = shipmentRouteSegment.getRelatedOne("OriginTelecomNumber", false);
        destinationAddress = shipmentRouteSegment.getRelatedOne("DestPostalAddress", false);
        if (destinationAddress != null) {
            destinationProvince = destinationAddress.getRelatedOne("StateProvinceGeo", false);
            destinationCountry = destinationAddress.getRelatedOne("CountryGeo", false);
        }
        destinationTelecomNumber = shipmentRouteSegment.getRelatedOne("DestTelecomNumber", false);
        shipmentPackageRouteSegs = shipmentRouteSegment.getRelated("ShipmentPackageRouteSeg", null, null,
                false);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    if (originAddress == null || originTelecomNumber == null) {
        return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                "FacilityShipmentUspsPriorityMailLabelOriginAddressMissing", locale));
    }

    // Origin Info
    // USPS wants a separate first name and last, best we can do is split the string on the white space, if that doesn't work then default to putting the attnName in both fields
    String fromAttnName = originAddress.getString("attnName");
    String fromFirstName = StringUtils.defaultIfEmpty(StringUtils.substringBefore(fromAttnName, " "),
            fromAttnName);
    String fromLastName = StringUtils.defaultIfEmpty(StringUtils.substringAfter(fromAttnName, " "),
            fromAttnName);
    UtilXml.addChildElementValue(rootElement, "FromFirstName", fromFirstName, requestDocument);
    UtilXml.addChildElementValue(rootElement, "FromLastName", fromLastName, requestDocument);
    UtilXml.addChildElementValue(rootElement, "FromFirm", originAddress.getString("toName"), requestDocument);
    // The following 2 assignments are not typos - USPS address1 = OFBiz address2, USPS address2 = OFBiz address1
    UtilXml.addChildElementValue(rootElement, "FromAddress1", originAddress.getString("address2"),
            requestDocument);
    UtilXml.addChildElementValue(rootElement, "FromAddress2", originAddress.getString("address1"),
            requestDocument);
    UtilXml.addChildElementValue(rootElement, "FromCity", originAddress.getString("city"), requestDocument);
    UtilXml.addChildElementValue(rootElement, "FromState", originAddress.getString("stateProvinceGeoId"),
            requestDocument);
    UtilXml.addChildElementValue(rootElement, "FromZip5", originAddress.getString("postalCode"),
            requestDocument);
    // USPS expects a phone number consisting of area code + contact number as a single numeric string
    String fromPhoneNumber = originTelecomNumber.getString("areaCode")
            + originTelecomNumber.getString("contactNumber");
    fromPhoneNumber = StringUtil.removeNonNumeric(fromPhoneNumber);
    UtilXml.addChildElementValue(rootElement, "FromPhone", fromPhoneNumber, requestDocument);

    // Destination Info
    UtilXml.addChildElementValue(rootElement, "ToName", destinationAddress.getString("attnName"),
            requestDocument);
    UtilXml.addChildElementValue(rootElement, "ToFirm", destinationAddress.getString("toName"),
            requestDocument);
    UtilXml.addChildElementValue(rootElement, "ToAddress1", destinationAddress.getString("address1"),
            requestDocument);
    UtilXml.addChildElementValue(rootElement, "ToAddress2", destinationAddress.getString("address2"),
            requestDocument);
    UtilXml.addChildElementValue(rootElement, "ToCity", destinationAddress.getString("city"), requestDocument);
    UtilXml.addChildElementValue(rootElement, "ToProvince", destinationProvince.getString("geoName"),
            requestDocument);
    // TODO: Test these country names, I think we're going to need to maintain a list of USPS names
    UtilXml.addChildElementValue(rootElement, "ToCountry", destinationCountry.getString("geoName"),
            requestDocument);
    UtilXml.addChildElementValue(rootElement, "ToPostalCode", destinationAddress.getString("postalCode"),
            requestDocument);
    // TODO: Figure out how to answer this question accurately
    UtilXml.addChildElementValue(rootElement, "ToPOBoxFlag", "N", requestDocument);
    String toPhoneNumber = destinationTelecomNumber.getString("countryCode")
            + destinationTelecomNumber.getString("areaCode")
            + destinationTelecomNumber.getString("contactNumber");
    UtilXml.addChildElementValue(rootElement, "ToPhone", toPhoneNumber, requestDocument);
    UtilXml.addChildElementValue(rootElement, "NonDeliveryOption", "RETURN", requestDocument);

    for (GenericValue shipmentPackageRouteSeg : shipmentPackageRouteSegs) {
        Document packageDocument = (Document) requestDocument.cloneNode(true);
        // This is our reference and can be whatever we want.  For lack of a better alternative we'll use shipmentId:shipmentPackageSeqId:shipmentRouteSegmentId
        String fromCustomsReference = shipmentRouteSegment.getString("shipmentId") + ":"
                + shipmentRouteSegment.getString("shipmentRouteSegmentId");
        fromCustomsReference = StringUtils.join(UtilMisc.toList(shipmentRouteSegment.get("shipmentId"),
                shipmentPackageRouteSeg.get("shipmentPackageSeqId"),
                shipmentRouteSegment.get("shipmentRouteSegementId")), ':');
        UtilXml.addChildElementValue(rootElement, "FromCustomsReference", fromCustomsReference,
                packageDocument);
        // Determine the container type for this package
        String container = "VARIABLE";
        String packageTypeCode = null;
        GenericValue shipmentPackage = null;
        List<GenericValue> shipmentPackageContents = null;
        try {
            shipmentPackage = shipmentPackageRouteSeg.getRelatedOne("ShipmentPackage", false);
            shipmentPackageContents = shipmentPackage.getRelated("ShipmentPackageContent", null, null, false);
            GenericValue shipmentBoxType = shipmentPackage.getRelatedOne("ShipmentBoxType", false);
            if (shipmentBoxType != null) {
                GenericValue carrierShipmentBoxType = EntityUtil.getFirst(shipmentBoxType
                        .getRelated("CarrierShipmentBoxType", UtilMisc.toMap("partyId", "USPS"), null, false));
                if (carrierShipmentBoxType != null) {
                    packageTypeCode = carrierShipmentBoxType.getString("packageTypeCode");
                    // Supported type codes
                    List<String> supportedPackageTypeCodes = UtilMisc.toList("LGFLATRATEBOX", "SMFLATRATEBOX",
                            "FLATRATEBOX", "MDFLATRATEBOX", "FLATRATEENV");
                    if (supportedPackageTypeCodes.contains(packageTypeCode)) {
                        container = packageTypeCode;
                    }
                }
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
        UtilXml.addChildElementValue(rootElement, "Container", container, packageDocument);
        // According to the docs sending an empty postage tag will cause the postage to be calculated
        UtilXml.addChildElementValue(rootElement, "Postage", "", packageDocument);

        BigDecimal packageWeight = shipmentPackage.getBigDecimal("weight");
        String weightUomId = shipmentPackage.getString("weightUomId");
        BigDecimal packageWeightPounds = UomWorker.convertUom(packageWeight, weightUomId, "WT_lb", dispatcher);
        Integer[] packagePoundsOunces = convertPoundsToPoundsOunces(packageWeightPounds);
        UtilXml.addChildElementValue(rootElement, "GrossPounds", packagePoundsOunces[0].toString(),
                packageDocument);
        UtilXml.addChildElementValue(rootElement, "GrossOunces", packagePoundsOunces[1].toString(),
                packageDocument);

        UtilXml.addChildElementValue(rootElement, "ContentType", "MERCHANDISE", packageDocument);
        UtilXml.addChildElementValue(rootElement, "Agreement", "N", packageDocument);
        UtilXml.addChildElementValue(rootElement, "ImageType", "PDF", packageDocument);
        // TODO: Try the different layouts
        UtilXml.addChildElementValue(rootElement, "ImageType", "ALLINONEFILE", packageDocument);
        UtilXml.addChildElementValue(rootElement, "CustomerRefNo", fromCustomsReference, packageDocument);

        // Add the shipping contents
        Element shippingContents = UtilXml.addChildElement(rootElement, "ShippingContents", packageDocument);
        for (GenericValue shipmentPackageContent : shipmentPackageContents) {
            Element itemDetail = UtilXml.addChildElement(shippingContents, "ItemDetail", packageDocument);
            GenericValue product = null;
            GenericValue originGeo = null;
            try {
                GenericValue shipmentItem = shipmentPackageContent.getRelatedOne("ShipmentItem", false);
                product = shipmentItem.getRelatedOne("Product", false);
                originGeo = product.getRelatedOne("OriginGeo", false);
            } catch (GenericEntityException e) {
                Debug.logInfo(e, module);
            }

            UtilXml.addChildElementValue(itemDetail, "Description", product.getString("productName"),
                    packageDocument);
            UtilXml.addChildElementValue(itemDetail, "Quantity", shipmentPackageContent
                    .getBigDecimal("quantity").setScale(0, BigDecimal.ROUND_CEILING).toPlainString(),
                    packageDocument);
            String packageContentValue = ShipmentWorker.getShipmentPackageContentValue(shipmentPackageContent)
                    .setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString();
            UtilXml.addChildElementValue(itemDetail, "Value", packageContentValue, packageDocument);
            BigDecimal productWeight = ProductWorker.getProductWeight(product, "WT_lbs", delegator, dispatcher);
            Integer[] productPoundsOunces = convertPoundsToPoundsOunces(productWeight);
            UtilXml.addChildElementValue(itemDetail, "NetPounds", productPoundsOunces[0].toString(),
                    packageDocument);
            UtilXml.addChildElementValue(itemDetail, "NetOunces", productPoundsOunces[1].toString(),
                    packageDocument);
            UtilXml.addChildElementValue(itemDetail, "HSTariffNumber", "", packageDocument);
            UtilXml.addChildElementValue(itemDetail, "CountryOfOrigin", originGeo.getString("geoName"),
                    packageDocument);
        }

        // Send the request
        Document responseDocument = null;
        String api = certify ? "PriorityMailIntlCertify" : "PriorityMailIntl";
        try {
            responseDocument = sendUspsRequest(api, requestDocument, delegator, shipmentGatewayConfigId,
                    resource, locale);
        } catch (UspsRequestException e) {
            Debug.logInfo(e, module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsPriorityMailLabelSendingError",
                    UtilMisc.toMap("errorString", e.getMessage()), locale));
        }
        Element responseElement = responseDocument.getDocumentElement();

        // TODO: No mention of error returns in the docs

        String labelImageString = UtilXml.childElementValue(responseElement, "LabelImage");
        if (UtilValidate.isEmpty(labelImageString)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsPriorityMailLabelResponseIncompleteElementLabelImage", locale));
        }
        shipmentPackageRouteSeg.setBytes("labelImage", Base64.base64Decode(labelImageString.getBytes()));
        String trackingCode = UtilXml.childElementValue(responseElement, "BarcodeNumber");
        if (UtilValidate.isEmpty(trackingCode)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsPriorityMailLabelResponseIncompleteElementBarcodeNumber", locale));
        }
        shipmentPackageRouteSeg.set("trackingCode", trackingCode);
        try {
            shipmentPackageRouteSeg.store();
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }

    }
    return ServiceUtil.returnSuccess();
}

From source file:org.egov.billsaccounting.services.CreateVoucher.java

public void validateTransaction(final List<HashMap<String, Object>> accountcodedetails,
        final List<HashMap<String, Object>> subledgerdetails) throws ApplicationRuntimeException, Exception {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("START | validateTransaction");
    // List<Transaxtion> transaxtionList = new ArrayList<Transaxtion>();
    BigDecimal totaldebitAmount = BigDecimal.valueOf(0);
    BigDecimal totalcreditAmount = BigDecimal.valueOf(0);
    final Map<String, BigDecimal> accDetAmtMap = new HashMap<String, BigDecimal>();
    for (final HashMap<String, Object> accDetailMap : accountcodedetails) {

        String glcode = null;/* www .  java2  s . c  o m*/

        final BigDecimal debitAmount = new BigDecimal(accDetailMap.get(VoucherConstant.DEBITAMOUNT).toString());
        final BigDecimal creditAmount = new BigDecimal(
                accDetailMap.get(VoucherConstant.CREDITAMOUNT).toString());

        totaldebitAmount = totaldebitAmount.add(debitAmount);
        totalcreditAmount = totalcreditAmount.add(creditAmount);
        if (accDetailMap.containsKey(VoucherConstant.GLCODE)
                && null != accDetailMap.get(VoucherConstant.GLCODE)) {
            glcode = accDetailMap.get(VoucherConstant.GLCODE).toString();
            if (null == chartOfAccountsDAO.getCChartOfAccountsByGlCode(glcode))
                throw new ApplicationRuntimeException("Not a valid account code" + glcode);
        } else
            throw new ApplicationRuntimeException("glcode is missing or null");
        if (debitAmount.compareTo(BigDecimal.ZERO) != 0 && creditAmount.compareTo(BigDecimal.ZERO) != 0)
            throw new ApplicationRuntimeException(
                    "Both debit amount and credit amount cannot be greater than zero");
        if (debitAmount.compareTo(BigDecimal.ZERO) == 0 && creditAmount.compareTo(BigDecimal.ZERO) == 0)
            throw new ApplicationRuntimeException("debit and credit both amount is Zero");
        if (null != accDetailMap.get(VoucherConstant.FUNCTIONCODE)
                && "" != accDetailMap.get(VoucherConstant.FUNCTIONCODE)) {
            final String functionCode = accDetailMap.get(VoucherConstant.FUNCTIONCODE).toString();
            if (null == functionDAO.getFunctionByCode(functionCode))
                throw new ApplicationRuntimeException("not a valid function code");
        }
        if (debitAmount.compareTo(BigDecimal.ZERO) != 0) {
            if (null != accDetAmtMap.get(VoucherConstant.DEBIT + glcode)) {
                final BigDecimal accountCodeTotDbAmt = accDetAmtMap.get(VoucherConstant.DEBIT + glcode)
                        .add(debitAmount);
                accDetAmtMap.put(VoucherConstant.DEBIT + glcode, accountCodeTotDbAmt);
            } else
                accDetAmtMap.put(VoucherConstant.DEBIT + glcode, debitAmount);

        } else if (creditAmount.compareTo(BigDecimal.ZERO) != 0)
            if (null != accDetAmtMap.get(VoucherConstant.CREDIT + glcode)) {
                final BigDecimal accountCodeTotCrAmt = accDetAmtMap.get(VoucherConstant.CREDIT + glcode)
                        .add(creditAmount);
                accDetAmtMap.put(VoucherConstant.CREDIT + glcode, accountCodeTotCrAmt);
            } else
                accDetAmtMap.put(VoucherConstant.CREDIT + glcode, creditAmount);
    }
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Total Debit  amount   :" + totaldebitAmount);
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Total Credit amount   :" + totalcreditAmount);
    totaldebitAmount = totaldebitAmount.setScale(2, BigDecimal.ROUND_HALF_UP);
    totalcreditAmount = totalcreditAmount.setScale(2, BigDecimal.ROUND_HALF_UP);
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Total Debit  amount after round off :" + totaldebitAmount);
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Total Credit amount after round off :" + totalcreditAmount);
    if (totaldebitAmount.compareTo(totalcreditAmount) != 0)
        throw new ApplicationRuntimeException("total debit and total credit amount is not matching");
    final Map<String, BigDecimal> subledAmtmap = new HashMap<String, BigDecimal>();
    for (final HashMap<String, Object> subdetailDetailMap : subledgerdetails) {
        String glcode = null;
        String detailtypeid = null;
        String detailKeyId = null;
        if (null != subdetailDetailMap.get(VoucherConstant.GLCODE)) {
            glcode = subdetailDetailMap.get(VoucherConstant.GLCODE).toString();
            if (null == chartOfAccountsDAO.getCChartOfAccountsByGlCode(glcode))
                throw new ApplicationRuntimeException("not a valid glcode");
        } else
            throw new ApplicationRuntimeException("glcode is missing");
        final Query querytds = persistenceService.getSession()
                .createQuery("select t.id from Recovery t where " + "t.chartofaccounts.glcode=:glcode");
        querytds.setString("glcode", glcode);
        querytds.setCacheable(true);
        if (null != querytds.list() && querytds.list().size() > 0
                && null == subdetailDetailMap.get(VoucherConstant.TDSID)
                && null != subdetailDetailMap.get(VoucherConstant.CREDITAMOUNT)
                && new BigDecimal(subdetailDetailMap.get(VoucherConstant.CREDITAMOUNT).toString())
                        .compareTo(BigDecimal.ZERO) != 0) {
            /*
             * Commenting out throw ApplicationRuntimeException since we are
             * using the same API for create Journal Voucher. There we are
             * not setting the TDS id..
             */
            // throw new
            // ApplicationRuntimeException("Recovery detail is missing for glcode :"+glcode);
        }
        // validate the glcode is a subledger code or not.

        final Query query = persistenceService.getSession()
                .createQuery("from CChartOfAccountDetail cd,CChartOfAccounts c where "
                        + "cd.glCodeId = c.id and c.glcode=:glcode");

        query.setString(VoucherConstant.GLCODE, glcode);
        query.setCacheable(true);
        if (null == query.list() || query.list().size() == 0)
            throw new ApplicationRuntimeException("This code is not a control code" + glcode);

        // validate subledger Detailtypeid

        if (null != subdetailDetailMap.get(VoucherConstant.DETAILTYPEID)) {
            detailtypeid = subdetailDetailMap.get(VoucherConstant.DETAILTYPEID).toString();
            final Session session = persistenceService.getSession();
            final Query qry = session.createQuery("from CChartOfAccountDetail cd,CChartOfAccounts c where "
                    + "cd.glCodeId = c.id and c.glcode=:glcode and cd.detailTypeId.id=:detailTypeId");
            qry.setString(VoucherConstant.GLCODE, glcode);
            qry.setInteger("detailTypeId", Integer.valueOf(detailtypeid));
            qry.setCacheable(true);
            if (null == qry.list() || qry.list().size() == 0)
                throw new ApplicationRuntimeException(
                        "The subledger type mapped to this account code is not correct " + glcode);
        } else
            throw new ApplicationRuntimeException("Subledger type value is missing for account code " + glcode);

        if (null != subdetailDetailMap.get(VoucherConstant.DETAILKEYID)) {
            detailKeyId = subdetailDetailMap.get(VoucherConstant.DETAILKEYID).toString();
            final Session session = persistenceService.getSession();
            final Query qry = session.createQuery(
                    "from Accountdetailkey adk where adk.accountdetailtype.id=:detailtypeid and adk.detailkey=:detailkey");
            qry.setInteger(VoucherConstant.DETAILTYPEID, Integer.valueOf(detailtypeid));
            qry.setInteger("detailkey", Integer.valueOf(detailKeyId));
            qry.setCacheable(true);
            if (null == qry.list() || qry.list().size() == 0)
                throw new ApplicationRuntimeException("Subledger data is not valid for account code " + glcode);
        } else
            throw new ApplicationRuntimeException("detailkeyid is missing");

        if (null != subdetailDetailMap.get(VoucherConstant.DEBITAMOUNT)
                && new BigDecimal(subdetailDetailMap.get(VoucherConstant.DEBITAMOUNT).toString())
                        .compareTo(BigDecimal.ZERO) != 0) {
            final BigDecimal dbtAmount = new BigDecimal(
                    subdetailDetailMap.get(VoucherConstant.DEBITAMOUNT).toString());
            if (null != subledAmtmap.get(VoucherConstant.DEBIT + glcode))
                subledAmtmap.put(VoucherConstant.DEBIT + glcode,
                        subledAmtmap.get(VoucherConstant.DEBIT + glcode).add(dbtAmount));
            else
                subledAmtmap.put(VoucherConstant.DEBIT + glcode, dbtAmount);

        } else if (null != subdetailDetailMap.get(VoucherConstant.CREDITAMOUNT)
                && new BigDecimal(subdetailDetailMap.get(VoucherConstant.CREDITAMOUNT).toString())
                        .compareTo(BigDecimal.ZERO) != 0) {
            final BigDecimal creditAmt = new BigDecimal(
                    subdetailDetailMap.get(VoucherConstant.CREDITAMOUNT).toString());
            if (null != subledAmtmap.get(VoucherConstant.CREDIT + glcode))
                subledAmtmap.put(VoucherConstant.CREDIT + glcode,
                        subledAmtmap.get(VoucherConstant.CREDIT + glcode).add(creditAmt));
            else
                subledAmtmap.put(VoucherConstant.CREDIT + glcode, creditAmt);

        } else
            throw new ApplicationRuntimeException(
                    "Incorrect Sub ledger amount supplied for glcode : " + glcode);

    }

    for (final HashMap<String, Object> accDetailMap : accountcodedetails) {

        final String glcode = accDetailMap.get(VoucherConstant.GLCODE).toString();

        if (null != subledAmtmap.get(VoucherConstant.DEBIT + glcode))
            // changed since equals does considers decimal values eg 20.0 is
            // not equal to 2
            if (subledAmtmap.get(VoucherConstant.DEBIT + glcode)
                    .compareTo(accDetAmtMap.get(VoucherConstant.DEBIT + glcode)) != 0)
                throw new ApplicationRuntimeException(
                        "Total of subleger debit amount is not matching with the account code amount "
                                + glcode);
        if (null != subledAmtmap.get(VoucherConstant.CREDIT + glcode))
            // changed since equals does considers decimal values eg 20.0 is
            // not equal to 2
            if (subledAmtmap.get(VoucherConstant.CREDIT + glcode)
                    .compareTo(accDetAmtMap.get(VoucherConstant.CREDIT + glcode)) != 0)
                throw new ApplicationRuntimeException(
                        "Total of subleger credit amount is not matching with the account code amount "
                                + glcode);

    }
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("END | validateTransaction");

}

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

public Map<String, BigDecimal> getSumOfConnectionTotalCollection(
        final WaterChargeDashBoardRequest collectionDetailsRequest, final String indexName,
        final String aggregationField, final String connectionTypeField, final String totalagrregatefild) {
    BoolQueryBuilder boolQuery = prepareWhereClause(collectionDetailsRequest, indexName);
    if (indexName.equals(WaterTaxConstants.WATER_TAX_INDEX_NAME)) {
        boolQuery = boolQuery.filter(QueryBuilders.matchQuery(STATUS, CONN_STATUS));
        boolQuery = boolQuery.filter(QueryBuilders.matchQuery("usage", connectionTypeField));
    } else {/*from  ww  w .  j  av  a2  s  . co m*/
        boolQuery = boolQuery.mustNot(QueryBuilders.matchQuery(STATUS, CANCELLED));
        boolQuery = boolQuery.filter(QueryBuilders.matchQuery("consumerType", connectionTypeField));
    }
    AggregationBuilder aggregation;
    if (totalagrregatefild == null)
        aggregation = AggregationBuilders.terms(BY_CITY).field(aggregationField).size(120)
                .subAggregation(AggregationBuilders.sum(TOTALDEMAND).field(TOTAL_AMOUNT));
    else
        aggregation = AggregationBuilders.terms(BY_CITY).field(aggregationField).size(120)
                .subAggregation(AggregationBuilders.sum(TOTALDEMAND).field(TOTAL_DEMAND));

    final SearchQuery searchQueryColl = new NativeSearchQueryBuilder().withIndices(indexName)
            .withQuery(boolQuery).addAggregation(aggregation).build();

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

    final StringTerms cityAggr = collAggr.get(BY_CITY);
    final Map<String, BigDecimal> totalconnectionTotalDemandMap = new HashMap<>();
    for (final Terms.Bucket entry : cityAggr.getBuckets()) {
        final Sum aggr = entry.getAggregations().get(TOTALDEMAND);
        totalconnectionTotalDemandMap.put(String.valueOf(entry.getKey()),
                BigDecimal.valueOf(aggr.getValue()).setScale(0, BigDecimal.ROUND_HALF_UP));
    }
    return totalconnectionTotalDemandMap;
}

From source file:com.selfsoft.business.service.impl.TbFixEntrustServiceImpl.java

public void printTbFixEntrustTemplateXTL(OutputStream os, String tpl, Long tbFixEntrustId) {

    try {/*from  w w  w.j a  v a 2  s  .  c om*/

        TbFixEntrust tbFixEntrust = this.findById(tbFixEntrustId);

        TbCustomer tbCustomer = tbCustomerService.findById(tbFixEntrust.getTbCustomer().getId());

        TbCarInfo tbCarInfo = tbCarInfoService.findById(tbFixEntrust.getTbCarInfo().getId());

        List<TbFixEntrustContent> tbFixEntrustContentList = this.composeContent(
                tbFixEntrustContentService.findTbFixEnTrustContentListByTbFixEntrustId(tbFixEntrustId));

        // ??
        TmCompany tmCompany = tmCompanyService.acquireUniqueTmCompany();

        /*
         * List<TbMaintainPartContent> maintainList =
         * tbMaintainPartContentService
         * .getViewEntrustMaintianContent(tbFixEntrustId);
         * 
         * 
         * List<TmStockOutDetVo> solePartList =
         * tmStockOutService.getSellByEntrustCode
         * (tbFixEntrust.getEntrustCode());
         */

        /**
         * ??
         */
        List<TbMaintianVo> maintianvos = tbMaintainPartContentService
                .getTbMaintianDetailVosByEntrustId(tbFixEntrust.getId(), Constants.BALANCE_ALL);

        /**
         * ?
         */
        List<TmStockOutDetVo> tmStockOutDetVos = tmStockOutService
                .getSellDetailByEntrustCode(tbFixEntrust.getEntrustCode(), Constants.BALANCE_ALL);

        /**
         * ??
         */

        List<TbMaintianVo> partAll = new ArrayList<TbMaintianVo>();

        if (null != maintianvos && maintianvos.size() > 0) {

            for (TbMaintianVo tbMaintianVo : maintianvos) {

                partAll.add(tbMaintianVo);

            }
        }

        if (null != tmStockOutDetVos && tmStockOutDetVos.size() > 0) {

            for (TmStockOutDetVo tmStockOutDetVo : tmStockOutDetVos) {

                TbMaintianVo tbMaintianVo = new TbMaintianVo();

                tbMaintianVo.setPartId(tmStockOutDetVo.getPartinfoId());

                tbMaintianVo.setHouseName(tmStockOutDetVo.getHouseName());

                tbMaintianVo.setPartCode(tmStockOutDetVo.getPartCode());

                tbMaintianVo.setPartName(tmStockOutDetVo.getPartName());

                tbMaintianVo.setUnitName(tmStockOutDetVo.getUnitName());

                tbMaintianVo.setPrice(tmStockOutDetVo.getPrice());

                tbMaintianVo.setPartQuantity(tmStockOutDetVo.getQuantity());

                tbMaintianVo.setTotal(tmStockOutDetVo.getTotal());

                tbMaintianVo.setIsFree(tmStockOutDetVo.getIsFree());

                tbMaintianVo.setProjectType(tmStockOutDetVo.getProjectType());

                tbMaintianVo.setZl(tmStockOutDetVo.getZl());

                tbMaintianVo.setXmlx(tmStockOutDetVo.getXmlx());

                partAll.add(tbMaintianVo);
            }
        }

        partAll = this.composePart(partAll);

        int fixSize = (tbFixEntrustContentList == null ? 0 : tbFixEntrustContentList.size());

        int maintainSize = (maintianvos == null ? 0 : maintianvos.size());

        int solePartSize = (tmStockOutDetVos == null ? 0 : tmStockOutDetVos.size());

        int partAllSize = (partAll == null ? 0 : partAll.size());

        HSSFWorkbook workbook = new HSSFWorkbook(this.getClass().getResourceAsStream(tpl));

        HSSFSheet sheet = workbook.getSheetAt(0);

        HSSFCellStyle style = workbook.createCellStyle();

        style.setWrapText(true);

        style.setAlignment(HSSFCellStyle.ALIGN_LEFT);

        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

        HSSFFont font = workbook.createFont();

        font.setFontName("");

        font.setFontHeightInPoints((short) 9);

        style.setFont(font);

        HSSFRow row = null;

        HSSFCell cell = null;

        row = sheet.getRow(3);

        cell = row.getCell(0);

        cell.setCellValue("  ??:" + "?" + " (?:70691M)  ?:"
                + tmCompany.getCompanyAddress() + "  ?: "
                + (tmCompany.getCompanyPhone() == null ? "" : tmCompany.getCompanyPhone()));

        row = sheet.getRow(0);

        cell = row.getCell(31);

        cell.setCellStyle(style);

        cell.setCellValue("*?:" + tbCustomer.getCustomerCode() + "\n" + "??:");

        row = sheet.getRow(6);

        cell = row.getCell(4);

        cell.setCellValue(tbCustomer.getCustomerName() == null ? "" : tbCustomer.getCustomerName());

        row = sheet.getRow(6);

        cell = row.getCell(24);

        cell.setCellStyle(style);

        cell.setCellValue(tbCustomer.getAddress() == null ? "" : tbCustomer.getAddress());

        row = sheet.getRow(6);

        cell = row.getCell(41);

        cell.setCellValue(tbCustomer.getContractPerson() == null ? "" : tbCustomer.getContractPerson());

        row = sheet.getRow(8);

        cell = row.getCell(41);

        cell.setCellValue(tbCustomer.getTelephone() == null ? "" : tbCustomer.getTelephone());

        row = sheet.getRow(8);

        cell = row.getCell(4);

        cell.setCellValue(tbCustomer.getTelephone() == null ? "" : tbCustomer.getTelephone());

        row = sheet.getRow(12);

        cell = row.getCell(0);

        String entrustCode = tbFixEntrust.getEntrustCode();

        String[] es = entrustCode.split("-");

        String newCode = "RO" + es[0].substring(2, 6) + es[1];

        cell.setCellValue(/* tbFixEntrust.getEntrustCode() */newCode);

        row = sheet.getRow(12);

        cell = row.getCell(9);

        cell.setCellValue(CommonMethod.parseDateToString(tbFixEntrust.getFixDate(), "yyyy-MM-dd HH:mm"));

        row = sheet.getRow(12);

        cell = row.getCell(18);

        cell.setCellValue(tbCarInfo.getLicenseCode());

        row = sheet.getRow(12);

        cell = row.getCell(26);

        cell.setCellStyle(style);

        cell.setCellValue(tbCarInfo.getTmCarModelType().getModelName());

        row = sheet.getRow(12);

        cell = row.getCell(34);

        cell.setCellValue(tbCarInfo.getChassisCode());

        // ?
        row = sheet.getRow(16);

        cell = row.getCell(0);

        cell.setCellValue("");

        row = sheet.getRow(16);

        cell = row.getCell(9);

        cell.setCellValue(CommonMethod.parseDateToString(tbCarInfo.getPurchaseDate(), "yyyy-MM-dd"));

        // ?
        row = sheet.getRow(16);

        cell = row.getCell(18);

        cell.setCellValue("");

        row = sheet.getRow(16);

        cell = row.getCell(26);

        cell.setCellValue(tbFixEntrust.getEnterStationKilo() == null ? ""
                : new BigDecimal(tbFixEntrust.getEnterStationKilo().toString())
                        .divide(new BigDecimal("1.00"), 0, BigDecimal.ROUND_HALF_UP).toString());

        row = sheet.getRow(16);

        cell = row.getCell(34);

        cell.setCellValue(CommonMethod.parseDateToString(tbFixEntrust.getEstimateDate(), "yyyy-MM-dd HH:mm"));

        Double fixCount = tbFixEntrustContentService.countTbFixEnTrustContentByTbFixEntrustId(tbFixEntrustId);

        row = sheet.getRow(75);

        cell = row.getCell(30);

        cell.setCellValue(new BigDecimal(fixCount).divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP)
                .toString());

        BigDecimal partPriceAll = new BigDecimal("0.00");

        if (partAllSize > 0) {

            for (int i = 0; i < partAllSize; i++) {

                TbMaintianVo tbMaintianVo = partAll.get(i);

                BigDecimal total = new BigDecimal(tbMaintianVo.getPrice())
                        .multiply(new BigDecimal(tbMaintianVo.getPartQuantity()));

                partPriceAll = partPriceAll.add(total);

            }

        }

        row = sheet.getRow(77);

        cell = row.getCell(30);

        cell.setCellValue(partPriceAll.divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP).toString());

        BigDecimal total = new BigDecimal(fixCount).add(partPriceAll).divide(new BigDecimal("1.00"), 2,
                BigDecimal.ROUND_HALF_UP);

        row = sheet.getRow(81);

        cell = row.getCell(30);

        cell.setCellValue(total.toString());

        row = sheet.getRow(79);

        cell = row.getCell(30);

        cell.setCellValue("0.00");

        ByteArrayOutputStream byteArrayOutImgLion = new ByteArrayOutputStream();

        ByteArrayOutputStream byteArrayOutDBZF = new ByteArrayOutputStream();

        BufferedImage bufferImgLion = ImageIO.read(this.getClass().getResourceAsStream("/xtl.png"));

        BufferedImage bufferImgDFBZ = ImageIO.read(this.getClass().getResourceAsStream("/xtl_logo.png"));

        ImageIO.write(bufferImgLion, "png", byteArrayOutImgLion);

        ImageIO.write(bufferImgDFBZ, "png", byteArrayOutDBZF);

        HSSFPatriarch patriarch = sheet.createDrawingPatriarch();

        HSSFClientAnchor anchorLion = new HSSFClientAnchor(0, 0, 1023, 200, (short) 40, 0, (short) 47, 2);

        HSSFClientAnchor anchorDBZF = new HSSFClientAnchor(0, 0, 1023, 100, (short) 0, 0, (short) 3, 3);

        patriarch.createPicture(anchorLion,
                workbook.addPicture(byteArrayOutImgLion.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));

        patriarch.createPicture(anchorDBZF,
                workbook.addPicture(byteArrayOutDBZF.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));

        int page = 1;

        if (fixSize / 8 >= (maintainSize + solePartSize) / 12) {

            page = fixSize / 8;

        }

        else {

            page = (maintainSize + solePartSize) / 12;

        }

        for (int i = 0; i < page; i++) {

            int p = 0;

            int k = 0;

            HSSFSheet sheetClone = workbook.cloneSheet(0);

            byteArrayOutImgLion = new ByteArrayOutputStream();

            byteArrayOutDBZF = new ByteArrayOutputStream();

            bufferImgLion = ImageIO.read(this.getClass().getResourceAsStream("/xtl.png"));

            bufferImgDFBZ = ImageIO.read(this.getClass().getResourceAsStream("/xtl_logo.png"));

            ImageIO.write(bufferImgLion, "png", byteArrayOutImgLion);

            ImageIO.write(bufferImgDFBZ, "png", byteArrayOutDBZF);

            patriarch = sheetClone.createDrawingPatriarch();

            anchorLion = new HSSFClientAnchor(0, 0, 1023, 200, (short) 40, 0, (short) 47, 2);

            anchorDBZF = new HSSFClientAnchor(0, 0, 1023, 200, (short) 0, 0, (short) 3, 3);

            patriarch.createPicture(anchorLion,
                    workbook.addPicture(byteArrayOutImgLion.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));

            patriarch.createPicture(anchorDBZF,
                    workbook.addPicture(byteArrayOutDBZF.toByteArray(), HSSFWorkbook.PICTURE_TYPE_PNG));

            if (fixSize > 8) {

                int printFixSize = (fixSize > (i + 2) * 8 ? (i + 2) * 8 : fixSize);

                for (int j = 8 * (i + 1); j < printFixSize; j++) {

                    TbFixEntrustContent content = tbFixEntrustContentList.get(j);

                    List<TbFixShare> tbFixShareList = tbFixShareService
                            .findTbFixShareListByTbFixEntrustContentId(content.getId());

                    String fixPersons = "";

                    String workTypes = "";

                    if (null != tbFixShareList && tbFixShareList.size() > 0) {

                        for (TbFixShare tbFixShare : tbFixShareList) {

                            if (null != tbFixShare.getTmUser()) {

                                TmUser tmUser = tmUserService.findById(tbFixShare.getTmUser().getId());

                                fixPersons += (tmUser.getUserRealName() == null
                                        || "".equals(tmUser.getUserRealName()) ? tmUser.getUserName()
                                                : tmUser.getUserRealName())
                                        + " ";

                                workTypes += (tmUser.getTmWorkType() == null ? ""
                                        : tmUser.getTmWorkType().getWorkName()) + " ";
                            }

                        }
                    }

                    row = sheetClone.getRow(23 + p * 2);

                    cell = row.getCell(2);

                    cell.setCellStyle(style);

                    cell.setCellValue(content.getStationName());

                    cell = row.getCell(20);

                    cell.setCellStyle(style);

                    cell.setCellValue(new BigDecimal(content.getFixHour())
                            .divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP).toString());

                    cell = row.getCell(24);

                    cell.setCellStyle(style);

                    cell.setCellValue(new BigDecimal(content.getWorkingHourPrice())
                            .divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP).toString());

                    cell = row.getCell(28);

                    cell.setCellStyle(style);

                    cell.setCellValue(new BigDecimal(content.getFixHourAll())
                            .divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP).toString());

                    cell = row.getCell(34);

                    cell.setCellStyle(style);

                    cell.setCellValue(content.getProjectType() == null ? "" : content.getProjectType());

                    cell = row.getCell(40);

                    cell.setCellStyle(style);

                    cell.setCellValue(workTypes);

                    cell = row.getCell(45);

                    cell.setCellStyle(style);

                    cell.setCellValue(fixPersons);

                    p++;

                }

            }

            if (partAllSize > 12) {

                int prinPartSize = (partAllSize > (i + 2) * 12 ? (i + 2) * 12 : partAllSize);

                for (int j = 12 * (i + 1); j < prinPartSize; j++) {

                    TbMaintianVo t = partAll.get(j);

                    row = sheetClone.getRow(41 + k * 2);

                    cell = row.getCell(2);

                    cell.setCellStyle(style);

                    cell.setCellValue(t.getPartCode());

                    cell = row.getCell(11);

                    cell.setCellStyle(style);

                    cell.setCellValue(t.getPartName());

                    cell = row.getCell(20);

                    cell.setCellStyle(style);

                    cell.setCellValue(new BigDecimal(t.getPartQuantity())
                            .divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP).toString());

                    cell = row.getCell(24);

                    cell.setCellStyle(style);

                    cell.setCellValue(new BigDecimal(t.getPrice())
                            .divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP).toString());

                    cell = row.getCell(28);

                    cell.setCellStyle(style);

                    cell.setCellValue(new BigDecimal(t.getPartQuantity()).multiply(new BigDecimal(t.getPrice()))
                            .divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP).toString());

                    cell = row.getCell(34);

                    cell.setCellStyle(style);

                    cell.setCellValue(t.getProjectType() == null ? "" : t.getProjectType());

                    // 
                    cell = row.getCell(40);

                    cell.setCellStyle(style);

                    cell.setCellValue("");

                    k++;

                }
            }

        }

        if (fixSize > 0) {

            int printFixSize = (fixSize > 8 ? 8 : fixSize);

            for (int j = 0; j < printFixSize; j++) {

                TbFixEntrustContent content = tbFixEntrustContentList.get(j);

                List<TbFixShare> tbFixShareList = tbFixShareService
                        .findTbFixShareListByTbFixEntrustContentId(content.getId());

                String fixPersons = "";

                String workTypes = "";

                if (null != tbFixShareList && tbFixShareList.size() > 0) {

                    for (TbFixShare tbFixShare : tbFixShareList) {

                        if (null != tbFixShare.getTmUser()) {

                            TmUser tmUser = tmUserService.findById(tbFixShare.getTmUser().getId());

                            fixPersons += (tmUser.getUserRealName() == null
                                    || "".equals(tmUser.getUserRealName()) ? tmUser.getUserName()
                                            : tmUser.getUserRealName())
                                    + " ";

                            workTypes += (tmUser.getTmWorkType() == null ? ""
                                    : tmUser.getTmWorkType().getWorkName()) + " ";
                        }

                    }
                }

                row = sheet.getRow(23 + j * 2);

                cell = row.getCell(2);

                cell.setCellStyle(style);

                cell.setCellValue(content.getStationName());

                cell = row.getCell(20);

                cell.setCellStyle(style);

                cell.setCellValue(new BigDecimal(content.getFixHour())
                        .divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP).toString());

                cell = row.getCell(24);

                cell.setCellStyle(style);

                cell.setCellValue(new BigDecimal(content.getWorkingHourPrice())
                        .divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP).toString());

                cell = row.getCell(28);

                cell.setCellStyle(style);

                cell.setCellValue(new BigDecimal(content.getFixHourAll())
                        .divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP).toString());

                cell = row.getCell(34);

                cell.setCellStyle(style);

                cell.setCellValue(content.getProjectType() == null ? "" : content.getProjectType());

                cell = row.getCell(40);

                cell.setCellStyle(style);

                cell.setCellValue(workTypes);

                cell = row.getCell(45);

                cell.setCellStyle(style);

                cell.setCellValue(fixPersons);

            }

        }

        if (partAllSize > 0) {

            int printPartSize = (partAllSize > 12 ? 12 : partAllSize);

            for (int j = 0; j < printPartSize; j++) {

                TbMaintianVo t = partAll.get(j);

                row = sheet.getRow(41 + j * 2);

                cell = row.getCell(2);

                cell.setCellStyle(style);

                cell.setCellValue(t.getPartCode());

                cell = row.getCell(11);

                cell.setCellStyle(style);

                cell.setCellValue(t.getPartName());

                cell = row.getCell(20);

                cell.setCellStyle(style);

                cell.setCellValue(new BigDecimal(t.getPartQuantity())
                        .divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP).toString());

                cell = row.getCell(24);

                cell.setCellStyle(style);

                cell.setCellValue(new BigDecimal(t.getPrice())
                        .divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP).toString());

                cell = row.getCell(28);

                cell.setCellStyle(style);

                cell.setCellValue(new BigDecimal(t.getPartQuantity()).multiply(new BigDecimal(t.getPrice()))
                        .divide(new BigDecimal("1.00"), 2, BigDecimal.ROUND_HALF_UP).toString());

                cell = row.getCell(34);

                cell.setCellStyle(style);

                cell.setCellValue(t.getProjectType() == null ? "" : t.getProjectType());

                // 
                cell = row.getCell(40);

                cell.setCellStyle(style);

                cell.setCellValue("");

            }

        }

        workbook.write(os);

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

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

public List<WaterChargeDashBoardResponse> getResponseTableDataForBillCollector(
        final WaterChargeDashBoardRequest collectionDetailsRequest) {

    final Map<String, WaterChargeDashBoardResponse> wardReceiptDetails = new HashMap<>();
    final Map<String, List<WaterChargeDashBoardResponse>> billCollectorWiseMap = new LinkedHashMap<>();

    final List<WaterChargeDashBoardResponse> billCollectorWiseTableData = new ArrayList<>();

    for (final WaterChargeDashBoardResponse tableData : getResponseTableData(collectionDetailsRequest))
        wardReceiptDetails.put(tableData.getWardName(), tableData);

    final List<BillCollectorIndex> billCollectorsList = getBillCollectorDetails(collectionDetailsRequest);

    for (final BillCollectorIndex billCollIndex : billCollectorsList) {
        final List<WaterChargeDashBoardResponse> collDetails = new ArrayList<>();
        if (wardReceiptDetails.get(billCollIndex.getRevenueWard()) != null
                && StringUtils.isNotBlank(billCollIndex.getRevenueWard()))
            if (billCollectorWiseMap.isEmpty() || !billCollectorWiseMap.isEmpty()
                    && !billCollectorWiseMap.containsKey(billCollIndex.getBillCollector())) {
                collDetails.add(wardReceiptDetails.get(billCollIndex.getRevenueWard()));
                billCollectorWiseMap.put(billCollIndex.getBillCollector(), collDetails);
            } else
                billCollectorWiseMap.get(billCollIndex.getBillCollector())
                        .add(wardReceiptDetails.get(billCollIndex.getRevenueWard()));
    }//  w ww .ja  v a2  s .  c om
    for (final Entry<String, List<WaterChargeDashBoardResponse>> entry : billCollectorWiseMap.entrySet()) {
        final WaterChargeDashBoardResponse collTableData = new WaterChargeDashBoardResponse();
        BigDecimal currDayColl = BigDecimal.ZERO;
        BigDecimal cytdColl = BigDecimal.ZERO;
        BigDecimal lytdColl = BigDecimal.ZERO;
        BigDecimal cytdDmd = BigDecimal.ZERO;
        BigDecimal performance = BigDecimal.ZERO;
        BigDecimal totalDmd = BigDecimal.ZERO;
        BigDecimal variance = BigDecimal.ZERO;

        for (final WaterChargeDashBoardResponse tableData : entry.getValue()) {
            currDayColl = currDayColl
                    .add(tableData.getTodayColl() == null ? BigDecimal.ZERO : tableData.getTodayColl());
            cytdColl = cytdColl.add(tableData.getCurrentYearTillDateColl() == null ? BigDecimal.ZERO
                    : tableData.getCurrentYearTillDateColl());
            cytdDmd = cytdDmd.add(tableData.getCurrentYearTillDateDmd() == null ? BigDecimal.ZERO
                    : tableData.getCurrentYearTillDateDmd());
            totalDmd = totalDmd
                    .add(tableData.getTotalDmd() == null ? BigDecimal.ZERO : tableData.getTotalDmd());
            lytdColl = lytdColl.add(tableData.getLastYearTillDateColl() == null ? BigDecimal.ZERO
                    : tableData.getLastYearTillDateColl());
        }
        collTableData.setBillCollector(entry.getKey());
        collTableData.setTodayColl(currDayColl);
        collTableData.setCurrentYearTillDateColl(cytdColl);
        collTableData.setCurrentYearTillDateDmd(cytdDmd);
        collTableData.setCurrentYearTillDateBalDmd(cytdDmd.subtract(cytdColl));
        collTableData.setTotalDmd(totalDmd);
        collTableData.setLastYearTillDateColl(lytdColl);
        if (cytdDmd != BigDecimal.valueOf(0)) {
            performance = collTableData.getCurrentYearTillDateColl().multiply(WaterTaxConstants.BIGDECIMAL_100)
                    .divide(cytdDmd, 1, BigDecimal.ROUND_HALF_UP);
            collTableData.setPerformance(performance);
        }
        if (collTableData.getLastYearTillDateColl().compareTo(BigDecimal.ZERO) == 0)
            variance = WaterTaxConstants.BIGDECIMAL_100;
        else
            variance = collTableData.getCurrentYearTillDateColl()
                    .subtract(collTableData.getLastYearTillDateColl())
                    .multiply(WaterTaxConstants.BIGDECIMAL_100)
                    .divide(collTableData.getLastYearTillDateColl(), 1, BigDecimal.ROUND_HALF_UP);
        collTableData.setLastYearVar(variance);
        billCollectorWiseTableData.add(collTableData);
    }
    return billCollectorWiseTableData;

}

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

/**
 * Populates Receipt Table Details/*from   www. ja v a  2s  .  c  o  m*/
 * 
 * @param collectionDetailsRequest
 * @return list
 */
public List<ReceiptTableData> getReceiptTableData(CollectionDetailsRequest collectionDetailsRequest) {
    ReceiptTableData receiptData;
    List<ReceiptTableData> receiptDataList = new ArrayList<>();
    Date fromDate;
    Date toDate;
    String name;
    BigDecimal variance;
    String aggregationField = REGION_NAME;
    final CFinancialYear financialYear = cFinancialYearService.getFinancialYearByDate(new Date());

    /**
     * Select the grouping based on the type parameter, by default the grouping is done based on Regions. If type is region,
     * group by Region, if type is district, group by District, if type is ulb, group by ULB
     */
    if (StringUtils.isNotBlank(collectionDetailsRequest.getType())) {
        if (collectionDetailsRequest.getType().equalsIgnoreCase(DASHBOARD_GROUPING_REGIONWISE))
            aggregationField = REGION_NAME;
        else if (collectionDetailsRequest.getType().equalsIgnoreCase(DASHBOARD_GROUPING_DISTRICTWISE))
            aggregationField = DISTRICT_NAME;
        else if (collectionDetailsRequest.getType().equalsIgnoreCase(DASHBOARD_GROUPING_ULBWISE))
            aggregationField = CITY_NAME;
        else if (collectionDetailsRequest.getType().equalsIgnoreCase(DASHBOARD_GROUPING_GRADEWISE))
            aggregationField = CITY_GRADE;
        else if (collectionDetailsRequest.getType().equalsIgnoreCase(DASHBOARD_GROUPING_WARDWISE))
            aggregationField = REVENUE_WARD;
    }
    /**
     * For Current day's collection if dates are sent in the request, consider the toDate, else take date range between
     * current date +1 day
     */
    if (StringUtils.isNotBlank(collectionDetailsRequest.getFromDate())
            && StringUtils.isNotBlank(collectionDetailsRequest.getToDate())) {
        fromDate = DateUtils.getDate(collectionDetailsRequest.getFromDate(), DATE_FORMAT_YYYYMMDD);
        toDate = DateUtils
                .addDays(DateUtils.getDate(collectionDetailsRequest.getToDate(), DATE_FORMAT_YYYYMMDD), 1);
    } else {
        fromDate = new Date();
        toDate = DateUtils.addDays(new Date(), 1);
    }
    Map<String, BigDecimal> currDayCollMap = getCollectionAndDemandCountResults(collectionDetailsRequest,
            fromDate, toDate, COLLECTION_INDEX_NAME, CONSUMER_CODE, aggregationField);
    /**
     * For collections between the date ranges if dates are sent in the request, consider the same, else calculate from
     * current year start date till current date+1 day
     */
    if (StringUtils.isNotBlank(collectionDetailsRequest.getFromDate())
            && StringUtils.isNotBlank(collectionDetailsRequest.getToDate())) {
        fromDate = DateUtils.getDate(collectionDetailsRequest.getFromDate(), DATE_FORMAT_YYYYMMDD);
        toDate = DateUtils
                .addDays(DateUtils.getDate(collectionDetailsRequest.getToDate(), DATE_FORMAT_YYYYMMDD), 1);
    } else {
        fromDate = DateUtils.startOfDay(financialYear.getStartingDate());
        toDate = DateUtils.addDays(new Date(), 1);
    }
    Map<String, BigDecimal> cytdCollMap = getCollectionAndDemandCountResults(collectionDetailsRequest, fromDate,
            toDate, COLLECTION_INDEX_NAME, CONSUMER_CODE, aggregationField);

    // For last year's till date collections
    Map<String, BigDecimal> lytdCollMap = getCollectionAndDemandCountResults(collectionDetailsRequest,
            DateUtils.addYears(fromDate, -1), DateUtils.addYears(toDate, -1), COLLECTION_INDEX_NAME,
            CONSUMER_CODE, aggregationField);
    for (Map.Entry<String, BigDecimal> entry : cytdCollMap.entrySet()) {
        receiptData = new ReceiptTableData();
        name = entry.getKey();
        if (aggregationField.equals(REGION_NAME))
            receiptData.setRegionName(name);
        else if (aggregationField.equals(DISTRICT_NAME)) {
            receiptData.setRegionName(collectionDetailsRequest.getRegionName());
            receiptData.setDistrictName(name);
        } else if (aggregationField.equals(CITY_NAME)) {
            receiptData.setUlbName(name);
            receiptData.setDistrictName(collectionDetailsRequest.getDistrictName());
            receiptData.setUlbGrade(collectionDetailsRequest.getUlbGrade());
        } else if (aggregationField.equals(CITY_GRADE))
            receiptData.setUlbGrade(name);
        else if (aggregationField.equals(REVENUE_WARD))
            receiptData.setWardName(name);

        receiptData.setCytdColl(entry.getValue());
        receiptData.setCurrDayColl(
                currDayCollMap.get(name) == null ? BigDecimal.valueOf(0) : currDayCollMap.get(name));
        receiptData.setLytdColl(lytdCollMap.get(name) == null ? BigDecimal.valueOf(0) : lytdCollMap.get(name));
        // variance = ((currentYearCollection
        // -lastYearCollection)*100)/lastYearCollection
        if (receiptData.getLytdColl().compareTo(BigDecimal.ZERO) == 0)
            variance = PropertyTaxConstants.BIGDECIMAL_100;
        else
            variance = ((receiptData.getCytdColl().subtract(receiptData.getLytdColl()))
                    .multiply(PropertyTaxConstants.BIGDECIMAL_100)).divide(receiptData.getLytdColl(), 1,
                            BigDecimal.ROUND_HALF_UP);
        receiptData.setLyVar(variance);
        receiptDataList.add(receiptData);
    }
    return receiptDataList;
}