Example usage for java.math BigDecimal setScale

List of usage examples for java.math BigDecimal setScale

Introduction

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

Prototype

@Deprecated(since = "9")
public BigDecimal setScale(int newScale, int roundingMode) 

Source Link

Document

Returns a BigDecimal whose scale is the specified value, and whose unscaled value is determined by multiplying or dividing this BigDecimal 's unscaled value by the appropriate power of ten to maintain its overall value.

Usage

From source file:org.wso2.carbon.appmgt.impl.utils.AppManagerUtil.java

/**
 * This method used to get WebApp from governance artifact specific to
 * copyAPI//  ww  w  .  j  av  a 2 s  .  co  m
 * 
 * @param artifact
 *            WebApp artifact
 * @param registry
 *            Registry
 * @return WebApp
 * @throws org.wso2.carbon.appmgt.api.AppManagementException
 *             if failed to get WebApp from artifact
 */
public static WebApp getAPI(GovernanceArtifact artifact, Registry registry, APIIdentifier oldId)
        throws AppManagementException {

    WebApp api;
    try {
        String providerName = artifact.getAttribute(AppMConstants.API_OVERVIEW_PROVIDER);
        String apiName = artifact.getAttribute(AppMConstants.API_OVERVIEW_NAME);
        String apiVersion = artifact.getAttribute(AppMConstants.API_OVERVIEW_VERSION);
        api = new WebApp(new APIIdentifier(providerName, apiName, apiVersion));
        // set rating
        String artifactPath = GovernanceUtils.getArtifactPath(registry, artifact.getId());
        BigDecimal bigDecimal = new BigDecimal(registry.getAverageRating(artifactPath));
        BigDecimal res = bigDecimal.setScale(1, RoundingMode.HALF_UP);
        api.setRating(res.floatValue());
        // set description
        api.setDescription(artifact.getAttribute(AppMConstants.API_OVERVIEW_DESCRIPTION));
        // set last access time
        api.setLastUpdated(registry.get(artifactPath).getLastModified());
        // set url
        api.setUrl(artifact.getAttribute(AppMConstants.API_OVERVIEW_ENDPOINT_URL));
        api.setLogoutURL(artifact.getAttribute(AppMConstants.API_OVERVIEW_LOGOUT_URL));
        api.setSandboxUrl(artifact.getAttribute(AppMConstants.API_OVERVIEW_SANDBOX_URL));
        api.setStatus(getApiStatus(artifact.getAttribute(AppMConstants.API_OVERVIEW_STATUS)));
        api.setThumbnailUrl(artifact.getAttribute(AppMConstants.API_OVERVIEW_THUMBNAIL_URL));
        api.setWsdlUrl(artifact.getAttribute(AppMConstants.API_OVERVIEW_WSDL));
        api.setWadlUrl(artifact.getAttribute(AppMConstants.API_OVERVIEW_WADL));
        api.setTechnicalOwner(artifact.getAttribute(AppMConstants.API_OVERVIEW_TEC_OWNER));
        api.setTechnicalOwnerEmail(artifact.getAttribute(AppMConstants.API_OVERVIEW_TEC_OWNER_EMAIL));
        api.setBusinessOwner(artifact.getAttribute(AppMConstants.API_OVERVIEW_BUSS_OWNER));
        api.setBusinessOwnerEmail(artifact.getAttribute(AppMConstants.API_OVERVIEW_BUSS_OWNER_EMAIL));
        api.setEndpointSecured(
                Boolean.parseBoolean(artifact.getAttribute(AppMConstants.API_OVERVIEW_ENDPOINT_SECURED)));
        api.setEndpointUTUsername(artifact.getAttribute(AppMConstants.API_OVERVIEW_ENDPOINT_USERNAME));
        api.setEndpointUTPassword(artifact.getAttribute(AppMConstants.API_OVERVIEW_ENDPOINT_PASSWORD));
        api.setTransports(artifact.getAttribute(AppMConstants.API_OVERVIEW_TRANSPORTS));

        api.setEndpointConfig(artifact.getAttribute(AppMConstants.API_OVERVIEW_ENDPOINT_CONFIG));

        api.setRedirectURL(artifact.getAttribute(AppMConstants.API_OVERVIEW_REDIRECT_URL));
        api.setAppOwner(artifact.getAttribute(AppMConstants.API_OVERVIEW_OWNER));
        api.setAdvertiseOnly(
                Boolean.parseBoolean(artifact.getAttribute(AppMConstants.API_OVERVIEW_ADVERTISE_ONLY)));

        api.setSubscriptionAvailability(
                artifact.getAttribute(AppMConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABILITY));
        api.setSubscriptionAvailableTenants(
                artifact.getAttribute(AppMConstants.API_OVERVIEW_SUBSCRIPTION_AVAILABLE_TENANTS));

        api.setResponseCache(artifact.getAttribute(AppMConstants.API_OVERVIEW_RESPONSE_CACHING));

        api.setSsoEnabled(artifact.getAttribute("sso_enableSso"));
        api.setUUID(artifact.getId());
        api.setThumbnailUrl(artifact.getAttribute(AppMConstants.APP_IMAGES_THUMBNAIL));

        int cacheTimeout = AppMConstants.API_RESPONSE_CACHE_TIMEOUT;
        try {
            cacheTimeout = Integer.parseInt(artifact.getAttribute(AppMConstants.API_OVERVIEW_CACHE_TIMEOUT));
        } catch (NumberFormatException e) {
            // ignore
        }

        String tenantDomainName = MultitenantUtils.getTenantDomain(replaceEmailDomainBack(providerName));
        int tenantId = ServiceReferenceHolder.getInstance().getRealmService().getTenantManager()
                .getTenantId(tenantDomainName);

        Set<Tier> availableTier = new HashSet<Tier>();
        String tiers = artifact.getAttribute(AppMConstants.API_OVERVIEW_TIER);
        Map<String, Tier> definedTiers = getTiers(tenantId);
        if (tiers != null && !"".equals(tiers)) {
            String[] tierNames = tiers.split("\\|\\|");
            for (String tierName : tierNames) {
                Tier definedTier = definedTiers.get(tierName);
                if (definedTier != null) {
                    availableTier.add(definedTier);
                } else {
                    log.warn("Unknown tier: " + tierName + " found on WebApp: " + apiName);
                }
            }
        }
        api.addAvailableTiers(availableTier);
        api.setContext(artifact.getAttribute(AppMConstants.API_OVERVIEW_CONTEXT));
        api.setLatest(Boolean.valueOf(artifact.getAttribute(AppMConstants.API_OVERVIEW_IS_LATEST)));
        ArrayList<URITemplate> urlPatternsList;

        urlPatternsList = AppMDAO.getAllURITemplates(api.getContext(), oldId.getVersion());
        Set<URITemplate> uriTemplates = new HashSet<URITemplate>(urlPatternsList);

        for (URITemplate uriTemplate : uriTemplates) {
            uriTemplate.setResourceURI(api.getUrl());
            uriTemplate.setResourceSandboxURI(api.getSandboxUrl());

        }
        api.setUriTemplates(uriTemplates);

        Set<String> tags = new HashSet<String>();
        org.wso2.carbon.registry.core.Tag[] tag = registry.getTags(artifactPath);
        for (Tag tag1 : tag) {
            tags.add(tag1.getTagName());
        }
        api.addTags(tags);
        api.setLastUpdated(registry.get(artifactPath).getLastModified());

        //Set Lifecycle status
        if (artifact.getLifecycleState() != null && artifact.getLifecycleState() != "") {
            if (artifact.getLifecycleState().toUpperCase().equalsIgnoreCase(APIStatus.INREVIEW.getStatus())) {
                api.setLifeCycleStatus(APIStatus.INREVIEW);
            } else {
                api.setLifeCycleStatus(APIStatus.valueOf(artifact.getLifecycleState().toUpperCase()));
            }
        }
        api.setLifeCycleName(artifact.getLifecycleName());

    } catch (GovernanceException e) {
        String msg = "Failed to get WebApp fro artifact ";
        throw new AppManagementException(msg, e);
    } catch (RegistryException e) {
        String msg = "Failed to get LastAccess time or Rating";
        throw new AppManagementException(msg, e);
    } catch (UserStoreException e) {
        String msg = "Failed to get User Realm of WebApp Provider";
        throw new AppManagementException(msg, e);
    }
    return api;
}

From source file:com.ugam.collage.plus.service.people_count.impl.PeopleAccountingServiceImpl.java

/**
 *
 *///from w ww . java2 s  .  com
