Example usage for java.math BigDecimal add

List of usage examples for java.math BigDecimal add

Introduction

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

Prototype

public BigDecimal add(BigDecimal augend) 

Source Link

Document

Returns a BigDecimal whose value is (this + augend) , and whose scale is max(this.scale(), augend.scale()) .

Usage

From source file:com.gst.portfolio.loanaccount.service.LoanWritePlatformServiceJpaRepositoryImpl.java

private CommandProcessingResult processLoanDisbursementDetail(final Loan loan, Long loanId, JsonCommand command,
        LoanDisbursementDetails loanDisbursementDetails) {
    final List<Long> existingTransactionIds = new ArrayList<>();
    final List<Long> existingReversedTransactionIds = new ArrayList<>();
    existingTransactionIds.addAll(loan.findExistingTransactionIds());
    existingReversedTransactionIds.addAll(loan.findExistingReversedTransactionIds());
    final Map<String, Object> changes = new LinkedHashMap<>();
    LocalDate recalculateFrom = null;
    ScheduleGeneratorDTO scheduleGeneratorDTO = this.loanUtilService.buildScheduleGeneratorDTO(loan,
            recalculateFrom);/*  w  w w  . j a  va  2 s . com*/

    ChangedTransactionDetail changedTransactionDetail = null;
    AppUser currentUser = getAppUserIfPresent();

    if (command.entityId() != null) {

        changedTransactionDetail = loan.updateDisbursementDateAndAmountForTranche(loanDisbursementDetails,
                command, changes, scheduleGeneratorDTO, currentUser);
    } else {
        // BigDecimal setAmount = loan.getApprovedPrincipal();
        Collection<LoanDisbursementDetails> loanDisburseDetails = loan.getDisbursementDetails();
        BigDecimal setAmount = BigDecimal.ZERO;
        for (LoanDisbursementDetails details : loanDisburseDetails) {
            if (details.actualDisbursementDate() != null) {
                setAmount = setAmount.add(details.principal());
            }
        }

        loan.repaymentScheduleDetail().setPrincipal(setAmount);

        if (loan.repaymentScheduleDetail().isInterestRecalculationEnabled()) {
            loan.regenerateRepaymentScheduleWithInterestRecalculation(scheduleGeneratorDTO, currentUser);
        } else {
            loan.regenerateRepaymentSchedule(scheduleGeneratorDTO, currentUser);
            loan.processPostDisbursementTransactions();
        }
    }

    saveAndFlushLoanWithDataIntegrityViolationChecks(loan);

    if (command.entityId() != null && changedTransactionDetail != null) {
        for (Map.Entry<Long, LoanTransaction> mapEntry : changedTransactionDetail.getNewTransactionMappings()
                .entrySet()) {
            updateLoanTransaction(mapEntry.getKey(), mapEntry.getValue());
        }
    }
    if (loan.repaymentScheduleDetail().isInterestRecalculationEnabled()) {
        createLoanScheduleArchive(loan, scheduleGeneratorDTO);
    }
    postJournalEntries(loan, existingTransactionIds, existingReversedTransactionIds);
    this.loanAccountDomainService.recalculateAccruals(loan);
    return new CommandProcessingResultBuilder() //
            .withOfficeId(loan.getOfficeId()) //
            .withClientId(loan.getClientId()) //
            .withGroupId(loan.getGroupId()) //
            .withLoanId(loanId) //
            .with(changes).build();
}

From source file:com.gst.portfolio.loanaccount.service.LoanWritePlatformServiceJpaRepositoryImpl.java

private void validateForAddAndDeleteTranche(final Loan loan) {

    BigDecimal totalDisbursedAmount = BigDecimal.ZERO;
    Collection<LoanDisbursementDetails> loanDisburseDetails = loan.getDisbursementDetails();
    for (LoanDisbursementDetails disbursementDetails : loanDisburseDetails) {
        if (disbursementDetails.actualDisbursementDate() != null) {
            totalDisbursedAmount = totalDisbursedAmount.add(disbursementDetails.principal());
        }//from   www  . j av  a  2  s  .  c o  m
    }
    if (totalDisbursedAmount.compareTo(loan.getApprovedPrincipal()) == 0) {
        final String errorMessage = "loan.disbursement.cannot.be.a.edited";
        throw new LoanMultiDisbursementException(errorMessage);
    }
}

From source file:nl.strohalm.cyclos.services.transactions.PaymentServiceImpl.java

