Example usage for java.math BigDecimal compareTo

List of usage examples for java.math BigDecimal compareTo

Introduction

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

Prototype

@Override
public int compareTo(BigDecimal val) 

Source Link

Document

Compares this BigDecimal with the specified BigDecimal .

Usage

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;/*from   w w  w . ja va2  s . co 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.broadleafcommerce.core.pricing.service.fulfillment.provider.BandedFulfillmentPricingProvider.java

@Override
public FulfillmentEstimationResponse estimateCostForFulfillmentGroup(FulfillmentGroup fulfillmentGroup,
        Set<FulfillmentOption> options) throws FulfillmentPriceException {

    //Set up the response object
    FulfillmentEstimationResponse res = new FulfillmentEstimationResponse();
    HashMap<FulfillmentOption, Money> shippingPrices = new HashMap<FulfillmentOption, Money>();
    res.setFulfillmentOptionPrices(shippingPrices);

    for (FulfillmentOption option : options) {
        if (canCalculateCostForFulfillmentGroup(fulfillmentGroup, option)) {

            List<? extends FulfillmentBand> bands = null;
            if (option instanceof BandedPriceFulfillmentOption) {
                bands = ((BandedPriceFulfillmentOption) option).getBands();
            } else if (option instanceof BandedWeightFulfillmentOption) {
                bands = ((BandedWeightFulfillmentOption) option).getBands();
            }//ww  w.ja v  a 2 s . co m

            if (bands == null || bands.isEmpty()) {
                //Something is misconfigured. There are no bands associated with this fulfillment option
                throw new IllegalStateException(
                        "There were no Fulfillment Price Bands configured for a BandedPriceFulfillmentOption with ID: "
                                + option.getId());
            }

            //Calculate the amount that the band will be applied to
            BigDecimal retailTotal = BigDecimal.ZERO;
            BigDecimal flatTotal = BigDecimal.ZERO;

            BigDecimal weightTotal = BigDecimal.ZERO;
            boolean foundCandidateForBand = false;
            for (FulfillmentGroupItem fulfillmentGroupItem : fulfillmentGroup.getFulfillmentGroupItems()) {

                //If this item has a Sku associated with it which also has a flat rate for this fulfillment option, don't add it to the price
                //or weight total but instead tack it onto the final rate
                boolean addToTotal = true;
                Sku sku = null;
                if (fulfillmentGroupItem.getOrderItem() instanceof DiscreteOrderItem) {
                    sku = ((DiscreteOrderItem) fulfillmentGroupItem.getOrderItem()).getSku();
                } else if (fulfillmentGroupItem.getOrderItem() instanceof BundleOrderItem) {
                    sku = ((BundleOrderItem) fulfillmentGroupItem.getOrderItem()).getSku();
                }

                if (sku != null && option.getUseFlatRates()) {
                    BigDecimal rate = sku.getFulfillmentFlatRates().get(option);
                    if (rate != null) {
                        addToTotal = false;
                        flatTotal = flatTotal.add(rate);
                    }
                }

                if (addToTotal) {
                    foundCandidateForBand = true;
                    BigDecimal price = (fulfillmentGroupItem.getTotalItemAmount() != null)
                            ? fulfillmentGroupItem.getTotalItemAmount().getAmount()
                            : null;
                    if (price == null) {
                        price = fulfillmentGroupItem.getOrderItem().getAveragePrice().getAmount()
                                .multiply(BigDecimal.valueOf(fulfillmentGroupItem.getQuantity()));
                    }
                    retailTotal = retailTotal.add(price);

                    if (sku != null && sku.getWeight() != null && sku.getWeight().getWeight() != null) {
                        BigDecimal convertedWeight = convertWeight(sku.getWeight().getWeight(),
                                sku.getWeight().getWeightUnitOfMeasure())
                                        .multiply(BigDecimal.valueOf(fulfillmentGroupItem.getQuantity()));
                        weightTotal = weightTotal.add(convertedWeight);
                    }
                }
            }

            //Used to keep track of the lowest price when there is are bands that have the same
            //minimum amount
            BigDecimal lowestBandFulfillmentPrice = null;
            //Used to keep track of the amount for the lowest band fulfillment price. Used to compare
            //if 2 bands are configured for the same minimum amount
            BigDecimal lowestBandFulfillmentPriceMinimumAmount = BigDecimal.ZERO;

            if (foundCandidateForBand) {
                for (FulfillmentBand band : bands) {

                    BigDecimal bandMinimumAmount = BigDecimal.ZERO;
                    boolean foundMatch = false;
                    if (band instanceof FulfillmentPriceBand) {
                        bandMinimumAmount = ((FulfillmentPriceBand) band).getRetailPriceMinimumAmount();
                        foundMatch = retailTotal.compareTo(bandMinimumAmount) >= 0;
                    } else if (band instanceof FulfillmentWeightBand) {
                        bandMinimumAmount = ((FulfillmentWeightBand) band).getMinimumWeight();
                        foundMatch = weightTotal.compareTo(bandMinimumAmount) >= 0;
                    }

                    if (foundMatch) {
                        //So far, we've found a potential match
                        //Now, determine if this is a percentage or actual amount
                        FulfillmentBandResultAmountType resultAmountType = band.getResultAmountType();
                        BigDecimal bandFulfillmentPrice = null;
                        if (FulfillmentBandResultAmountType.RATE.equals(resultAmountType)) {
                            bandFulfillmentPrice = band.getResultAmount();
                        } else if (FulfillmentBandResultAmountType.PERCENTAGE.equals(resultAmountType)) {
                            //Since this is a percentage, we calculate the result amount based on retailTotal and the band percentage
                            bandFulfillmentPrice = retailTotal.multiply(band.getResultAmount());
                        } else {
                            LOG.warn("Unknown FulfillmentBandResultAmountType: " + resultAmountType.getType()
                                    + " Should be RATE or PERCENTAGE. Ignoring.");
                        }

                        if (bandFulfillmentPrice != null) {

                            //haven't initialized the lowest price yet so just take on this one
                            if (lowestBandFulfillmentPrice == null) {
                                lowestBandFulfillmentPrice = bandFulfillmentPrice;
                                lowestBandFulfillmentPriceMinimumAmount = bandMinimumAmount;
                            }

                            //If there is a duplicate price band (meaning, 2 price bands are configured with the same miniumum retail price)
                            //then the lowest fulfillment amount should only be updated if the result of the current band being looked at
                            //is cheaper
                            if (lowestBandFulfillmentPriceMinimumAmount.compareTo(bandMinimumAmount) == 0) {
                                if (bandFulfillmentPrice.compareTo(lowestBandFulfillmentPrice) <= 0) {
                                    lowestBandFulfillmentPrice = bandFulfillmentPrice;
                                    lowestBandFulfillmentPriceMinimumAmount = bandMinimumAmount;
                                }
                            } else if (bandMinimumAmount
                                    .compareTo(lowestBandFulfillmentPriceMinimumAmount) > 0) {
                                lowestBandFulfillmentPrice = bandFulfillmentPrice;
                                lowestBandFulfillmentPriceMinimumAmount = bandMinimumAmount;
                            }

                        } else {
                            throw new IllegalStateException("Bands must have a non-null fulfillment price");
                        }
                    }
                }
            }

            //If I didn't find a valid band, initialize the fulfillment price to zero
            if (lowestBandFulfillmentPrice == null) {
                lowestBandFulfillmentPrice = BigDecimal.ZERO;
            }
            //add the flat rate amount calculated on the Sku
            lowestBandFulfillmentPrice = lowestBandFulfillmentPrice.add(flatTotal);

            shippingPrices.put(option, BroadleafCurrencyUtils.getMoney(lowestBandFulfillmentPrice,
                    fulfillmentGroup.getOrder().getCurrency()));
        }
    }

    return res;
}

From source file:com.lp.server.lieferschein.ejbfac.LieferscheinFacBean.java

public boolean isAuftragpositionenMengeVorhanden(AuftragpositionDto[] auftragpositionenDto, Integer lagerIId,
        TheClientDto theClientDto) throws EJBExceptionLP {

    try {/*from w w w  .j  a va 2s .  c o  m*/
        // boolean bEsGibtNochPositiveOffene = false;
        // if (getMandantFac().darfAnwenderAufZusatzfunktionZugreifen(
        // MandantFac.ZUSATZFUNKTION_VERLEIH, theClientDto)) {
        // bEsGibtNochPositiveOffene =
        // gibtEsPositivOffeneAuftragsMengen(auftragpositionenDto) ;
        // }

        for (AuftragpositionDto auftragpositionDto : auftragpositionenDto) {
            if (isAuftragPositionStatusErledigt(auftragpositionDto))
                continue;
            if (null == auftragpositionDto.getNMenge())
                continue;

            // TODO: Negative (und 0 Menge) vorerst nicht beruecksichtigen
            if (auftragpositionDto.getNMenge().signum() <= 0)
                continue;

            ArtikelDto artikelDto = getArtikelFac().artikelFindByPrimaryKey(auftragpositionDto.getArtikelIId(),
                    theClientDto);

            if (!artikelDto.isLagerbewirtschaftet())
                continue;

            BigDecimal verfuegbareMenge = getLagerFac().getLagerstand(auftragpositionDto.getArtikelIId(),
                    lagerIId, theClientDto);

            if (verfuegbareMenge.compareTo(auftragpositionDto.getNOffeneMenge()) < 0)
                return false;
        }
    } catch (RemoteException ex) {
        throwEJBExceptionLPRespectOld(ex);
    }

    return true;
}

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

/**
 * @param yearId/*from  www. j  ava2  s.  c  o m*/
 * @param monthId
 * @param costCentreId
 * @param empcntClientProjectDataList
 * @param employee
 * @param month
 * @param year
 * @param costCentre
 * @param countType
 * @param allignedTimeOne
 * @param assistedTimeOne
 * @param apportionedTimeOne
 * @param totalTimeOne
 */
private void getZeroProjectsDetail(Integer yearId, Integer monthId, String costCentreId,
        List<EmpcntClientProjectData> empOpenCntClientProjectDataList,
        List<EmpcntClientProjectData> empCloseCntClientProjectDataList, EmployeeMaster employee, TabMonth month,
        TabYear year, CostCentre costCentre, CountClassification countType, BigDecimal allignedTimeZero,
        BigDecimal assistedTimeZero, BigDecimal apportionedTimeOne, BigDecimal totalTimeOne,
        Integer countTypeId, Map<String, EmployeePcTagsTeamStruct> employeePcTagsTeamStructMap) {

    logger.debug("<====getZeroProjectsDetail START====>");
    Integer employeeId = employee.getEmployeeId();
    BigDecimal deviderHour = new BigDecimal(Constants.TOTAL_WORKING_HOURS);
    logger.debug("getZeroProjectsDetail parameter===>" + employeeId + "::" + yearId + "::" + monthId + "::"
            + costCentreId + "::" + deviderHour);

    // Get list of project from execution data for that employee
    List<Integer> projectIdList = executionDataDao.findByPersonYearMonthCostCentre(employeeId, yearId, monthId,
            costCentreId);
    // logger.debug("execution data projects===>" + projectIdList.size());
    if (projectIdList.isEmpty()) {
        BigDecimal remainProportion = BigDecimal.ONE;
        Map<Integer, BigDecimal> assignedProjectsHour = new HashMap<Integer, BigDecimal>();
        getRevenueCountProportion(empOpenCntClientProjectDataList, empCloseCntClientProjectDataList, employee,
                month, year, costCentre, countType, remainProportion, assignedProjectsHour, countTypeId,
                employeePcTagsTeamStructMap);
    } else {
        // logger.debug("Else Project details present in execution data ===>");
        // Get valid projects list=>project is both revenue data and
        // execution data
        Set<Integer> validAllProjects = new HashSet<Integer>();
        for (Integer projectId : projectIdList) {
            List<CollageProjectRevenue> listValues = collageProjectRevenueDao
                    .findByYearIdMonthIdProjectIdCostCentreId(yearId, monthId, projectId, costCentreId);
            if (!listValues.isEmpty()) {
                validAllProjects.add(projectId);
            }

        }
        // logger.debug("validAllProjects :size===>" +
        // validAllProjects.size());
        // Total hour worked by an Employee
        List<BigDecimal> toatalHours = executionDataDao.findByPersonIdYearIdMonthIdCostCentreId(employeeId,
                yearId, monthId, costCentreId);
        BigDecimal toatlTime = toatalHours.get(0);
        // logger.debug("ToatalHours===>" + toatlTime);

        // Separate assigned projects from execution data projects

        Map<Integer, BigDecimal> assignedProjectsHour = new HashMap<Integer, BigDecimal>();
        Map<Integer, Integer> assignedProjectsCompany = new HashMap<Integer, Integer>();
        List<Object[]> allProjectTimeList = executionDataDao
                .findByEmployeeIdYearIdMonthIdCostCentreId(employeeId, yearId, monthId, costCentreId);
        for (Object[] result : allProjectTimeList) {
            Integer projectId = (Integer) result[0];
            BigDecimal hour = (BigDecimal) result[1];
            Integer companyId = (Integer) result[2];
            if (validAllProjects.contains(projectId)) {
                // logger.debug("UnAssignedProjects===>" +
                // projectId+"::"+hour+"::"+companyId);
                assignedProjectsHour.put(projectId, hour);
                assignedProjectsCompany.put(projectId, companyId);
            }

        }
        /*
         * Do the calculation as per time spent on projects and put it to
         * assisted count
         */
        // logger.debug("validEmployeeProjectCount!=validAllProjectCount :(Both in assigned and unassigned projects)");
        if (toatlTime.compareTo(new BigDecimal(Constants.TOTAL_WORKING_HOURS)) >= 0) {
            // logger.debug("Worked hours===> >=168");
            for (Integer key : assignedProjectsCompany.keySet()) {
                // Get time spent on each project by employee id
                Integer projectId = key;
                Integer companyIdByProject = assignedProjectsCompany.get(key);
                ProjectMaster projectMaster = new ProjectMaster();
                projectMaster.setProjectId(projectId);
                CompanyMaster companyMaster = new CompanyMaster();
                companyMaster.setCompanyId(companyIdByProject);
                // logger.debug("1254 :Both in assigned and unassigned projects======>"+totalTimeOne);
                EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                        companyMaster, countType, month, projectMaster, year, costCentre, allignedTimeZero,
                        assistedTimeZero, apportionedTimeOne, totalTimeOne);
                if (countTypeId == 1) {
                    empOpenCntClientProjectDataList.add(empcntClientProjectData);
                }
                if (countTypeId == 2) {
                    empCloseCntClientProjectDataList.add(empcntClientProjectData);
                }
            }
        } else {
            // logger.debug("Worked hours===> <168");
            BigDecimal revenueProportion = BigDecimal.ZERO;

            for (Integer key : assignedProjectsHour.keySet()) {
                Integer projectId = key;
                // logger.debug("projectId===> "+projectId);
                BigDecimal timeByProject = assignedProjectsHour.get(key);
                Integer companyIdByProject = assignedProjectsCompany.get(key);
                ProjectMaster projectMaster = new ProjectMaster();
                projectMaster.setProjectId(projectId);
                CompanyMaster companyMaster = new CompanyMaster();
                companyMaster.setCompanyId(companyIdByProject);
                // logger.debug("timeByProject===> "+timeByProject);
                BigDecimal assistedHours = timeByProject.divide(deviderHour, 2, RoundingMode.HALF_EVEN);
                assistedHours = assistedHours.setScale(2, RoundingMode.CEILING);
                // logger.debug("assignedProjectsHour===> "+assingnedHours);
                revenueProportion = revenueProportion.add(assistedHours);
                logger.debug("1338 :======>" + revenueProportion);
                EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                        companyMaster, countType, month, projectMaster, year, costCentre, allignedTimeZero,
                        assistedHours, allignedTimeZero, assistedHours);
                if (countTypeId == 1) {
                    empOpenCntClientProjectDataList.add(empcntClientProjectData);
                }
                if (countTypeId == 2) {
                    empCloseCntClientProjectDataList.add(empcntClientProjectData);
                }
            }
            /*
             * Revenue count put it to apportioned count
             */
            // logger.debug("revenueProportion===> "+revenueProportion);
            if (revenueProportion.compareTo(BigDecimal.ONE) == -1) {
                BigDecimal remainProportion = BigDecimal.ONE.subtract(revenueProportion);
                logger.debug("remainProportion===> " + remainProportion);
                getRevenueCountProportion(empOpenCntClientProjectDataList, empCloseCntClientProjectDataList,
                        employee, month, year, costCentre, countType, remainProportion, assignedProjectsHour,
                        countTypeId, employeePcTagsTeamStructMap);
            }
        }
    }
    // logger.debug("<====getZeroProjectDetail END====>");
}