private void getRevenueCountProportion(List<EmpcntClientProjectData> empOpenCntClientProjectDataList,
        List<EmpcntClientProjectData> empCloseCntClientProjectDataList, EmployeeMaster employee, TabMonth month,
        TabYear year, CostCentre costCentre, CountClassification countType, BigDecimal remainProportion,
        Map<Integer, BigDecimal> unAssignedProjects, Integer countTypeId,
        Map<String, EmployeePcTagsTeamStruct> employeePcTagsTeamStructMap) {

    logger.debug("<====getRevenueCountProportion Start====>");
    logger.debug("unAssignedProjects:" + unAssignedProjects.size());
    // get the EmpCntPcApportionApproach for the employee
    Integer employeeId = employee.getEmployeeId();
    Integer yearId = year.getYearId();
    Integer monthId = month.getMonthId();
    String costCentreId = costCentre.getCostCentreId();
    BigDecimal deviderHour = new BigDecimal(Constants.TOTAL_WORKING_HOURS);
    Integer apportionApproach = 0;
    BigDecimal allignedTimeZero = BigDecimal.ZERO;
    BigDecimal asistededTimeZero = BigDecimal.ZERO;
    List<EmpCntPcApportionApproach> empCntPcApportionApproachList = empCntPcApportionApproachDao
            .findByYearIdMonthIdEmployeeId(yearId, monthId, employeeId);
    if (!empCntPcApportionApproachList.isEmpty()) {
        apportionApproach = empCntPcApportionApproachList.get(0).getApportionApproach();
    } else {
        return;
    }

    // logger.debug("1363 : apportionApproach===> "+apportionApproach);
    // get the EmployeePcTagsTeamStruct for the employee
    List<EmployeePcTagsTeamStruct> employeePcTagsTeamStructList = employeePcTagsTeamStructDao
            .findByYearIdMonthIdEmployeeId(yearId, monthId, employeeId);

    if (apportionApproach == 1) {
        for (EmployeePcTagsTeamStruct employeePcTagsTeamStruct : employeePcTagsTeamStructList) {
            BigDecimal count = BigDecimal.ZERO;
            Map<Integer, CollageProjectRevenue> revenueMap = new HashMap<Integer, CollageProjectRevenue>();
            Map<Integer, ProjectMaster> projectMap = new HashMap<Integer, ProjectMaster>();

            BigDecimal proportion = employeePcTagsTeamStruct.getProportion();
            String profitcentreId = employeePcTagsTeamStruct.getProfitCentre().getProfitCentreId();

            // Calculate for each profit centre
            BigDecimal pcProportion = proportion.multiply(remainProportion);

            // asissted projects on count
            List<CollageProjectRevenue> collageProjectRevenueList = collageProjectRevenueDao
                    .findByYearIdMonthIdProfitCentreIdCostCentreId(yearId, monthId, profitcentreId,
                            costCentreId);
            if (!collageProjectRevenueList.isEmpty()) {
                // Select valid project id
                for (CollageProjectRevenue proRevenue : collageProjectRevenueList) {
                    Integer projectId = proRevenue.getProjectMaster().getProjectId();
                    if (unAssignedProjects.isEmpty()) {
                        revenueMap.put(projectId, proRevenue);
                        List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId);
                        projectMap.put(projectId, projectList.get(0));
                    } else {
                        if (unAssignedProjects.containsKey(projectId) == false) {
                            revenueMap.put(projectId, proRevenue);
                            List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId);
                            projectMap.put(projectId, projectList.get(0));
                        }
                    }

                }

                Integer projectCount = revenueMap.size();
                count = new BigDecimal(projectCount);
                if (projectCount > 0) {
                    for (Integer key : revenueMap.keySet()) {
                        BigDecimal projectValue = BigDecimal.ONE.divide(count, 2, RoundingMode.HALF_EVEN);
                        projectValue = projectValue.multiply(pcProportion);
                        ProjectMaster projectMaster = projectMap.get(key);
                        CompanyMaster companyMaster = projectMaster.getCompanyMaster();
                        projectValue = projectValue.setScale(2, RoundingMode.CEILING);
                        // logger.debug("1406 projectValue:======>"+projectValue);
                        EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                                companyMaster, countType, month, projectMaster, year, costCentre,
                                allignedTimeZero, asistededTimeZero, projectValue, projectValue);
                        if (countTypeId == 1) {
                            empOpenCntClientProjectDataList.add(empcntClientProjectData);
                        }
                        if (countTypeId == 2) {
                            empCloseCntClientProjectDataList.add(empcntClientProjectData);
                        }
                        // copy proprotion
                        String mapId = yearId + "-" + monthId + "-" + employeeId + "-" + profitcentreId;
                        EmployeePcTagsTeamStruct employeePcTagsTeamStructCopy = employeePcTagsTeamStruct;
                        employeePcTagsTeamStructCopy.setApportionedCnt(projectValue);
                        employeePcTagsTeamStructMap.put(mapId, employeePcTagsTeamStructCopy);
                    }
                }
            }
        }
    } else if (apportionApproach == 2) {
        for (EmployeePcTagsTeamStruct employeePcTagsTeamStruct : employeePcTagsTeamStructList) {
            BigDecimal count = BigDecimal.ZERO;
            Map<Integer, BigDecimal> hoursMap = new HashMap<Integer, BigDecimal>();
            Map<Integer, Integer> companyMap = new HashMap<Integer, Integer>();

            BigDecimal proportion = employeePcTagsTeamStruct.getProportion();
            String profitcentreId = employeePcTagsTeamStruct.getProfitCentre().getProfitCentreId();
            // Calculate for each profit centre
            BigDecimal pcProportion = proportion.multiply(remainProportion);
            BigDecimal hoursSum = BigDecimal.ZERO;

            List<Object[]> objectList = executionDataDao.findByYearIdMonthIdCostCentreIdProfitCentreId(yearId,
                    monthId, costCentreId, profitcentreId);

            if (!objectList.isEmpty()) {

                for (Object[] result : objectList) {
                    Integer projectId = (Integer) result[0];
                    BigDecimal hour = (BigDecimal) result[1];
                    Integer companyId = (Integer) result[2];
                    if (unAssignedProjects.isEmpty()) {
                        hoursMap.put(projectId, hour);
                        companyMap.put(projectId, companyId);
                        hoursSum.add(hour);
                    } else {
                        if (unAssignedProjects.containsKey(projectId) == false) {
                            hoursMap.put(projectId, hour);
                            companyMap.put(projectId, companyId);
                            hoursSum.add(hour);
                        }
                    }
                }
                for (Integer projectId : hoursMap.keySet()) {
                    BigDecimal hour = hoursMap.get(projectId);
                    ProjectMaster projectMaster = new ProjectMaster();
                    projectMaster.setProjectId(projectId);
                    Integer companyId = companyMap.get(projectId);
                    CompanyMaster companyMaster = new CompanyMaster();
                    companyMaster.setCompanyId(companyId);
                    BigDecimal resultHour = hour.divide(hoursSum, 2, RoundingMode.HALF_EVEN);
                    resultHour = resultHour.multiply(pcProportion);
                    resultHour = resultHour.setScale(2, RoundingMode.CEILING);
                    // logger.debug("1462 :resultHour=====>"+resultHour);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            companyMaster, countType, month, projectMaster, year, costCentre, asistededTimeZero,
                            allignedTimeZero, resultHour, resultHour);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    // copy proprotion
                    String mapId = yearId + "-" + monthId + "-" + employeeId + "-" + profitcentreId;
                    EmployeePcTagsTeamStruct employeePcTagsTeamStructCopy = employeePcTagsTeamStruct;
                    employeePcTagsTeamStructCopy.setApportionedCnt(resultHour);
                    employeePcTagsTeamStructMap.put(mapId, employeePcTagsTeamStructCopy);
                }
            }

        }
    } else if (apportionApproach == 3) {
        for (EmployeePcTagsTeamStruct employeePcTagsTeamStruct : employeePcTagsTeamStructList) {
            Map<Integer, CollageProjectRevenue> revenueMap = new HashMap<Integer, CollageProjectRevenue>();
            Map<Integer, ProjectMaster> projectMap = new HashMap<Integer, ProjectMaster>();

            BigDecimal proportion = employeePcTagsTeamStruct.getProportion();
            BigDecimal devider = new BigDecimal(100);
            proportion = proportion.divide(devider);
            logger.debug("===========================================>" + proportion);
            String profitcentreId = employeePcTagsTeamStruct.getProfitCentre().getProfitCentreId();
            // Calculate for each profit centre
            BigDecimal pcProportion = proportion.multiply(remainProportion);
            BigDecimal revenueSum = BigDecimal.ZERO;
            List<CollageProjectRevenue> collageProjectRevenueList = collageProjectRevenueDao
                    .findByYearIdMonthIdProfitCentreIdCostCentreId(yearId, monthId, profitcentreId,
                            costCentreId);
            if (!collageProjectRevenueList.isEmpty()) {

                for (CollageProjectRevenue revenue : collageProjectRevenueList) {
                    if (unAssignedProjects.isEmpty()) {
                        Integer projectId = revenue.getProjectMaster().getProjectId();
                        logger.debug("1497 =projectId====>" + projectId);
                        revenueMap.put(projectId, revenue);
                        List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId);
                        projectMap.put(projectId, projectList.get(0));
                        BigDecimal revenueVal = revenue.getRevenueValue();
                        // logger.debug("1503 =RevenueValue====>"+revenueVal);
                        revenueSum = revenueSum.add(revenueVal);
                    } else {
                        Integer projectId = revenue.getProjectMaster().getProjectId();
                        if (unAssignedProjects.containsKey(projectId) == false) {
                            // logger.debug("1507 =projectId====>"+projectId);
                            revenueMap.put(projectId, revenue);
                            List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId);
                            projectMap.put(projectId, projectList.get(0));
                            BigDecimal revenueVal = revenue.getRevenueValue();
                            // logger.debug("1514 =RevenueValue====>"+revenue.getRevenueValue()
                            // +" : "+revenueVal);
                            revenueSum = revenueSum.add(revenueVal);

                        }
                    }
                }
                logger.debug("1543 =revenueSum====>" + revenueSum);
                for (Integer projectId : revenueMap.keySet()) {
                    CollageProjectRevenue collageProjectRevenue = revenueMap.get(projectId);
                    ProjectMaster projectMaster = projectMap.get(projectId);
                    CompanyMaster companyMaster = projectMaster.getCompanyMaster();
                    BigDecimal revenueValue = collageProjectRevenue.getRevenueValue();

                    logger.debug("1516 =revenueSum : revenueValue====>" + revenueSum + " : " + revenueValue);
                    revenueValue = revenueValue.divide(revenueSum, 2, RoundingMode.HALF_EVEN);
                    revenueValue = revenueValue.multiply(pcProportion);
                    revenueValue = revenueValue.setScale(2, RoundingMode.CEILING);
                    logger.debug("1515 :Aportioned Count======>" + revenueValue);

                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            companyMaster, countType, month, projectMaster, year, costCentre, allignedTimeZero,
                            asistededTimeZero, revenueValue, revenueValue);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    // copy proprotion
                    String mapId = yearId + "-" + monthId + "-" + employeeId + "-" + profitcentreId;
                    EmployeePcTagsTeamStruct employeePcTagsTeamStructCopy = employeePcTagsTeamStruct;
                    employeePcTagsTeamStructCopy.setApportionedCnt(revenueValue);
                    employeePcTagsTeamStructMap.put(mapId, employeePcTagsTeamStructCopy);
                }
            }

        }

    }
    // logger.debug("<====getRevenueCountProportion End====>");
}

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