@Override
public StatisticalResultDTO getSimulateConversionGraph(final ConversionSimulationDTO input) {
    final LocalSettings localSettings = settingsService.getLocalSettings();
    final byte precision = (byte) localSettings.getPrecision().getValue();

    // get series
    final TransactionFeePreviewForRatesDTO temp = simulateConversion(input);
    final int series = temp.getFees().size();
    // get range of points, but without values for A < 0
    BigDecimal initialARate = null;
    RatesResultDTO rates = new RatesResultDTO();
    if (input.isUseActualRates()) {
        rates = rateService.getRatesForTransferFrom(input.getAccount(), input.getAmount(), null);
        rates.setDate(input.getDate());//www . ja v  a  2 s  .c  o m
        initialARate = rates.getaRate();
    } else {
        initialARate = input.getArate();
    }

    // lowerlimit takes care that values for A < 0 are left out of the graph
    final Double lowerLimit = (initialARate == null) ? null : initialARate.negate().doubleValue();
    final Number[] xRange = GraphHelper.getOptimalRangeAround(0, 33, 0, 0.8, lowerLimit);

    // Data structure to build the table
    final Number[][] tableCells = new Number[xRange.length][series];
    // initialize series names and x labels
    final String[] seriesNames = new String[series];
    final byte[] seriesOrder = new byte[series];
    final Calendar[] xPointDates = new Calendar[xRange.length];
    final Calendar now = Calendar.getInstance();
    BigDecimal inputARate = temp.getARate();
    BigDecimal inputDRate = temp.getDRate();
    // assign data
    for (int i = 0; i < xRange.length; i++) {
        final ConversionSimulationDTO inputPointX = (ConversionSimulationDTO) input.clone();
        final Calendar date = (Calendar) ((input.isUseActualRates()) ? input.getDate().clone() : now.clone());
        date.add(Calendar.DAY_OF_YEAR, xRange[i].intValue());
        xPointDates[i] = date;
        // Set useActualRates for this input to false, otherwise simulateConversion will use the account's the balance and rates of that date, and
        // we don't want that.
        inputPointX.setUseActualRates(false);
        if (inputARate != null) {
            final BigDecimal aRate = inputARate.add(new BigDecimal(xRange[i].doubleValue()));
            inputPointX.setArate(aRate);
        }
        if (inputDRate != null) {
            final BigDecimal dRate = inputDRate.subtract(new BigDecimal(xRange[i].doubleValue()));
            inputPointX.setDrate(dRate);
        }

        final TransactionFeePreviewDTO tempResult = simulateConversion(inputPointX);
        int j = 0;
        for (final TransactionFee fee : tempResult.getFees().keySet()) {
            tableCells[i][j] = new StatisticalNumber(tempResult.getFees().get(fee).doubleValue(), precision);
            byte index;
            switch (fee.getChargeType()) {
            case D_RATE:
                index = 2;
                break;
            case A_RATE:
            case MIXED_A_D_RATES:
                index = 3;
                break;
            default:
                index = 1;
                break;
            }
            seriesOrder[j] = index;
            seriesNames[j++] = fee.getName();
        }
    }

    // create the graph object
    final StatisticalResultDTO result = new StatisticalResultDTO(tableCells);
    result.setBaseKey("conversionSimulation.result.graph");
    result.setHelpFile("account_management");
    // date labels along x-axis
    final String[] rowKeys = new String[xRange.length];
    Arrays.fill(rowKeys, "");
    result.setRowKeys(rowKeys);
    for (int i = 0; i < rowKeys.length; i++) {
        final String rowHeader = localSettings.getDateConverterForGraphs().toString(xPointDates[i]);
        result.setRowHeader(rowHeader, i);
    }
    // mark the actual date upon which the x-axis is based as a vertical line
    final Calendar baseDate = (input.isUseActualRates()) ? (Calendar) input.getDate().clone() : now;
    final String baseDateString = localSettings.getDateConverterForGraphs().toString(baseDate);
    final Marker[] markers = new Marker[1];
    markers[0] = new CategoryMarker(baseDateString);
    markers[0].setPaint(Color.ORANGE);
    final String todayString = localSettings.getDateConverterForGraphs().toString(now);
    if (todayString.equals(baseDateString)) {
        markers[0].setLabel("global.today");
    }
    result.setDomainMarkers(markers);

    // Series labels indicate fee names
    final String[] columnKeys = new String[series];
    Arrays.fill(columnKeys, "");
    result.setColumnKeys(columnKeys);
    for (int j = 0; j < columnKeys.length; j++) {
        result.setColumnHeader(seriesNames[j], j);
    }

    // order the series
    result.orderSeries(seriesOrder);

    final TransferType tt = fetchService.fetch(input.getTransferType(),
            RelationshipHelper.nested(TransferType.Relationships.FROM, AccountType.Relationships.CURRENCY));
    result.setYAxisUnits(tt.getCurrency().getSymbol());
    result.setShowTable(false);
    result.setGraphType(StatisticalResultDTO.GraphType.STACKED_AREA);
    return result;
}

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

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

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

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

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

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

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

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

                }

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

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

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

            if (!objectList.isEmpty()) {

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

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

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

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

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

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

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

        }

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

From source file:com.ah.be.parameter.BeParaModuleDefImpl.java