From source file:com.lp.server.lieferschein.ejbfac.LieferscheinFacBean.java

/**
 * Bei einem auftragbezogenen Lieferschein ist es moeglich, all jene offenen
 * oder teilerledigten Auftragpositionen innerhalb einer Transaktion zu
 * uebernehmen, die keine Benutzerinteraktion benoetigen. <br>
 * Es gilt:/*from ww w . j a v  a 2s .c o m*/
 * <ul>
 * <li>Handeingabepositionen werden uebernommen.
 * <li>Nicht Serien- oder Chargennummertragende Artikelpositionen werden mit
 * jener Menge uebernommen, die auf Lager liegt.
 * <li>Artikelpositionen mit Seriennummer werden nicht uebernommen.
 * <li>Artikelpositionen mit Chargennummer werden mit jener Menge
 * uebernommen, die auf Lager liegt, wenn es genau eine Charge gibt.
 * </ul>
 * Die restlichen Positionen koennen nicht automatisch uebernommen werden.
 * 
 * @param iIdLieferscheinI
 *            PK des Lieferscheins
 * @param auftragIIdI
 *            Integer
 * @param theClientDto
 *            String der aktuelle Benutzer
 * @throws EJBExceptionLP
 *             Ausnahme
 */
public void uebernimmAlleOffenenAuftragpositionenOhneBenutzerinteraktion(Integer iIdLieferscheinI,
        Integer auftragIIdI, TheClientDto theClientDto) throws EJBExceptionLP {
    checkLieferscheinIId(iIdLieferscheinI);
    try {
        LieferscheinDto lieferscheinDto = lieferscheinFindByPrimaryKey(iIdLieferscheinI, theClientDto);
        AuftragpositionDto[] aAuftragpositionDto = getAuftragpositionFac()
                .auftragpositionFindByAuftrag(auftragIIdI);

        boolean bEsGibtNochPositiveOffene = false;
        if (getMandantFac().darfAnwenderAufZusatzfunktionZugreifen(MandantFac.ZUSATZFUNKTION_VERLEIH,
                theClientDto)) {
            for (int i = 0; i < aAuftragpositionDto.length; i++) {
                if (!AuftragServiceFac.AUFTRAGPOSITIONSTATUS_ERLEDIGT
                        .equals(aAuftragpositionDto[i].getAuftragpositionstatusCNr())) {
                    if (aAuftragpositionDto[i].getNMenge() != null
                            && aAuftragpositionDto[i].getNMenge().doubleValue() > 0) {
                        bEsGibtNochPositiveOffene = true;
                    }
                }
            }
        }

        for (int i = 0; i < aAuftragpositionDto.length; i++) {
            if (!AuftragServiceFac.AUFTRAGPOSITIONSTATUS_ERLEDIGT
                    .equals(aAuftragpositionDto[i].getAuftragpositionstatusCNr())) {
                // IMS 2129
                if (aAuftragpositionDto[i].getNMenge() != null) {

                    // wenn es noch positive offene gibt, dann duerfen dei
                    // negativen noch nicht geliert werden

                    if (aAuftragpositionDto[i].getNMenge().doubleValue() < 0 && bEsGibtNochPositiveOffene) {
                        continue;
                    }

                    // dieses Flag legt fest, ob eine Lieferscheinposition
                    // fuer die aktuelle
                    // Auftragposition angleget oder aktualisiert werden
                    // soll
                    boolean bLieferscheinpositionErzeugen = false;

                    // die Menge, mit der eine neue Lieferscheinposition
                    // angelegt oder eine
                    // bestehende Lieferscheinposition aktualisiert werden
                    // soll
                    BigDecimal nMengeFuerLieferscheinposition = null;

                    // die Serien- oder Chargennummer, die bei der Abbuchung
                    // verwendet werden soll
                    String cSerienchargennummer = null;

                    if (aAuftragpositionDto[i].getPositionsartCNr()
                            .equals(AuftragServiceFac.AUFTRAGPOSITIONART_HANDEINGABE)) {
                        bLieferscheinpositionErzeugen = true;
                        nMengeFuerLieferscheinposition = aAuftragpositionDto[i].getNOffeneMenge();
                    } else if (aAuftragpositionDto[i].getPositionsartCNr()
                            .equals(AuftragServiceFac.AUFTRAGPOSITIONART_IDENT)) {
                        ArtikelDto artikelDto = getArtikelFac()
                                .artikelFindByPrimaryKey(aAuftragpositionDto[i].getArtikelIId(), theClientDto);

                        // nicht lagerbewirtschaftete Artikel werden mit der
                        // vollen offenen Menge uebernommen
                        if (!Helper.short2boolean(artikelDto.getBLagerbewirtschaftet())) {
                            bLieferscheinpositionErzeugen = true;
                            nMengeFuerLieferscheinposition = aAuftragpositionDto[i].getNOffeneMenge();
                        } else {
                            if (Helper.short2boolean(artikelDto.getBSeriennrtragend())) {
                                // seriennummerbehaftete Artikel koennen
                                // nicht automatisch uebernommen werden
                            } else if (Helper.short2boolean(artikelDto.getBChargennrtragend())) {
                                // chargennummernbehaftete Artikel koennen
                                // nur uebernommen werden, wenn
                                // es nur eine Charge gibt und mit der
                                // Menge, die in dieser Charge
                                // vorhanden ist
                                SeriennrChargennrAufLagerDto[] alleChargennummern = getLagerFac()
                                        .getAllSerienChargennrAufLager(artikelDto.getIId(),
                                                lieferscheinDto.getLagerIId(), theClientDto, true, false);
                                if (alleChargennummern != null && alleChargennummern.length == 1) {
                                    BigDecimal nLagerstd = alleChargennummern[0].getNMenge();
                                    cSerienchargennummer = alleChargennummern[0].getCSeriennrChargennr();
                                    // ist ausreichend auf Lager?
                                    if (nLagerstd.compareTo(aAuftragpositionDto[i].getNOffeneMenge()) >= 0) {
                                        bLieferscheinpositionErzeugen = true;
                                        nMengeFuerLieferscheinposition = aAuftragpositionDto[i]
                                                .getNOffeneMenge();
                                    }
                                    // nicht genug auf Lager, aber es kann
                                    // zumindest ein Teil abgebucht werden.
                                    else if (nLagerstd.compareTo(new BigDecimal(0)) > 0) {
                                        bLieferscheinpositionErzeugen = true;
                                        nMengeFuerLieferscheinposition = nLagerstd;
                                    }
                                }
                            } else {
                                // bei lagerbewirtschafteten Artikeln muss
                                // die Menge auf Lager
                                // beruecksichtigt werden
                                BigDecimal nMengeAufLager = getLagerFac().getMengeAufLager(artikelDto.getIId(),
                                        lieferscheinDto.getLagerIId(), null, theClientDto);

                                if (nMengeAufLager.doubleValue() >= aAuftragpositionDto[i].getNOffeneMenge()
                                        .doubleValue()) {
                                    bLieferscheinpositionErzeugen = true;
                                    nMengeFuerLieferscheinposition = aAuftragpositionDto[i].getNOffeneMenge();
                                } else if (nMengeAufLager.doubleValue() > 0
                                        && nMengeAufLager.doubleValue() < aAuftragpositionDto[i]
                                                .getNOffeneMenge().doubleValue()) {
                                    bLieferscheinpositionErzeugen = true;
                                    nMengeFuerLieferscheinposition = nMengeAufLager;
                                }
                            }
                        }
                    }

                    if (bLieferscheinpositionErzeugen && nMengeFuerLieferscheinposition != null) {
                        LieferscheinpositionDto lieferscheinpositionBisherDto = getLieferscheinpositionByLieferscheinAuftragposition(
                                iIdLieferscheinI, aAuftragpositionDto[i].getIId());

                        if (lieferscheinpositionBisherDto == null) {
                            LieferscheinpositionDto lieferscheinpositionDto = aAuftragpositionDto[i]
                                    .cloneAsLieferscheinpositionDto();

                            if (aAuftragpositionDto[i].getPositioniIdArtikelset() != null) {

                                LieferscheinpositionDto[] lPositionDtos = null;
                                Query query = em.createNamedQuery("LieferscheinpositionfindByAuftragposition");
                                query.setParameter(1, aAuftragpositionDto[i].getPositioniIdArtikelset());
                                Collection<?> cl = query.getResultList();
                                lPositionDtos = assembleLieferscheinpositionDtos(cl);

                                for (int j = 0; j < lPositionDtos.length; j++) {
                                    if (lPositionDtos[j].getLieferscheinIId().equals(iIdLieferscheinI)) {
                                        lieferscheinpositionDto
                                                .setPositioniIdArtikelset(lPositionDtos[j].getIId());
                                        break;
                                    }
                                }

                            }

                            lieferscheinpositionDto.setLieferscheinIId(iIdLieferscheinI);
                            lieferscheinpositionDto.setNMenge(nMengeFuerLieferscheinposition);
                            lieferscheinpositionDto.setSeriennrChargennrMitMenge(
                                    SeriennrChargennrMitMengeDto.erstelleDtoAusEinerChargennummer(
                                            cSerienchargennummer, nMengeFuerLieferscheinposition));
                            lieferscheinpositionDto.setISort(null);
                            getLieferscheinpositionFac().createLieferscheinposition(lieferscheinpositionDto,
                                    false, theClientDto);
                        } else {
                            lieferscheinpositionBisherDto.setNMenge(nMengeFuerLieferscheinposition);

                            if (aAuftragpositionDto[i].getPositionsartCNr()
                                    .equals(AuftragServiceFac.AUFTRAGPOSITIONART_IDENT)) {
                                ArtikelDto artikelDto = getArtikelFac().artikelFindByPrimaryKey(
                                        aAuftragpositionDto[i].getArtikelIId(), theClientDto);

                                if (Helper.short2boolean(artikelDto.getBSeriennrtragend())
                                        || Helper.short2boolean(artikelDto.getBChargennrtragend())) {
                                    lieferscheinpositionBisherDto.setSeriennrChargennrMitMenge(
                                            SeriennrChargennrMitMengeDto.erstelleDtoAusEinerChargennummer(
                                                    cSerienchargennummer, nMengeFuerLieferscheinposition));
                                } else {
                                    lieferscheinpositionBisherDto.setSeriennrChargennrMitMenge(null);
                                }

                            }

                            getLieferscheinpositionFac().updateLieferscheinpositionSichtAuftrag(
                                    lieferscheinpositionBisherDto, theClientDto);
                        }
                    }
                } else {
                    LieferscheinpositionDto lieferscheinpositionDto = aAuftragpositionDto[i]
                            .cloneAsLieferscheinpositionDto();
                    lieferscheinpositionDto.setLieferscheinIId(iIdLieferscheinI);
                    lieferscheinpositionDto.setISort(null);
                    getLieferscheinpositionFac().createLieferscheinposition(lieferscheinpositionDto, false,
                            theClientDto);
                }
            }
        }
    } catch (RemoteException ex) {
        throwEJBExceptionLPRespectOld(ex);
    }
}