private EgDemand generateNextYearDemandForAdvertisement(final Advertisement advertisement,
        final EgDemandReason oldencroachmentFeeReasonInstallment, final EgDemandReason oldtaxReasonInstallment,
        final EgDemandReason newencroachmentFeeReasonInstallment,
        final EgDemandReason newtaxReasonInstallment) {
    BigDecimal totalDemandAmount = BigDecimal.ZERO;
    final EgDemand demand = advertisement.getDemandId();

    Boolean enchroachmentFeeAlreadyExistInDemand = false;
    Boolean taxFeeAlreadyExistInDemand = false;

    EgDemandDetails oldEncroachmentDetail = null;
    EgDemandDetails oldTaxDemandDetail = null;
    final Set<EgDemandDetails> dmadDtl = demand.getEgDemandDetails();

    if (LOGGER.isInfoEnabled())
        LOGGER.info("Demand Detail size" + dmadDtl.size());
    for (final EgDemandDetails dmdDtl : dmadDtl) {
        // Assumption: tax amount is mandatory.
        if (dmdDtl.getEgDemandReason().getId() == oldtaxReasonInstallment.getId())
            oldTaxDemandDetail = dmdDtl;
        if (dmdDtl.getEgDemandReason().getId() == oldencroachmentFeeReasonInstallment.getId())
            oldEncroachmentDetail = dmdDtl;
        if (dmdDtl.getEgDemandReason().getId() == newtaxReasonInstallment.getId())
            taxFeeAlreadyExistInDemand = true;
        if (dmdDtl.getEgDemandReason().getId() == newencroachmentFeeReasonInstallment.getId())
            enchroachmentFeeAlreadyExistInDemand = true;
    }/* w  ww. ja  v  a2 s.co  m*/
    // Copy last financial year tax and encroachment details to new
    // installment
    // if tax and encroachment fee already present in new installment, then
    // we are not updating.

    if (!enchroachmentFeeAlreadyExistInDemand && oldEncroachmentDetail != null) {
        demand.addEgDemandDetails(createDemandDetails(oldEncroachmentDetail.getAmount(),
                newencroachmentFeeReasonInstallment, BigDecimal.ZERO));
        totalDemandAmount = totalDemandAmount.add(oldEncroachmentDetail.getAmount());
    }
    if (!taxFeeAlreadyExistInDemand && oldTaxDemandDetail != null) {
        demand.addEgDemandDetails(
                createDemandDetails(oldTaxDemandDetail.getAmount(), newtaxReasonInstallment, BigDecimal.ZERO));
        totalDemandAmount = totalDemandAmount.add(oldTaxDemandDetail.getAmount());
    }
    demand.setEgInstallmentMaster(newencroachmentFeeReasonInstallment.getEgInstallmentMaster());
    demand.addBaseDemand(totalDemandAmount.setScale(0, BigDecimal.ROUND_HALF_UP));

    return demand;
}

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

/**
 * Format like <blue>[if discount striked]SYMBOL BASEAMOUNT</blue> [if
 * discount <red>SYMBOL DISCOUNTAMOUNT</red>] [if discount <red>Save:
 * PERCENTAGE AMOUNT</red>] [if qty discount <red>Buy QTY save [if price qty
 * discount AMOUNT] [if percent qty discount PERCENT]</red>]
 * // w  ww .  j  ava 2s.co  m
 * @param ctx
 * @param view
 * @return
 */
public static String formatHTMLProductPriceWithAttributes(Locale locale, String currency, Product view,
        Collection attributes, boolean showDiscountDate) {

    if (currency == null) {
        log.error("Currency is null ...");
        return "-N/A-";
    }

    int decimalPlace = 2;

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

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

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

    // determine any properties prices
    BigDecimal attributesPrice = null;

    if (attributes != null) {
        Iterator i = attributes.iterator();
        while (i.hasNext()) {
            ProductAttribute attr = (ProductAttribute) i.next();
            if (!attr.isAttributeDisplayOnly() && attr.getOptionValuePrice().longValue() > 0) {
                if (attributesPrice == null) {
                    attributesPrice = new BigDecimal(0);
                }
                attributesPrice = attributesPrice.add(attr.getOptionValuePrice());
            }
        }
    }

    if (attributesPrice != null) {
        bdprodprice = bdprodprice.add(attributesPrice);// new price with
        // properties
    }

    // discount price
    java.util.Date spdate = null;
    java.util.Date spenddate = null;
    BigDecimal bddiscountprice = null;
    Special special = view.getSpecial();
    if (special != null) {
        bddiscountprice = special.getSpecialNewProductPrice();
        if (attributesPrice != null) {
            bddiscountprice = bddiscountprice.add(attributesPrice);// new
            // price
            // with
            // properties
        }
        spdate = special.getSpecialDateAvailable();
        spenddate = special.getExpiresDate();
    }

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

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

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

    Date dt = new Date();

    // discount price String
    String discountprice = null;
    String savediscount = null;
    if (bddiscountprice != null && (spdate != null && spdate.before(new Date(dt.getTime()))
            && spenddate.after(new Date(dt.getTime())))) {

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

        discountprice = CurrencyUtil.displayFormatedAmountWithCurrency(bddiscountprice, currency);

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

        Float percentagediscount = new Float(fsdiscount);

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

    }

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

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

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

}

From source file:org.kuali.kfs.module.purap.service.impl.PurapAccountingServiceImpl.java

/**
 * @see org.kuali.kfs.module.purap.service.PurapAccountingService#generateAccountDistributionForProrationWithZeroTotal(java.util.List,
 *      java.lang.Integer)/*from  www  .j  a v a 2 s. c o m*/
 */