private void changeOsVersionFile() {
    String fingerprints = ImportTextFileAction.OS_VERSION_FILE_PATH + ImportTextFileAction.OS_VERSION_FILE_NAME;
    String fingerprintsChg = ImportTextFileAction.OS_VERSION_FILE_PATH
            + ImportTextFileAction.OS_VERSION_FILE_NAME_CHG;
    FileWriter fWriter = null;//from w w  w .j a v  a  2 s. com
    try {
        if (new File(fingerprints).exists() && new File(fingerprintsChg).exists()) {
            List<String> lines = NmsUtil.readFileByLines(fingerprints);
            List<String> replaceOsName = new ArrayList<>();
            List<String> replaceOption55 = new ArrayList<>();
            String preHmVer = NmsUtil.getHiveOSVersion(NmsUtil
                    .getVersionInfo(BeAdminCentOSTools.ahBackupdir + File.separatorChar + "hivemanager.ver"));

            // parse os_dhcp_fingerprints_changes.xml
            SAXReader reader = new SAXReader();
            Document document = reader.read(new File(fingerprintsChg));
            Element root = document.getRootElement();
            List<?> fingerprintElems = root.elements();
            for (Object obj : fingerprintElems) {
                Element fingerprintElem = (Element) obj;
                String osName = fingerprintElem.attributeValue("osname");
                for (Iterator<?> iterator = fingerprintElem.elementIterator(); iterator.hasNext();) {
                    Element option55Elem = (Element) iterator.next();
                    String node_option55_text = option55Elem.getText();
                    Attribute version = option55Elem.attribute("version");
                    String version_text = version.getText();
                    if (NmsUtil.compareSoftwareVersion(preHmVer, version_text) <= 0) {
                        if (!replaceOption55.contains(node_option55_text)) {
                            replaceOsName.add(osName);
                            replaceOption55.add(node_option55_text);
                        }
                    }
                }
            }

            if (replaceOption55.isEmpty()) {
                log.debug("No need to modify os_dhcp_fingerprints.txt.");
                FileUtils.deleteQuietly(new File(fingerprintsChg));
                return;
            }

            for (String option55 : replaceOption55) {
                int size = lines.size();
                boolean remove = false;
                for (int i = size - 1; i >= 0; i--) {
                    if (remove) {
                        lines.remove(i);
                        remove = false;
                    } else {
                        if (option55.equals(lines.get(i))) {
                            if (i < size - 1 && i > 0
                                    && lines.get(i - 1).startsWith(ImportTextFileAction.OS_STR)
                                    && lines.get(i + 1).equals(ImportTextFileAction.END_STR)) {
                                lines.remove(i + 1);
                                lines.remove(i);
                                remove = true;
                            } else {
                                lines.remove(i);
                            }
                        }
                    }
                }
            }

            //insert
            for (int i = 0; i < replaceOption55.size(); i++) {
                String option55 = replaceOption55.get(i);
                String osName = ImportTextFileAction.OS_STR + replaceOsName.get(i);

                if (!lines.contains(option55)) {
                    if (lines.contains(osName)) {
                        List<String> temp = lines.subList(lines.indexOf(osName), lines.size());
                        int index = lines.indexOf(osName) + temp.indexOf(ImportTextFileAction.END_STR);
                        lines.add(index, option55);

                    } else {
                        lines.add(osName);
                        lines.add(option55);
                        lines.add(ImportTextFileAction.END_STR);
                    }
                }
            }

            fWriter = new FileWriter(fingerprints, false);
            for (String line : lines) {
                if (line != null && line.startsWith(ImportTextFileAction.VERSION_STR)) {
                    String version = line.substring(line.indexOf(ImportTextFileAction.VERSION_STR)
                            + ImportTextFileAction.VERSION_STR.length());
                    BigDecimal b1 = new BigDecimal(version);
                    BigDecimal b2 = new BigDecimal("0.1");
                    float fVer = b1.add(b2).floatValue();
                    String versionStr = ImportTextFileAction.VERSION_STR + String.valueOf(fVer) + "\r\n";
                    fWriter.write(versionStr);
                } else {
                    fWriter.write(line + "\r\n");
                }
            }
            fWriter.close();

            //compress file
            String strCmd = "";
            StringBuffer strCmdBuf = new StringBuffer();
            strCmdBuf.append("tar zcvf ");
            strCmdBuf.append(
                    ImportTextFileAction.OS_VERSION_FILE_PATH + ImportTextFileAction.OS_VERSION_FILE_NAME_TAR);
            strCmdBuf.append(" -C ");
            strCmdBuf.append(ImportTextFileAction.OS_VERSION_FILE_PATH);
            strCmdBuf.append(" " + ImportTextFileAction.OS_VERSION_FILE_NAME);
            strCmd = strCmdBuf.toString();
            boolean compressResult = BeAdminCentOSTools.exeSysCmd(strCmd);
            if (!compressResult) {
                log.error("compress os_dhcp_fingerprints.txt error.");
                return;
            }

            FileUtils.deleteQuietly(new File(fingerprintsChg));
        } else {
            if (new File(fingerprintsChg).exists()) {
                FileUtils.deleteQuietly(new File(fingerprintsChg));
            }
        }
    } catch (Exception e) {
        setDebugMessage("change OsVersionFile error: ", e);
    } finally {
        if (fWriter != null) {
            try {
                fWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

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

/**
 * @param empcntClientProjectDataList//from w w  w  .ja va 2s .  c  o  m
 * @param empClientProjectTeamStructList
 * @param employee
 * @param month
 * @param year
 * @param costCentre
 * @param countType
 * @param allignedTimeZero
 * @param assistedTimeZero
 * @param apportionedTimeZero
 * @param allignedTimeOne
 * @param totalTimeOne
 * @return
 */

private void getMultipleProjectDetail(List<EmpcntClientProjectData> empOpenCntClientProjectDataList,
        List<EmpcntClientProjectData> empCloseCntClientProjectDataList,
        List<EmpClientProjectTeamStruct> empClientProjectTeamStructList, EmployeeMaster employee,
        TabMonth month, TabYear year, CostCentre costCentre, CountClassification countType,
        BigDecimal allignedTimeZero, BigDecimal assistedTimeZero, BigDecimal apportionedTimeZero,
        BigDecimal allignedTimeOne, BigDecimal totalTimeOne, Integer countTypeId,
        Map<String, EmployeePcTagsTeamStruct> employeePcTagsTeamStructMap) {

    logger.debug("<====getMultipleProjectDetail START====>");
    Integer employeeId = employee.getEmployeeId();
    Integer yearId = year.getYearId();
    Integer monthId = month.getMonthId();
    String costCentreId = costCentre.getCostCentreId();
    BigDecimal deviderHour = new BigDecimal(Constants.TOTAL_WORKING_HOURS);
    logger.debug("getMultipleProjectDetail parameter===>" + employeeId + "::" + yearId + "::" + monthId + "::"
            + costCentreId + "::" + deviderHour);

    // Get project details
    Map<Integer, EmpClientProjectTeamStruct> employeeProjectIds = new HashMap<Integer, EmpClientProjectTeamStruct>();

    Map<Integer, EmpClientProjectTeamStruct> validEmployeeProjectIds = new HashMap<Integer, EmpClientProjectTeamStruct>();

    for (EmpClientProjectTeamStruct empClientProjectTeamStructThree : empClientProjectTeamStructList) {
        employeeProjectIds.put(empClientProjectTeamStructThree.getProjectMaster().getProjectId(),
                empClientProjectTeamStructThree);
    }

    validEmployeeProjectIds.putAll(employeeProjectIds);
    // logger.debug("validEmployeeProjectIds 1:size===>" +
    // validEmployeeProjectIds.size());

    // check in revenue table
    for (Integer key : employeeProjectIds.keySet()) {
        EmpClientProjectTeamStruct mapValues = employeeProjectIds.get(key);
        List<CollageProjectRevenue> listValues = collageProjectRevenueDao
                .findByYearIdMonthIdProjectIdCostCentreId(mapValues.getTabYear().getYearId(),
                        mapValues.getTabMonth().getMonthId(), mapValues.getProjectMaster().getProjectId(),
                        costCentre.getCostCentreId());
        if (listValues.isEmpty()) {
            validEmployeeProjectIds.remove(key);
        }
    }
    // logger.debug("validEmployeeProjectIds 2:size===>" +
    // validEmployeeProjectIds.size());
    // For all invalid projects calculate count zero
    if (validEmployeeProjectIds.isEmpty()) {
        getZeroProjectsDetail(yearId, monthId, costCentreId, empOpenCntClientProjectDataList,
                empCloseCntClientProjectDataList, employee, month, year, costCentre, countType,
                allignedTimeZero, assistedTimeZero, totalTimeOne, totalTimeOne, countTypeId,
                employeePcTagsTeamStructMap);
    }
    // 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 List is empty
    if (projectIdList.isEmpty()) {
        // logger.debug("Contain InValid projects (: Find by Revenue)===>");

        Map<Integer, BigDecimal> projectRevenueMap = new HashMap<Integer, BigDecimal>();
        BigDecimal sumOfRevenue = BigDecimal.ZERO;

        List<Object[]> collageProjectRevenueList = collageProjectRevenueDao.findByCostCentreIdYearIdMonthId(
                costCentre.getCostCentreId(), year.getYearId(), month.getMonthId());

        for (Object[] collageProjectRevenue : collageProjectRevenueList) {
            Integer projectId = (Integer) collageProjectRevenue[0];
            BigDecimal revenue = (BigDecimal) collageProjectRevenue[1];
            projectRevenueMap.put(projectId, revenue);
        }
        // logger.debug("projectRevenueMap size===>" +
        // projectRevenueMap.size());

        for (Integer key : projectRevenueMap.keySet()) {
            sumOfRevenue = sumOfRevenue.add(projectRevenueMap.get(key));
        }
        logger.debug("sumOfRevenue===>" + sumOfRevenue);

        for (Integer projectId : validEmployeeProjectIds.keySet()) {
            EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId);
            BigDecimal revenue = projectRevenueMap.get(projectId);
            logger.debug("revenue===>" + revenue);
            BigDecimal projectRevenueCount = revenue.divide(sumOfRevenue, 2, RoundingMode.HALF_EVEN);
            projectRevenueCount = projectRevenueCount.setScale(2, RoundingMode.CEILING);
            // logger.debug("685 empOpenCntClientProjectData ProjectId:Revenue===>"+projectId+" : "
            // + projectRevenueCount);
            EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                    mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year,
                    costCentre, projectRevenueCount, BigDecimal.ZERO, BigDecimal.ZERO, projectRevenueCount);
            if (countTypeId == 1) {
                empOpenCntClientProjectDataList.add(empcntClientProjectData);
            }
            if (countTypeId == 2) {
                empCloseCntClientProjectDataList.add(empcntClientProjectData);
            }
        }
    } else {
        // logger.debug("Else Contain Valid projects===>");
        Integer validEmployeeProjectCount = validEmployeeProjectIds.size();
        // 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);
            }

        }
        Integer validAllProjectCount = validAllProjects.size();
        // 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> assignedProjects = new HashMap<Integer, BigDecimal>();
        Map<Integer, BigDecimal> unAssignedProjects = new HashMap<Integer, BigDecimal>();
        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 (validEmployeeProjectIds.containsKey(projectId) && validAllProjects.contains(projectId)) {
                // logger.debug("UnAssignedProjects===>" +
                // projectId+"::"+hour+"::"+companyId);
                assignedProjects.put(projectId, hour);
            }
            if (!validEmployeeProjectIds.containsKey(projectId) && validAllProjects.contains(projectId)) {
                // logger.debug("assignedProjects===>" +
                // projectId+"::"+hour+"::"+companyId);
                unAssignedProjects.put(projectId, hour);
            }
        }

        if (validEmployeeProjectCount == validAllProjectCount
                && validAllProjects.containsAll(validEmployeeProjectIds.keySet())
                && unAssignedProjects.isEmpty()) {

            // logger.debug("validEmployeeProjectCount==validAllProjectCount :(Only in assigned projects)");
            for (Integer key : assignedProjects.keySet()) {
                // Get time spent on each project by employee id
                Integer projectId = key;
                BigDecimal timeByProject = assignedProjects.get(key);
                EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId);
                // logger.debug("744 : Worked hours (Only in assigned projects) 1===>"+timeByProject+
                // " : "+toatlTime);
                BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN);
                workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                // logger.debug("745: Worked hours (Only in assigned projects) 2===>"+workedHours);
                EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                        mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year,
                        costCentre, workedHours, assistedTimeZero, apportionedTimeZero, workedHours);
                if (countTypeId == 1) {
                    empOpenCntClientProjectDataList.add(empcntClientProjectData);
                }
                if (countTypeId == 2) {
                    empCloseCntClientProjectDataList.add(empcntClientProjectData);
                }
            }

        } else if (!assignedProjects.isEmpty() && !unAssignedProjects.isEmpty()) {
            // 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 : assignedProjects.keySet()) {
                    // Get time spent on each project by employee id
                    Integer projectId = key;
                    BigDecimal timeByProject = assignedProjects.get(key);
                    EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId);
                    BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN);
                    workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                    // logger.debug("768: Aligned hours (Both in assigned and unassigned projects) 1===>"+workedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year,
                            costCentre, workedHours, assistedTimeZero, apportionedTimeZero, workedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
                for (Integer key : unAssignedProjects.keySet()) {
                    // Get time spent on each project by employee id
                    Integer projectId = key;
                    BigDecimal timeByProject = unAssignedProjects.get(key);
                    List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId);
                    ProjectMaster projectMaster = projectList.get(0);
                    CompanyMaster companyMaster = projectMaster.getCompanyMaster();
                    BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN);
                    workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                    // logger.debug("787: Assisted hours (Both in assigned and unassigned projects) 2===>"+workedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            companyMaster, countType, month, projectMaster, year, costCentre,
                            apportionedTimeZero, workedHours, apportionedTimeZero, workedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
            } else {
                // logger.debug("Worked hours===> <168");
                BigDecimal totalUnAssingnedHours = BigDecimal.ZERO;
                BigDecimal assingnedHours = BigDecimal.ZERO;
                for (Integer key : unAssignedProjects.keySet()) {
                    // Get time spent on each project by employee id
                    Integer projectId = key;
                    // logger.debug("Project Id===>"+key);
                    BigDecimal timeByProject = unAssignedProjects.get(key);
                    BigDecimal workedHours = timeByProject.divide(deviderHour, 2, RoundingMode.HALF_EVEN);
                    workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                    totalUnAssingnedHours = totalUnAssingnedHours.add(workedHours);
                    // Assign to assisted count for unAssignedProjects
                    List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId);
                    ProjectMaster projectMaster = projectList.get(0);
                    CompanyMaster companyMaster = projectMaster.getCompanyMaster();
                    // logger.debug("811: Assisted hours (Both in assigned and unassigned projects) 2===>"+workedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            companyMaster, countType, month, projectMaster, year, costCentre,
                            apportionedTimeZero, workedHours, apportionedTimeZero, workedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
                totalUnAssingnedHours = BigDecimal.ONE.subtract(totalUnAssingnedHours);
                // logger.debug("totalUnAssingnedHours===> "+totalUnAssingnedHours);
                for (Map.Entry<Integer, BigDecimal> entry : assignedProjects.entrySet()) {
                    assingnedHours = assingnedHours.add(entry.getValue());
                }
                // logger.debug("Aligned Hours===> "+assingnedHours);
                for (Integer key : assignedProjects.keySet()) {
                    Integer projectId = key;
                    BigDecimal timeByProject = assignedProjects.get(key);
                    // logger.debug("831 :projectId : timeByProject===> "+projectId+" : "+timeByProject);
                    EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId);
                    BigDecimal averageWorkedHours = timeByProject.divide(assingnedHours, 2,
                            RoundingMode.HALF_EVEN);
                    // logger.debug("834 :averageWorkedHours : assingnedHours===> "+averageWorkedHours+" : "+assingnedHours);
                    BigDecimal actualWorkedHours = averageWorkedHours.multiply(totalUnAssingnedHours);
                    actualWorkedHours = actualWorkedHours.setScale(2, RoundingMode.CEILING);
                    // logger.debug("836: actualWorkedHours : totalUnAssingnedHours 2===>"+actualWorkedHours+" : "+totalUnAssingnedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year,
                            costCentre, actualWorkedHours, assistedTimeZero, apportionedTimeZero,
                            actualWorkedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
            }
        } else if (assignedProjects.isEmpty() && !unAssignedProjects.isEmpty()) {
            // logger.debug("Only in unassigned projects===>");
            if (toatlTime.compareTo(new BigDecimal(Constants.TOTAL_WORKING_HOURS)) >= 0) {
                // logger.debug(" unassigned projects Worked hours===> >=168");
                for (Integer key : unAssignedProjects.keySet()) {
                    // Get time spent on each project by employee id
                    Integer projectId = key;
                    BigDecimal timeByProject = unAssignedProjects.get(key);
                    List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId);
                    ProjectMaster projectMaster = projectList.get(0);
                    CompanyMaster companyMaster = projectMaster.getCompanyMaster();
                    BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN);
                    workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                    // logger.debug("860: Assisted hours (Both in assigned and unassigned projects) 2===>"+workedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            companyMaster, countType, month, projectMaster, year, costCentre,
                            apportionedTimeZero, workedHours, apportionedTimeZero, workedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
            } else {
                // logger.debug("unassigned projects Worked hours===> <168");
                BigDecimal totalUnAssingnedHours = BigDecimal.ZERO;
                BigDecimal assingnedHours = BigDecimal.ZERO;
                for (Integer key : unAssignedProjects.keySet()) {
                    // Get time spent on each project by employee id
                    Integer projectId = key;
                    BigDecimal timeByProject = unAssignedProjects.get(key);
                    BigDecimal workedHours = timeByProject.divide(deviderHour, 2, RoundingMode.HALF_EVEN);
                    workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                    totalUnAssingnedHours = totalUnAssingnedHours.add(workedHours);
                    // Assign to assisted count for unAssignedProjects
                    List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId);
                    ProjectMaster projectMaster = projectList.get(0);
                    CompanyMaster companyMaster = projectMaster.getCompanyMaster();
                    // logger.debug("884: Assisted hours in unassigned projects) 2===>"+workedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            companyMaster, countType, month, projectMaster, year, costCentre,
                            apportionedTimeZero, workedHours, apportionedTimeZero, workedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
                // logger.debug("totalUnAssingnedHours===> "+totalUnAssingnedHours);
                if (totalUnAssingnedHours.compareTo(BigDecimal.ONE) == -1) {
                    BigDecimal remainProportion = BigDecimal.ONE.subtract(totalUnAssingnedHours);
                    getRevenueCountProportion(empOpenCntClientProjectDataList, empCloseCntClientProjectDataList,
                            employee, month, year, costCentre, countType, remainProportion, unAssignedProjects,
                            countTypeId, employeePcTagsTeamStructMap);
                }
            }
        }

    }
    // logger.debug("<====getMultipleProjectDetail END====>");
}

