List of usage examples for java.math BigDecimal divide
public BigDecimal divide(BigDecimal divisor, MathContext mc)
From source file:com.opengamma.examples.bloomberg.loader.DemoEquityOptionCollarPortfolioLoader.java
private void addNodes(final ManageablePortfolioNode rootNode, final String underlying, final boolean includeUnderlying, final Period[] expiries) { final ExternalId ticker = ExternalSchemes.bloombergTickerSecurityId(underlying); ManageableSecurity underlyingSecurity = null; if (includeUnderlying) { underlyingSecurity = getOrLoadEquity(ticker); }/* w ww . j a v a 2 s. c o m*/ final ExternalIdBundle bundle = underlyingSecurity == null ? ExternalIdBundle.of(ticker) : underlyingSecurity.getExternalIdBundle(); final HistoricalTimeSeriesInfoDocument timeSeriesInfo = getOrLoadTimeSeries(ticker, bundle); final double estimatedCurrentStrike = getOrLoadMostRecentPoint(timeSeriesInfo); final Set<ExternalId> optionChain = getOptionChain(ticker); //TODO: reuse positions/nodes? final String longName = underlyingSecurity == null ? "" : underlyingSecurity.getName(); final String formattedName = MessageFormatter.format("[{}] {}", underlying, longName).getMessage(); final ManageablePortfolioNode equityNode = new ManageablePortfolioNode(formattedName); final BigDecimal underlyingAmount = VALUE_OF_UNDERLYING.divide(BigDecimal.valueOf(estimatedCurrentStrike), BigDecimal.ROUND_HALF_EVEN); if (includeUnderlying) { addPosition(equityNode, underlyingAmount, ticker); } final TreeMap<LocalDate, Set<BloombergTickerParserEQOption>> optionsByExpiry = new TreeMap<LocalDate, Set<BloombergTickerParserEQOption>>(); for (final ExternalId optionTicker : optionChain) { s_logger.debug("Got option {}", optionTicker); final BloombergTickerParserEQOption optionInfo = BloombergTickerParserEQOption .getOptionParser(optionTicker); s_logger.debug("Got option info {}", optionInfo); final LocalDate key = optionInfo.getExpiry(); Set<BloombergTickerParserEQOption> set = optionsByExpiry.get(key); if (set == null) { set = new HashSet<BloombergTickerParserEQOption>(); optionsByExpiry.put(key, set); } set.add(optionInfo); } final Set<ExternalId> tickersToLoad = new HashSet<ExternalId>(); final BigDecimal expiryCount = BigDecimal.valueOf(expiries.length); final BigDecimal defaultAmountAtExpiry = underlyingAmount.divide(expiryCount, BigDecimal.ROUND_DOWN); final BigDecimal spareAmountAtExpiry = defaultAmountAtExpiry.add(BigDecimal.ONE); int spareCount = underlyingAmount.subtract(defaultAmountAtExpiry.multiply(expiryCount)).intValue(); for (final Period bucketPeriod : expiries) { final ManageablePortfolioNode bucketNode = new ManageablePortfolioNode( bucketPeriod.toString().substring(1)); final LocalDate nowish = LocalDate.now().withDayOfMonth(20); //This avoids us picking different options every time this script is run final LocalDate targetExpiry = nowish.plus(bucketPeriod); final LocalDate chosenExpiry = optionsByExpiry.floorKey(targetExpiry); if (chosenExpiry == null) { s_logger.info("No options for {} on {}", targetExpiry, underlying); continue; } s_logger.info("Using time {} for bucket {} ({})", new Object[] { chosenExpiry, bucketPeriod, targetExpiry }); final Set<BloombergTickerParserEQOption> optionsAtExpiry = optionsByExpiry.get(chosenExpiry); final TreeMap<Double, Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> optionsByStrike = new TreeMap<>(); for (final BloombergTickerParserEQOption option : optionsAtExpiry) { // s_logger.info("option {}", option); final double key = option.getStrike(); Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike.get(key); if (pair == null) { pair = Pair.of(null, null); } if (option.getOptionType() == OptionType.CALL) { pair = Pair.of(option, pair.getSecond()); } else { pair = Pair.of(pair.getFirst(), option); } optionsByStrike.put(key, pair); } //cascading collar? final BigDecimal amountAtExpiry = spareCount-- > 0 ? spareAmountAtExpiry : defaultAmountAtExpiry; s_logger.info(" est strike {}", estimatedCurrentStrike); final Double[] strikes = optionsByStrike.keySet().toArray(new Double[0]); int strikeIndex = Arrays.binarySearch(strikes, estimatedCurrentStrike); if (strikeIndex < 0) { strikeIndex = -(1 + strikeIndex); } s_logger.info("strikes length {} index {} strike of index {}", new Object[] { Integer.valueOf(strikes.length), Integer.valueOf(strikeIndex), Double.valueOf(strikes[strikeIndex]) }); int minIndex = strikeIndex - _numOptions; minIndex = Math.max(0, minIndex); int maxIndex = strikeIndex + _numOptions; maxIndex = Math.min(strikes.length - 1, maxIndex); s_logger.info("min {} max {}", Integer.valueOf(minIndex), Integer.valueOf(maxIndex)); final StringBuffer sb = new StringBuffer("strikes: ["); for (int j = minIndex; j <= maxIndex; j++) { sb.append(" "); sb.append(strikes[j]); } sb.append(" ]"); s_logger.info(sb.toString()); //Short Calls final ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> calls = new ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>(); for (int j = minIndex; j < strikeIndex; j++) { final Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike .get(strikes[j]); if (pair == null) { throw new OpenGammaRuntimeException("no pair for strike" + strikes[j]); } calls.add(pair); } spreadOptions(bucketNode, calls, OptionType.CALL, -1, tickersToLoad, amountAtExpiry, includeUnderlying, calls.size()); // Long Puts final ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>> puts = new ArrayList<Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption>>(); for (int j = strikeIndex + 1; j <= maxIndex; j++) { final Pair<BloombergTickerParserEQOption, BloombergTickerParserEQOption> pair = optionsByStrike .get(strikes[j]); if (pair == null) { throw new OpenGammaRuntimeException("no pair for strike" + strikes[j]); } puts.add(pair); } spreadOptions(bucketNode, puts, OptionType.PUT, 1, tickersToLoad, amountAtExpiry, includeUnderlying, puts.size()); if (bucketNode.getChildNodes().size() + bucketNode.getPositionIds().size() > 0) { equityNode.addChildNode(bucketNode); //Avoid generating empty nodes } } for (final ExternalId optionTicker : tickersToLoad) { final ManageableSecurity loaded = getOrLoadSecurity(optionTicker); if (loaded == null) { throw new OpenGammaRuntimeException("Unexpected option type " + loaded); } //TODO [LAPANA-29] Should be able to do this for index options too if (includeUnderlying) { try { final HistoricalTimeSeriesInfoDocument loadedTs = getOrLoadTimeSeries(optionTicker, loaded.getExternalIdBundle()); if (loadedTs == null) { throw new OpenGammaRuntimeException("Failed to get time series for " + loaded); } } catch (final Exception ex) { s_logger.info("Failed to get time series for " + loaded, ex); } } } if (equityNode.getPositionIds().size() + equityNode.getChildNodes().size() > 0) { rootNode.addChildNode(equityNode); } }
From source file:org.egov.wtms.service.es.WaterChargeCollectionDocService.java
/** * Prepares Collection Table Data/*from w ww. j a va2 s .c o m*/ * * @param collectionDetailsRequest * @return List */ public List<WaterChargeDashBoardResponse> getResponseTableData( final WaterChargeDashBoardRequest collectionDetailsRequest) { final List<WaterChargeDashBoardResponse> collIndDataList = new ArrayList<>(); Date fromDate; Date toDate; String name; WaterChargeDashBoardResponse collIndData; BigDecimal cytdDmd; BigDecimal performance; BigDecimal balance; BigDecimal variance; String aggregationField = WaterTaxConstants.REGIONNAMEAGGREGATIONFIELD; Map<String, BillCollectorIndex> wardWiseBillCollectors = new HashMap<>(); final CFinancialYear financialYear = cFinancialYearService.getCurrentFinancialYear(); /** * Select the grouping based on the type parameter, by default the * grouping is done based on Regions. If type is region, group by * Region, if type is district, group by District, if type is ulb, group * by ULB */ if (StringUtils.isNotBlank(collectionDetailsRequest.getType())) if (collectionDetailsRequest.getType().equalsIgnoreCase(DASHBOARD_GROUPING_REGIONWISE)) aggregationField = WaterTaxConstants.REGIONNAMEAGGREGATIONFIELD; else if (collectionDetailsRequest.getType().equalsIgnoreCase(DASHBOARD_GROUPING_DISTRICTWISE)) aggregationField = WaterTaxConstants.DISTRICTNAMEAGGREGATIONFIELD; else if (collectionDetailsRequest.getType().equalsIgnoreCase(DASHBOARD_GROUPING_ULBWISE)) aggregationField = WaterTaxConstants.CITYNAMEAGGREGATIONFIELD; else if (collectionDetailsRequest.getType().equalsIgnoreCase(DASHBOARD_GROUPING_GRADEWISE)) aggregationField = WaterTaxConstants.CITYGRADEAGGREGATIONFIELD; else if (collectionDetailsRequest.getType().equalsIgnoreCase(DASHBOARD_GROUPING_WARDWISE) || collectionDetailsRequest.getType() .equalsIgnoreCase(PropertyTaxConstants.DASHBOARD_GROUPING_BILLCOLLECTORWISE)) aggregationField = WaterTaxConstants.REVENUEWARDAGGREGATIONFIELD; /** * As per Elastic Search functionality, to get the total collections * between 2 dates, add a day to the endDate and fetch the results For * Current day's collection if dates are sent in the request, consider * the toDate, else take date range between current date +1 day */ if (StringUtils.isNotBlank(collectionDetailsRequest.getFromDate()) && StringUtils.isNotBlank(collectionDetailsRequest.getToDate())) { fromDate = DateUtils.getDate(collectionDetailsRequest.getToDate(), DATE_FORMAT_YYYYMMDD); toDate = org.apache.commons.lang3.time.DateUtils .addDays(DateUtils.getDate(collectionDetailsRequest.getToDate(), DATE_FORMAT_YYYYMMDD), 1); } else { fromDate = new Date(); toDate = org.apache.commons.lang3.time.DateUtils.addDays(new Date(), 1); } Long startTime = System.currentTimeMillis(); // For today collection final Map<String, BigDecimal> todayCollMap = getCollectionAndDemandValues(collectionDetailsRequest, fromDate, toDate, WaterTaxConstants.COLLECTION_INDEX_NAME, TOTAL_AMOUNT, aggregationField); /** * For collection and demand between the date ranges if dates are sent * in the request, consider fromDate and toDate+1 , else calculate from * current year start date till current date+1 day */ if (StringUtils.isNotBlank(collectionDetailsRequest.getFromDate()) && StringUtils.isNotBlank(collectionDetailsRequest.getToDate())) { fromDate = DateUtils.getDate(collectionDetailsRequest.getFromDate(), DATE_FORMAT_YYYYMMDD); toDate = org.apache.commons.lang3.time.DateUtils .addDays(DateUtils.getDate(collectionDetailsRequest.getToDate(), DATE_FORMAT_YYYYMMDD), 1); } else { fromDate = DateUtils.startOfDay(financialYear.getStartingDate()); toDate = org.apache.commons.lang3.time.DateUtils.addDays(new Date(), 1); } final int noOfMonths = DateUtils.noOfMonthsBetween(fromDate, toDate) + 1; final Map<String, BigDecimal> cytdCollMap = getCollectionAndDemandValues(collectionDetailsRequest, fromDate, toDate, COLLECTION_INDEX_NAME, TOTAL_AMOUNT, aggregationField); // For total demand final Map<String, BigDecimal> totalDemandMap = getCollectionAndDemandValues(collectionDetailsRequest, fromDate, toDate, WaterTaxConstants.WATER_TAX_INDEX_NAME, WaterTaxConstants.WATERCHARGETOTALDEMAND, aggregationField); // For current year demand final Map<String, BigDecimal> currYrTotalDemandMap = getCollectionAndDemandValues(collectionDetailsRequest, fromDate, toDate, WaterTaxConstants.WATER_TAX_INDEX_NAME, WaterTaxConstants.WATERCHARGETOTALDEMAND, aggregationField); // For last year's till today's date collections final Map<String, BigDecimal> lytdCollMap = getCollectionAndDemandValues(collectionDetailsRequest, org.apache.commons.lang3.time.DateUtils.addYears(fromDate, -1), org.apache.commons.lang3.time.DateUtils.addYears(toDate, -1), WaterTaxConstants.COLLECTION_INDEX_NAME, TOTAL_AMOUNT, aggregationField); if (DASHBOARD_GROUPING_WARDWISE.equalsIgnoreCase(collectionDetailsRequest.getType())) wardWiseBillCollectors = getWardWiseBillCollectors(collectionDetailsRequest); Long timeTaken = System.currentTimeMillis() - startTime; if (LOGGER.isDebugEnabled()) LOGGER.debug("Time taken by getCollectionAndDemandValues() is (millisecs) : " + timeTaken); startTime = System.currentTimeMillis(); for (final Map.Entry<String, BigDecimal> entry : cytdCollMap.entrySet()) { collIndData = new WaterChargeDashBoardResponse(); name = entry.getKey(); if (aggregationField.equals(WaterTaxConstants.REGIONNAMEAGGREGATIONFIELD)) collIndData.setRegionName(name); else if (aggregationField.equals(WaterTaxConstants.DISTRICTNAMEAGGREGATIONFIELD)) { collIndData.setRegionName(collectionDetailsRequest.getRegionName()); collIndData.setDistrictName(name); } else if (WaterTaxConstants.CITYNAMEAGGREGATIONFIELD.equals(aggregationField)) { collIndData.setUlbName(name); collIndData.setDistrictName(collectionDetailsRequest.getDistrictName()); collIndData.setUlbGrade(collectionDetailsRequest.getUlbGrade()); } else if (aggregationField.equals(WaterTaxConstants.CITYGRADEAGGREGATIONFIELD)) collIndData.setUlbGrade(name); else if (WaterTaxConstants.REVENUEWARDAGGREGATIONFIELD.equals(aggregationField)) collIndData.setWardName(name); if (DASHBOARD_GROUPING_WARDWISE.equalsIgnoreCase(collectionDetailsRequest.getType()) && !wardWiseBillCollectors.isEmpty()) collIndData.setBillCollector(wardWiseBillCollectors.get(name) == null ? StringUtils.EMPTY : wardWiseBillCollectors.get(name).getBillCollector()); collIndData.setTodayColl(todayCollMap.get(name) == null ? BigDecimal.ZERO : todayCollMap.get(name)); collIndData.setCurrentYearTillDateColl(entry.getValue()); // Proportional Demand = (totalDemand/12)*noOfmonths final BigDecimal currentYearTotalDemand = currYrTotalDemandMap.get(name) == null ? BigDecimal.valueOf(0) : currYrTotalDemandMap.get(name); cytdDmd = currentYearTotalDemand.divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP) .multiply(BigDecimal.valueOf(noOfMonths)); collIndData.setCurrentYearTillDateDmd(cytdDmd); if (cytdDmd != BigDecimal.valueOf(0)) { balance = cytdDmd.subtract(collIndData.getCurrentYearTillDateColl()); performance = collIndData.getCurrentYearTillDateColl().multiply(WaterTaxConstants.BIGDECIMAL_100) .divide(cytdDmd, 1, BigDecimal.ROUND_HALF_UP); collIndData.setPerformance(performance); collIndData.setCurrentYearTillDateBalDmd(balance); } collIndData.setTotalDmd(totalDemandMap.get(name) == null ? BigDecimal.ZERO : totalDemandMap.get(name)); collIndData.setLastYearTillDateColl( lytdCollMap.get(name) == null ? BigDecimal.ZERO : lytdCollMap.get(name)); // variance = ((currentYearCollection - // lastYearCollection)*100)/lastYearCollection if (collIndData.getLastYearTillDateColl().compareTo(BigDecimal.ZERO) == 0) variance = WaterTaxConstants.BIGDECIMAL_100; else variance = collIndData.getCurrentYearTillDateColl().subtract(collIndData.getLastYearTillDateColl()) .multiply(WaterTaxConstants.BIGDECIMAL_100) .divide(collIndData.getLastYearTillDateColl(), 1, BigDecimal.ROUND_HALF_UP); collIndData.setLastYearVar(variance); collIndDataList.add(collIndData); } timeTaken = System.currentTimeMillis() - startTime; if (LOGGER.isDebugEnabled()) LOGGER.debug("Time taken for setting values in getResponseTableData() is (millisecs): " + timeTaken); return collIndDataList; }
From source file:edu.harvard.iq.dvn.ingest.statdataio.impl.plugins.por.PORFileReader.java
private double base30Tobase10Conversion(String base30String) { // new base(radix) number int oldBase = 30; //dbgLog.fine("base30String="+base30String); // trim white-spaces from the both ends String base30StringClean = StringUtils.trim(base30String); //dbgLog.fine("base30StringClean="+base30StringClean); // check the negative/positive sign boolean isNegativeNumber = false; boolean hasPositiveSign = false; if (base30StringClean.startsWith("-")) { isNegativeNumber = true;/*from ww w . j ava2 s . c o m*/ } if (base30StringClean.startsWith("+")) { hasPositiveSign = true; } // remove the sign if exits String base30StringNoSign = null; if ((isNegativeNumber) || (hasPositiveSign)) { base30StringNoSign = base30StringClean.substring(1); } else { base30StringNoSign = new String(base30StringClean); } // check the scientific notation // if so, divide it into the significand and exponent String significand = null; long exponent = 0; int plusIndex = base30StringNoSign.indexOf("+"); int minusIndex = base30StringNoSign.indexOf("-"); if (plusIndex > 0) { significand = base30StringNoSign.substring(0, plusIndex); exponent = Long.valueOf(base30StringNoSign.substring(plusIndex + 1), oldBase); } else if (minusIndex > 0) { significand = base30StringNoSign.substring(0, minusIndex); exponent = -1 * Long.valueOf(base30StringNoSign.substring(minusIndex + 1), oldBase); } else { significand = new String(base30StringNoSign); } // "move" decimal point; for each shift right, subtract one from exponent; end result is a string with no decimal int decimalIndex = significand.indexOf("."); if (decimalIndex != -1) { exponent -= (significand.length() - (decimalIndex + 1)); significand = significand.substring(0, decimalIndex) + significand.substring(decimalIndex + 1); } MathContext mc = new MathContext(15, RoundingMode.HALF_UP); long base10Significand = Long.parseLong(significand, oldBase); BigDecimal base10value = new BigDecimal(String.valueOf(base10Significand), mc); BigDecimal exponentialComponent = new BigDecimal("1", mc); for (int g = 0; g < Math.abs(exponent); g++) { exponentialComponent = exponentialComponent.multiply(new BigDecimal("30", mc)); } if (exponent >= 0) { base10value = base10value.multiply(exponentialComponent, mc); } else { base10value = base10value.divide(exponentialComponent, mc); } // negative sign if applicable if (isNegativeNumber) { base10value = base10value.multiply(new BigDecimal("-1", mc)); } return base10value.doubleValue(); }
From source file:org.openbravo.erpCommon.ad_forms.DocInvoice.java
private ArrayList<HashMap<String, String>> calculateAccDefPlan(Period startingPeriod, int periodNumber, BigDecimal amount, String strCurrencyId) { Period period = startingPeriod; Date date = period.getEndingDate(); ArrayList<HashMap<String, String>> plan = new ArrayList<HashMap<String, String>>(); int i = 1;/*from ww w. jav a 2s . co m*/ BigDecimal total = BigDecimal.ZERO; int stdPrecision = 0; OBContext.setAdminMode(true); try { stdPrecision = OBDal.getInstance().get(Currency.class, this.C_Currency_ID).getStandardPrecision() .intValue(); } finally { OBContext.restorePreviousMode(); } BigDecimal periodAmount = amount .divide(new BigDecimal(periodNumber), new MathContext(32, RoundingMode.HALF_UP)) .setScale(stdPrecision, BigDecimal.ROUND_HALF_UP); while (i <= periodNumber) { if (!OBDateUtils.formatDate(date).equals(DateAcct)) { HashMap<String, String> hm = new HashMap<String, String>(); hm.put("date", OBDateUtils.formatDate(date)); hm.put("amount", i == periodNumber ? amount.subtract(total).toString() : periodAmount.toString()); plan.add(hm); } try { AcctServerData[] data = AcctServerData.periodOpen(connectionProvider, AD_Client_ID, DocumentType, AD_Org_ID, OBDateUtils.formatDate(period.getEndingDate())); if ("".equals(data[0].period)) { setStatus(STATUS_PeriodClosed); throw new OBException("@PeriodNotAvailable@"); } } catch (ServletException e) { log4j.warn("DocInvoice - Error checking period open.", e); e.printStackTrace(); } if (i < periodNumber) { period = AccDefUtility.getNextPeriod(period); date = period.getEndingDate(); } total = total.add(periodAmount); i++; } return plan; }
From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.por.PORFileReader.java
private double base30Tobase10Conversion(String base30String) { // new base(radix) number int oldBase = 30; //dbgLog.fine("base30String="+base30String); // trim white-spaces from the both ends String base30StringClean = StringUtils.trim(base30String); //dbgLog.fine("base30StringClean="+base30StringClean); // check the negative/positive sign boolean isNegativeNumber = false; boolean hasPositiveSign = false; if (base30StringClean.startsWith("-")) { isNegativeNumber = true;/*from w w w. ja v a2 s.c o m*/ } if (base30StringClean.startsWith("+")) { hasPositiveSign = true; } // remove the sign if exits String base30StringNoSign = null; if ((isNegativeNumber) || (hasPositiveSign)) { base30StringNoSign = base30StringClean.substring(1); } else { base30StringNoSign = base30StringClean; } // check the scientific notation // if so, divide it into the significand and exponent String significand = null; long exponent = 0; int plusIndex = base30StringNoSign.indexOf("+"); int minusIndex = base30StringNoSign.indexOf("-"); if (plusIndex > 0) { significand = base30StringNoSign.substring(0, plusIndex); exponent = Long.valueOf(base30StringNoSign.substring(plusIndex + 1), oldBase); } else if (minusIndex > 0) { significand = base30StringNoSign.substring(0, minusIndex); exponent = -1 * Long.valueOf(base30StringNoSign.substring(minusIndex + 1), oldBase); } else { significand = base30StringNoSign; } // "move" decimal point; for each shift right, subtract one from exponent; end result is a string with no decimal int decimalIndex = significand.indexOf("."); if (decimalIndex != -1) { exponent -= (significand.length() - (decimalIndex + 1)); significand = significand.substring(0, decimalIndex) + significand.substring(decimalIndex + 1); } // TODO: Verify that the MathContext/Rounding methods are OK: // -- L.A. 4.0 beta MathContext mc = new MathContext(15, RoundingMode.HALF_UP); long base10Significand = Long.parseLong(significand, oldBase); BigDecimal base10value = new BigDecimal(String.valueOf(base10Significand), mc); BigDecimal exponentialComponent = new BigDecimal("1", mc); for (int g = 0; g < Math.abs(exponent); g++) { exponentialComponent = exponentialComponent.multiply(new BigDecimal("30", mc)); } if (exponent >= 0) { base10value = base10value.multiply(exponentialComponent, mc); } else { base10value = base10value.divide(exponentialComponent, mc); } // negative sign if applicable if (isNegativeNumber) { base10value = base10value.multiply(new BigDecimal("-1", mc)); } return base10value.doubleValue(); }
From source file:org.egov.wtms.service.es.WaterChargeCollectionDocService.java
public List<WaterChargeConnectionTypeResponse> getFullCollectionIndexDtlsForCOnnectionType( final WaterChargeDashBoardRequest collectionDetailsRequest) { final List<WaterChargeConnectionTypeResponse> collectionIndexDetailsList = new ArrayList<>(); final WaterChargeConnectionTypeResponse collectionIndexDetails = new WaterChargeConnectionTypeResponse(); Date fromDate;/*from w w w . j av a2 s .co m*/ Date toDate; BigDecimal todayColl;// need to test BigDecimal tillDateColl;// need to test final Long startTime = System.currentTimeMillis(); final CFinancialYear financialyear = cFinancialYearService.getCurrentFinancialYear(); /** * As per Elastic Search functionality, to get the total collections * between 2 dates, add a day to the endDate and fetch the results For * Current day's collection if dates are sent in the request, consider * the toDate, else take date range between current date +1 day */ if (StringUtils.isNotBlank(collectionDetailsRequest.getFromDate()) && StringUtils.isNotBlank(collectionDetailsRequest.getToDate())) { fromDate = DateUtils.getDate(collectionDetailsRequest.getFromDate(), DATE_FORMAT_YYYYMMDD); toDate = org.apache.commons.lang3.time.DateUtils .addDays(DateUtils.getDate(collectionDetailsRequest.getToDate(), DATE_FORMAT_YYYYMMDD), 1); } else { fromDate = new Date(); toDate = org.apache.commons.lang3.time.DateUtils.addDays(new Date(), 1); } // Todays collection todayColl = getCollectionBetweenDates(collectionDetailsRequest, fromDate, toDate, null); collectionIndexDetails.setTodayColl(todayColl); // Last year Todays day collection todayColl = getCollectionBetweenDates(collectionDetailsRequest, org.apache.commons.lang3.time.DateUtils.addYears(fromDate, -1), org.apache.commons.lang3.time.DateUtils.addYears(toDate, -1), null); collectionIndexDetails.setLastYearTodayColl(todayColl); /** * For collections between the date ranges if dates are sent in the * request, consider the same, else calculate from current year start * date till current date+1 day */ if (StringUtils.isNotBlank(collectionDetailsRequest.getFromDate()) && StringUtils.isNotBlank(collectionDetailsRequest.getToDate())) { fromDate = DateUtils.getDate(collectionDetailsRequest.getFromDate(), DATE_FORMAT_YYYYMMDD); toDate = org.apache.commons.lang3.time.DateUtils .addDays(DateUtils.getDate(collectionDetailsRequest.getToDate(), DATE_FORMAT_YYYYMMDD), 1); } else { fromDate = DateUtils.startOfDay(financialyear.getStartingDate()); toDate = org.apache.commons.lang3.time.DateUtils.addDays(new Date(), 1); } // Current Year till today collection tillDateColl = getCollectionBetweenDates(collectionDetailsRequest, fromDate, toDate, null); collectionIndexDetails.setCurrentYearTillDateColl(tillDateColl); // Last year till same date of todays date collection tillDateColl = getCollectionBetweenDates(collectionDetailsRequest, org.apache.commons.lang3.time.DateUtils.addYears(fromDate, -1), org.apache.commons.lang3.time.DateUtils.addYears(toDate, -1), null); collectionIndexDetails.setLastYearTillDateColl(tillDateColl); final Long timeTaken = System.currentTimeMillis() - startTime; if (LOGGER.isDebugEnabled()) LOGGER.debug("Time taken by getCompleteCollectionIndexDetails() is (millisecs) : " + timeTaken); /** * For fetching total demand between the date ranges if dates are sent * in the request, consider fromDate and toDate+1 , else calculate from * current year start date till current date+1 day */ if (StringUtils.isNotBlank(collectionDetailsRequest.getFromDate()) && StringUtils.isNotBlank(collectionDetailsRequest.getToDate())) { fromDate = DateUtils.getDate(collectionDetailsRequest.getFromDate(), "yyyy-MM-dd"); toDate = org.apache.commons.lang3.time.DateUtils .addDays(DateUtils.getDate(collectionDetailsRequest.getToDate(), "yyyy-MM-dd"), 1); } else { fromDate = DateUtils.startOfDay(financialyear.getStartingDate()); toDate = org.apache.commons.lang3.time.DateUtils.addDays(new Date(), 1); } // starts from final BigDecimal totalDemand = getTotalDemandBasedOnInputFilters(collectionDetailsRequest); if (LOGGER.isDebugEnabled()) LOGGER.debug("Time taken by getTotalDemandBasedOnInputFilters() is (millisecs): " + timeTaken); final int noOfMonths = DateUtils.noOfMonthsBetween(fromDate, toDate) + 1; collectionIndexDetails.setTotalDmd(totalDemand); // Proportional Demand = (totalDemand/12)*noOfmonths final BigDecimal proportionalDemand = totalDemand.divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP) .multiply(BigDecimal.valueOf(noOfMonths)); if (proportionalDemand.compareTo(BigDecimal.ZERO) > 0) collectionIndexDetails .setCurrentYearTillDateDmd(proportionalDemand.setScale(0, BigDecimal.ROUND_HALF_UP)); if (proportionalDemand.compareTo(BigDecimal.ZERO) > 0) collectionIndexDetails.setPerformance( collectionIndexDetails.getCurrentYearTillDateColl().multiply(WaterTaxConstants.BIGDECIMAL_100) .divide(proportionalDemand, 1, BigDecimal.ROUND_HALF_UP)); BigDecimal variation; if (collectionIndexDetails.getLastYearTillDateColl().compareTo(BigDecimal.ZERO) == 0) variation = WaterTaxConstants.BIGDECIMAL_100; else variation = collectionIndexDetails.getCurrentYearTillDateColl() .subtract(collectionIndexDetails.getLastYearTillDateColl()) .multiply(WaterTaxConstants.BIGDECIMAL_100) .divide(collectionIndexDetails.getLastYearTillDateColl(), 1, BigDecimal.ROUND_HALF_UP); collectionIndexDetails.setLastYearVar(variation); if (LOGGER.isDebugEnabled()) LOGGER.debug( "Time taken for setting values in getConsolidatedDemandInfo() is (millisecs): " + timeTaken); collectionIndexDetailsList.add(collectionIndexDetails); return collectionIndexDetailsList; }
From source file:org.kuali.coeus.propdev.impl.print.NIHResearchAndRelatedXmlStream.java
private BigDecimal calculateFundingMonths(DevelopmentProposal developmentProposal, BudgetPersonnelDetails budgetPersonnelDetails, String budgetPeriodType) { BigDecimal fundingMonths = ScaleTwoDecimal.ZERO.bigDecimalValue(); if (personExistsInProposal(developmentProposal, budgetPersonnelDetails) && budgetPeriodType.equals(budgetPersonnelDetails.getPeriodTypeCode())) { if (budgetPersonnelDetails != null) { BigDecimal totalMonths = getMonthsBetweenDates(budgetPersonnelDetails.getStartDate(), budgetPersonnelDetails.getEndDate()); fundingMonths = budgetPersonnelDetails.getPercentEffort().bigDecimalValue() .multiply(new ScaleTwoDecimal(totalMonths).bigDecimalValue()); fundingMonths = fundingMonths.divide(new ScaleTwoDecimal(100).bigDecimalValue(), RoundingMode.HALF_UP); }//w w w .j ava 2 s . c o m } return fundingMonths.setScale(0); }
From source file:org.egov.wtms.service.es.WaterChargeCollectionDocService.java
private void prepareResponseDataForConnectionType(final WaterChargeDashBoardRequest collectionDetailsRequest, final List<WaterChargeConnectionTypeResponse> waterchargeConndemandList, final String aggregationField, final Map<String, BigDecimal> connectionResidentialTotalDemandMap, final Map<String, Long> connectionCommercialcountMap, final Map<String, BigDecimal> connectionCOmmercialTotalDemandMap, final Map.Entry<String, Long> entry, final Map<String, BigDecimal> connectionResidentialTotalCollectionMap, final Map<String, BigDecimal> connectionCOmmercialTotalCollectionMap) { String name;/* ww w .jav a2s .c om*/ final WaterChargeConnectionTypeResponse receiptData = new WaterChargeConnectionTypeResponse(); name = entry.getKey(); if (WaterTaxConstants.REGIONNAMEAGGREGATIONFIELD.equals(aggregationField)) receiptData.setRegionName(name); else if (WaterTaxConstants.DISTRICTNAMEAGGREGATIONFIELD.equals(aggregationField)) { receiptData.setRegionName(collectionDetailsRequest.getRegionName()); receiptData.setDistrictName(name); } else if (WaterTaxConstants.CITYNAMEAGGREGATIONFIELD.equals(aggregationField)) { receiptData.setUlbName(name); receiptData.setDistrictName(collectionDetailsRequest.getDistrictName()); receiptData.setUlbGrade(collectionDetailsRequest.getUlbGrade()); } else if (WaterTaxConstants.CITYGRADEAGGREGATIONFIELD.equals(aggregationField)) receiptData.setUlbGrade(name); else if (WaterTaxConstants.REVENUEWARDAGGREGATIONFIELD.equals(aggregationField)) receiptData.setWardName(name); final Date fromDate = new DateTime().withMonthOfYear(4).dayOfMonth().withMinimumValue().toDate(); final Date toDate = org.apache.commons.lang3.time.DateUtils.addDays(new Date(), 1); final int noOfMonths = DateUtils.noOfMonthsBetween(fromDate, toDate) + 1; final BigDecimal totalResDemandValue = !connectionResidentialTotalDemandMap.isEmpty() && connectionResidentialTotalDemandMap.get(name) != null ? connectionResidentialTotalDemandMap.get(name).setScale(0, BigDecimal.ROUND_HALF_UP) : BigDecimal.ZERO; final BigDecimal totalResCollections = !connectionResidentialTotalCollectionMap.isEmpty() && connectionResidentialTotalCollectionMap.get(name) != null ? connectionResidentialTotalCollectionMap.get(name).setScale(0, BigDecimal.ROUND_HALF_UP) : BigDecimal.ZERO; final BigDecimal proportionalDemand = totalResDemandValue .divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(noOfMonths)); receiptData.setResidentialAchievement(totalResCollections.multiply(WaterTaxConstants.BIGDECIMAL_100) .divide(proportionalDemand, 1, BigDecimal.ROUND_HALF_UP)); final BigDecimal totalCommDemandValue = !connectionCOmmercialTotalDemandMap.isEmpty() && connectionCOmmercialTotalDemandMap.get(name) != null ? connectionCOmmercialTotalDemandMap.get(name).setScale(0, BigDecimal.ROUND_HALF_UP) : BigDecimal.ZERO; final BigDecimal totalCommCollections = !connectionCOmmercialTotalCollectionMap.isEmpty() && connectionCOmmercialTotalCollectionMap.get(name) != null ? connectionCOmmercialTotalCollectionMap.get(name).setScale(0, BigDecimal.ROUND_HALF_UP) : BigDecimal.ZERO; final BigDecimal commproportionalDemand = totalCommDemandValue .divide(BigDecimal.valueOf(12), BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(noOfMonths)); receiptData.setCommercialAchievement(commproportionalDemand.compareTo(BigDecimal.ZERO) > 0 ? totalCommCollections.multiply(WaterTaxConstants.BIGDECIMAL_100).divide(commproportionalDemand, 1, BigDecimal.ROUND_HALF_UP) : BigDecimal.ZERO); receiptData .setWaterChargeCommercialaverage(connectionCommercialcountMap.get(name) != null ? totalCommDemandValue.divide(BigDecimal.valueOf(connectionCommercialcountMap.get(name)), 1, BigDecimal.ROUND_HALF_UP) : BigDecimal.ZERO); receiptData.setWaterChargeResidentialaverage( totalResDemandValue.divide(BigDecimal.valueOf(entry.getValue()), 1, BigDecimal.ROUND_HALF_UP)); receiptData.setResidentialConnectionCount(entry.getValue()); receiptData.setUlbName(name); receiptData.setResidentialtotalCollection(!connectionResidentialTotalCollectionMap.isEmpty() && connectionResidentialTotalCollectionMap.get(name) != null ? connectionResidentialTotalCollectionMap.get(name) : BigDecimal.ZERO); receiptData.setCommercialConnectionCount(connectionCommercialcountMap.get(name)); receiptData.setComercialtotalCollection(!connectionCOmmercialTotalCollectionMap.isEmpty() && connectionCOmmercialTotalCollectionMap.get(name) != null ? connectionCOmmercialTotalCollectionMap.get(name) : BigDecimal.ZERO); waterchargeConndemandList.add(receiptData); }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * The hyperbolic cosine./*from w w w . ja v a 2s. com*/ * * @param x The argument. * @return The cosh(x) = (exp(x)+exp(-x))/2 . */ static public BigDecimal cosh(final BigDecimal x) { if (x.compareTo(BigDecimal.ZERO) < 0) { return cos(x.negate()); } else if (x.compareTo(BigDecimal.ZERO) == 0) { return BigDecimal.ONE; } else { if (x.doubleValue() > 1.5) { /* cosh^2(x) = 1+ sinh^2(x). */ return hypot(1, sinh(x)); } else { BigDecimal xhighpr = scalePrec(x, 2); /* Simple Taylor expansion, sum_{0=1..infinity} x^(2i)/(2i)! */ BigDecimal resul = BigDecimal.ONE; /* x^i */ BigDecimal xpowi = BigDecimal.ONE; /* 2i factorial */ BigInteger ifac = BigInteger.ONE; /* The absolute error in the result is the error in x^2/2 which is x times the error in x. */ double xUlpDbl = 0.5 * x.ulp().doubleValue() * x.doubleValue(); /* The error in the result is set by the error in x^2/2 itself, xUlpDbl. * We need at most k terms to push x^(2k)/(2k)! below this value. * x^(2k) < xUlpDbl; (2k)*log(x) < log(xUlpDbl); */ int k = (int) (Math.log(xUlpDbl) / Math.log(x.doubleValue())) / 2; /* The individual terms are all smaller than 1, so an estimate of 1.0 for * the absolute value will give a safe relative error estimate for the indivdual terms */ MathContext mcTay = new MathContext(err2prec(1., xUlpDbl / k)); for (int i = 1;; i++) { /* TBD: at which precision will 2*i-1 or 2*i overflow? */ ifac = ifac.multiply(new BigInteger("" + (2 * i - 1))); ifac = ifac.multiply(new BigInteger("" + (2 * i))); xpowi = xpowi.multiply(xhighpr).multiply(xhighpr); BigDecimal corr = xpowi.divide(new BigDecimal(ifac), mcTay); resul = resul.add(corr); if (corr.abs().doubleValue() < 0.5 * xUlpDbl) { break; } } /* The error in the result is governed by the error in x itself. */ MathContext mc = new MathContext(err2prec(resul.doubleValue(), xUlpDbl)); return resul.round(mc); } } }
From source file:com.inkubator.hrm.service.impl.PayTempKalkulasiServiceImpl.java
@Override @Transactional(readOnly = false, isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED, rollbackFor = Exception.class) public List<PayTempKalkulasi> getAllDataCalculatedPayment(Date startPeriodDate, Date endPeriodDate, Date createdOn, String createdBy) throws Exception { //initial//w w w .j ava 2 s . c om PaySalaryComponent totalIncomeComponent = paySalaryComponentDao .getEntityBySpecificModelComponent(HRMConstant.MODEL_COMP_TAKE_HOME_PAY); PaySalaryComponent taxComponent = paySalaryComponentDao .getEntityBySpecificModelComponent(HRMConstant.MODEL_COMP_TAX); PaySalaryComponent ceilComponent = paySalaryComponentDao .getEntityBySpecificModelComponent(HRMConstant.MODEL_COMP_CEIL); List<PayTempKalkulasi> datas = new ArrayList<PayTempKalkulasi>(); ScriptEngineManager mgr = new ScriptEngineManager(); ScriptEngine jsEngine = mgr.getEngineByName("JavaScript"); Double basicSalary = null; Double workingDay = null; Double lessTime = null; Double moreTime = null; Double overTIme = null; Double totalDay = this.getDefaultWorkingDay(startPeriodDate, endPeriodDate); //total working day dari kelompok kerja DEFAULT(reguler) Double outPut = null; //Start calculation List<EmpData> totalEmployee = empDataDao.getAllDataNotTerminateAndJoinDateLowerThan(endPeriodDate); /*List<EmpData> totalEmployee = new ArrayList<EmpData>(); EmpData emp = empDataDao.getEntiyByPK((long)130); totalEmployee.add(emp);*/ for (EmpData empData : totalEmployee) { LOGGER.info( " ============= EMPLOYEE : " + empData.getBioData().getFirstName() + " ====================="); /** * Set initial variabel untuk masing2 karyawan, * yang akan dibutuhkan untuk perhitungan model komponen FORMULA (if any) * */ basicSalary = Double.parseDouble(empData.getBasicSalaryDecrypted()); PayTempOvertime payTempOvertime = payTempOvertimeDao.getEntityByEmpDataId(empData.getId()); overTIme = payTempOvertime != null ? payTempOvertime.getOvertime() : 0.0; PayTempAttendanceStatus payTempAttendanceStatus = payTempAttendanceStatusDao .getEntityByEmpDataId(empData.getId()); workingDay = payTempAttendanceStatus != null ? (double) payTempAttendanceStatus.getTotalAttendance() : 0.0; lessTime = ((workingDay > 0) && (workingDay < totalDay)) ? totalDay - workingDay : 0.0; moreTime = (workingDay > totalDay) ? workingDay - totalDay : 0.0; /** * Saat ini totalIncome masih temporary, karena belum dikurangi * pajak dan pembulatan CSR Sedangkan untuk final totalIncome (take * home pay) ada di proses(step) selanjutnya di batch proses, * silahkan lihat batch-config.xml */ BigDecimal totalIncome = new BigDecimal(0); List<PayComponentDataException> payComponentExceptions = payComponentDataExceptionDao .getAllByEmpId(empData.getId()); for (PayComponentDataException dataException : payComponentExceptions) { PayTempKalkulasi kalkulasi = new PayTempKalkulasi(); kalkulasi.setId(Long.parseLong(RandomNumberUtil.getRandomNumber(12))); kalkulasi.setEmpData(empData); kalkulasi.setPaySalaryComponent(dataException.getPaySalaryComponent()); kalkulasi.setFactor( this.getFactorBasedCategory(dataException.getPaySalaryComponent().getComponentCategory())); kalkulasi.setNominal(dataException.getNominal()); kalkulasi.setCreatedBy(createdBy); kalkulasi.setCreatedOn(createdOn); datas.add(kalkulasi); totalIncome = this.calculateTotalIncome(totalIncome, kalkulasi); //calculate totalIncome temporary LOGGER.info("Save By ComponentDataException - " + dataException.getPaySalaryComponent().getName() + ", nominal : " + dataException.getNominal()); } int timeTmb = DateTimeUtil.getTotalDay(empData.getJoinDate(), createdOn); List<Long> componentIds = Lambda.extract(payComponentExceptions, Lambda.on(PayComponentDataException.class).getPaySalaryComponent().getId()); List<PaySalaryComponent> listPayComponetNotExcp = paySalaryComponentDao .getAllDataByEmpTypeIdAndActiveFromTmAndIdNotIn(empData.getEmployeeType().getId(), timeTmb, componentIds); if (null == Lambda.selectFirst(listPayComponetNotExcp, Lambda.having(Lambda.on(PaySalaryComponent.class).getModelComponent().getSpesific(), Matchers.equalTo(HRMConstant.MODEL_COMP_BASIC_SALARY))) && null == Lambda.selectFirst(payComponentExceptions, Lambda.having( Lambda.on(PayComponentDataException.class).getPaySalaryComponent() .getModelComponent().getSpesific(), Matchers.equalTo(HRMConstant.MODEL_COMP_BASIC_SALARY)))) { throw new BussinessException("global.error_user_does_not_have_basic_salary", empData.getNikWithFullName()); } for (PaySalaryComponent paySalaryComponent : listPayComponetNotExcp) { if (paySalaryComponent.getModelComponent().getSpesific().equals(HRMConstant.MODEL_COMP_UPLOAD)) { PayTempUploadData payUpload = this.payTempUploadDataDao .getEntityByEmpIdAndComponentId(empData.getId(), paySalaryComponent.getId()); if (payUpload != null) { PayTempKalkulasi kalkulasi = new PayTempKalkulasi(); kalkulasi.setId(Long.parseLong(RandomNumberUtil.getRandomNumber(12))); kalkulasi.setEmpData(empData); kalkulasi.setPaySalaryComponent(payUpload.getPaySalaryComponent()); kalkulasi.setFactor(this .getFactorBasedCategory(payUpload.getPaySalaryComponent().getComponentCategory())); BigDecimal nominal = new BigDecimal(payUpload.getNominalValue()); kalkulasi.setNominal(nominal); kalkulasi.setCreatedBy(createdBy); kalkulasi.setCreatedOn(createdOn); datas.add(kalkulasi); totalIncome = this.calculateTotalIncome(totalIncome, kalkulasi); //calculate totalIncome temporary LOGGER.info("Save By Upload - " + payUpload.getPaySalaryComponent().getName() + ", nominal : " + nominal); } } else if (paySalaryComponent.getModelComponent().getSpesific() .equals(HRMConstant.MODEL_COMP_BASIC_SALARY)) { PayTempKalkulasi kalkulasi = new PayTempKalkulasi(); kalkulasi.setId(Long.parseLong(RandomNumberUtil.getRandomNumber(12))); kalkulasi.setEmpData(empData); kalkulasi.setPaySalaryComponent(paySalaryComponent); kalkulasi.setFactor(this.getFactorBasedCategory(paySalaryComponent.getComponentCategory())); BigDecimal nominal = new BigDecimal(empData.getBasicSalaryDecrypted()); if ((timeTmb / 30) < 1) { //jika TMB belum memenuhi satu bulan, jadi basic salary dibagi pro-rate nominal = nominal.divide(new BigDecimal(timeTmb), RoundingMode.UP); } kalkulasi.setNominal(nominal); kalkulasi.setCreatedBy(createdBy); kalkulasi.setCreatedOn(createdOn); datas.add(kalkulasi); totalIncome = this.calculateTotalIncome(totalIncome, kalkulasi); //calculate totalIncome temporary LOGGER.info("Save By Basic Salary " + (((timeTmb / 30) < 1) ? "Not Full" : "Full") + ", nominal : " + nominal); } else if (paySalaryComponent.getModelComponent().getSpesific() .equals(HRMConstant.MODEL_COMP_LOAN)) { //cek apakah modelReferensi di paySalaryComponent valid atau tidak LoanNewType loanType = loanNewTypeDao .getEntiyByPK((long) paySalaryComponent.getModelReffernsil()); if (loanType == null) { throw new BussinessException("salaryCalculation.error_salary_component_reference", paySalaryComponent.getName()); } List<LoanNewApplicationInstallment> installments = loanNewApplicationInstallmentDao .getAllDataDisbursedByEmpDataIdAndLoanTypeIdAndPeriodDate(empData.getId(), loanType.getId(), startPeriodDate, endPeriodDate); for (LoanNewApplicationInstallment installment : installments) { PayTempKalkulasi kalkulasi = new PayTempKalkulasi(); kalkulasi.setId(Long.parseLong(RandomNumberUtil.getRandomNumber(12))); kalkulasi.setEmpData(empData); kalkulasi.setPaySalaryComponent(paySalaryComponent); kalkulasi.setFactor(this.getFactorBasedCategory(paySalaryComponent.getComponentCategory())); BigDecimal nominal = new BigDecimal(installment.getTotalPayment()); nominal = nominal.setScale(0, RoundingMode.UP); kalkulasi.setNominal(nominal); //set detail loan int termin = installment.getLoanNewApplication().getTermin(); long cicilanKe = termin - installment.getNumOfInstallment(); kalkulasi.setDetail(cicilanKe + "/" + termin); kalkulasi.setCreatedBy(createdBy); kalkulasi.setCreatedOn(createdOn); datas.add(kalkulasi); totalIncome = this.calculateTotalIncome(totalIncome, kalkulasi); //calculate totalIncome temporary LOGGER.info("Save By Loan - " + paySalaryComponent.getName() + ", nominal : " + nominal); } } else if (paySalaryComponent.getModelComponent().getSpesific() .equals(HRMConstant.MODEL_COMP_REIMBURSEMENT)) { //cek apakah modelReferensi di paySalaryComponent valid atau tidak RmbsType rmbsType = rmbsTypeDao.getEntiyByPK((long) paySalaryComponent.getModelReffernsil()); if (rmbsType == null) { throw new BussinessException("salaryCalculation.error_salary_component_reference", paySalaryComponent.getName()); } List<RmbsApplication> reimbursments = rmbsApplicationDao .getAllDataDisbursedByEmpDataIdAndRmbsTypeIdAndPeriodDate(empData.getId(), rmbsType.getId(), startPeriodDate, endPeriodDate); for (RmbsApplication reimbursment : reimbursments) { PayTempKalkulasi kalkulasi = new PayTempKalkulasi(); kalkulasi.setId(Long.parseLong(RandomNumberUtil.getRandomNumber(12))); kalkulasi.setEmpData(empData); kalkulasi.setPaySalaryComponent(paySalaryComponent); kalkulasi.setFactor(this.getFactorBasedCategory(paySalaryComponent.getComponentCategory())); kalkulasi.setNominal(reimbursment.getNominal()); //set detail reimbursement kalkulasi.setDetail(reimbursment.getCode()); kalkulasi.setCreatedBy(createdBy); kalkulasi.setCreatedOn(createdOn); datas.add(kalkulasi); totalIncome = this.calculateTotalIncome(totalIncome, kalkulasi); //calculate totalIncome temporary LOGGER.info("Save By Reimbursment, nominal : " + reimbursment.getNominal()); } } else if (paySalaryComponent.getModelComponent().getSpesific() .equals(HRMConstant.MODEL_COMP_FORMULA)) { String formulaOne = paySalaryComponent.getFormula(); if (formulaOne != null) { jsEngine.put("bS", basicSalary); jsEngine.put("wD", workingDay); jsEngine.put("lT", lessTime); jsEngine.put("mT", moreTime); jsEngine.put("oT", overTIme); jsEngine.put("tD", totalDay); outPut = (Double) jsEngine.eval(formulaOne); PayTempKalkulasi kalkulasi = new PayTempKalkulasi(); kalkulasi.setId(Long.parseLong(RandomNumberUtil.getRandomNumber(12))); kalkulasi.setEmpData(empData); kalkulasi.setPaySalaryComponent(paySalaryComponent); kalkulasi.setFactor(this.getFactorBasedCategory(paySalaryComponent.getComponentCategory())); BigDecimal nominal = new BigDecimal(outPut); kalkulasi.setNominal(nominal); kalkulasi.setCreatedBy(createdBy); kalkulasi.setCreatedOn(createdOn); datas.add(kalkulasi); totalIncome = this.calculateTotalIncome(totalIncome, kalkulasi); //calculate totalIncome temporary LOGGER.info("Save By Formula, nominal : " + nominal); } } else if (paySalaryComponent.getModelComponent().getSpesific() .equals(HRMConstant.MODEL_COMP_BENEFIT_TABLE)) { //cek apakah modelReferensi di paySalaryComponent valid atau tidak BenefitGroup benefitGroup = benefitGroupDao .getEntiyByPK((long) paySalaryComponent.getModelReffernsil()); if (benefitGroup == null) { throw new BussinessException("salaryCalculation.error_salary_component_reference", paySalaryComponent.getName()); } //cek apakah tunjangan yg didapatkan sesuai dengan hak dari golonganJabatan karyawan BenefitGroupRate benefitGroupRate = benefitGroupRateDao .getEntityByBenefitGroupIdAndGolJabatanId(benefitGroup.getId(), empData.getGolonganJabatan().getId()); if (benefitGroupRate != null) { PayTempKalkulasi kalkulasi = new PayTempKalkulasi(); kalkulasi.setId(Long.parseLong(RandomNumberUtil.getRandomNumber(12))); kalkulasi.setEmpData(empData); kalkulasi.setPaySalaryComponent(paySalaryComponent); kalkulasi.setFactor(this.getFactorBasedCategory(paySalaryComponent.getComponentCategory())); //nominal untuk benefit dikali nilai dari measurement BigDecimal nominal = new BigDecimal(benefitGroupRate.getNominal()).multiply(this .getMultiplierFromMeasurement(benefitGroupRate.getBenefitGroup().getMeasurement())); kalkulasi.setNominal(nominal); //set detail benefit kalkulasi.setDetail(benefitGroupRate.getGolonganJabatan().getCode()); kalkulasi.setCreatedBy(createdBy); kalkulasi.setCreatedOn(createdOn); datas.add(kalkulasi); totalIncome = this.calculateTotalIncome(totalIncome, kalkulasi); //calculate totalIncome temporary LOGGER.info("Save By Benefit - " + paySalaryComponent.getName() + ", nominal : " + nominal); } } } //create totalIncome Kalkulasi, hasil penjumlahan nominal dari semua component di atas PayTempKalkulasi totalIncomeKalkulasi = new PayTempKalkulasi(); totalIncomeKalkulasi.setId(Long.parseLong(RandomNumberUtil.getRandomNumber(12))); totalIncomeKalkulasi.setEmpData(empData); totalIncomeKalkulasi.setPaySalaryComponent(totalIncomeComponent); totalIncomeKalkulasi .setFactor(this.getFactorBasedCategory(totalIncomeComponent.getComponentCategory())); totalIncomeKalkulasi.setNominal(totalIncome); totalIncomeKalkulasi.setCreatedBy(createdBy); totalIncomeKalkulasi.setCreatedOn(createdOn); datas.add(totalIncomeKalkulasi); //create initial tax Kalkulasi, set nominal 0. Akan dibutuhkan di batch proses step selanjutnya PayTempKalkulasi taxKalkulasi = new PayTempKalkulasi(); taxKalkulasi.setId(Long.parseLong(RandomNumberUtil.getRandomNumber(12))); taxKalkulasi.setEmpData(empData); taxKalkulasi.setPaySalaryComponent(taxComponent); taxKalkulasi.setFactor(this.getFactorBasedCategory(taxComponent.getComponentCategory())); taxKalkulasi.setNominal(new BigDecimal(0)); taxKalkulasi.setCreatedBy(createdBy); taxKalkulasi.setCreatedOn(createdOn); datas.add(taxKalkulasi); //create initial ceil Kalkulasi, set nominal 0. Akan dibutuhkan di batch proses step selanjutnya PayTempKalkulasi ceilKalkulasi = new PayTempKalkulasi(); ceilKalkulasi.setId(Long.parseLong(RandomNumberUtil.getRandomNumber(12))); ceilKalkulasi.setEmpData(empData); ceilKalkulasi.setPaySalaryComponent(ceilComponent); ceilKalkulasi.setFactor(this.getFactorBasedCategory(ceilComponent.getComponentCategory())); ceilKalkulasi.setNominal(new BigDecimal(0)); ceilKalkulasi.setCreatedBy(createdBy); ceilKalkulasi.setCreatedOn(createdOn); datas.add(ceilKalkulasi); } return datas; }