@Override
public List<PurApAccountingLine> generateAccountDistributionForProrationWithZeroTotal(
        PurchasingAccountsPayableDocument purapDoc) {
    String methodName = "generateAccountDistributionForProrationWithZeroTotal()";
    if (LOG.isDebugEnabled()) {
        LOG.debug(methodName + " started");
    }

    List<PurApAccountingLine> accounts = generatePercentSummary(purapDoc);

    // find the total percent and strip trailing zeros
    BigDecimal totalPercentValue = BigDecimal.ZERO;
    for (PurApAccountingLine accountingLine : accounts) {
        BigDecimal linePercent = BigDecimal.ZERO;
        if (ObjectUtils.isNotNull(accountingLine.getAccountLinePercent())) {
            linePercent = accountingLine.getAccountLinePercent();
        }

        totalPercentValue = totalPercentValue.add(linePercent).movePointLeft(2).stripTrailingZeros()
                .movePointRight(2);
    }

    if ((BigDecimal.ZERO.compareTo(totalPercentValue.remainder(ONE_HUNDRED))) != 0) {
        throwRuntimeException(methodName, "Invalid Percent Total of '" + totalPercentValue
                + "' does not allow for account distribution (must be multiple of 100)");
    }

    List newAccounts = new ArrayList();
    BigDecimal logDisplayOnlyTotal = BigDecimal.ZERO;
    BigDecimal percentUsed = BigDecimal.ZERO;
    int accountListSize = accounts.size();
    int i = 0;
    for (PurApAccountingLine accountingLine : accounts) {
        i++;
        BigDecimal percentToUse = BigDecimal.ZERO;
        KualiDecimal amt = KualiDecimal.ZERO;

        if (ObjectUtils.isNotNull(accountingLine.getAmount())) {
            amt = accountingLine.getAmount();
        }

        if (LOG.isDebugEnabled()) {
            LOG.debug(methodName + " " + accountingLine.getChartOfAccountsCode() + "-"
                    + accountingLine.getAccountNumber() + " " + amt + "/" + percentToUse);
        }

        // if it's the last account make up the leftover percent
        BigDecimal acctPercent = BigDecimal.ZERO;
        if (ObjectUtils.isNotNull(accountingLine.getAccountLinePercent())) {
            acctPercent = accountingLine.getAccountLinePercent();
        }

        if ((i != accountListSize) || (accountListSize == 1)) {
            // this account is not the last account or there is only one account
            percentToUse = (acctPercent.divide(totalPercentValue, SCALE, BIG_DECIMAL_ROUNDING_MODE))
                    .multiply(ONE_HUNDRED);
            percentUsed = percentUsed
                    .add(((acctPercent.divide(totalPercentValue, SCALE, BIG_DECIMAL_ROUNDING_MODE)))
                            .multiply(ONE_HUNDRED));
        } else {
            // this account is the last account so we have to makeup whatever is left out of 100
            percentToUse = ONE_HUNDRED.subtract(percentUsed);
        }

        PurApAccountingLine newAccountingLine = accountingLine.createBlankAmountsCopy();
        if (LOG.isDebugEnabled()) {
            LOG.debug(methodName + " pct = " + percentToUse);
        }
        newAccountingLine
                .setAccountLinePercent(percentToUse.setScale(acctPercent.scale(), BIG_DECIMAL_ROUNDING_MODE));
        if (LOG.isDebugEnabled()) {
            LOG.debug(methodName + " adding " + newAccountingLine.getAccountLinePercent());
        }
        newAccounts.add(newAccountingLine);
        logDisplayOnlyTotal = logDisplayOnlyTotal.add(newAccountingLine.getAccountLinePercent());
        if (LOG.isDebugEnabled()) {
            LOG.debug(methodName + " total = " + logDisplayOnlyTotal);
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug(methodName + " ended");
    }
    return newAccounts;
}

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

public static Map<String, Object> uspsUpdateShipmentRateInfo(DispatchContext dctx,
        Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    String shipmentId = (String) context.get("shipmentId");
    String shipmentRouteSegmentId = (String) context.get("shipmentRouteSegmentId");
    Locale locale = (Locale) context.get("locale");

    Map<String, Object> shipmentGatewayConfig = ShipmentServices.getShipmentGatewayConfigFromShipment(delegator,
            shipmentId, locale);//from w  w  w.j a v a2  s .  com
    String shipmentGatewayConfigId = (String) shipmentGatewayConfig.get("shipmentGatewayConfigId");
    String resource = (String) shipmentGatewayConfig.get("configProps");
    if (UtilValidate.isEmpty(shipmentGatewayConfigId) && UtilValidate.isEmpty(resource)) {
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resourceError, "FacilityShipmentUspsGatewayNotAvailable", locale));
    }

    try {
        GenericValue shipmentRouteSegment = EntityQuery.use(delegator).from("ShipmentRouteSegment")
                .where("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId).queryOne();
        if (shipmentRouteSegment == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "ProductShipmentRouteSegmentNotFound",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }

        // ensure the carrier is USPS
        if (!"USPS".equals(shipmentRouteSegment.getString("carrierPartyId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsNotRouteSegmentCarrier",
                    UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId),
                    locale));
        }

        // get the origin address
        GenericValue originAddress = shipmentRouteSegment.getRelatedOne("OriginPostalAddress", false);
        if (originAddress == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentRouteSegmentOriginPostalAddressNotFound",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }
        if (!"USA".equals(originAddress.getString("countryGeoId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsRouteSegmentOriginCountryGeoNotInUsa",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }
        String originZip = originAddress.getString("postalCode");
        if (UtilValidate.isEmpty(originZip)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsRouteSegmentOriginZipCodeMissing",
                    UtilMisc.toMap("contactMechId", originAddress.getString("contactMechId")), locale));
        }

        // get the destination address
        GenericValue destinationAddress = shipmentRouteSegment.getRelatedOne("DestPostalAddress", false);
        if (destinationAddress == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentRouteSegmentDestPostalAddressNotFound",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }
        if (!"USA".equals(destinationAddress.getString("countryGeoId"))) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsRouteSegmentOriginCountryGeoNotInUsa",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }
        String destinationZip = destinationAddress.getString("postalCode");
        if (UtilValidate.isEmpty(destinationZip)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsRouteSegmentDestinationZipCodeMissing",
                    UtilMisc.toMap("contactMechId", destinationAddress.getString("contactMechId")), locale));
        }

        // get the service type from the CarrierShipmentMethod
        String shipmentMethodTypeId = shipmentRouteSegment.getString("shipmentMethodTypeId");
        String partyId = shipmentRouteSegment.getString("carrierPartyId");

        GenericValue carrierShipmentMethod = EntityQuery.use(delegator).from("CarrierShipmentMethod")
                .where("partyId", partyId, "roleTypeId", "CARRIER", "shipmentMethodTypeId",
                        shipmentMethodTypeId)
                .queryOne();
        if (carrierShipmentMethod == null) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsNoCarrierShipmentMethod",
                    UtilMisc.toMap("carrierPartyId", partyId, "shipmentMethodTypeId", shipmentMethodTypeId),
                    locale));
        }
        String serviceType = carrierShipmentMethod.getString("carrierServiceCode");
        if (UtilValidate.isEmpty(serviceType)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentUspsNoCarrierServiceCodeFound",
                    UtilMisc.toMap("carrierPartyId", partyId, "shipmentMethodTypeId", shipmentMethodTypeId),
                    locale));
        }

        // get the packages for this shipment route segment
        List<GenericValue> shipmentPackageRouteSegList = shipmentRouteSegment
                .getRelated("ShipmentPackageRouteSeg", null, UtilMisc.toList("+shipmentPackageSeqId"), false);
        if (UtilValidate.isEmpty(shipmentPackageRouteSegList)) {
            return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                    "FacilityShipmentPackageRouteSegsNotFound",
                    UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId),
                    locale));
        }

        BigDecimal actualTransportCost = BigDecimal.ZERO;

        String carrierDeliveryZone = null;
        String carrierRestrictionCodes = null;
        String carrierRestrictionDesc = null;

        // send a new request for each package
        for (Iterator<GenericValue> i = shipmentPackageRouteSegList.iterator(); i.hasNext();) {

            GenericValue shipmentPackageRouteSeg = i.next();
            Document requestDocument = createUspsRequestDocument("RateRequest", true, delegator,
                    shipmentGatewayConfigId, resource);

            Element packageElement = UtilXml.addChildElement(requestDocument.getDocumentElement(), "Package",
                    requestDocument);
            packageElement.setAttribute("ID", "0");

            UtilXml.addChildElementValue(packageElement, "Service", serviceType, requestDocument);
            UtilXml.addChildElementValue(packageElement, "ZipOrigination", originZip, requestDocument);
            UtilXml.addChildElementValue(packageElement, "ZipDestination", destinationZip, requestDocument);

            GenericValue shipmentPackage = null;
            shipmentPackage = shipmentPackageRouteSeg.getRelatedOne("ShipmentPackage", false);

            // weight elements - Pounds, Ounces
            String weightStr = shipmentPackage.getString("weight");
            if (UtilValidate.isEmpty(weightStr)) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                        "FacilityShipmentUspsWeightNotFound",
                        UtilMisc.toMap("shipmentId", shipmentPackage.getString("shipmentId"),
                                "shipmentPackageSeqId", shipmentPackage.getString("shipmentPackageSeqId")),
                        locale));
            }

            BigDecimal weight = BigDecimal.ZERO;
            try {
                weight = new BigDecimal(weightStr);
            } catch (NumberFormatException nfe) {
                nfe.printStackTrace(); // TODO: handle exception
            }

            String weightUomId = shipmentPackage.getString("weightUomId");
            if (UtilValidate.isEmpty(weightUomId)) {
                weightUomId = "WT_lb"; // assume weight is in pounds
            }
            if (!"WT_lb".equals(weightUomId)) {
                // attempt a conversion to pounds
                Map<String, Object> result = new HashMap<String, Object>();
                try {
                    result = dispatcher.runSync("convertUom", UtilMisc.<String, Object>toMap("uomId",
                            weightUomId, "uomIdTo", "WT_lb", "originalValue", weight));
                } catch (GenericServiceException ex) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                            "FacilityShipmentUspsWeightConversionError",
                            UtilMisc.toMap("errorString", ex.getMessage()), locale));
                }

                if (result.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_SUCCESS)
                        && result.get("convertedValue") != null) {
                    weight = weight.multiply((BigDecimal) result.get("convertedValue"));
                } else {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                            "FacilityShipmentUspsWeightUnsupported",
                            UtilMisc.toMap("weightUomId", weightUomId, "shipmentId",
                                    shipmentPackage.getString("shipmentId"), "shipmentPackageSeqId",
                                    shipmentPackage.getString("shipmentPackageSeqId"), "weightUom", "WT_lb"),
                            locale));
                }

            }

            BigDecimal weightPounds = weight.setScale(0, BigDecimal.ROUND_FLOOR);
            BigDecimal weightOunces = weight.multiply(new BigDecimal("16")).remainder(new BigDecimal("16"))
                    .setScale(0, BigDecimal.ROUND_CEILING);

            DecimalFormat df = new DecimalFormat("#");
            UtilXml.addChildElementValue(packageElement, "Pounds", df.format(weightPounds), requestDocument);
            UtilXml.addChildElementValue(packageElement, "Ounces", df.format(weightOunces), requestDocument);

            // Container element
            GenericValue carrierShipmentBoxType = null;
            List<GenericValue> carrierShipmentBoxTypes = null;
            carrierShipmentBoxTypes = shipmentPackage.getRelated("CarrierShipmentBoxType",
                    UtilMisc.toMap("partyId", "USPS"), null, false);

            if (carrierShipmentBoxTypes.size() > 0) {
                carrierShipmentBoxType = carrierShipmentBoxTypes.get(0);
            }

            if (carrierShipmentBoxType != null
                    && UtilValidate.isNotEmpty(carrierShipmentBoxType.getString("packagingTypeCode"))) {
                UtilXml.addChildElementValue(packageElement, "Container",
                        carrierShipmentBoxType.getString("packagingTypeCode"), requestDocument);
            } else {
                // default to "None", for customers using their own package
                UtilXml.addChildElementValue(packageElement, "Container", "None", requestDocument);
            }

            // Size element
            if (carrierShipmentBoxType != null && UtilValidate.isNotEmpty("oversizeCode")) {
                UtilXml.addChildElementValue(packageElement, "Size",
                        carrierShipmentBoxType.getString("oversizeCode"), requestDocument);
            } else {
                // default to "Regular", length + girth measurement <= 84 inches
                UtilXml.addChildElementValue(packageElement, "Size", "Regular", requestDocument);
            }

            // Although only applicable for Parcel Post, this tag is required for all requests
            UtilXml.addChildElementValue(packageElement, "Machinable", "False", requestDocument);

            Document responseDocument = null;
            try {
                responseDocument = sendUspsRequest("Rate", requestDocument, delegator, shipmentGatewayConfigId,
                        resource, locale);
            } catch (UspsRequestException e) {
                Debug.logInfo(e, module);
                return ServiceUtil.returnError(
                        UtilProperties.getMessage(resourceError, "FacilityShipmentUspsRateDomesticSendingError",
                                UtilMisc.toMap("errorString", e.getMessage()), locale));
            }

            Element respPackageElement = UtilXml.firstChildElement(responseDocument.getDocumentElement(),
                    "Package");
            if (respPackageElement == null) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                        "FacilityShipmentUspsRateDomesticResponseIncompleteElementPackage", locale));
            }

            Element respErrorElement = UtilXml.firstChildElement(respPackageElement, "Error");
            if (respErrorElement != null) {
                return ServiceUtil
                        .returnError(UtilProperties
                                .getMessage(resourceError, "FacilityShipmentUspsRateDomesticResponseError",
                                        UtilMisc.toMap("errorString",
                                                UtilXml.childElementValue(respErrorElement, "Description")),
                                        locale));
            }

            // update the ShipmentPackageRouteSeg
            String postageString = UtilXml.childElementValue(respPackageElement, "Postage");
            if (UtilValidate.isEmpty(postageString)) {
                return ServiceUtil.returnError(UtilProperties.getMessage(resourceError,
                        "FacilityShipmentUspsRateDomesticResponseIncompleteElementPostage", locale));
            }

            BigDecimal postage = BigDecimal.ZERO;
            try {
                postage = new BigDecimal(postageString);
            } catch (NumberFormatException nfe) {
                nfe.printStackTrace(); // TODO: handle exception
            }
            actualTransportCost = actualTransportCost.add(postage);

            shipmentPackageRouteSeg.setString("packageTransportCost", postageString);
            shipmentPackageRouteSeg.store();

            // if this is the last package, get the zone and APO/FPO restrictions for the ShipmentRouteSegment
            if (!i.hasNext()) {
                carrierDeliveryZone = UtilXml.childElementValue(respPackageElement, "Zone");
                carrierRestrictionCodes = UtilXml.childElementValue(respPackageElement, "RestrictionCodes");
                carrierRestrictionDesc = UtilXml.childElementValue(respPackageElement,
                        "RestrictionDescription");
            }
        }

        // update the ShipmentRouteSegment
        shipmentRouteSegment.set("carrierDeliveryZone", carrierDeliveryZone);
        shipmentRouteSegment.set("carrierRestrictionCodes", carrierRestrictionCodes);
        shipmentRouteSegment.set("carrierRestrictionDesc", carrierRestrictionDesc);
        shipmentRouteSegment.setString("actualTransportCost", String.valueOf(actualTransportCost));
        shipmentRouteSegment.store();

    } catch (GenericEntityException gee) {
        Debug.logInfo(gee, module);
        return ServiceUtil.returnError(
                UtilProperties.getMessage(resourceError, "FacilityShipmentUspsRateDomesticReadingError",
                        UtilMisc.toMap("errorString", gee.getMessage()), locale));
    }

    return ServiceUtil.returnSuccess();
}