From source file:com.gst.portfolio.loanaccount.serialization.LoanApplicationCommandFromApiJsonHelper.java

public void validateLoanMultiDisbursementdate(final JsonElement element,
        final DataValidatorBuilder baseDataValidator, LocalDate expectedDisbursement,
        BigDecimal totalPrincipal) {

    this.validateDisbursementsAreDatewiseOrdered(element, baseDataValidator);

    final JsonObject topLevelJsonElement = element.getAsJsonObject();
    final Locale locale = this.fromApiJsonHelper.extractLocaleParameter(topLevelJsonElement);
    final String dateFormat = this.fromApiJsonHelper.extractDateFormatParameter(topLevelJsonElement);
    if (this.fromApiJsonHelper.parameterExists(LoanApiConstants.disbursementDataParameterName, element)
            && expectedDisbursement != null && totalPrincipal != null) {
        BigDecimal tatalDisbursement = BigDecimal.ZERO;
        boolean isFirstinstallmentOnExpectedDisbursementDate = false;
        final JsonArray variationArray = this.fromApiJsonHelper
                .extractJsonArrayNamed(LoanApiConstants.disbursementDataParameterName, element);
        List<LocalDate> expectedDisbursementDates = new ArrayList<>();
        if (variationArray != null && variationArray.size() > 0) {
            int i = 0;
            do {/*from  w w w . j a  va  2s .c o m*/
                final JsonObject jsonObject = variationArray.get(i).getAsJsonObject();
                if (jsonObject.has(LoanApiConstants.disbursementDateParameterName)
                        && jsonObject.has(LoanApiConstants.disbursementPrincipalParameterName)) {
                    LocalDate expectedDisbursementDate = this.fromApiJsonHelper.extractLocalDateNamed(
                            LoanApiConstants.disbursementDateParameterName, jsonObject, dateFormat, locale);
                    if (expectedDisbursementDates.contains(expectedDisbursementDate)) {
                        baseDataValidator.reset().parameter(LoanApiConstants.disbursementDateParameterName)
                                .failWithCode(LoanApiConstants.DISBURSEMENT_DATE_UNIQUE_ERROR);
                    }
                    if (expectedDisbursementDate.isBefore(expectedDisbursement)) {
                        baseDataValidator.reset().parameter(LoanApiConstants.disbursementDataParameterName)
                                .failWithCode(LoanApiConstants.DISBURSEMENT_DATE_BEFORE_ERROR);
                    }
                    expectedDisbursementDates.add(expectedDisbursementDate);

                    BigDecimal principal = this.fromApiJsonHelper.extractBigDecimalNamed(
                            LoanApiConstants.disbursementPrincipalParameterName, jsonObject, locale);
                    baseDataValidator.reset().parameter(LoanApiConstants.disbursementDataParameterName)
                            .parameterAtIndexArray(LoanApiConstants.disbursementPrincipalParameterName, i)
                            .value(principal).notBlank();
                    if (principal != null) {
                        tatalDisbursement = tatalDisbursement.add(principal);
                    }

                    baseDataValidator.reset().parameter(LoanApiConstants.disbursementDataParameterName)
                            .parameterAtIndexArray(LoanApiConstants.disbursementDateParameterName, i)
                            .value(expectedDisbursementDate).notNull();

                    if (expectedDisbursement.equals(expectedDisbursementDate)) {
                        isFirstinstallmentOnExpectedDisbursementDate = true;
                    }

                }
                i++;
            } while (i < variationArray.size());
            if (!isFirstinstallmentOnExpectedDisbursementDate) {
                baseDataValidator.reset().parameter(LoanApiConstants.disbursementDateParameterName)
                        .failWithCode(LoanApiConstants.DISBURSEMENT_DATE_START_WITH_ERROR);
            }

            if (tatalDisbursement.compareTo(totalPrincipal) == 1) {
                baseDataValidator.reset().parameter(LoanApiConstants.disbursementPrincipalParameterName)
                        .failWithCode(LoanApiConstants.APPROVED_AMOUNT_IS_LESS_THAN_SUM_OF_TRANCHES);
            }
            final String interestTypeParameterName = "interestType";
            final Integer interestType = this.fromApiJsonHelper
                    .extractIntegerSansLocaleNamed(interestTypeParameterName, element);
            baseDataValidator.reset().parameter(interestTypeParameterName).value(interestType).ignoreIfNull()
                    .integerSameAsNumber(InterestMethod.DECLINING_BALANCE.getValue());

        }

    }

}