From source file:org.apache.fineract.portfolio.loanproduct.serialization.LoanProductDataValidator.java

public void validateForUpdate(final String json, final LoanProduct loanProduct) {
    if (StringUtils.isBlank(json)) {
        throw new InvalidJsonException();
    }//  www.  ja va  2 s . c om

    final Type typeOfMap = new TypeToken<Map<String, Object>>() {
    }.getType();
    this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);

    final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
    final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
            .resource("loanproduct");

    final JsonElement element = this.fromApiJsonHelper.parse(json);
    if (this.fromApiJsonHelper.parameterExists("name", element)) {
        final String name = this.fromApiJsonHelper.extractStringNamed("name", element);
        baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100);
    }

    if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.shortName, element)) {
        final String shortName = this.fromApiJsonHelper.extractStringNamed(LoanProductConstants.shortName,
                element);
        baseDataValidator.reset().parameter(LoanProductConstants.shortName).value(shortName).notBlank()
                .notExceedingLengthOf(4);
    }

    if (this.fromApiJsonHelper.parameterExists("description", element)) {
        final String description = this.fromApiJsonHelper.extractStringNamed("description", element);
        baseDataValidator.reset().parameter("description").value(description).notExceedingLengthOf(500);
    }

    if (this.fromApiJsonHelper.parameterExists("fundId", element)) {
        final Long fundId = this.fromApiJsonHelper.extractLongNamed("fundId", element);
        baseDataValidator.reset().parameter("fundId").value(fundId).ignoreIfNull().integerGreaterThanZero();
    }

    if (this.fromApiJsonHelper.parameterExists("includeInBorrowerCycle", element)) {
        final Boolean includeInBorrowerCycle = this.fromApiJsonHelper
                .extractBooleanNamed("includeInBorrowerCycle", element);
        baseDataValidator.reset().parameter("includeInBorrowerCycle").value(includeInBorrowerCycle)
                .ignoreIfNull().validateForBooleanValue();
    }

    if (this.fromApiJsonHelper.parameterExists("currencyCode", element)) {
        final String currencyCode = this.fromApiJsonHelper.extractStringNamed("currencyCode", element);
        baseDataValidator.reset().parameter("currencyCode").value(currencyCode).notBlank()
                .notExceedingLengthOf(3);
    }

    if (this.fromApiJsonHelper.parameterExists("digitsAfterDecimal", element)) {
        final Integer digitsAfterDecimal = this.fromApiJsonHelper.extractIntegerNamed("digitsAfterDecimal",
                element, Locale.getDefault());
        baseDataValidator.reset().parameter("digitsAfterDecimal").value(digitsAfterDecimal).notNull()
                .inMinMaxRange(0, 6);
    }

    if (this.fromApiJsonHelper.parameterExists("inMultiplesOf", element)) {
        final Integer inMultiplesOf = this.fromApiJsonHelper.extractIntegerNamed("inMultiplesOf", element,
                Locale.getDefault());
        baseDataValidator.reset().parameter("inMultiplesOf").value(inMultiplesOf).ignoreIfNull()
                .integerZeroOrGreater();
    }

    final String minPrincipalParameterName = "minPrincipal";
    BigDecimal minPrincipalAmount = null;
    if (this.fromApiJsonHelper.parameterExists(minPrincipalParameterName, element)) {
        minPrincipalAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minPrincipalParameterName,
                element);
        baseDataValidator.reset().parameter(minPrincipalParameterName).value(minPrincipalAmount).ignoreIfNull()
                .positiveAmount();
    }

    final String maxPrincipalParameterName = "maxPrincipal";
    BigDecimal maxPrincipalAmount = null;
    if (this.fromApiJsonHelper.parameterExists(maxPrincipalParameterName, element)) {
        maxPrincipalAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(maxPrincipalParameterName,
                element);
        baseDataValidator.reset().parameter(maxPrincipalParameterName).value(maxPrincipalAmount).ignoreIfNull()
                .positiveAmount();
    }

    if (this.fromApiJsonHelper.parameterExists("principal", element)) {
        final BigDecimal principal = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("principal",
                element);
        baseDataValidator.reset().parameter("principal").value(principal).positiveAmount();
    }

    if (this.fromApiJsonHelper.parameterExists("inArrearsTolerance", element)) {
        final BigDecimal inArrearsTolerance = this.fromApiJsonHelper
                .extractBigDecimalWithLocaleNamed("inArrearsTolerance", element);
        baseDataValidator.reset().parameter("inArrearsTolerance").value(inArrearsTolerance).ignoreIfNull()
                .zeroOrPositiveAmount();
    }

    final String minNumberOfRepaymentsParameterName = "minNumberOfRepayments";
    Integer minNumberOfRepayments = null;
    if (this.fromApiJsonHelper.parameterExists(minNumberOfRepaymentsParameterName, element)) {
        minNumberOfRepayments = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed(minNumberOfRepaymentsParameterName, element);
        baseDataValidator.reset().parameter(minNumberOfRepaymentsParameterName).value(minNumberOfRepayments)
                .ignoreIfNull().integerGreaterThanZero();
    }

    final String maxNumberOfRepaymentsParameterName = "maxNumberOfRepayments";
    Integer maxNumberOfRepayments = null;
    if (this.fromApiJsonHelper.parameterExists(maxNumberOfRepaymentsParameterName, element)) {
        maxNumberOfRepayments = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed(maxNumberOfRepaymentsParameterName, element);
        baseDataValidator.reset().parameter(maxNumberOfRepaymentsParameterName).value(maxNumberOfRepayments)
                .ignoreIfNull().integerGreaterThanZero();
    }

    if (this.fromApiJsonHelper.parameterExists("numberOfRepayments", element)) {
        final Integer numberOfRepayments = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed("numberOfRepayments", element);
        baseDataValidator.reset().parameter("numberOfRepayments").value(numberOfRepayments).notNull()
                .integerGreaterThanZero();
    }

    if (this.fromApiJsonHelper.parameterExists("repaymentEvery", element)) {
        final Integer repaymentEvery = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("repaymentEvery",
                element);
        baseDataValidator.reset().parameter("repaymentEvery").value(repaymentEvery).notNull()
                .integerGreaterThanZero();
    }

    if (this.fromApiJsonHelper.parameterExists("repaymentFrequencyType", element)) {
        final Integer repaymentFrequencyType = this.fromApiJsonHelper
                .extractIntegerNamed("repaymentFrequencyType", element, Locale.getDefault());
        baseDataValidator.reset().parameter("repaymentFrequencyType").value(repaymentFrequencyType).notNull()
                .inMinMaxRange(0, 3);
    }

    if (this.fromApiJsonHelper.parameterExists("transactionProcessingStrategyId", element)) {
        final Long transactionProcessingStrategyId = this.fromApiJsonHelper
                .extractLongNamed("transactionProcessingStrategyId", element);
        baseDataValidator.reset().parameter("transactionProcessingStrategyId")
                .value(transactionProcessingStrategyId).notNull().integerGreaterThanZero();
    }

    // grace validation
    if (this.fromApiJsonHelper.parameterExists("graceOnPrincipalPayment", element)) {
        final Integer graceOnPrincipalPayment = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed("graceOnPrincipalPayment", element);
        baseDataValidator.reset().parameter("graceOnPrincipalPayment").value(graceOnPrincipalPayment)
                .zeroOrPositiveAmount();
    }

    if (this.fromApiJsonHelper.parameterExists("graceOnInterestPayment", element)) {
        final Integer graceOnInterestPayment = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed("graceOnInterestPayment", element);
        baseDataValidator.reset().parameter("graceOnInterestPayment").value(graceOnInterestPayment)
                .zeroOrPositiveAmount();
    }

    if (this.fromApiJsonHelper.parameterExists("graceOnInterestCharged", element)) {
        final Integer graceOnInterestCharged = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed("graceOnInterestCharged", element);
        baseDataValidator.reset().parameter("graceOnInterestCharged").value(graceOnInterestCharged)
                .zeroOrPositiveAmount();
    }

    if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.graceOnArrearsAgeingParameterName,
            element)) {
        final Integer graceOnArrearsAgeing = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed(LoanProductConstants.graceOnArrearsAgeingParameterName, element);
        baseDataValidator.reset().parameter(LoanProductConstants.graceOnArrearsAgeingParameterName)
                .value(graceOnArrearsAgeing).integerZeroOrGreater();
    }

    if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.overdueDaysForNPAParameterName, element)) {
        final Integer overdueDaysForNPA = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed(LoanProductConstants.overdueDaysForNPAParameterName, element);
        baseDataValidator.reset().parameter(LoanProductConstants.overdueDaysForNPAParameterName)
                .value(overdueDaysForNPA).integerZeroOrGreater();
    }

    //
    if (this.fromApiJsonHelper.parameterExists("amortizationType", element)) {
        final Integer amortizationType = this.fromApiJsonHelper.extractIntegerNamed("amortizationType", element,
                Locale.getDefault());
        baseDataValidator.reset().parameter("amortizationType").value(amortizationType).notNull()
                .inMinMaxRange(0, 1);
    }

    if (this.fromApiJsonHelper.parameterExists("interestType", element)) {
        final Integer interestType = this.fromApiJsonHelper.extractIntegerNamed("interestType", element,
                Locale.getDefault());
        baseDataValidator.reset().parameter("interestType").value(interestType).notNull().inMinMaxRange(0, 1);
    }
    Integer interestCalculationPeriodType = loanProduct.getLoanProductRelatedDetail()
            .getInterestCalculationPeriodMethod().getValue();
    if (this.fromApiJsonHelper.parameterExists("interestCalculationPeriodType", element)) {
        interestCalculationPeriodType = this.fromApiJsonHelper
                .extractIntegerNamed("interestCalculationPeriodType", element, Locale.getDefault());
        baseDataValidator.reset().parameter("interestCalculationPeriodType")
                .value(interestCalculationPeriodType).notNull().inMinMaxRange(0, 1);
    }

    /**
     * { @link DaysInYearType }
     */
    if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.daysInYearTypeParameterName, element)) {
        final Integer daysInYearType = this.fromApiJsonHelper.extractIntegerNamed(
                LoanProductConstants.daysInYearTypeParameterName, element, Locale.getDefault());
        baseDataValidator.reset().parameter(LoanProductConstants.daysInYearTypeParameterName)
                .value(daysInYearType).notNull().isOneOfTheseValues(1, 360, 364, 365);
    }

    /**
     * { @link DaysInMonthType }
     */
    if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.daysInMonthTypeParameterName, element)) {
        final Integer daysInMonthType = this.fromApiJsonHelper.extractIntegerNamed(
                LoanProductConstants.daysInMonthTypeParameterName, element, Locale.getDefault());
        baseDataValidator.reset().parameter(LoanProductConstants.daysInMonthTypeParameterName)
                .value(daysInMonthType).notNull().isOneOfTheseValues(1, 30);
    }

    if (this.fromApiJsonHelper.parameterExists(
            LoanProductConstants.accountMovesOutOfNPAOnlyOnArrearsCompletionParamName, element)) {
        Boolean npaChangeConfig = this.fromApiJsonHelper.extractBooleanNamed(
                LoanProductConstants.accountMovesOutOfNPAOnlyOnArrearsCompletionParamName, element);
        baseDataValidator.reset()
                .parameter(LoanProductConstants.accountMovesOutOfNPAOnlyOnArrearsCompletionParamName)
                .value(npaChangeConfig).notNull().isOneOfTheseValues(true, false);
    }

    // Interest recalculation settings
    Boolean isInterestRecalculationEnabled = loanProduct.isInterestRecalculationEnabled();
    if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.isInterestRecalculationEnabledParameterName,
            element)) {
        isInterestRecalculationEnabled = this.fromApiJsonHelper
                .extractBooleanNamed(LoanProductConstants.isInterestRecalculationEnabledParameterName, element);
        baseDataValidator.reset().parameter(LoanProductConstants.isInterestRecalculationEnabledParameterName)
                .value(isInterestRecalculationEnabled).notNull().isOneOfTheseValues(true, false);
    }

    if (isInterestRecalculationEnabled != null) {
        if (isInterestRecalculationEnabled) {
            validateInterestRecalculationParams(element, baseDataValidator, loanProduct);
        }
    }

    // interest rates
    boolean isLinkedToFloatingInterestRates = loanProduct.isLinkedToFloatingInterestRate();
    if (this.fromApiJsonHelper.parameterExists("isLinkedToFloatingInterestRates", element)) {
        isLinkedToFloatingInterestRates = this.fromApiJsonHelper
                .extractBooleanNamed("isLinkedToFloatingInterestRates", element);
    }
    if (isLinkedToFloatingInterestRates) {
        if (this.fromApiJsonHelper.parameterExists("interestRatePerPeriod", element)) {
            baseDataValidator.reset().parameter("interestRatePerPeriod").failWithCode(
                    "not.supported.when.isLinkedToFloatingInterestRates.is.true",
                    "interestRatePerPeriod param is not supported when isLinkedToFloatingInterestRates is true");
        }

        if (this.fromApiJsonHelper.parameterExists("minInterestRatePerPeriod", element)) {
            baseDataValidator.reset().parameter("minInterestRatePerPeriod").failWithCode(
                    "not.supported.when.isLinkedToFloatingInterestRates.is.true",
                    "minInterestRatePerPeriod param is not supported when isLinkedToFloatingInterestRates is true");
        }

        if (this.fromApiJsonHelper.parameterExists("maxInterestRatePerPeriod", element)) {
            baseDataValidator.reset().parameter("maxInterestRatePerPeriod").failWithCode(
                    "not.supported.when.isLinkedToFloatingInterestRates.is.true",
                    "maxInterestRatePerPeriod param is not supported when isLinkedToFloatingInterestRates is true");
        }

        if (this.fromApiJsonHelper.parameterExists("interestRateFrequencyType", element)) {
            baseDataValidator.reset().parameter("interestRateFrequencyType").failWithCode(
                    "not.supported.when.isLinkedToFloatingInterestRates.is.true",
                    "interestRateFrequencyType param is not supported when isLinkedToFloatingInterestRates is true");
        }

        Integer interestType = this.fromApiJsonHelper.parameterExists("interestType", element)
                ? this.fromApiJsonHelper.extractIntegerNamed("interestType", element, Locale.getDefault())
                : loanProduct.getLoanProductRelatedDetail().getInterestMethod().getValue();
        if ((interestType == null || interestType != InterestMethod.DECLINING_BALANCE.getValue())
                || (isInterestRecalculationEnabled == null || isInterestRecalculationEnabled == false)) {
            baseDataValidator.reset().parameter("isLinkedToFloatingInterestRates").failWithCode(
                    "supported.only.for.declining.balance.interest.recalculation.enabled",
                    "Floating interest rates are supported only for declining balance and interest recalculation enabled loan products");
        }

        Long floatingRatesId = loanProduct.getFloatingRates() == null ? null
                : loanProduct.getFloatingRates().getFloatingRate().getId();
        if (this.fromApiJsonHelper.parameterExists("floatingRatesId", element)) {
            floatingRatesId = this.fromApiJsonHelper.extractLongNamed("floatingRatesId", element);
        }
        baseDataValidator.reset().parameter("floatingRatesId").value(floatingRatesId).notNull();

        BigDecimal interestRateDifferential = loanProduct.getFloatingRates() == null ? null
                : loanProduct.getFloatingRates().getInterestRateDifferential();
        if (this.fromApiJsonHelper.parameterExists("interestRateDifferential", element)) {
            interestRateDifferential = this.fromApiJsonHelper
                    .extractBigDecimalWithLocaleNamed("interestRateDifferential", element);
        }
        baseDataValidator.reset().parameter("interestRateDifferential").value(interestRateDifferential)
                .notNull().zeroOrPositiveAmount();

        final String minDifferentialLendingRateParameterName = "minDifferentialLendingRate";
        BigDecimal minDifferentialLendingRate = loanProduct.getFloatingRates() == null ? null
                : loanProduct.getFloatingRates().getMinDifferentialLendingRate();
        if (this.fromApiJsonHelper.parameterExists(minDifferentialLendingRateParameterName, element)) {
            minDifferentialLendingRate = this.fromApiJsonHelper
                    .extractBigDecimalWithLocaleNamed(minDifferentialLendingRateParameterName, element);
        }
        baseDataValidator.reset().parameter(minDifferentialLendingRateParameterName)
                .value(minDifferentialLendingRate).notNull().zeroOrPositiveAmount();

        final String defaultDifferentialLendingRateParameterName = "defaultDifferentialLendingRate";
        BigDecimal defaultDifferentialLendingRate = loanProduct.getFloatingRates() == null ? null
                : loanProduct.getFloatingRates().getDefaultDifferentialLendingRate();
        if (this.fromApiJsonHelper.parameterExists(defaultDifferentialLendingRateParameterName, element)) {
            defaultDifferentialLendingRate = this.fromApiJsonHelper
                    .extractBigDecimalWithLocaleNamed(defaultDifferentialLendingRateParameterName, element);
        }
        baseDataValidator.reset().parameter(defaultDifferentialLendingRateParameterName)
                .value(defaultDifferentialLendingRate).notNull().zeroOrPositiveAmount();

        final String maxDifferentialLendingRateParameterName = "maxDifferentialLendingRate";
        BigDecimal maxDifferentialLendingRate = loanProduct.getFloatingRates() == null ? null
                : loanProduct.getFloatingRates().getMaxDifferentialLendingRate();
        if (this.fromApiJsonHelper.parameterExists(maxDifferentialLendingRateParameterName, element)) {
            maxDifferentialLendingRate = this.fromApiJsonHelper
                    .extractBigDecimalWithLocaleNamed(maxDifferentialLendingRateParameterName, element);
        }
        baseDataValidator.reset().parameter(maxDifferentialLendingRateParameterName)
                .value(maxDifferentialLendingRate).notNull().zeroOrPositiveAmount();

        if (defaultDifferentialLendingRate != null
                && defaultDifferentialLendingRate.compareTo(BigDecimal.ZERO) != -1) {
            if (minDifferentialLendingRate != null
                    && minDifferentialLendingRate.compareTo(BigDecimal.ZERO) != -1) {
                baseDataValidator.reset().parameter("defaultDifferentialLendingRate")
                        .value(defaultDifferentialLendingRate).notLessThanMin(minDifferentialLendingRate);
            }
        }

        if (maxDifferentialLendingRate != null && maxDifferentialLendingRate.compareTo(BigDecimal.ZERO) != -1) {
            if (minDifferentialLendingRate != null
                    && minDifferentialLendingRate.compareTo(BigDecimal.ZERO) != -1) {
                baseDataValidator.reset().parameter("maxDifferentialLendingRate")
                        .value(maxDifferentialLendingRate).notLessThanMin(minDifferentialLendingRate);
            }
        }

        if (maxDifferentialLendingRate != null && maxDifferentialLendingRate.compareTo(BigDecimal.ZERO) != -1) {
            if (defaultDifferentialLendingRate != null
                    && defaultDifferentialLendingRate.compareTo(BigDecimal.ZERO) != -1) {
                baseDataValidator.reset().parameter("maxDifferentialLendingRate")
                        .value(maxDifferentialLendingRate).notLessThanMin(defaultDifferentialLendingRate);
            }
        }

        Boolean isFloatingInterestRateCalculationAllowed = loanProduct.getFloatingRates() == null ? null
                : loanProduct.getFloatingRates().isFloatingInterestRateCalculationAllowed();
        if (this.fromApiJsonHelper.parameterExists("isFloatingInterestRateCalculationAllowed", element)) {
            isFloatingInterestRateCalculationAllowed = this.fromApiJsonHelper
                    .extractBooleanNamed("isFloatingInterestRateCalculationAllowed", element);
        }
        baseDataValidator.reset().parameter("isFloatingInterestRateCalculationAllowed")
                .value(isFloatingInterestRateCalculationAllowed).notNull().isOneOfTheseValues(true, false);
    } else {
        if (this.fromApiJsonHelper.parameterExists("floatingRatesId", element)) {
            baseDataValidator.reset().parameter("floatingRatesId").failWithCode(
                    "not.supported.when.isLinkedToFloatingInterestRates.is.false",
                    "floatingRatesId param is not supported when isLinkedToFloatingInterestRates is not supplied or false");
        }

        if (this.fromApiJsonHelper.parameterExists("interestRateDifferential", element)) {
            baseDataValidator.reset().parameter("interestRateDifferential").failWithCode(
                    "not.supported.when.isLinkedToFloatingInterestRates.is.false",
                    "interestRateDifferential param is not supported when isLinkedToFloatingInterestRates is not supplied or false");
        }

        if (this.fromApiJsonHelper.parameterExists("minDifferentialLendingRate", element)) {
            baseDataValidator.reset().parameter("minDifferentialLendingRate").failWithCode(
                    "not.supported.when.isLinkedToFloatingInterestRates.is.false",
                    "minDifferentialLendingRate param is not supported when isLinkedToFloatingInterestRates is not supplied or false");
        }

        if (this.fromApiJsonHelper.parameterExists("defaultDifferentialLendingRate", element)) {
            baseDataValidator.reset().parameter("defaultDifferentialLendingRate").failWithCode(
                    "not.supported.when.isLinkedToFloatingInterestRates.is.false",
                    "defaultDifferentialLendingRate param is not supported when isLinkedToFloatingInterestRates is not supplied or false");
        }

        if (this.fromApiJsonHelper.parameterExists("maxDifferentialLendingRate", element)) {
            baseDataValidator.reset().parameter("maxDifferentialLendingRate").failWithCode(
                    "not.supported.when.isLinkedToFloatingInterestRates.is.false",
                    "maxDifferentialLendingRate param is not supported when isLinkedToFloatingInterestRates is not supplied or false");
        }

        if (this.fromApiJsonHelper.parameterExists("isFloatingInterestRateCalculationAllowed", element)) {
            baseDataValidator.reset().parameter("isFloatingInterestRateCalculationAllowed").failWithCode(
                    "not.supported.when.isLinkedToFloatingInterestRates.is.false",
                    "isFloatingInterestRateCalculationAllowed param is not supported when isLinkedToFloatingInterestRates is not supplied or false");
        }

        final String minInterestRatePerPeriodParameterName = "minInterestRatePerPeriod";
        BigDecimal minInterestRatePerPeriod = loanProduct.getMinNominalInterestRatePerPeriod();
        if (this.fromApiJsonHelper.parameterExists(minInterestRatePerPeriodParameterName, element)) {
            minInterestRatePerPeriod = this.fromApiJsonHelper
                    .extractBigDecimalWithLocaleNamed(minInterestRatePerPeriodParameterName, element);
        }
        baseDataValidator.reset().parameter(minInterestRatePerPeriodParameterName)
                .value(minInterestRatePerPeriod).ignoreIfNull().zeroOrPositiveAmount();

        final String maxInterestRatePerPeriodParameterName = "maxInterestRatePerPeriod";
        BigDecimal maxInterestRatePerPeriod = loanProduct.getMaxNominalInterestRatePerPeriod();
        if (this.fromApiJsonHelper.parameterExists(maxInterestRatePerPeriodParameterName, element)) {
            maxInterestRatePerPeriod = this.fromApiJsonHelper
                    .extractBigDecimalWithLocaleNamed(maxInterestRatePerPeriodParameterName, element);
        }
        baseDataValidator.reset().parameter(maxInterestRatePerPeriodParameterName)
                .value(maxInterestRatePerPeriod).ignoreIfNull().zeroOrPositiveAmount();

        BigDecimal interestRatePerPeriod = loanProduct.getLoanProductRelatedDetail()
                .getNominalInterestRatePerPeriod();
        if (this.fromApiJsonHelper.parameterExists("interestRatePerPeriod", element)) {
            interestRatePerPeriod = this.fromApiJsonHelper
                    .extractBigDecimalWithLocaleNamed("interestRatePerPeriod", element);
        }
        baseDataValidator.reset().parameter("interestRatePerPeriod").value(interestRatePerPeriod).notNull()
                .zeroOrPositiveAmount();

        Integer interestRateFrequencyType = loanProduct.getLoanProductRelatedDetail()
                .getInterestPeriodFrequencyType().getValue();
        if (this.fromApiJsonHelper.parameterExists("interestRateFrequencyType", element)) {
            interestRateFrequencyType = this.fromApiJsonHelper.extractIntegerNamed("interestRateFrequencyType",
                    element, Locale.getDefault());
        }
        baseDataValidator.reset().parameter("interestRateFrequencyType").value(interestRateFrequencyType)
                .notNull().inMinMaxRange(0, 3);
    }

    // Guarantee Funds
    Boolean holdGuaranteeFunds = loanProduct.isHoldGuaranteeFundsEnabled();
    if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.holdGuaranteeFundsParamName, element)) {
        holdGuaranteeFunds = this.fromApiJsonHelper
                .extractBooleanNamed(LoanProductConstants.holdGuaranteeFundsParamName, element);
        baseDataValidator.reset().parameter(LoanProductConstants.holdGuaranteeFundsParamName)
                .value(holdGuaranteeFunds).notNull().isOneOfTheseValues(true, false);
    }

    if (holdGuaranteeFunds != null) {
        if (holdGuaranteeFunds) {
            validateGuaranteeParams(element, baseDataValidator, null);
        }
    }

    if (this.fromApiJsonHelper
            .parameterExists(LoanProductConstants.principalThresholdForLastInstallmentParamName, element)) {
        BigDecimal principalThresholdForLastInstallment = this.fromApiJsonHelper
                .extractBigDecimalWithLocaleNamed(
                        LoanProductConstants.principalThresholdForLastInstallmentParamName, element);
        baseDataValidator.reset().parameter(LoanProductConstants.principalThresholdForLastInstallmentParamName)
                .value(principalThresholdForLastInstallment).notNull().notLessThanMin(BigDecimal.ZERO)
                .notGreaterThanMax(BigDecimal.valueOf(100));
    }
    if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.canDefineEmiAmountParamName, element)) {
        final Boolean canDefineInstallmentAmount = this.fromApiJsonHelper
                .extractBooleanNamed(LoanProductConstants.canDefineEmiAmountParamName, element);
        baseDataValidator.reset().parameter(LoanProductConstants.canDefineEmiAmountParamName)
                .value(canDefineInstallmentAmount).isOneOfTheseValues(true, false);
    }

    if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.installmentAmountInMultiplesOfParamName,
            element)) {
        final Integer installmentAmountInMultiplesOf = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(
                LoanProductConstants.installmentAmountInMultiplesOfParamName, element);
        baseDataValidator.reset().parameter(LoanProductConstants.installmentAmountInMultiplesOfParamName)
                .value(installmentAmountInMultiplesOf).ignoreIfNull().integerGreaterThanZero();
    }

    final Integer accountingRuleType = this.fromApiJsonHelper.extractIntegerNamed("accountingRule", element,
            Locale.getDefault());
    baseDataValidator.reset().parameter("accountingRule").value(accountingRuleType).ignoreIfNull()
            .inMinMaxRange(1, 4);

    final Long fundAccountId = this.fromApiJsonHelper
            .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue(), element);
    baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue())
            .value(fundAccountId).ignoreIfNull().integerGreaterThanZero();

    final Long loanPortfolioAccountId = this.fromApiJsonHelper
            .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.LOAN_PORTFOLIO.getValue(), element);
    baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.LOAN_PORTFOLIO.getValue())
            .value(loanPortfolioAccountId).ignoreIfNull().integerGreaterThanZero();

    final Long transfersInSuspenseAccountId = this.fromApiJsonHelper
            .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element);
    baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue())
            .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero();

    final Long incomeFromInterestId = this.fromApiJsonHelper
            .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_LOANS.getValue(), element);
    baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_LOANS.getValue())
            .value(incomeFromInterestId).ignoreIfNull().integerGreaterThanZero();

    final Long incomeFromFeeId = this.fromApiJsonHelper
            .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element);
    baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue())
            .value(incomeFromFeeId).ignoreIfNull().integerGreaterThanZero();

    final Long incomeFromPenaltyId = this.fromApiJsonHelper
            .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element);
    baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue())
            .value(incomeFromPenaltyId).ignoreIfNull().integerGreaterThanZero();

    final Long incomeFromRecoveryAccountId = this.fromApiJsonHelper
            .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_RECOVERY.getValue(), element);
    baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_RECOVERY.getValue())
            .value(incomeFromRecoveryAccountId).ignoreIfNull().integerGreaterThanZero();

    final Long writeOffAccountId = this.fromApiJsonHelper
            .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.LOSSES_WRITTEN_OFF.getValue(), element);
    baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.LOSSES_WRITTEN_OFF.getValue())
            .value(writeOffAccountId).ignoreIfNull().integerGreaterThanZero();

    final Long overpaymentAccountId = this.fromApiJsonHelper
            .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.OVERPAYMENT.getValue(), element);
    baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.OVERPAYMENT.getValue())
            .value(overpaymentAccountId).ignoreIfNull().integerGreaterThanZero();

    final Long receivableInterestAccountId = this.fromApiJsonHelper
            .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_RECEIVABLE.getValue(), element);
    baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_RECEIVABLE.getValue())
            .value(receivableInterestAccountId).ignoreIfNull().integerGreaterThanZero();

    final Long receivableFeeAccountId = this.fromApiJsonHelper
            .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.FEES_RECEIVABLE.getValue(), element);
    baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.FEES_RECEIVABLE.getValue())
            .value(receivableFeeAccountId).ignoreIfNull().integerGreaterThanZero();

    final Long receivablePenaltyAccountId = this.fromApiJsonHelper
            .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.PENALTIES_RECEIVABLE.getValue(), element);
    baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.PENALTIES_RECEIVABLE.getValue())
            .value(receivablePenaltyAccountId).ignoreIfNull().integerGreaterThanZero();

    validatePaymentChannelFundSourceMappings(baseDataValidator, element);
    validateChargeToIncomeAccountMappings(baseDataValidator, element);

    validateMinMaxConstraints(element, baseDataValidator, loanProduct);

    if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.useBorrowerCycleParameterName, element)) {
        final Boolean useBorrowerCycle = this.fromApiJsonHelper
                .extractBooleanNamed(LoanProductConstants.useBorrowerCycleParameterName, element);
        baseDataValidator.reset().parameter(LoanProductConstants.useBorrowerCycleParameterName)
                .value(useBorrowerCycle).ignoreIfNull().validateForBooleanValue();
        if (useBorrowerCycle) {
            validateBorrowerCycleVariations(element, baseDataValidator);
        }
    }

    validateMultiDisburseLoanData(baseDataValidator, element);

    // validateLoanConfigurableAttributes(baseDataValidator,element);

    validateVariableInstallmentSettings(baseDataValidator, element);

    validatePartialPeriodSupport(interestCalculationPeriodType, baseDataValidator, element, loanProduct);

    throwExceptionIfValidationWarningsExist(dataValidationErrors);
}