From source file:com.wasteofplastic.acidisland.commands.IslandCmd.java

private void resetMoney(Player player) {
    if (!Settings.useEconomy) {
        return;// ww w . j  a  v a 2s.c  o m
    }
    // Set player's balance in acid island to the starting balance
    try {
        // plugin.getLogger().info("DEBUG: " + player.getName() + " " +
        // Settings.general_worldName);
        if (VaultHelper.econ == null) {
            // plugin.getLogger().warning("DEBUG: econ is null!");
            VaultHelper.setupEconomy();
        }
        Double playerBalance = VaultHelper.econ.getBalance(player, Settings.worldName);
        // plugin.getLogger().info("DEBUG: playerbalance = " +
        // playerBalance);
        // Round the balance to 2 decimal places and slightly down to
        // avoid issues when withdrawing the amount later
        BigDecimal bd = new BigDecimal(playerBalance);
        bd = bd.setScale(2, RoundingMode.HALF_DOWN);
        playerBalance = bd.doubleValue();
        // plugin.getLogger().info("DEBUG: playerbalance after rounding = "
        // + playerBalance);
        if (playerBalance != Settings.startingMoney) {
            if (playerBalance > Settings.startingMoney) {
                Double difference = playerBalance - Settings.startingMoney;
                EconomyResponse response = VaultHelper.econ.withdrawPlayer(player, Settings.worldName,
                        difference);
                // plugin.getLogger().info("DEBUG: withdrawn");
                if (response.transactionSuccess()) {
                    plugin.getLogger()
                            .info("FYI:" + player.getName() + " had " + VaultHelper.econ.format(playerBalance)
                                    + " when they typed /island and it was set to " + Settings.startingMoney);
                } else {
                    plugin.getLogger().warning("Problem trying to withdraw " + playerBalance + " from "
                            + player.getName() + "'s account when they typed /island!");
                    plugin.getLogger().warning("Error from economy was: " + response.errorMessage);
                }
            } else {
                Double difference = Settings.startingMoney - playerBalance;
                EconomyResponse response = VaultHelper.econ.depositPlayer(player, Settings.worldName,
                        difference);
                if (response.transactionSuccess()) {
                    plugin.getLogger()
                            .info("FYI:" + player.getName() + " had " + VaultHelper.econ.format(playerBalance)
                                    + " when they typed /island and it was set to " + Settings.startingMoney);
                } else {
                    plugin.getLogger().warning("Problem trying to deposit " + playerBalance + " from "
                            + player.getName() + "'s account when they typed /island!");
                    plugin.getLogger().warning("Error from economy was: " + response.errorMessage);
                }

            }
        }
    } catch (final Exception e) {
        plugin.getLogger()
                .severe("Error trying to zero " + player.getName() + "'s account when they typed /island!");
        plugin.getLogger().severe(e.getMessage());
    }

}