From source file:ca.uhn.fhir.jpa.dao.BaseFhirResourceDao.java

private Set<Long> addPredicateQuantity(String theParamName, Set<Long> thePids,
        List<? extends IQueryParameterType> theList) {
    if (theList == null || theList.isEmpty()) {
        return thePids;
    }/* ww w.java  2 s  .  co  m*/

    CriteriaBuilder builder = myEntityManager.getCriteriaBuilder();
    CriteriaQuery<Long> cq = builder.createQuery(Long.class);
    Root<ResourceIndexedSearchParamQuantity> from = cq.from(ResourceIndexedSearchParamQuantity.class);
    cq.select(from.get("myResourcePid").as(Long.class));

    List<Predicate> codePredicates = new ArrayList<Predicate>();
    for (IQueryParameterType nextOr : theList) {
        IQueryParameterType params = nextOr;

        String systemValue;
        String unitsValue;
        QuantityCompararatorEnum cmpValue;
        BigDecimal valueValue;
        boolean approx = false;

        if (params instanceof BaseQuantityDt) {
            BaseQuantityDt param = (BaseQuantityDt) params;
            systemValue = param.getSystemElement().getValueAsString();
            unitsValue = param.getUnitsElement().getValueAsString();
            cmpValue = QuantityCompararatorEnum.VALUESET_BINDER
                    .fromCodeString(param.getComparatorElement().getValueAsString());
            valueValue = param.getValueElement().getValue();
        } else if (params instanceof QuantityParam) {
            QuantityParam param = (QuantityParam) params;
            systemValue = param.getSystem().getValueAsString();
            unitsValue = param.getUnits();
            cmpValue = param.getComparator();
            valueValue = param.getValue().getValue();
            approx = param.isApproximate();
        } else {
            throw new IllegalArgumentException("Invalid quantity type: " + params.getClass());
        }

        Predicate system = null;
        if (!isBlank(systemValue)) {
            system = builder.equal(from.get("mySystem"), systemValue);
        }

        Predicate code = null;
        if (!isBlank(unitsValue)) {
            code = builder.equal(from.get("myUnits"), unitsValue);
        }

        Predicate num;
        if (cmpValue == null) {
            BigDecimal mul = approx ? new BigDecimal(0.1) : new BigDecimal(0.01);
            BigDecimal low = valueValue.subtract(valueValue.multiply(mul));
            BigDecimal high = valueValue.add(valueValue.multiply(mul));
            Predicate lowPred = builder.gt(from.get("myValue").as(BigDecimal.class), low);
            Predicate highPred = builder.lt(from.get("myValue").as(BigDecimal.class), high);
            num = builder.and(lowPred, highPred);
        } else {
            switch (cmpValue) {
            case GREATERTHAN:
                Expression<Number> path = from.get("myValue");
                num = builder.gt(path, valueValue);
                break;
            case GREATERTHAN_OR_EQUALS:
                path = from.get("myValue");
                num = builder.ge(path, valueValue);
                break;
            case LESSTHAN:
                path = from.get("myValue");
                num = builder.lt(path, valueValue);
                break;
            case LESSTHAN_OR_EQUALS:
                path = from.get("myValue");
                num = builder.le(path, valueValue);
                break;
            default:
                throw new IllegalStateException(cmpValue.getCode());
            }
        }

        if (system == null && code == null) {
            codePredicates.add(num);
        } else if (system == null) {
            Predicate singleCode = builder.and(code, num);
            codePredicates.add(singleCode);
        } else if (code == null) {
            Predicate singleCode = builder.and(system, num);
            codePredicates.add(singleCode);
        } else {
            Predicate singleCode = builder.and(system, code, num);
            codePredicates.add(singleCode);
        }
    }

    Predicate masterCodePredicate = builder.or(codePredicates.toArray(new Predicate[0]));

    Predicate type = builder.equal(from.get("myResourceType"), myResourceName);
    Predicate name = builder.equal(from.get("myParamName"), theParamName);
    if (thePids.size() > 0) {
        Predicate inPids = (from.get("myResourcePid").in(thePids));
        cq.where(builder.and(type, name, masterCodePredicate, inPids));
    } else {
        cq.where(builder.and(type, name, masterCodePredicate));
    }

    TypedQuery<Long> q = myEntityManager.createQuery(cq);
    return new HashSet<Long>(q.getResultList());
}