From source file:net.groupbuy.dao.impl.ProductDaoImpl.java

public Page<Product> findPage(ProductCategory productCategory, Brand brand, Promotion promotion, List<Tag> tags,
        Map<Attribute, String> attributeValue, BigDecimal startPrice, BigDecimal endPrice, Boolean isMarketable,
        Boolean isList, Boolean isTop, Boolean isGift, Boolean isOutOfStock, Boolean isStockAlert,
        OrderType orderType, Pageable pageable) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Product> criteriaQuery = criteriaBuilder.createQuery(Product.class);
    Root<Product> root = criteriaQuery.from(Product.class);
    criteriaQuery.select(root);//from w  w w  . j  a  v a  2s  .c o m
    Predicate restrictions = criteriaBuilder.conjunction();
    if (productCategory != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.or(criteriaBuilder.equal(root.get("productCategory"), productCategory),
                        criteriaBuilder.like(root.get("productCategory").<String>get("treePath"),
                                "%" + ProductCategory.TREE_PATH_SEPARATOR + productCategory.getId()
                                        + ProductCategory.TREE_PATH_SEPARATOR + "%")));
    }
    if (brand != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("brand"), brand));
    }
    if (promotion != null) {
        Subquery<Product> subquery1 = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot1 = subquery1.from(Product.class);
        subquery1.select(subqueryRoot1);
        subquery1.where(criteriaBuilder.equal(subqueryRoot1, root),
                criteriaBuilder.equal(subqueryRoot1.join("promotions"), promotion));

        Subquery<Product> subquery2 = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot2 = subquery2.from(Product.class);
        subquery2.select(subqueryRoot2);
        subquery2.where(criteriaBuilder.equal(subqueryRoot2, root),
                criteriaBuilder.equal(subqueryRoot2.join("productCategory").join("promotions"), promotion));

        Subquery<Product> subquery3 = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot3 = subquery3.from(Product.class);
        subquery3.select(subqueryRoot3);
        subquery3.where(criteriaBuilder.equal(subqueryRoot3, root),
                criteriaBuilder.equal(subqueryRoot3.join("brand").join("promotions"), promotion));

        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.exists(subquery1),
                criteriaBuilder.exists(subquery2), criteriaBuilder.exists(subquery3)));
    }
    if (tags != null && !tags.isEmpty()) {
        Subquery<Product> subquery = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot = subquery.from(Product.class);
        subquery.select(subqueryRoot);
        subquery.where(criteriaBuilder.equal(subqueryRoot, root), subqueryRoot.join("tags").in(tags));
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.exists(subquery));
    }
    if (attributeValue != null) {
        for (Entry<Attribute, String> entry : attributeValue.entrySet()) {
            String propertyName = Product.ATTRIBUTE_VALUE_PROPERTY_NAME_PREFIX
                    + entry.getKey().getPropertyIndex();
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.equal(root.get(propertyName), entry.getValue()));
        }
    }
    if (startPrice != null && endPrice != null && startPrice.compareTo(endPrice) > 0) {
        BigDecimal temp = startPrice;
        startPrice = endPrice;
        endPrice = temp;
    }
    if (startPrice != null && startPrice.compareTo(new BigDecimal(0)) >= 0) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.ge(root.<Number>get("price"), startPrice));
    }
    if (endPrice != null && endPrice.compareTo(new BigDecimal(0)) >= 0) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.le(root.<Number>get("price"), endPrice));
    }
    if (isMarketable != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isMarketable"), isMarketable));
    }
    if (isList != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isList"), isList));
    }
    if (isTop != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isTop"), isTop));
    }
    if (isGift != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isGift"), isGift));
    }
    Path<Integer> stock = root.get("stock");
    Path<Integer> allocatedStock = root.get("allocatedStock");
    if (isOutOfStock != null) {
        if (isOutOfStock) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock),
                    criteriaBuilder.lessThanOrEqualTo(stock, allocatedStock));
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.isNull(stock),
                    criteriaBuilder.greaterThan(stock, allocatedStock)));
        }
    }
    if (isStockAlert != null) {
        Setting setting = SettingUtils.get();
        if (isStockAlert) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock),
                    criteriaBuilder.lessThanOrEqualTo(stock,
                            criteriaBuilder.sum(allocatedStock, setting.getStockAlertCount())));
        } else {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.or(criteriaBuilder.isNull(stock), criteriaBuilder.greaterThan(stock,
                            criteriaBuilder.sum(allocatedStock, setting.getStockAlertCount()))));
        }
    }
    criteriaQuery.where(restrictions);
    List<Order> orders = pageable.getOrders();
    if (orderType == OrderType.priceAsc) {
        orders.add(Order.asc("price"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.priceDesc) {
        orders.add(Order.desc("price"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.salesDesc) {
        orders.add(Order.desc("sales"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.scoreDesc) {
        orders.add(Order.desc("score"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.dateDesc) {
        orders.add(Order.desc("createDate"));
    } else {
        orders.add(Order.desc("isTop"));
        orders.add(Order.desc("modifyDate"));
    }
    return super.findPage(criteriaQuery, pageable);
}

From source file:com.gst.portfolio.loanproduct.serialization.LoanProductDataValidator.java

public void validateForUpdate(final String json, final LoanProduct loanProduct) {
    if (StringUtils.isBlank(json)) {
        throw new InvalidJsonException();
    }//from ww w  .  ja v a2s  .c  om

    final Type typeOfMap = new TypeToken<Map<String, Object>>() {
    }.getType();
    this.fromApiJsonHelper.checkForUnsupportedParameters(typeOfMap, json, this.supportedParameters);

    final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
    final DataValidatorBuilder baseDataValidator = new DataValidatorBuilder(dataValidationErrors)
            .resource("loanproduct");

    final JsonElement element = this.fromApiJsonHelper.parse(json);
    if (this.fromApiJsonHelper.parameterExists("name", element)) {
        final String name = this.fromApiJsonHelper.extractStringNamed("name", element);
        baseDataValidator.reset().parameter("name").value(name).notBlank().notExceedingLengthOf(100);
    }

    if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.shortName, element)) {
        final String shortName = this.fromApiJsonHelper.extractStringNamed(LoanProductConstants.shortName,
                element);
        baseDataValidator.reset().parameter(LoanProductConstants.shortName).value(shortName).notBlank()
                .notExceedingLengthOf(4);
    }

    if (this.fromApiJsonHelper.parameterExists("description", element)) {
        final String description = this.fromApiJsonHelper.extractStringNamed("description", element);
        baseDataValidator.reset().parameter("description").value(description).notExceedingLengthOf(500);
    }

    if (this.fromApiJsonHelper.parameterExists("fundId", element)) {
        final Long fundId = this.fromApiJsonHelper.extractLongNamed("fundId", element);
        baseDataValidator.reset().parameter("fundId").value(fundId).ignoreIfNull().integerGreaterThanZero();
    }

    if (this.fromApiJsonHelper.parameterExists("includeInBorrowerCycle", element)) {
        final Boolean includeInBorrowerCycle = this.fromApiJsonHelper
                .extractBooleanNamed("includeInBorrowerCycle", element);
        baseDataValidator.reset().parameter("includeInBorrowerCycle").value(includeInBorrowerCycle)
                .ignoreIfNull().validateForBooleanValue();
    }

    if (this.fromApiJsonHelper.parameterExists("currencyCode", element)) {
        final String currencyCode = this.fromApiJsonHelper.extractStringNamed("currencyCode", element);
        baseDataValidator.reset().parameter("currencyCode").value(currencyCode).notBlank()
                .notExceedingLengthOf(3);
    }

    if (this.fromApiJsonHelper.parameterExists("digitsAfterDecimal", element)) {
        final Integer digitsAfterDecimal = this.fromApiJsonHelper.extractIntegerNamed("digitsAfterDecimal",
                element, Locale.getDefault());
        baseDataValidator.reset().parameter("digitsAfterDecimal").value(digitsAfterDecimal).notNull()
                .inMinMaxRange(0, 6);
    }

    if (this.fromApiJsonHelper.parameterExists("inMultiplesOf", element)) {
        final Integer inMultiplesOf = this.fromApiJsonHelper.extractIntegerNamed("inMultiplesOf", element,
                Locale.getDefault());
        baseDataValidator.reset().parameter("inMultiplesOf").value(inMultiplesOf).ignoreIfNull()
                .integerZeroOrGreater();
    }

    final String minPrincipalParameterName = "minPrincipal";
    BigDecimal minPrincipalAmount = null;
    if (this.fromApiJsonHelper.parameterExists(minPrincipalParameterName, element)) {
        minPrincipalAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(minPrincipalParameterName,
                element);
        baseDataValidator.reset().parameter(minPrincipalParameterName).value(minPrincipalAmount).ignoreIfNull()
                .positiveAmount();
    }

    final String maxPrincipalParameterName = "maxPrincipal";
    BigDecimal maxPrincipalAmount = null;
    if (this.fromApiJsonHelper.parameterExists(maxPrincipalParameterName, element)) {
        maxPrincipalAmount = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed(maxPrincipalParameterName,
                element);
        baseDataValidator.reset().parameter(maxPrincipalParameterName).value(maxPrincipalAmount).ignoreIfNull()
                .positiveAmount();
    }

    if (this.fromApiJsonHelper.parameterExists("principal", element)) {
        final BigDecimal principal = this.fromApiJsonHelper.extractBigDecimalWithLocaleNamed("principal",
                element);
        baseDataValidator.reset().parameter("principal").value(principal).positiveAmount();
    }

    if (this.fromApiJsonHelper.parameterExists("inArrearsTolerance", element)) {
        final BigDecimal inArrearsTolerance = this.fromApiJsonHelper
                .extractBigDecimalWithLocaleNamed("inArrearsTolerance", element);
        baseDataValidator.reset().parameter("inArrearsTolerance").value(inArrearsTolerance).ignoreIfNull()
                .zeroOrPositiveAmount();
    }

    final String minNumberOfRepaymentsParameterName = "minNumberOfRepayments";
    Integer minNumberOfRepayments = null;
    if (this.fromApiJsonHelper.parameterExists(minNumberOfRepaymentsParameterName, element)) {
        minNumberOfRepayments = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed(minNumberOfRepaymentsParameterName, element);
        baseDataValidator.reset().parameter(minNumberOfRepaymentsParameterName).value(minNumberOfRepayments)
                .ignoreIfNull().integerGreaterThanZero();
    }

    final String maxNumberOfRepaymentsParameterName = "maxNumberOfRepayments";
    Integer maxNumberOfRepayments = null;
    if (this.fromApiJsonHelper.parameterExists(maxNumberOfRepaymentsParameterName, element)) {
        maxNumberOfRepayments = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed(maxNumberOfRepaymentsParameterName, element);
        baseDataValidator.reset().parameter(maxNumberOfRepaymentsParameterName).value(maxNumberOfRepayments)
                .ignoreIfNull().integerGreaterThanZero();
    }

    if (this.fromApiJsonHelper.parameterExists("numberOfRepayments", element)) {
        final Integer numberOfRepayments = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed("numberOfRepayments", element);
        baseDataValidator.reset().parameter("numberOfRepayments").value(numberOfRepayments).notNull()
                .integerGreaterThanZero();
    }

    if (this.fromApiJsonHelper.parameterExists("repaymentEvery", element)) {
        final Integer repaymentEvery = this.fromApiJsonHelper.extractIntegerWithLocaleNamed("repaymentEvery",
                element);
        baseDataValidator.reset().parameter("repaymentEvery").value(repaymentEvery).notNull()
                .integerGreaterThanZero();
    }

    if (this.fromApiJsonHelper.parameterExists("repaymentFrequencyType", element)) {
        final Integer repaymentFrequencyType = this.fromApiJsonHelper
                .extractIntegerNamed("repaymentFrequencyType", element, Locale.getDefault());
        baseDataValidator.reset().parameter("repaymentFrequencyType").value(repaymentFrequencyType).notNull()
                .inMinMaxRange(0, 3);
    }

    if (this.fromApiJsonHelper.parameterExists("transactionProcessingStrategyId", element)) {
        final Long transactionProcessingStrategyId = this.fromApiJsonHelper
                .extractLongNamed("transactionProcessingStrategyId", element);
        baseDataValidator.reset().parameter("transactionProcessingStrategyId")
                .value(transactionProcessingStrategyId).notNull().integerGreaterThanZero();
    }

    // grace validation
    if (this.fromApiJsonHelper.parameterExists("graceOnPrincipalPayment", element)) {
        final Integer graceOnPrincipalPayment = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed("graceOnPrincipalPayment", element);
        baseDataValidator.reset().parameter("graceOnPrincipalPayment").value(graceOnPrincipalPayment)
                .zeroOrPositiveAmount();
    }

    if (this.fromApiJsonHelper.parameterExists("graceOnInterestPayment", element)) {
        final Integer graceOnInterestPayment = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed("graceOnInterestPayment", element);
        baseDataValidator.reset().parameter("graceOnInterestPayment").value(graceOnInterestPayment)
                .zeroOrPositiveAmount();
    }

    if (this.fromApiJsonHelper.parameterExists("graceOnInterestCharged", element)) {
        final Integer graceOnInterestCharged = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed("graceOnInterestCharged", element);
        baseDataValidator.reset().parameter("graceOnInterestCharged").value(graceOnInterestCharged)
                .zeroOrPositiveAmount();
    }

    if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.graceOnArrearsAgeingParameterName,
            element)) {
        final Integer graceOnArrearsAgeing = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed(LoanProductConstants.graceOnArrearsAgeingParameterName, element);
        baseDataValidator.reset().parameter(LoanProductConstants.graceOnArrearsAgeingParameterName)
                .value(graceOnArrearsAgeing).integerZeroOrGreater();
    }

    if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.overdueDaysForNPAParameterName, element)) {
        final Integer overdueDaysForNPA = this.fromApiJsonHelper
                .extractIntegerWithLocaleNamed(LoanProductConstants.overdueDaysForNPAParameterName, element);
        baseDataValidator.reset().parameter(LoanProductConstants.overdueDaysForNPAParameterName)
                .value(overdueDaysForNPA).integerZeroOrGreater();
    }

    //
    if (this.fromApiJsonHelper.parameterExists("amortizationType", element)) {
        final Integer amortizationType = this.fromApiJsonHelper.extractIntegerNamed("amortizationType", element,
                Locale.getDefault());
        baseDataValidator.reset().parameter("amortizationType").value(amortizationType).notNull()
                .inMinMaxRange(0, 1);
    }

    if (this.fromApiJsonHelper.parameterExists("interestType", element)) {
        final Integer interestType = this.fromApiJsonHelper.extractIntegerNamed("interestType", element,
                Locale.getDefault());
        baseDataValidator.reset().parameter("interestType").value(interestType).notNull().inMinMaxRange(0, 1);
    }
    Integer interestCalculationPeriodType = loanProduct.getLoanProductRelatedDetail()
            .getInterestCalculationPeriodMethod().getValue();
    if (this.fromApiJsonHelper.parameterExists("interestCalculationPeriodType", element)) {
        interestCalculationPeriodType = this.fromApiJsonHelper
                .extractIntegerNamed("interestCalculationPeriodType", element, Locale.getDefault());
        baseDataValidator.reset().parameter("interestCalculationPeriodType")
                .value(interestCalculationPeriodType).notNull().inMinMaxRange(0, 1);
    }

    /**
     * { @link DaysInYearType }
     */
    if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.daysInYearTypeParameterName, element)) {
        final Integer daysInYearType = this.fromApiJsonHelper.extractIntegerNamed(
                LoanProductConstants.daysInYearTypeParameterName, element, Locale.getDefault());
        baseDataValidator.reset().parameter(LoanProductConstants.daysInYearTypeParameterName)
                .value(daysInYearType).notNull().isOneOfTheseValues(1, 360, 364, 365);
    }

    /**
     * { @link DaysInMonthType }
     */
    if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.daysInMonthTypeParameterName, element)) {
        final Integer daysInMonthType = this.fromApiJsonHelper.extractIntegerNamed(
                LoanProductConstants.daysInMonthTypeParameterName, element, Locale.getDefault());
        baseDataValidator.reset().parameter(LoanProductConstants.daysInMonthTypeParameterName)
                .value(daysInMonthType).notNull().isOneOfTheseValues(1, 30);
    }

    if (this.fromApiJsonHelper.parameterExists(
            LoanProductConstants.accountMovesOutOfNPAOnlyOnArrearsCompletionParamName, element)) {
        Boolean npaChangeConfig = this.fromApiJsonHelper.extractBooleanNamed(
                LoanProductConstants.accountMovesOutOfNPAOnlyOnArrearsCompletionParamName, element);
        baseDataValidator.reset()
                .parameter(LoanProductConstants.accountMovesOutOfNPAOnlyOnArrearsCompletionParamName)
                .value(npaChangeConfig).notNull().isOneOfTheseValues(true, false);
    }

    // Interest recalculation settings
    Boolean isInterestRecalculationEnabled = loanProduct.isInterestRecalculationEnabled();
    if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.isInterestRecalculationEnabledParameterName,
            element)) {
        isInterestRecalculationEnabled = this.fromApiJsonHelper
                .extractBooleanNamed(LoanProductConstants.isInterestRecalculationEnabledParameterName, element);
        baseDataValidator.reset().parameter(LoanProductConstants.isInterestRecalculationEnabledParameterName)
                .value(isInterestRecalculationEnabled).notNull().isOneOfTheseValues(true, false);
    }

    if (isInterestRecalculationEnabled != null) {
        if (isInterestRecalculationEnabled) {
            validateInterestRecalculationParams(element, baseDataValidator, loanProduct);
        }
    }

    // interest rates
    boolean isLinkedToFloatingInterestRates = loanProduct.isLinkedToFloatingInterestRate();
    if (this.fromApiJsonHelper.parameterExists("isLinkedToFloatingInterestRates", element)) {
        isLinkedToFloatingInterestRates = this.fromApiJsonHelper
                .extractBooleanNamed("isLinkedToFloatingInterestRates", element);
    }
    if (isLinkedToFloatingInterestRates) {
        if (this.fromApiJsonHelper.parameterExists("interestRatePerPeriod", element)) {
            baseDataValidator.reset().parameter("interestRatePerPeriod").failWithCode(
                    "not.supported.when.isLinkedToFloatingInterestRates.is.true",
                    "interestRatePerPeriod param is not supported when isLinkedToFloatingInterestRates is true");
        }

        if (this.fromApiJsonHelper.parameterExists("minInterestRatePerPeriod", element)) {
            baseDataValidator.reset().parameter("minInterestRatePerPeriod").failWithCode(
                    "not.supported.when.isLinkedToFloatingInterestRates.is.true",
                    "minInterestRatePerPeriod param is not supported when isLinkedToFloatingInterestRates is true");
        }

        if (this.fromApiJsonHelper.parameterExists("maxInterestRatePerPeriod", element)) {
            baseDataValidator.reset().parameter("maxInterestRatePerPeriod").failWithCode(
                    "not.supported.when.isLinkedToFloatingInterestRates.is.true",
                    "maxInterestRatePerPeriod param is not supported when isLinkedToFloatingInterestRates is true");
        }

        if (this.fromApiJsonHelper.parameterExists("interestRateFrequencyType", element)) {
            baseDataValidator.reset().parameter("interestRateFrequencyType").failWithCode(
                    "not.supported.when.isLinkedToFloatingInterestRates.is.true",
                    "interestRateFrequencyType param is not supported when isLinkedToFloatingInterestRates is true");
        }

        Integer interestType = this.fromApiJsonHelper.parameterExists("interestType", element)
                ? this.fromApiJsonHelper.extractIntegerNamed("interestType", element, Locale.getDefault())
                : loanProduct.getLoanProductRelatedDetail().getInterestMethod().getValue();
        if ((interestType == null || interestType != InterestMethod.DECLINING_BALANCE.getValue())
                || (isInterestRecalculationEnabled == null || isInterestRecalculationEnabled == false)) {
            baseDataValidator.reset().parameter("isLinkedToFloatingInterestRates").failWithCode(
                    "supported.only.for.declining.balance.interest.recalculation.enabled",
                    "Floating interest rates are supported only for declining balance and interest recalculation enabled loan products");
        }

        Long floatingRatesId = loanProduct.getFloatingRates() == null ? null
                : loanProduct.getFloatingRates().getFloatingRate().getId();
        if (this.fromApiJsonHelper.parameterExists("floatingRatesId", element)) {
            floatingRatesId = this.fromApiJsonHelper.extractLongNamed("floatingRatesId", element);
        }
        baseDataValidator.reset().parameter("floatingRatesId").value(floatingRatesId).notNull();

        BigDecimal interestRateDifferential = loanProduct.getFloatingRates() == null ? null
                : loanProduct.getFloatingRates().getInterestRateDifferential();
        if (this.fromApiJsonHelper.parameterExists("interestRateDifferential", element)) {
            interestRateDifferential = this.fromApiJsonHelper
                    .extractBigDecimalWithLocaleNamed("interestRateDifferential", element);
        }
        baseDataValidator.reset().parameter("interestRateDifferential").value(interestRateDifferential)
                .notNull().zeroOrPositiveAmount();

        final String minDifferentialLendingRateParameterName = "minDifferentialLendingRate";
        BigDecimal minDifferentialLendingRate = loanProduct.getFloatingRates() == null ? null
                : loanProduct.getFloatingRates().getMinDifferentialLendingRate();
        if (this.fromApiJsonHelper.parameterExists(minDifferentialLendingRateParameterName, element)) {
            minDifferentialLendingRate = this.fromApiJsonHelper
                    .extractBigDecimalWithLocaleNamed(minDifferentialLendingRateParameterName, element);
        }
        baseDataValidator.reset().parameter(minDifferentialLendingRateParameterName)
                .value(minDifferentialLendingRate).notNull().zeroOrPositiveAmount();

        final String defaultDifferentialLendingRateParameterName = "defaultDifferentialLendingRate";
        BigDecimal defaultDifferentialLendingRate = loanProduct.getFloatingRates() == null ? null
                : loanProduct.getFloatingRates().getDefaultDifferentialLendingRate();
        if (this.fromApiJsonHelper.parameterExists(defaultDifferentialLendingRateParameterName, element)) {
            defaultDifferentialLendingRate = this.fromApiJsonHelper
                    .extractBigDecimalWithLocaleNamed(defaultDifferentialLendingRateParameterName, element);
        }
        baseDataValidator.reset().parameter(defaultDifferentialLendingRateParameterName)
                .value(defaultDifferentialLendingRate).notNull().zeroOrPositiveAmount();

        final String maxDifferentialLendingRateParameterName = "maxDifferentialLendingRate";
        BigDecimal maxDifferentialLendingRate = loanProduct.getFloatingRates() == null ? null
                : loanProduct.getFloatingRates().getMaxDifferentialLendingRate();
        if (this.fromApiJsonHelper.parameterExists(maxDifferentialLendingRateParameterName, element)) {
            maxDifferentialLendingRate = this.fromApiJsonHelper
                    .extractBigDecimalWithLocaleNamed(maxDifferentialLendingRateParameterName, element);
        }
        baseDataValidator.reset().parameter(maxDifferentialLendingRateParameterName)
                .value(maxDifferentialLendingRate).notNull().zeroOrPositiveAmount();

        if (defaultDifferentialLendingRate != null
                && defaultDifferentialLendingRate.compareTo(BigDecimal.ZERO) != -1) {
            if (minDifferentialLendingRate != null
                    && minDifferentialLendingRate.compareTo(BigDecimal.ZERO) != -1) {
                baseDataValidator.reset().parameter("defaultDifferentialLendingRate")
                        .value(defaultDifferentialLendingRate).notLessThanMin(minDifferentialLendingRate);
            }
        }

        if (maxDifferentialLendingRate != null && maxDifferentialLendingRate.compareTo(BigDecimal.ZERO) != -1) {
            if (minDifferentialLendingRate != null
                    && minDifferentialLendingRate.compareTo(BigDecimal.ZERO) != -1) {
                baseDataValidator.reset().parameter("maxDifferentialLendingRate")
                        .value(maxDifferentialLendingRate).notLessThanMin(minDifferentialLendingRate);
            }
        }

        if (maxDifferentialLendingRate != null && maxDifferentialLendingRate.compareTo(BigDecimal.ZERO) != -1) {
            if (defaultDifferentialLendingRate != null
                    && defaultDifferentialLendingRate.compareTo(BigDecimal.ZERO) != -1) {
                baseDataValidator.reset().parameter("maxDifferentialLendingRate")
                        .value(maxDifferentialLendingRate).notLessThanMin(defaultDifferentialLendingRate);
            }
        }

        Boolean isFloatingInterestRateCalculationAllowed = loanProduct.getFloatingRates() == null ? null
                : loanProduct.getFloatingRates().isFloatingInterestRateCalculationAllowed();
        if (this.fromApiJsonHelper.parameterExists("isFloatingInterestRateCalculationAllowed", element)) {
            isFloatingInterestRateCalculationAllowed = this.fromApiJsonHelper
                    .extractBooleanNamed("isFloatingInterestRateCalculationAllowed", element);
        }
        baseDataValidator.reset().parameter("isFloatingInterestRateCalculationAllowed")
                .value(isFloatingInterestRateCalculationAllowed).notNull().isOneOfTheseValues(true, false);
    } else {
        if (this.fromApiJsonHelper.parameterExists("floatingRatesId", element)) {
            baseDataValidator.reset().parameter("floatingRatesId").failWithCode(
                    "not.supported.when.isLinkedToFloatingInterestRates.is.false",
                    "floatingRatesId param is not supported when isLinkedToFloatingInterestRates is not supplied or false");
        }

        if (this.fromApiJsonHelper.parameterExists("interestRateDifferential", element)) {
            baseDataValidator.reset().parameter("interestRateDifferential").failWithCode(
                    "not.supported.when.isLinkedToFloatingInterestRates.is.false",
                    "interestRateDifferential param is not supported when isLinkedToFloatingInterestRates is not supplied or false");
        }

        if (this.fromApiJsonHelper.parameterExists("minDifferentialLendingRate", element)) {
            baseDataValidator.reset().parameter("minDifferentialLendingRate").failWithCode(
                    "not.supported.when.isLinkedToFloatingInterestRates.is.false",
                    "minDifferentialLendingRate param is not supported when isLinkedToFloatingInterestRates is not supplied or false");
        }

        if (this.fromApiJsonHelper.parameterExists("defaultDifferentialLendingRate", element)) {
            baseDataValidator.reset().parameter("defaultDifferentialLendingRate").failWithCode(
                    "not.supported.when.isLinkedToFloatingInterestRates.is.false",
                    "defaultDifferentialLendingRate param is not supported when isLinkedToFloatingInterestRates is not supplied or false");
        }

        if (this.fromApiJsonHelper.parameterExists("maxDifferentialLendingRate", element)) {
            baseDataValidator.reset().parameter("maxDifferentialLendingRate").failWithCode(
                    "not.supported.when.isLinkedToFloatingInterestRates.is.false",
                    "maxDifferentialLendingRate param is not supported when isLinkedToFloatingInterestRates is not supplied or false");
        }

        if (this.fromApiJsonHelper.parameterExists("isFloatingInterestRateCalculationAllowed", element)) {
            baseDataValidator.reset().parameter("isFloatingInterestRateCalculationAllowed").failWithCode(
                    "not.supported.when.isLinkedToFloatingInterestRates.is.false",
                    "isFloatingInterestRateCalculationAllowed param is not supported when isLinkedToFloatingInterestRates is not supplied or false");
        }

        final String minInterestRatePerPeriodParameterName = "minInterestRatePerPeriod";
        BigDecimal minInterestRatePerPeriod = loanProduct.getMinNominalInterestRatePerPeriod();
        if (this.fromApiJsonHelper.parameterExists(minInterestRatePerPeriodParameterName, element)) {
            minInterestRatePerPeriod = this.fromApiJsonHelper
                    .extractBigDecimalWithLocaleNamed(minInterestRatePerPeriodParameterName, element);
        }
        baseDataValidator.reset().parameter(minInterestRatePerPeriodParameterName)
                .value(minInterestRatePerPeriod).ignoreIfNull().zeroOrPositiveAmount();

        final String maxInterestRatePerPeriodParameterName = "maxInterestRatePerPeriod";
        BigDecimal maxInterestRatePerPeriod = loanProduct.getMaxNominalInterestRatePerPeriod();
        if (this.fromApiJsonHelper.parameterExists(maxInterestRatePerPeriodParameterName, element)) {
            maxInterestRatePerPeriod = this.fromApiJsonHelper
                    .extractBigDecimalWithLocaleNamed(maxInterestRatePerPeriodParameterName, element);
        }
        baseDataValidator.reset().parameter(maxInterestRatePerPeriodParameterName)
                .value(maxInterestRatePerPeriod).ignoreIfNull().zeroOrPositiveAmount();

        BigDecimal interestRatePerPeriod = loanProduct.getLoanProductRelatedDetail()
                .getNominalInterestRatePerPeriod();
        if (this.fromApiJsonHelper.parameterExists("interestRatePerPeriod", element)) {
            interestRatePerPeriod = this.fromApiJsonHelper
                    .extractBigDecimalWithLocaleNamed("interestRatePerPeriod", element);
        }
        baseDataValidator.reset().parameter("interestRatePerPeriod").value(interestRatePerPeriod).notNull()
                .zeroOrPositiveAmount();

        Integer interestRateFrequencyType = loanProduct.getLoanProductRelatedDetail()
                .getInterestPeriodFrequencyType().getValue();
        if (this.fromApiJsonHelper.parameterExists("interestRateFrequencyType", element)) {
            interestRateFrequencyType = this.fromApiJsonHelper.extractIntegerNamed("interestRateFrequencyType",
                    element, Locale.getDefault());
        }
        baseDataValidator.reset().parameter("interestRateFrequencyType").value(interestRateFrequencyType)
                .notNull().inMinMaxRange(0, 3);
    }

    // Guarantee Funds
    Boolean holdGuaranteeFunds = loanProduct.isHoldGuaranteeFundsEnabled();
    if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.holdGuaranteeFundsParamName, element)) {
        holdGuaranteeFunds = this.fromApiJsonHelper
                .extractBooleanNamed(LoanProductConstants.holdGuaranteeFundsParamName, element);
        baseDataValidator.reset().parameter(LoanProductConstants.holdGuaranteeFundsParamName)
                .value(holdGuaranteeFunds).notNull().isOneOfTheseValues(true, false);
    }

    if (holdGuaranteeFunds != null) {
        if (holdGuaranteeFunds) {
            validateGuaranteeParams(element, baseDataValidator, null);
        }
    }

    if (this.fromApiJsonHelper
            .parameterExists(LoanProductConstants.principalThresholdForLastInstallmentParamName, element)) {
        BigDecimal principalThresholdForLastInstallment = this.fromApiJsonHelper
                .extractBigDecimalWithLocaleNamed(
                        LoanProductConstants.principalThresholdForLastInstallmentParamName, element);
        baseDataValidator.reset().parameter(LoanProductConstants.principalThresholdForLastInstallmentParamName)
                .value(principalThresholdForLastInstallment).notNull().notLessThanMin(BigDecimal.ZERO)
                .notGreaterThanMax(BigDecimal.valueOf(100));
    }
    if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.canDefineEmiAmountParamName, element)) {
        final Boolean canDefineInstallmentAmount = this.fromApiJsonHelper
                .extractBooleanNamed(LoanProductConstants.canDefineEmiAmountParamName, element);
        baseDataValidator.reset().parameter(LoanProductConstants.canDefineEmiAmountParamName)
                .value(canDefineInstallmentAmount).isOneOfTheseValues(true, false);
    }

    if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.installmentAmountInMultiplesOfParamName,
            element)) {
        final Integer installmentAmountInMultiplesOf = this.fromApiJsonHelper.extractIntegerWithLocaleNamed(
                LoanProductConstants.installmentAmountInMultiplesOfParamName, element);
        baseDataValidator.reset().parameter(LoanProductConstants.installmentAmountInMultiplesOfParamName)
                .value(installmentAmountInMultiplesOf).ignoreIfNull().integerGreaterThanZero();
    }

    final Integer accountingRuleType = this.fromApiJsonHelper.extractIntegerNamed("accountingRule", element,
            Locale.getDefault());
    baseDataValidator.reset().parameter("accountingRule").value(accountingRuleType).ignoreIfNull()
            .inMinMaxRange(1, 4);

    final Long fundAccountId = this.fromApiJsonHelper
            .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue(), element);
    baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.FUND_SOURCE.getValue())
            .value(fundAccountId).ignoreIfNull().integerGreaterThanZero();

    final Long loanPortfolioAccountId = this.fromApiJsonHelper
            .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.LOAN_PORTFOLIO.getValue(), element);
    baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.LOAN_PORTFOLIO.getValue())
            .value(loanPortfolioAccountId).ignoreIfNull().integerGreaterThanZero();

    final Long transfersInSuspenseAccountId = this.fromApiJsonHelper
            .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue(), element);
    baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.TRANSFERS_SUSPENSE.getValue())
            .value(transfersInSuspenseAccountId).ignoreIfNull().integerGreaterThanZero();

    final Long incomeFromInterestId = this.fromApiJsonHelper
            .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_LOANS.getValue(), element);
    baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_ON_LOANS.getValue())
            .value(incomeFromInterestId).ignoreIfNull().integerGreaterThanZero();

    final Long incomeFromFeeId = this.fromApiJsonHelper
            .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue(), element);
    baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_FEES.getValue())
            .value(incomeFromFeeId).ignoreIfNull().integerGreaterThanZero();

    final Long incomeFromPenaltyId = this.fromApiJsonHelper
            .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue(), element);
    baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_PENALTIES.getValue())
            .value(incomeFromPenaltyId).ignoreIfNull().integerGreaterThanZero();

    final Long incomeFromRecoveryAccountId = this.fromApiJsonHelper
            .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_RECOVERY.getValue(), element);
    baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INCOME_FROM_RECOVERY.getValue())
            .value(incomeFromRecoveryAccountId).ignoreIfNull().integerGreaterThanZero();

    final Long writeOffAccountId = this.fromApiJsonHelper
            .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.LOSSES_WRITTEN_OFF.getValue(), element);
    baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.LOSSES_WRITTEN_OFF.getValue())
            .value(writeOffAccountId).ignoreIfNull().integerGreaterThanZero();

    final Long overpaymentAccountId = this.fromApiJsonHelper
            .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.OVERPAYMENT.getValue(), element);
    baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.OVERPAYMENT.getValue())
            .value(overpaymentAccountId).ignoreIfNull().integerGreaterThanZero();

    final Long receivableInterestAccountId = this.fromApiJsonHelper
            .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_RECEIVABLE.getValue(), element);
    baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.INTEREST_RECEIVABLE.getValue())
            .value(receivableInterestAccountId).ignoreIfNull().integerGreaterThanZero();

    final Long receivableFeeAccountId = this.fromApiJsonHelper
            .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.FEES_RECEIVABLE.getValue(), element);
    baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.FEES_RECEIVABLE.getValue())
            .value(receivableFeeAccountId).ignoreIfNull().integerGreaterThanZero();

    final Long receivablePenaltyAccountId = this.fromApiJsonHelper
            .extractLongNamed(LOAN_PRODUCT_ACCOUNTING_PARAMS.PENALTIES_RECEIVABLE.getValue(), element);
    baseDataValidator.reset().parameter(LOAN_PRODUCT_ACCOUNTING_PARAMS.PENALTIES_RECEIVABLE.getValue())
            .value(receivablePenaltyAccountId).ignoreIfNull().integerGreaterThanZero();

    validatePaymentChannelFundSourceMappings(baseDataValidator, element);
    validateChargeToIncomeAccountMappings(baseDataValidator, element);

    validateMinMaxConstraints(element, baseDataValidator, loanProduct);

    if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.useBorrowerCycleParameterName, element)) {
        final Boolean useBorrowerCycle = this.fromApiJsonHelper
                .extractBooleanNamed(LoanProductConstants.useBorrowerCycleParameterName, element);
        baseDataValidator.reset().parameter(LoanProductConstants.useBorrowerCycleParameterName)
                .value(useBorrowerCycle).ignoreIfNull().validateForBooleanValue();
        if (useBorrowerCycle) {
            validateBorrowerCycleVariations(element, baseDataValidator);
        }
    }

    validateMultiDisburseLoanData(baseDataValidator, element);

    // validateLoanConfigurableAttributes(baseDataValidator,element);

    validateVariableInstallmentSettings(baseDataValidator, element);

    validatePartialPeriodSupport(interestCalculationPeriodType, baseDataValidator, element, loanProduct);

    if (this.fromApiJsonHelper.parameterExists(LoanProductConstants.canUseForTopup, element)) {
        final Boolean canUseForTopup = this.fromApiJsonHelper
                .extractBooleanNamed(LoanProductConstants.canUseForTopup, element);
        baseDataValidator.reset().parameter(LoanProductConstants.canUseForTopup).value(canUseForTopup)
                .validateForBooleanValue();
    }

    throwExceptionIfValidationWarningsExist(dataValidationErrors);
}