From source file:fr.paris.lutece.plugins.suggest.web.SuggestJspBean.java

/**
 * Gets the form statistics page/*from w ww.j a v a 2 s . com*/
 *
 * @param request
 *            the http request
 * @return the form test page
 */
public String getStatistics(HttpServletRequest request) {
    Plugin plugin = getPlugin();
    Locale locale = getLocale();
    Timestamp tFirstDateFilter = null;
    Timestamp tLastDateFilter = null;
    SuggestFilter suggestFilter = new SuggestFilter();
    suggestFilter.setIdState(Suggest.STATE_ENABLE);

    List<Suggest> listSuggest = SuggestHome.getSuggestList(suggestFilter, plugin);

    String strIdSuggest = request.getParameter(PARAMETER_ID_SUGGEST);
    String strFirstDateFilter = request.getParameter(PARAMETER_FIRST_DATE_FILTER);
    String strLastDateFilter = request.getParameter(PARAMETER_LAST_DATE_FILTER);
    String strIdCategory = request.getParameter(PARAMETER_ID_CATEGORY_FILTER);
    String strIdType = request.getParameter(PARAMETER_ID_TYPE_SUGGEST);

    int nIdCategory = SuggestUtils.getIntegerParameter(strIdCategory);
    int nIdType = SuggestUtils.getIntegerParameter(strIdType);

    if ((strIdSuggest != null) && !strIdSuggest.equals(EMPTY_STRING)) {
        _nIdSuggest = SuggestUtils.getIntegerParameter(strIdSuggest);
    } else if (listSuggest.size() > 0) {
        _nIdSuggest = listSuggest.get(0).getIdSuggest();
    }

    Suggest suggest = SuggestHome.findByPrimaryKey(_nIdSuggest, plugin);

    if ((strFirstDateFilter != null) && !strFirstDateFilter.equals("")) {
        try {
            tFirstDateFilter = new Timestamp(DateUtil.formatDate(strFirstDateFilter, locale).getTime());
        } catch (Exception e) {
            tFirstDateFilter = null;
        }
    }

    if ((strLastDateFilter != null) && !strLastDateFilter.equals("")) {
        try {
            tLastDateFilter = new Timestamp(DateUtil.formatDate(strLastDateFilter, locale).getTime());
        } catch (Exception e) {
            tLastDateFilter = null;
        }
    }

    // build Filter
    SubmitFilter filter = new SubmitFilter();
    filter.setIdSuggest(_nIdSuggest);
    filter.setDateFirst(tFirstDateFilter);
    filter.setDateLast(tLastDateFilter);
    filter.setIdCategory(nIdCategory);
    filter.setIdType(nIdType);

    // number of comments
    filter.setIdSuggestSubmitState(SuggestSubmit.STATE_PUBLISH);

    int nNbComments = _commentSubmitService.getCountCommentSubmit(filter, plugin);

    // number of votes
    filter.setIdSuggestSubmitState(SuggestSubmit.STATE_PUBLISH);

    int nNbVotes = 0;

    List<SuggestSubmit> listSuggestSubmit = _suggestSubmitService.getSuggestSubmitList(filter, plugin);
    List<String> listUsersKey = new ArrayList<String>();

    for (SuggestSubmit d : listSuggestSubmit) {
        nNbVotes += d.getNumberVote();

        if (!listUsersKey.contains(d.getLuteceUserKey())) {
            listUsersKey.add(d.getLuteceUserKey());
        }
    }

    // number of suggest submit
    filter.setIdSuggestSubmitState(SuggestSubmit.STATE_DISABLE);

    int nNbSuggestSubmitDisabled = _suggestSubmitService.getCountSuggestSubmit(filter, plugin);
    filter.setIdSuggestSubmitState(SuggestSubmit.STATE_WAITING_FOR_PUBLISH);

    int nNbSuggestSubmitWaiting = _suggestSubmitService.getCountSuggestSubmit(filter, plugin);
    filter.setIdSuggestSubmitState(SuggestSubmit.STATE_PUBLISH);

    int nNbSuggestSubmitPublished = _suggestSubmitService.getCountSuggestSubmit(filter, plugin);

    // high scores
    SuggestUtils.initSubmitFilterBySort(filter, SubmitFilter.SORT_BY_SCORE_DESC);

    int nNumberMaxSuggestSubmit = AppPropertiesService.getPropertyInt(PROPERTY_SUGGESTSUBMIT_HIGHSCORES, 10);
    listSuggestSubmit = _suggestSubmitService.getSuggestSubmitList(filter, plugin, nNumberMaxSuggestSubmit);

    ReferenceList refSuggestList = SuggestUtils.getRefListSuggest(listSuggest, false);

    Map<String, Object> model = new HashMap<String, Object>();

    model.put(MARK_FIRST_DATE_FILTER, (tFirstDateFilter == null) ? null : new Date(tFirstDateFilter.getTime()));
    model.put(MARK_LAST_DATE_FILTER, (tLastDateFilter == null) ? null : new Date(tLastDateFilter.getTime()));
    model.put(MARK_SUGGEST, suggest);

    if (nNbSuggestSubmitPublished != 0) {
        float fV = (float) nNbVotes / nNbSuggestSubmitPublished;
        float fC = (float) nNbComments / nNbSuggestSubmitPublished;

        BigDecimal bd = new BigDecimal(fV);
        bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP);

        BigDecimal bd2 = new BigDecimal(fC);
        bd2 = bd2.setScale(2, BigDecimal.ROUND_HALF_UP);

        model.put(MARK_NUMBER_VOTES, bd.toString());
        model.put(MARK_NUMBER_COMMENTS, bd2.toString());
    }

    if ((suggest.getCategories() != null) && !suggest.getCategories().isEmpty()) {
        ReferenceList refCategoryList = SuggestUtils.getRefListCategory(suggest.getCategories());
        SuggestUtils.addEmptyItem(refCategoryList);
        model.put(MARK_CATEGORY_LIST, refCategoryList);
        model.put(MARK_SUGGEST_SUBMIT_CATEGORY_SELECTED, nIdCategory);

        if (nIdCategory != SuggestUtils.CONSTANT_ID_NULL) {
            model.put(MARK_CATEGORY_FILTER, CategoryHome.findByPrimaryKey(nIdCategory, plugin));
        }
    }

    if ((suggest.getSuggestSubmitTypes() != null) && !suggest.getSuggestSubmitTypes().isEmpty()) {
        ReferenceList refSuggestSubmitTypes = SuggestUtils.getRefListType(suggest.getSuggestSubmitTypes());
        SuggestUtils.addEmptyItem(refSuggestSubmitTypes);
        model.put(MARK_SUGGEST_SUBMIT_TYPE_LIST, refSuggestSubmitTypes);
        model.put(MARK_SUGGEST_SUBMIT_TYPE_SELECTED, nIdType);

        if (nIdType != SuggestUtils.CONSTANT_ID_NULL) {
            model.put(MARK_TYPE_FILTER, SuggestSubmitTypeHome.findByPrimaryKey(nIdType, plugin));
        }
    }

    model.put(MARK_NUMBER_SUGGESTSUBMIT_DISABLED, nNbSuggestSubmitDisabled);
    model.put(MARK_NUMBER_SUGGESTSUBMIT_WAITING, nNbSuggestSubmitWaiting);
    model.put(MARK_NUMBER_SUGGESTSUBMIT_PUBLISHED, nNbSuggestSubmitPublished);
    model.put(MARK_NUMBER_USERS, listUsersKey.size());
    model.put(MARK_HIGH_SCORES, listSuggestSubmit);
    model.put(MARK_SUGGEST_LIST, refSuggestList);
    model.put(MARK_URL, AppPathService.getBaseUrl(request) + JSP_MANAGE_COMMENT_SUBMIT + "?id_suggest_submit=");

    HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_STATISTICS_SUGGEST, locale, model);

    return getAdminPage(template.getHtml());
}