From source file:com.ylife.shoppingcart.service.impl.ShoppingCartServiceImpl.java

/**
 * ??//from   w w  w .j  a  va  2s  .  c om
 *
 * @param businessId
 * @param shopdata
 * @return
 */
@Override
public Map<String, Object> getEveryThirdPriceMap(Long businessId, List<ShoppingCart> shopdata,
        Long distinctId) {
    Map<String, Object> paramMap = new HashMap<>();
    // 1?? 0?
    paramMap.put(STOCK, "1");
    List<ShoppingCart> shoplist = new ArrayList<>();
    if (CollectionUtils.isNotEmpty(shopdata)) {

        for (int i = 0; i < shopdata.size(); i++) {
            if (businessId.equals(shopdata.get(i).getThirdId())) {
                shoplist.add(shopdata.get(i));
            }
        }
    }
    // ?
    BigDecimal sumPrice = BigDecimal.valueOf(0);
    // ?
    BigDecimal sumOldPrice = BigDecimal.valueOf(0);
    // ?
    BigDecimal prePrice = BigDecimal.valueOf(0);
    // ??
    BigDecimal flag = BigDecimal.ZERO;
    // boss?
    BigDecimal bossSumPrice = BigDecimal.ZERO;
    ProductWare productWare;
    Map<String, Object> para = new HashMap<>();
    if (CollectionUtils.isNotEmpty(shoplist)) {
        Long goodssum = 0L;
        BigDecimal goodsprice = BigDecimal.ZERO;
        BigDecimal totalprice = BigDecimal.ZERO;

        for (int v = 0; v < shoplist.size(); v++) {

            if (shoplist.get(v).getFitId() == null) {

                // ?
                goodsprice = shoplist.get(v).getGoodsDetailBean().getProductVo().getGoodsInfoPreferPrice();
                //?
                if ("0".equals(shoplist.get(v).getGoodsDetailBean().getProductVo().getGoodsInfoAdded())) {
                    paramMap.put(STOCK, "0");
                }
                // ?
                String discountFlag = "";
                DecimalFormat myformat = null;
                // 
                if ("1".equals(discountFlag)) {
                    myformat = new DecimalFormat("0.0");
                } else if ("2".equals(discountFlag)) {
                    myformat = new DecimalFormat("0");
                } else {
                    myformat = new DecimalFormat("0.00");
                }
                goodsprice = BigDecimal.valueOf(Double.valueOf(myformat.format(goodsprice)));
                // ??()
                shoplist.get(v).getGoodsDetailBean().getProductVo().setGoodsInfoPreferPrice(goodsprice);
                // ?
                goodssum = shoplist.get(v).getGoodsNum();
                // boss?
                if (shoplist.get(v).getThirdId() == 0) {
                    if (shoplist.get(v).getSubjectId() != null && shoplist.get(v).getSubjectId() > 0) {
                        bossSumPrice = bossSumPrice.add(BigDecimal
                                .valueOf(
                                        Double.valueOf(myformat.format(shoplist.get(v).getSubjectGoodsPrice())))
                                .multiply(BigDecimal.valueOf(goodssum)));
                    } else {
                        bossSumPrice = bossSumPrice.add(goodsprice.multiply(BigDecimal.valueOf(goodssum)));
                    }
                }
                // ?
                if (shoplist.get(v).getSubjectId() != null && shoplist.get(v).getSubjectId() > 0) {
                    sumOldPrice = sumOldPrice.add(BigDecimal
                            .valueOf(Double.valueOf(myformat.format(shoplist.get(v).getSubjectGoodsPrice())))
                            .multiply(BigDecimal.valueOf(goodssum)));
                    flag = flag.add(BigDecimal
                            .valueOf(Double.valueOf(myformat.format(shoplist.get(v).getSubjectGoodsPrice())))
                            .multiply(BigDecimal.valueOf(goodssum)));
                } else {
                    sumOldPrice = sumOldPrice.add(goodsprice.multiply(BigDecimal.valueOf(goodssum)));
                    flag = flag.add(goodsprice.multiply(BigDecimal.valueOf(goodssum)));
                }
            }

        }
        List<ShoppingCart> cartList = null;
        // ?id?
        cartList = new ArrayList<>();
        for (ShoppingCart sc : shoplist) {
            if (sc.getFitId() == null) {
                cartList.add(sc);

            }
        }
    }
    paramMap.put("sumOldPrice", sumOldPrice);
    paramMap.put(BOSSSUMPRICE, bossSumPrice);
    paramMap.put(SUMPRICE, flag);
    return paramMap;
}

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

/**
 * @param yearId//ww  w  .  j a  v a 2s  .  co 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====>");
}