From source file:net.groupbuy.dao.impl.ProductDaoImpl.java

public List<Product> findList(ProductCategory productCategory, Brand brand, Promotion promotion, List<Tag> tags,
        Map<Attribute, String> attributeValue, BigDecimal startPrice, BigDecimal endPrice, Boolean isMarketable,
        Boolean isList, Boolean isTop, Boolean isGift, Boolean isOutOfStock, Boolean isStockAlert,
        OrderType orderType, Integer count, List<Filter> filters, List<Order> orders) {
    CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder();
    CriteriaQuery<Product> criteriaQuery = criteriaBuilder.createQuery(Product.class);
    Root<Product> root = criteriaQuery.from(Product.class);
    criteriaQuery.select(root);//  ww  w .j  a v  a  2 s  .c  om
    Predicate restrictions = criteriaBuilder.conjunction();
    if (productCategory != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.or(criteriaBuilder.equal(root.get("productCategory"), productCategory),
                        criteriaBuilder.like(root.get("productCategory").<String>get("treePath"),
                                "%" + ProductCategory.TREE_PATH_SEPARATOR + productCategory.getId()
                                        + ProductCategory.TREE_PATH_SEPARATOR + "%")));
    }
    if (brand != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("brand"), brand));
    }
    if (promotion != null) {
        Subquery<Product> subquery1 = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot1 = subquery1.from(Product.class);
        subquery1.select(subqueryRoot1);
        subquery1.where(criteriaBuilder.equal(subqueryRoot1, root),
                criteriaBuilder.equal(subqueryRoot1.join("promotions"), promotion));

        Subquery<Product> subquery2 = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot2 = subquery2.from(Product.class);
        subquery2.select(subqueryRoot2);
        subquery2.where(criteriaBuilder.equal(subqueryRoot2, root),
                criteriaBuilder.equal(subqueryRoot2.join("productCategory").join("promotions"), promotion));

        Subquery<Product> subquery3 = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot3 = subquery3.from(Product.class);
        subquery3.select(subqueryRoot3);
        subquery3.where(criteriaBuilder.equal(subqueryRoot3, root),
                criteriaBuilder.equal(subqueryRoot3.join("brand").join("promotions"), promotion));

        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.exists(subquery1),
                criteriaBuilder.exists(subquery2), criteriaBuilder.exists(subquery3)));
    }
    if (tags != null && !tags.isEmpty()) {
        Subquery<Product> subquery = criteriaQuery.subquery(Product.class);
        Root<Product> subqueryRoot = subquery.from(Product.class);
        subquery.select(subqueryRoot);
        subquery.where(criteriaBuilder.equal(subqueryRoot, root), subqueryRoot.join("tags").in(tags));
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.exists(subquery));
    }
    if (attributeValue != null) {
        for (Entry<Attribute, String> entry : attributeValue.entrySet()) {
            String propertyName = Product.ATTRIBUTE_VALUE_PROPERTY_NAME_PREFIX
                    + entry.getKey().getPropertyIndex();
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.equal(root.get(propertyName), entry.getValue()));
        }
    }
    if (startPrice != null && endPrice != null && startPrice.compareTo(endPrice) > 0) {
        BigDecimal temp = startPrice;
        startPrice = endPrice;
        endPrice = temp;
    }
    if (startPrice != null && startPrice.compareTo(new BigDecimal(0)) >= 0) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.ge(root.<Number>get("price"), startPrice));
    }
    if (endPrice != null && endPrice.compareTo(new BigDecimal(0)) >= 0) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.le(root.<Number>get("price"), endPrice));
    }
    if (isMarketable != null) {
        restrictions = criteriaBuilder.and(restrictions,
                criteriaBuilder.equal(root.get("isMarketable"), isMarketable));
    }
    if (isList != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isList"), isList));
    }
    if (isTop != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isTop"), isTop));
    }
    if (isGift != null) {
        restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.equal(root.get("isGift"), isGift));
    }
    Path<Integer> stock = root.get("stock");
    Path<Integer> allocatedStock = root.get("allocatedStock");
    if (isOutOfStock != null) {
        if (isOutOfStock) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock),
                    criteriaBuilder.lessThanOrEqualTo(stock, allocatedStock));
        } else {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.or(criteriaBuilder.isNull(stock),
                    criteriaBuilder.greaterThan(stock, allocatedStock)));
        }
    }
    if (isStockAlert != null) {
        Setting setting = SettingUtils.get();
        if (isStockAlert) {
            restrictions = criteriaBuilder.and(restrictions, criteriaBuilder.isNotNull(stock),
                    criteriaBuilder.lessThanOrEqualTo(stock,
                            criteriaBuilder.sum(allocatedStock, setting.getStockAlertCount())));
        } else {
            restrictions = criteriaBuilder.and(restrictions,
                    criteriaBuilder.or(criteriaBuilder.isNull(stock), criteriaBuilder.greaterThan(stock,
                            criteriaBuilder.sum(allocatedStock, setting.getStockAlertCount()))));
        }
    }
    criteriaQuery.where(restrictions);
    if (orderType == OrderType.priceAsc) {
        orders.add(Order.asc("price"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.priceDesc) {
        orders.add(Order.desc("price"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.salesDesc) {
        orders.add(Order.desc("sales"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.scoreDesc) {
        orders.add(Order.desc("score"));
        orders.add(Order.desc("createDate"));
    } else if (orderType == OrderType.dateDesc) {
        orders.add(Order.desc("createDate"));
    } else {
        orders.add(Order.desc("isTop"));
        orders.add(Order.desc("modifyDate"));
    }
    return super.findList(criteriaQuery, null, count, filters, orders);
}

From source file:org.egov.dao.budget.BudgetDetailsHibernateDAO.java

/**
 * This API is handling the budget checking
 * /*  w ww .ja v a  2  s . c o  m*/
 * @param paramMap
 *            paramMap contains 1. debitAmt (mandatory) 2. creditAmt
 *            (mandatory) 3. deptid (optional) 4. functionid (optional) 5.
 *            functionaryid (optional) 6. schemeid (optional) 7. subschemeid
 *            (optional) 8. boundaryid (optional) 9. glcode (mandatory) -
 *            based on the glcode, we can get the budgetheadid 10. asondate
 *            (manadtory) - to get the actuals, we need asondate
 *            11.mis.budgetcheckreq-Boolean-(optional) set to false if
 *            budget check not to be done for this bill default is True.
 * @return @
 */
@Override
public boolean budgetaryCheckForBill(final Map<String, Object> paramMap) {
    String cashbasedbudgetType = EMPTY_STRING, txnType = EMPTY_STRING;
    BigDecimal debitAmt = null;
    BigDecimal creditAmt = null;
    BigDecimal txnAmt = null;
    String glCode = "";
    Date asondate = null;
    Date fromdate = null;
    try {
        String budgetCheckConfig = budgetCheckConfigService.getConfigValue();
        if (budgetCheckConfig.equals(BudgetControlType.BudgetCheckOption.NONE.toString())) {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("Application Level budget check disabled skipping budget check.");
            return true;
        }
        if (paramMap.get("mis.budgetcheckreq") != null
                && ((Boolean) paramMap.get("mis.budgetcheckreq")).equals(false)) {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("voucher Level budget check disabled  so skipping budget check.");
            return true;
        }
        if (paramMap.get("debitAmt") != null)
            debitAmt = (BigDecimal) paramMap.get("debitAmt");
        if (paramMap.get("creditAmt") != null)
            creditAmt = (BigDecimal) paramMap.get("creditAmt");

        if (debitAmt == null && creditAmt == null)
            throw new ValidationException(EMPTY_STRING, "Both Debit and Credit amount is null");

        if (debitAmt != null && debitAmt.compareTo(BigDecimal.ZERO) == 0 && creditAmt != null
                && creditAmt.compareTo(BigDecimal.ZERO) == 0)
            throw new ValidationException(EMPTY_STRING, "Both Debit and Credit amount is zero");

        if (debitAmt != null && debitAmt.compareTo(BigDecimal.ZERO) > 0 && creditAmt != null
                && creditAmt.compareTo(BigDecimal.ZERO) > 0)
            throw new ValidationException(EMPTY_STRING, "Both Debit and Credit amount is greater than zero");

        // get the type of budget from appconfig .
        List<AppConfigValues> list = appConfigValuesService.getConfigValuesByModuleAndKey(EGF,
                "budgetaryCheck_budgettype_cashbased");
        if (list.isEmpty())
            throw new ValidationException(EMPTY_STRING,
                    "budgetaryCheck_budgettype_cashbased is not defined in AppConfig");

        cashbasedbudgetType = list.get(0).getValue();
        if (cashbasedbudgetType.equalsIgnoreCase("Y")) // cash based budget
        {
            if (LOGGER.isDebugEnabled())
                LOGGER.debug("cashbasedbudgetType==" + cashbasedbudgetType);
        } else // Accural based budgeting
        {
            if (debitAmt != null && debitAmt.compareTo(BigDecimal.ZERO) > 0) {
                txnType = "debit";
                txnAmt = debitAmt;
            } else {
                txnType = "credit";
                txnAmt = creditAmt;
            }

            if (paramMap.get("glcode") != null)
                glCode = paramMap.get("glcode").toString();
            if (paramMap.get(Constants.ASONDATE) != null)
                asondate = (Date) paramMap.get(Constants.ASONDATE);

            if (glCode == null)
                throw new ValidationException(EMPTY_STRING, "glcode is null");
            if (txnAmt == null)
                throw new ValidationException(EMPTY_STRING, "txnAmt is null");
            if (txnType == null)
                throw new ValidationException(EMPTY_STRING, "txnType is null");
            if (asondate == null)
                throw new ValidationException(EMPTY_STRING, "As On Date is null");

            // check the account code needs budget checking
            final CChartOfAccounts coa = chartOfAccountsHibernateDAO.getCChartOfAccountsByGlCode(glCode);
            if (coa.getBudgetCheckReq() != null && coa.getBudgetCheckReq()) {
                // get budgethead for the glcode
                final List<BudgetGroup> budgetHeadListByGlcode = getBudgetHeadByGlcode(coa);

                if (!isBudgetCheckingRequiredForType(txnType,
                        budgetHeadListByGlcode.get(0).getBudgetingType().toString())) {
                    if (LOGGER.isDebugEnabled())
                        LOGGER.debug("No need to check budget for :" + glCode + " as the transaction type is "
                                + txnType + "so skipping budget check");
                    return true;
                }

                // get the financialyear from asondate
                final CFinancialYear finyear = financialYearHibDAO.getFinancialYearByDate(asondate);
                final SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy", Constants.LOCALE);
                if (finyear == null)
                    throw new ValidationException(EMPTY_STRING,
                            "Financial year is not defined for this date [" + sdf.format(asondate) + "]");
                fromdate = finyear.getStartingDate();

                paramMap.put("financialyearid", Long.valueOf(finyear.getId()));
                paramMap.put(BUDGETHEADID, budgetHeadListByGlcode);
                paramMap.put("fromdate", fromdate);
                paramMap.put(Constants.ASONDATE, finyear.getEndingDate());

                paramMap.put(GLCODEID, coa.getId());
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("************ BudgetCheck Details For bill *********************");
                final BigDecimal budgetedAmt = getBudgetedAmtForYear(paramMap); // get
                // the
                // budgetedamount

                if (LOGGER.isDebugEnabled())
                    LOGGER.debug(".................Budgeted amount......................" + budgetedAmt);
                if (budgetCheckConfigService.getConfigValue()
                        .equalsIgnoreCase(BudgetControlType.BudgetCheckOption.MANDATORY.toString()))
                    if (budgetedAmt.compareTo(BigDecimal.ZERO) == 0) {
                        if (LOGGER.isDebugEnabled())
                            LOGGER.debug(
                                    "Budget check failed Because of  Budgeted not allocated for the combination");
                        return false;
                    }

                final BigDecimal actualAmt = getActualBudgetUtilizedForBudgetaryCheck(paramMap); // get
                // actual
                // amount
                // only
                // Generalledger
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("..................Voucher Actual amount......................." + actualAmt);

                BigDecimal billAmt = getBillAmountForBudgetCheck(paramMap); // get
                // actual
                // amount
                // of
                // Bill
                EgBillregister bill = null;

                if (paramMap.get("bill") != null)
                    bill = (EgBillregister) paramMap.get("bill");
                if (bill != null && bill.getEgBillregistermis().getBudgetaryAppnumber() != null) {
                    if (LOGGER.isDebugEnabled())
                        LOGGER.debug(".............Found BillId so subtracting txn amount......................"
                                + txnAmt);
                    billAmt = billAmt.subtract(txnAmt);
                }

                if (LOGGER.isDebugEnabled())
                    LOGGER.debug(
                            "........................Bill Actual amount ........................" + billAmt);

                final BigDecimal diff = budgetedAmt.subtract(actualAmt).subtract(billAmt); // get
                // diff
                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("......................diff amount......................" + diff);
                }
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("************ BudgetCheck Details For bill End *********************");

                if (budgetCheckConfigService.getConfigValue()
                        .equalsIgnoreCase(BudgetControlType.BudgetCheckOption.MANDATORY.toString())) {
                    if (txnAmt.compareTo(diff) <= 0) {
                        if (paramMap.get("bill") != null)
                            getAppNumberForBill(paramMap);
                        return true;
                    } else
                        return false;
                }
                if (budgetCheckConfigService.getConfigValue()
                        .equalsIgnoreCase(BudgetControlType.BudgetCheckOption.ANTICIPATORY.toString())) {
                    getAppNumberForBill(paramMap);
                    return true;
                }

            } else
                return true;

        }
    } catch (final ValidationException v) {
        LOGGER.error("Exp in budgetary check API()=" + v.getErrors());
        throw v;
    } catch (final Exception e) {
        LOGGER.error("Exp in budgetary check API()=" + e.getMessage());
        throw e;
    }
    return true;
}