From source file:org.apache.ofbiz.accounting.invoice.InvoiceServices.java

public static Map<String, Object> createCommissionInvoices(DispatchContext dctx, Map<String, Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    List<String> salesInvoiceIds = UtilGenerics.checkList(context.get("invoiceIds"));
    List<Map<String, String>> invoicesCreated = new LinkedList<Map<String, String>>();
    Map<String, List<Map<String, Object>>> commissionParties = new HashMap<String, List<Map<String, Object>>>();
    for (String salesInvoiceId : salesInvoiceIds) {
        List<String> salesRepPartyIds = UtilGenerics.checkList(context.get("partyIds"));
        BigDecimal amountTotal = InvoiceWorker.getInvoiceTotal(delegator, salesInvoiceId);
        if (amountTotal.signum() == 0) {
            Debug.logWarning("Invoice [" + salesInvoiceId + "] has an amount total of [" + amountTotal
                    + "], so no commission invoice will be created", module);
            return ServiceUtil.returnError(UtilProperties.getMessage(resource,
                    "AccountingInvoiceCommissionZeroInvoiceAmount", locale));
        }/*from  w  ww  . j  av  a2 s.  c  om*/
        BigDecimal appliedFraction = amountTotal.divide(amountTotal, 12, ROUNDING);
        GenericValue invoice = null;
        boolean isReturn = false;
        List<String> billFromVendorInvoiceRoles = new ArrayList<String>();
        List<GenericValue> invoiceItems = new ArrayList<GenericValue>();
        try {
            List<EntityExpr> invoiceRoleConds = UtilMisc.toList(
                    EntityCondition.makeCondition("invoiceId", EntityOperator.EQUALS, salesInvoiceId),
                    EntityCondition.makeCondition("roleTypeId", EntityOperator.EQUALS, "BILL_FROM_VENDOR"));
            EntityQuery roleQuery = EntityQuery.use(delegator).select("partyId").from("InvoiceRole")
                    .where(invoiceRoleConds);
            billFromVendorInvoiceRoles = EntityUtil.getFieldListFromEntityList(roleQuery.queryList(), "partyId",
                    true);

            invoiceRoleConds = UtilMisc.toList(
                    EntityCondition.makeCondition("invoiceId", EntityOperator.EQUALS, salesInvoiceId),
                    EntityCondition.makeCondition("roleTypeId", EntityOperator.EQUALS, "SALES_REP"));
            // if the receiving parties is empty then we will create commission invoices for all sales agent associated to sales invoice.
            if (UtilValidate.isEmpty(salesRepPartyIds)) {
                salesRepPartyIds = EntityUtil.getFieldListFromEntityList(
                        roleQuery.where(invoiceRoleConds).queryList(), "partyId", true);
                if (UtilValidate.isEmpty(salesRepPartyIds)) {
                    return ServiceUtil.returnError(UtilProperties.getMessage(resource,
                            "No party found with role sales representative for sales invoice " + salesInvoiceId,
                            locale));
                }
            } else {
                List<String> salesInvoiceRolePartyIds = EntityUtil.getFieldListFromEntityList(
                        roleQuery.where(invoiceRoleConds).queryList(), "partyId", true);
                if (UtilValidate.isNotEmpty(salesInvoiceRolePartyIds)) {
                    salesRepPartyIds = UtilGenerics.checkList(
                            CollectionUtils.intersection(salesRepPartyIds, salesInvoiceRolePartyIds));
                }
            }
            invoice = EntityQuery.use(delegator).from("Invoice").where("invoiceId", salesInvoiceId).queryOne();
            String invoiceTypeId = invoice.getString("invoiceTypeId");
            if ("CUST_RTN_INVOICE".equals(invoiceTypeId)) {
                isReturn = true;
            } else if (!"SALES_INVOICE".equals(invoiceTypeId)) {
                Debug.logWarning("This type of invoice has no commission; returning success", module);
                return ServiceUtil.returnError(
                        UtilProperties.getMessage(resource, "AccountingInvoiceCommissionInvalid", locale));
            }
            invoiceItems = EntityQuery.use(delegator).from("InvoiceItem").where("invoiceId", salesInvoiceId)
                    .queryList();
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(e.getMessage());
        }
        // Map of commission Lists (of Maps) for each party.
        // Determine commissions for various parties.
        for (GenericValue invoiceItem : invoiceItems) {
            BigDecimal amount = ZERO;
            BigDecimal quantity = ZERO;
            quantity = invoiceItem.getBigDecimal("quantity");
            amount = invoiceItem.getBigDecimal("amount");
            amount = isReturn ? amount.negate() : amount;
            String productId = invoiceItem.getString("productId");
            String invoiceItemSeqId = invoiceItem.getString("invoiceItemSeqId");
            String invoiceId = invoiceItem.getString("invoiceId");
            // Determine commission parties for this invoiceItem
            if (UtilValidate.isNotEmpty(productId)) {
                Map<String, Object> resultMap = null;
                try {
                    resultMap = dispatcher.runSync("getCommissionForProduct",
                            UtilMisc.<String, Object>toMap("productId", productId, "invoiceId", invoiceId,
                                    "invoiceItemSeqId", invoiceItemSeqId, "invoiceItemTypeId",
                                    invoiceItem.getString("invoiceItemTypeId"), "amount", amount, "quantity",
                                    quantity, "userLogin", userLogin));
                } catch (GenericServiceException e) {
                    return ServiceUtil.returnError(e.getMessage());
                }
                // build a Map of partyIds (both to and from) in a commission and the amounts
                // Note that getCommissionForProduct returns a List of Maps with a lot values.  See services.xml definition for reference.
                List<Map<String, Object>> itemCommissions = UtilGenerics
                        .checkList(resultMap.get("commissions"));
                if (UtilValidate.isNotEmpty(itemCommissions)) {
                    for (Map<String, Object> commissionMap : itemCommissions) {
                        commissionMap.put("invoice", invoice);
                        commissionMap.put("appliedFraction", appliedFraction);
                        if (!billFromVendorInvoiceRoles.contains(commissionMap.get("partyIdFrom"))
                                || !salesRepPartyIds.contains(commissionMap.get("partyIdTo"))) {
                            continue;
                        }
                        String partyIdFromTo = (String) commissionMap.get("partyIdFrom")
                                + (String) commissionMap.get("partyIdTo");
                        if (!commissionParties.containsKey(partyIdFromTo)) {
                            commissionParties.put(partyIdFromTo, UtilMisc.toList(commissionMap));
                        } else {
                            (commissionParties.get(partyIdFromTo)).add(commissionMap);
                        }
                    }
                }
            }
        }
    }
    Timestamp now = UtilDateTime.nowTimestamp();
    // Create invoice for each commission receiving party
    for (Map.Entry<String, List<Map<String, Object>>> commissionParty : commissionParties.entrySet()) {
        List<GenericValue> toStore = new LinkedList<GenericValue>();
        List<Map<String, Object>> commList = commissionParty.getValue();
        // get the billing parties
        if (UtilValidate.isEmpty(commList)) {
            continue;
        }
        // From and To are reversed between commission and invoice
        String partyIdBillTo = (String) (commList.get(0)).get("partyIdFrom");
        String partyIdBillFrom = (String) (commList.get(0)).get("partyIdTo");
        GenericValue invoice = (GenericValue) (commList.get(0)).get("invoice");
        BigDecimal appliedFraction = (BigDecimal) (commList.get(0)).get("appliedFraction");
        Long days = (Long) (commList.get(0)).get("days");
        // create the invoice record
        // To and From are in commission's sense, opposite for invoice
        Map<String, Object> createInvoiceMap = new HashMap<String, Object>();
        createInvoiceMap.put("partyId", partyIdBillTo);
        createInvoiceMap.put("partyIdFrom", partyIdBillFrom);
        createInvoiceMap.put("invoiceDate", now);
        // if there were days associated with the commission agreement, then set a dueDate for the invoice.
        if (days != null) {
            createInvoiceMap.put("dueDate", UtilDateTime.getDayEnd(now, days));
        }
        createInvoiceMap.put("invoiceTypeId", "COMMISSION_INVOICE");
        // start with INVOICE_IN_PROCESS, in the INVOICE_READY we can't change the invoice (or shouldn't be able to...)
        createInvoiceMap.put("statusId", "INVOICE_IN_PROCESS");
        createInvoiceMap.put("currencyUomId", invoice.getString("currencyUomId"));
        createInvoiceMap.put("userLogin", userLogin);
        // store the invoice first
        Map<String, Object> createInvoiceResult = null;
        try {
            createInvoiceResult = dispatcher.runSync("createInvoice", createInvoiceMap);
        } catch (GenericServiceException e) {
            return ServiceUtil.returnError(
                    UtilProperties.getMessage(resource, "AccountingInvoiceCommissionError", locale), null, null,
                    createInvoiceResult);
        }
        String invoiceId = (String) createInvoiceResult.get("invoiceId");
        // create the bill-from (or pay-to) contact mech as the primary PAYMENT_LOCATION of the party from the store
        GenericValue partyContactMechPurpose = null;
        try {
            partyContactMechPurpose = EntityQuery.use(delegator).from("PartyContactMechPurpose")
                    .where("partyId", partyIdBillTo, "contactMechPurposeTypeId", "BILLING_LOCATION")
                    .queryFirst();
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(e.getMessage());
        }
        if (partyContactMechPurpose != null) {
            GenericValue invoiceContactMech = delegator.makeValue("InvoiceContactMech",
                    UtilMisc.toMap("invoiceId", invoiceId, "contactMechId",
                            partyContactMechPurpose.getString("contactMechId"), "contactMechPurposeTypeId",
                            "BILLING_LOCATION"));
            toStore.add(invoiceContactMech);
        }
        try {
            partyContactMechPurpose = EntityQuery.use(delegator).from("PartyContactMechPurpose")
                    .where("partyId", partyIdBillTo, "contactMechPurposeTypeId", "PAYMENT_LOCATION")
                    .queryFirst();
        } catch (GenericEntityException e) {
            return ServiceUtil.returnError(e.getMessage());
        }
        if (partyContactMechPurpose != null) {
            GenericValue invoiceContactMech = delegator.makeValue("InvoiceContactMech",
                    UtilMisc.toMap("invoiceId", invoiceId, "contactMechId",
                            partyContactMechPurpose.getString("contactMechId"), "contactMechPurposeTypeId",
                            "PAYMENT_LOCATION"));
            toStore.add(invoiceContactMech);
        }
        // create the item records
        for (Map<String, Object> commissionMap : commList) {
            BigDecimal elemAmount = ((BigDecimal) commissionMap.get("commission")).multiply(appliedFraction);
            BigDecimal quantity = (BigDecimal) commissionMap.get("quantity");
            String invoiceIdFrom = (String) commissionMap.get("invoiceId");
            String invoiceItemSeqIdFrom = (String) commissionMap.get("invoiceItemSeqId");
            elemAmount = elemAmount.setScale(DECIMALS, ROUNDING);
            Map<String, Object> resMap = null;
            try {
                resMap = dispatcher.runSync("createInvoiceItem",
                        UtilMisc.toMap("invoiceId", invoiceId, "productId", commissionMap.get("productId"),
                                "invoiceItemTypeId", "COMM_INV_ITEM", "quantity", quantity, "amount",
                                elemAmount, "userLogin", userLogin));
                dispatcher.runSync("createInvoiceItemAssoc",
                        UtilMisc.toMap("invoiceIdFrom", invoiceIdFrom, "invoiceItemSeqIdFrom",
                                invoiceItemSeqIdFrom, "invoiceIdTo", invoiceId, "invoiceItemSeqIdTo",
                                resMap.get("invoiceItemSeqId"), "invoiceItemAssocTypeId", "COMMISSION_INVOICE",
                                "partyIdFrom", partyIdBillFrom, "partyIdTo", partyIdBillTo, "quantity",
                                quantity, "amount", elemAmount, "userLogin", userLogin));
            } catch (GenericServiceException e) {
                return ServiceUtil.returnError(e.getMessage());
            }
            if (ServiceUtil.isError(resMap)) {
                return ServiceUtil.returnError(
                        UtilProperties.getMessage(resource, "AccountingInvoiceCommissionErrorItem", locale),
                        null, null, resMap);
            }
        }
        // store value objects
        try {
            delegator.storeAll(toStore);
        } catch (GenericEntityException e) {
            Debug.logError(e, "Entity/data problem creating commission invoice: " + e.toString(), module);
            return ServiceUtil.returnError(
                    UtilProperties.getMessage(resource, "AccountingInvoiceCommissionEntityDataProblem",
                            UtilMisc.toMap("reason", e.toString()), locale));
        }
        invoicesCreated.add(UtilMisc.<String, String>toMap("commissionInvoiceId", invoiceId,
                "salesRepresentative ", partyIdBillFrom));
    }
    String invCreated = Integer.toString(invoicesCreated.size());
    Map<String, Object> result = ServiceUtil.returnSuccess(UtilProperties.getMessage(resource,
            "AccountingCommissionInvoicesCreated", UtilMisc.toMap("invoicesCreated", invCreated), locale));
    Debug.logInfo("Created Commission invoices for each commission receiving parties " + invCreated, module);
    result.put("invoicesCreated", invoicesCreated);
    return result;
}

From source file:com.exilant.eGov.src.common.EGovernCommon.java

public BigDecimal getAccountBalance(final Date VoucherDate, final String bankAccountId)
        throws TaskFailedException {
    BigDecimal totalAvailable = BigDecimal.ZERO;
    BigDecimal opeAvailable = BigDecimal.ZERO;
    Query pst = null;/*  w  w  w.j  ava2  s.c  o m*/
    List<Object[]> resultset = null;
    List<Object[]> resultset1 = null;
    try {
        final SimpleDateFormat formatter = dtFormat;
        final String vcDate = formatter.format(VoucherDate);

        final String str = "SELECT case when sum(openingDebitBalance) = null then 0 else sum(openingDebitBalance) end-  case when sum(openingCreditBalance) = null  then 0 else sum(openingCreditBalance) end AS \"openingBalance\" "
                + "FROM transactionSummary WHERE financialYearId=( SELECT id FROM financialYear WHERE startingDate <=?"
                + "AND endingDate >= ?)  AND glCodeId =(select glcodeid from bankaccount where id=?)";
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("getAccountBalance(EGovernCommon.java): " + str);
        pst = persistenceService.getSession().createSQLQuery(str);
        pst.setString(0, vcDate);
        pst.setString(1, vcDate);
        pst.setString(2, bankAccountId);
        resultset = pst.list();
        for (final Object[] element : resultset)
            opeAvailable = new BigDecimal(element[0].toString());
        if (resultset == null || resultset.size() == 0)
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Else resultset in getbalance");

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("opening balance  " + opeAvailable);
        // resultset.close();

        final String str1 = "SELECT (case when sum(gl.debitAmount) = null then 0 else sum(gl.debitAmount) end) - (case when sum(gl.creditAmount) = null then 0 else sum(gl.creditAmount) end) + "
                + opeAvailable
                + " as \"totalAmount\" FROM   generalLedger gl, voucherHeader vh WHERE vh.id = gl.voucherHeaderId AND gl.glCodeid = (select glcodeid from bankaccount where id=?) AND  "
                + " vh.voucherDate >=( SELECT TO_CHAR(startingDate, 'dd-Mon-yyyy') FROM financialYear WHERE startingDate <= ? AND endingDate >= ?) AND vh.voucherDate <= ? and vh.status!=4";

        if (LOGGER.isDebugEnabled())
            LOGGER.debug("Curr Yr Bal: " + str1);
        pst = persistenceService.getSession().createSQLQuery(str1);
        pst.setString(0, bankAccountId);
        pst.setString(1, vcDate);
        pst.setString(2, vcDate);
        pst.setString(3, vcDate);
        resultset1 = pst.list();
        for (final Object[] element : resultset1) {
            totalAvailable = new BigDecimal(element[0].toString());
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("total balance  " + totalAvailable);
        }
        if (resultset1 == null || resultset1.size() == 0)
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Else resultset in getbalance...");

        totalAvailable = totalAvailable.setScale(2, BigDecimal.ROUND_HALF_UP);
        if (LOGGER.isDebugEnabled())
            LOGGER.debug("total balance before return " + totalAvailable);

    } catch (final Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw taskExc;
    }
    return totalAvailable;
}