List of usage examples for java.math BigDecimal subtract
public BigDecimal subtract(BigDecimal subtrahend)
From source file:com.nkapps.billing.dao.OverpaymentDaoImpl.java
@Override public void returnStateCommit(Session session, BankStatement bs, BigDecimal returnSum, Long issuerSerialNumber, String issuerIp, LocalDateTime dateTime) throws Exception { if (!bs.getBankStatementPayments().isEmpty()) { // if bankstatement has payments String q = " SELECT p.id AS id, p.tin AS tin, p.paymentNum AS paymentNum, p.paymentDate AS paymentDate," + " p.paymentSum AS paymentSum, p.sourceCode AS sourceCode," + " p.state AS state, p.tinDebtor as tinDebtor,p.claim as claim, p.issuerSerialNumber as issuerSerialNumber," + " p.issuerIp as issuerIp,p.dateCreated AS dateCreated, p.dateUpdated as dateUpdated, " + " p.paymentSum - COALESCE((SELECT SUM(paidSum) FROM KeyPayment kp WHERE kp.payment = p),0) AS overSum " + " FROM Payment p JOIN p.bankStatementPayment bsp " + " WHERE p.state IN (1,2) AND p.claim = 0 " + " AND bsp.id.bankStatement = :bs" + " ORDER BY p.paymentDate, p.paymentNum "; Query query = session.createQuery(q); query.setParameter("bs", bs); query.setResultTransformer(Transformers.aliasToBean(Payment.class)); List<Payment> paymentList = query.list(); for (Payment payment : paymentList) { if (payment.getOverSum().compareTo(returnSum) <= 0) { payment.setPaymentSum(payment.getPaymentSum().subtract(payment.getOverSum())); payment.setState((short) 3); // payment.setIssuerSerialNumber(issuerSerialNumber); payment.setIssuerIp(issuerIp); payment.setDateUpdated(dateTime); session.update(payment); returnSum = returnSum.subtract(payment.getOverSum()); } else { payment.setPaymentSum(payment.getPaymentSum().subtract(returnSum)); payment.setIssuerSerialNumber(issuerSerialNumber); payment.setIssuerIp(issuerIp); payment.setDateUpdated(dateTime); session.update(payment); returnSum = BigDecimal.ZERO; }// w ww. j a v a2 s.co m if (returnSum.compareTo(BigDecimal.ZERO) <= 0) { break; } } } }
From source file:com.wso2telco.dep.reportingservice.northbound.NbHostObjectUtils.java
/** * Apply charges with tax./*from www. j a v a 2 s.co m*/ * * @param apiYear the api year * @param apiMonth the api month * @param application the application * @param apiName the api name * @param apiVersion the api version * @param operatorSub the operator sub * @param CatEntry the cat entry * @param rate the rate * @throws Exception */ private static void applyChargesWithTax(String apiYear, String apiMonth, Application application, String apiName, String apiVersion, BillingSubscription.OperatorSubscription operatorSub, Map.Entry<CategoryCharge, BilledCharge> CatEntry, ChargeRate rate) throws Exception { String month = apiMonth; String year = apiYear; boolean isSurcharge = false; if (application == null) { throw new APIManagementException("no key generated for this api"); } APIKey prodKey = getAppKey(application, APIConstants.API_KEY_TYPE_PRODUCTION); TaxDAO taxDAO = new TaxDAO(); Set<APIRequestDTO> requestTimes = new HashSet<APIRequestDTO>(); if (prodKey != null) { String api_version = apiName + ":v" + apiVersion; requestTimes = taxDAO.getNbAPIRequestTimesForSubscription(Short.parseShort(year), Short.parseShort(month), apiName, api_version, prodKey.getConsumerKey(), operatorSub.getOperationId(), CatEntry.getKey().getCategory(), CatEntry.getKey().getSubcategory()); } // ChargeRate rate = operatorSub.getRate(); String billCategory = CatEntry.getKey().getCategory(); String billSubCategory = CatEntry.getKey().getSubcategory(); BigDecimal billRate = rate.getValue(); BigDecimal OpscomPercnt = null; Object SubsRate = getRateSubcategory(rate, billCategory, billSubCategory); if (SubsRate != null) { billRate = new BigDecimal((String) SubsRate); } // Surcharge value if (rate.getSurchargeEntity() != null) { billRate = new BigDecimal(rate.getSurchargeEntity().getSurchargeElementValue()); OpscomPercnt = new BigDecimal(rate.getSurchargeEntity().getSurchargeElementOpco()) .divide(new BigDecimal(100)); isSurcharge = true; } List<Tax> taxList = taxDAO.getTaxesForTaxList(rate.getTaxList()); BigDecimal totalCharge = BigDecimal.ZERO; BigDecimal totalTax = BigDecimal.ZERO; BigDecimal totalOpcom = BigDecimal.ZERO; BigDecimal totalAdscom = BigDecimal.ZERO; int reqCount = 0; for (APIRequestDTO req : requestTimes) { if (reqCount >= CatEntry.getValue().getCount()) { break; } BigDecimal charge = billRate.multiply(new BigDecimal(req.getRequestCount())); if (isSurcharge) { BigDecimal opcoCommision = billRate.multiply(OpscomPercnt); totalOpcom = totalOpcom.add(opcoCommision); totalAdscom = totalAdscom.add(charge.subtract(opcoCommision)); } else { totalCharge = totalCharge.add(charge); } Date date = req.getDate(); for (Tax tax : taxList) { // check if the date of payment request falls between this tax // validity period if (!date.before(tax.getEffective_from()) && !date.after(tax.getEffective_to())) { // totalTax += taxFraction x charge totalTax = totalTax.add(tax.getValue().multiply(charge)); } } reqCount++; } CatEntry.getValue().addPrice(totalCharge); CatEntry.getValue().addTax(totalTax); CatEntry.getValue().addOpcom(totalOpcom); CatEntry.getValue().addAdscom(totalAdscom); }
From source file:com.github.jonmarsh.waveform_processing_for_imagej.WaveformUtils.java
/** * Computes real roots for quadratic equation of the form * {@code ax^2 + bx + c = 0}, given real coefficients {@code a}, {@code b}, * and {@code c}. If there are two distinct roots, they are returned in a * two-element array. If there is a single root or two identical roots, the * result is returned in a single-element array. If there are no real-valued * roots, the function returns a zero-length array. Note that the * discriminant {@code b*b-4*a*c} contains the potential for catastrophic * cancellation if its two terms are nearly equal, so in this case the * algorithm uses {@code BigDecimal}s and methods described by W. Kahan in * "On the Cost of Floating-Point Computation Without Extra-Precise * Arithmetic"//from ww w .j a v a 2s .co m * (<a href="http://www.cs.berkeley.edu/~wkahan/Qdrtcs.pdf">www.cs.berkeley.edu/~wkahan/Qdrtcs.pdf/</a>), * which references TJ Dekker (A Floating-Point Technique for Extending the * Available Precision,? pp 234-242 in Numerische Mathematik 18, 1971). * * @param a quadratic coefficient * @param b linear coefficient * @param c constant term * @return array of distinct roots in order from least to greatest, or * zero-length array if there are no real-valued roots */ public static final double[] quadraticRoots(double a, double b, double c) { if (a == 0.0) { if (b == 0.0) { return new double[0]; } else { return new double[] { -c / b }; } } else if (b == 0.0) { if (c == 0.0) { return new double[] { 0.0 }; } else { double q = Math.sqrt(-c / a); return new double[] { -q, q }; } } else if (c == 0.0) { if (a == 0.0) { return new double[] { 0.0 }; } else { double r = -b / a; if (r < 0.0) { return new double[] { r, 0.0 }; } else { return new double[] { 0.0, r }; } } } else { double p = b * b; double q = 4.0 * a * c; double d = p - q; double sqrtD = Math.sqrt(d); double pie = 3; // see reference cited in javadoc for the origin of this number if (pie * Math.abs(d) < p + q) { BigDecimal aBD = new BigDecimal(a, MathContext.DECIMAL64); BigDecimal bBD = new BigDecimal(b, MathContext.DECIMAL64); BigDecimal cBD = new BigDecimal(c, MathContext.DECIMAL64); BigDecimal pBD = bBD.multiply(bBD); BigDecimal qBD = aBD.multiply(cBD).multiply(new BigDecimal(4, MathContext.DECIMAL64)); BigDecimal dBD = pBD.subtract(qBD); if (dBD.doubleValue() < 0) { // discriminant < 0.0 return new double[0]; } else if (dBD.doubleValue() == 0) { // discriminant is truly zero to double precision return new double[] { -b / (2.0 * a) }; } sqrtD = sqrt(dBD, MathContext.DECIMAL64).doubleValue(); } double s = -0.5 * (b + Math.signum(b) * sqrtD); double r1 = s / a; double r2 = c / s; if (r1 < r2) { return new double[] { r1, r2 }; } else if (r1 > r2) { return new double[] { r2, r1 }; } else { return new double[] { r1 }; } } }
From source file:com.salesmanager.core.service.order.OrderService.java
/** * Refunds an order, adjust the Order entity, add an OrderTotal object and * sends an email to the Customer//from w w w . ja v a2s. c om * * @param order * @param refundAmount * @throws Exception */ @Transactional public void refundOrder(Order order, BigDecimal refundAmount, Locale locale) throws Exception { MerchantService mservice = (MerchantService) ServiceFactory.getService(ServiceFactory.MerchantService); MerchantStore store = mservice.getMerchantStore(order.getMerchantId()); CustomerService cservice = (CustomerService) ServiceFactory.getService(ServiceFactory.CustomerService); Customer customer = cservice.getCustomer(order.getCustomerId()); PaymentService pservice = (PaymentService) ServiceFactory.getService(ServiceFactory.PaymentService); pservice.refundTransaction(store, order, refundAmount); // calculate new total !!!! BigDecimal newTotal = order.getTotal(); newTotal = newTotal.subtract(refundAmount); order.setTotal(newTotal); LabelUtil util = LabelUtil.getInstance(); util.setLocale(locale); // create a new total OrderTotal ot = new OrderTotal(); ot.setModule(OrderConstants.OT_REFUND); ot.setOrderId(order.getOrderId()); ot.setSortOrder(1000); ot.setTitle(util.getText("label.cart.refund")); ot.setValue(refundAmount); ot.setText(CurrencyUtil.getAmount(refundAmount, order.getCurrency())); orderTotalDao.saveOrUpdate(ot); // update status order.setOrderStatus(OrderConstants.STATUSREFUND); orderDao.saveOrUpdate(order); OrderImpl oImpl = new OrderImpl(); oImpl.sendOrderStatusEmail(order, util.getText("label.order.refundmessage", CurrencyUtil.displayFormatedAmountWithCurrency(refundAmount, order.getCurrency())), customer); }
From source file:org.projectforge.business.fibu.datev.EmployeeSalaryExportDao.java
/** * Exports the filtered list as table with almost all fields. *///from w w w. ja v a 2 s. co m @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW) public byte[] export(final List<EmployeeSalaryDO> list) { log.info("Exporting employee salary list."); Validate.notEmpty(list); Collections.sort(list, new Comparator<EmployeeSalaryDO>() { @Override public int compare(final EmployeeSalaryDO o1, final EmployeeSalaryDO o2) { return (o1.getEmployee().getUser().getFullname()) .compareTo(o2.getEmployee().getUser().getFullname()); } }); final EmployeeFilter filter = new EmployeeFilter(); filter.setShowOnlyActiveEntries(true); filter.setDeleted(false); final List<EmployeeDO> employees = employeeDao.getList(filter); final List<EmployeeDO> missedEmployees = new ArrayList<EmployeeDO>(); for (final EmployeeDO employee : employees) { boolean found = false; for (final EmployeeSalaryDO salary : list) { if (salary.getEmployeeId().equals(employee.getId()) == true) { found = true; break; } } if (found == false) { missedEmployees.add(employee); } } if (CollectionUtils.isNotEmpty(missedEmployees) == true) { Collections.sort(missedEmployees, new Comparator<EmployeeDO>() { @Override public int compare(final EmployeeDO o1, final EmployeeDO o2) { return (o1.getUser().getFullname()).compareTo(o2.getUser().getFullname()); } }); } final ExportWorkbook xls = new ExportWorkbook(); final ContentProvider contentProvider = new MyContentProvider(xls); // create a default Date format and currency column xls.setContentProvider(contentProvider); final EmployeeSalaryDO first = list.get(0); final int year = first.getYear(); final int month = first.getMonth(); final DayHolder buchungsdatum = new DayHolder(); buchungsdatum.setDate(year, month, 1); final MonthHolder monthHolder = new MonthHolder(buchungsdatum.getDate()); final BigDecimal numberOfWorkingDays = monthHolder.getNumberOfWorkingDays(); buchungsdatum.setEndOfMonth(); final String sheetTitle = DateHelper.formatMonth(year, month); final ExportSheet sheet = xls.addSheet(sheetTitle); sheet.createFreezePane(0, 1); final ExportSheet employeeSheet = xls.addSheet(ThreadLocalUserContext.getLocalizedString("fibu.employee")); employeeSheet.setColumnWidth(0, MyXlsContentProvider.LENGTH_USER * 256); employeeSheet.setColumnWidth(1, 14 * 256); employeeSheet.setColumnWidth(2, 12 * 256); employeeSheet.setColumnWidth(3, 12 * 256); employeeSheet.setColumnWidth(4, 12 * 256); final ContentProvider provider = employeeSheet.getContentProvider(); provider.putFormat("STUNDEN", "0.00;[Red]-0.00"); final ExportRow employeeRow = employeeSheet.addRow(); employeeRow.addCell(0, ThreadLocalUserContext.getLocalizedString("fibu.employee")); employeeRow.addCell(1, ThreadLocalUserContext.getLocalizedString("fibu.employee.wochenstunden")); employeeRow.addCell(2, ThreadLocalUserContext.getLocalizedString("fibu.employee.sollstunden")); employeeRow.addCell(3, ThreadLocalUserContext.getLocalizedString("fibu.employee.iststunden")); employeeRow.addCell(4, ThreadLocalUserContext.getLocalizedString("fibu.common.difference")); // build all column names, title, widths from fixed and variable columns final int numCols = ExcelColumn.values().length; final String[] colNames = new String[numCols]; final String[] colTitles = new String[numCols]; final int[] colWidths = new int[numCols]; int idx = 0; for (final ExcelColumn col : EnumSet.range(ExcelColumn.START, ExcelColumn.END)) { colNames[idx] = col.name(); colTitles[idx] = ThreadLocalUserContext.getLocalizedString(col.theTitle); colWidths[idx] = col.width; ++idx; } // column property names sheet.setPropertyNames(colNames); final ContentProvider sheetProvider = sheet.getContentProvider(); sheetProvider.putFormat("STUNDEN", "0.00"); sheetProvider.putFormat("BRUTTO_MIT_AG", "#,##0.00;[Red]-#,##0.00"); sheetProvider.putFormat("KORREKTUR", "#,##0.00;[Red]-#,##0.00"); sheetProvider.putFormat("SUMME", "#,##0.00;[Red]-#,##0.00"); sheetProvider.putFormat("KOST1", "#"); sheetProvider.putFormat("KOST2", "#"); sheetProvider.putFormat("KONTO", "#"); sheetProvider.putFormat("GEGENKONTO", "#"); sheetProvider.putFormat("DATUM", "dd.MM.yyyy"); // inform provider of column widths for (int ci = 0; ci < colWidths.length; ++ci) { sheetProvider.putColWidth(ci, colWidths[ci]); } final ExportRow headRow = sheet.addRow(); int i = 0; for (final String title : colTitles) { headRow.addCell(i++, title); } for (final EmployeeSalaryDO salary : list) { final PropertyMapping mapping = new PropertyMapping(); final PFUserDO user = getUserGroupCache().getUser(salary.getEmployee().getUserId()); Validate.isTrue(year == salary.getYear()); Validate.isTrue(month == salary.getMonth()); final MonthlyEmployeeReport report = monthlyEmployeeReportDao.getReport(year, month, user); mapping.add(ExcelColumn.MITARBEITER, user.getFullname()); final Kost1DO kost1 = salary.getEmployee().getKost1(); final BigDecimal bruttoMitAGAnteil = salary.getBruttoMitAgAnteil(); final BigDecimal netDuration = new BigDecimal(report.getTotalNetDuration()); final Map<String, Kost2Row> rows = report.getKost2Rows(); BigDecimal sum = BigDecimal.ZERO; int j = rows.size(); for (final Kost2Row row : rows.values()) { final Kost2DO kost2 = row.getKost2(); final MonthlyEmployeeReportEntry entry = report.getKost2Durations().get(kost2.getId()); mapping.add(ExcelColumn.KOST1, kost1.getNummer()); mapping.add(ExcelColumn.MITARBEITER, user.getFullname()); mapping.add(ExcelColumn.KOST2, kost2.getNummer()); final BigDecimal duration = new BigDecimal(entry.getMillis() / 1000); // Seconds // duration = duration.divide(new BigDecimal(60 * 60 * 24), 8, RoundingMode.HALF_UP); // Fraction of day (24 hours) // mapping.add(ExcelColumn.STUNDEN, duration); mapping.add(ExcelColumn.STUNDEN, duration.divide(new BigDecimal(3600), 2, RoundingMode.HALF_UP)); mapping.add(ExcelColumn.BEZEICHNUNG, kost2.getToolTip()); final BigDecimal betrag; if (NumberHelper.isNotZero(netDuration) == true) { betrag = CurrencyHelper.multiply(bruttoMitAGAnteil, new BigDecimal(entry.getMillis()).divide(netDuration, 8, RoundingMode.HALF_UP)); } else { betrag = BigDecimal.ZERO; } sum = sum.add(betrag); if (--j == 0) { final BigDecimal korrektur = bruttoMitAGAnteil.subtract(sum); mapping.add(ExcelColumn.BRUTTO_MIT_AG, betrag.add(korrektur)); mapping.add(ExcelColumn.KORREKTUR, korrektur); if (NumberHelper.isEqual(sum.add(korrektur), bruttoMitAGAnteil) == true) { mapping.add(ExcelColumn.SUMME, bruttoMitAGAnteil); } else { mapping.add(ExcelColumn.SUMME, "*** " + sum + " != " + bruttoMitAGAnteil); } } else { mapping.add(ExcelColumn.BRUTTO_MIT_AG, betrag); mapping.add(ExcelColumn.KORREKTUR, ""); mapping.add(ExcelColumn.SUMME, ""); } mapping.add(ExcelColumn.DATUM, buchungsdatum.getCalendar()); // Last day of month mapping.add(ExcelColumn.KONTO, KONTO); // constant. mapping.add(ExcelColumn.GEGENKONTO, GEGENKONTO); // constant. sheet.addRow(mapping.getMapping(), 0); } addEmployeeRow(employeeSheet, salary.getEmployee(), numberOfWorkingDays, netDuration); } for (final EmployeeDO employee : missedEmployees) { final PFUserDO user = getUserGroupCache().getUser(employee.getUserId()); final PropertyMapping mapping = new PropertyMapping(); mapping.add(ExcelColumn.MITARBEITER, user.getFullname()); mapping.add(ExcelColumn.SUMME, "***"); mapping.add(ExcelColumn.BEZEICHNUNG, "*** FEHLT! ***"); sheet.addRow(mapping.getMapping(), 0); final MonthlyEmployeeReport report = monthlyEmployeeReportDao.getReport(year, month, user); final BigDecimal netDuration = new BigDecimal(report.getTotalNetDuration()); addEmployeeRow(employeeSheet, employee, numberOfWorkingDays, netDuration); } // sheet.setZoom(3, 4); // 75% final ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { xls.write(baos); } catch (final IOException ex) { log.fatal("Exception encountered " + ex, ex); throw new RuntimeException(ex); } return baos.toByteArray(); }
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 av a 2 s. com*/ 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:com.wso2telco.dep.reportingservice.southbound.SbHostObjectUtils.java
/** * Apply charges with tax.//w ww . j a v a 2 s. com * * @param apiYear the api year * @param apiMonth the api month * @param application the application * @param apiName the api name * @param apiVersion the api version * @param operatorSub the operator sub * @param CatEntry the cat entry * @param rate the rate * @throws Exception */ private static void applyChargesWithTax(String apiYear, String apiMonth, Application application, String apiName, String apiVersion, BillingSubscription.OperatorSubscription operatorSub, Map.Entry<CategoryCharge, BilledCharge> CatEntry, ChargeRate rate) throws Exception { String month = apiMonth; String year = apiYear; boolean isSurcharge = false; if (application == null) { throw new APIManagementException("no key generated for this api"); } APIKey prodKey = getAppKey(application, APIConstants.API_KEY_TYPE_PRODUCTION); Set<APIRequestDTO> requestTimes = new HashSet<APIRequestDTO>(); if (prodKey != null) { String api_version = apiName + ":v" + apiVersion; TaxDAO taxDAO = new TaxDAO(); requestTimes = taxDAO.getAPIRequestTimesForSubscription(Short.parseShort(year), Short.parseShort(month), apiName, api_version, prodKey.getConsumerKey(), operatorSub.getOperator(), operatorSub.getOperationId(), CatEntry.getKey().getCategory(), CatEntry.getKey().getSubcategory()); } String billCategory = CatEntry.getKey().getCategory(); String billSubCategory = CatEntry.getKey().getSubcategory(); BigDecimal billRate = rate.getValue(); BigDecimal OpscomPercnt = null; Object SubsRate = getRateSubcategory(rate, billCategory, billSubCategory); if (SubsRate != null) { billRate = new BigDecimal((String) SubsRate); } // Surcharge value if (rate.getSurchargeEntity() != null) { billRate = new BigDecimal(rate.getSurchargeEntity().getSurchargeElementValue()); OpscomPercnt = new BigDecimal(rate.getSurchargeEntity().getSurchargeElementOpco()) .divide(new BigDecimal(100)); isSurcharge = true; } TaxDAO taxDAO = new TaxDAO(); List<Tax> taxList = taxDAO.getTaxesForTaxList(rate.getTaxList()); BigDecimal totalCharge = BigDecimal.ZERO; BigDecimal totalTax = BigDecimal.ZERO; BigDecimal totalOpcom = BigDecimal.ZERO; BigDecimal totalAdscom = BigDecimal.ZERO; int reqCount = 0; for (APIRequestDTO req : requestTimes) { if (reqCount >= CatEntry.getValue().getCount()) { break; } BigDecimal charge = billRate.multiply(new BigDecimal(req.getRequestCount())); if (isSurcharge) { BigDecimal opcoCommision = billRate.multiply(OpscomPercnt); totalOpcom = totalOpcom.add(opcoCommision); totalAdscom = totalAdscom.add(charge.subtract(opcoCommision)); } else { totalCharge = totalCharge.add(charge); } Date date = req.getDate(); for (Tax tax : taxList) { // check if the date of payment request falls between this tax // validity period if (!date.before(tax.getEffective_from()) && !date.after(tax.getEffective_to())) { totalTax = totalTax.add(tax.getValue().multiply(charge)); } } reqCount++; } CatEntry.getValue().addPrice(totalCharge); CatEntry.getValue().addTax(totalTax); CatEntry.getValue().addOpcom(totalOpcom); CatEntry.getValue().addAdscom(totalAdscom); }
From source file:org.kuali.ole.select.document.service.impl.OlePaymentRequestServiceImpl.java
/** * @see org.kuali.ole.select.document.service.OlePaymentRequestService#calculateProrateItemSurcharge(org.kuali.ole.select.document.OlePaymentRequestDocument) *//*from ww w. j a v a 2s . c o m*/ @Override public void calculateProrateItemSurcharge(OlePaymentRequestDocument paymentRequestDocument) { LOG.debug("Inside Calculation for ProrateItemSurcharge"); // KualiDecimal addChargeItem = paymentRequestDocument.getGrandPreTaxTotalExcludingDiscount().subtract(paymentRequestDocument.getLineItemPreTaxTotal()); BigDecimal addChargeItem = BigDecimal.ZERO; List<OlePaymentRequestItem> item = paymentRequestDocument.getItems(); for (OlePaymentRequestItem items : item) { if (!items.getItemType().isQuantityBasedGeneralLedgerIndicator() && !items.getItemTypeCode() .equalsIgnoreCase(PurapConstants.ItemTypeCodes.ITEM_TYPE_PMT_TERMS_DISCOUNT_CODE) && items.getItemUnitPrice() != null) { addChargeItem = addChargeItem.add(items.getItemUnitPrice()); } } List<BigDecimal> newUnitPriceList = new ArrayList<BigDecimal>(); BigDecimal totalExtPrice = new BigDecimal(0); BigDecimal newUnitPrice = new BigDecimal(0); BigDecimal extPrice = new BigDecimal(0); BigDecimal unitPricePercent = new BigDecimal(0); BigDecimal hundred = new BigDecimal(100); BigDecimal one = new BigDecimal(1); BigDecimal totalSurCharge = new BigDecimal(0); BigDecimal totalItemQuantity = new BigDecimal(0); BigDecimal itemSurchargeCons = new BigDecimal(0); for (int i = 0; item.size() > i; i++) { OlePaymentRequestItem items = (OlePaymentRequestItem) paymentRequestDocument.getItem(i); if ((items.getItemType().isQuantityBasedGeneralLedgerIndicator()) && !ObjectUtils.isNull(items.getItemQuantity())) { if (paymentRequestDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY)) { totalItemQuantity = totalItemQuantity.add(items.getItemQuantity().bigDecimalValue()); } if (paymentRequestDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_DOLLAR) || paymentRequestDocument.getProrateBy().equals(OLEConstants.MANUAL_PRORATE) || paymentRequestDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY)) { if (items.getItemDiscount() == null) { items.setItemDiscount(KualiDecimal.ZERO); } if (items.getItemDiscountType() != null && items.getItemDiscountType() .equalsIgnoreCase(OleSelectConstant.DISCOUNT_TYPE_PERCENTAGE)) { newUnitPrice = (hundred.subtract(items.getItemDiscount().bigDecimalValue())).divide(hundred) .multiply(items.getItemListPrice().bigDecimalValue()); } else { newUnitPrice = items.getItemListPrice().bigDecimalValue() .subtract(items.getItemDiscount().bigDecimalValue()); } newUnitPriceList.add(newUnitPrice); extPrice = newUnitPrice.multiply(items.getItemQuantity().bigDecimalValue()); totalExtPrice = totalExtPrice.add(extPrice); } if (paymentRequestDocument.getProrateBy().equals(OLEConstants.MANUAL_PRORATE)) { if (items.getItemSurcharge() == null) { items.setItemSurcharge(BigDecimal.ZERO); } totalSurCharge = totalSurCharge .add(items.getItemQuantity().bigDecimalValue().multiply(items.getItemSurcharge())); } } } if (paymentRequestDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY)) { if (totalItemQuantity.compareTo(BigDecimal.ZERO) != 0) { itemSurchargeCons = one.divide(totalItemQuantity, 8, RoundingMode.HALF_UP); } } for (int i = 0, j = 0; item.size() > i; i++) { OlePaymentRequestItem items = (OlePaymentRequestItem) paymentRequestDocument.getItem(i); if (items.getItemType().isQuantityBasedGeneralLedgerIndicator() && newUnitPriceList.size() > j && !ObjectUtils.isNull(items.getItemQuantity())) { if (paymentRequestDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_DOLLAR)) { if (totalExtPrice.compareTo(BigDecimal.ZERO) != 0) { unitPricePercent = newUnitPriceList.get(j).divide(totalExtPrice, 8, RoundingMode.HALF_UP); } items.setItemSurcharge( unitPricePercent.multiply(addChargeItem).setScale(4, RoundingMode.HALF_UP)); items.setItemUnitPrice(newUnitPriceList.get(j).add(items.getItemSurcharge())); } if (paymentRequestDocument.getProrateBy().equals(OLEConstants.PRORATE_BY_QTY)) { items.setItemSurcharge( itemSurchargeCons.multiply(addChargeItem).setScale(4, RoundingMode.HALF_UP)); items.setItemUnitPrice(newUnitPriceList.get(j).add(items.getItemSurcharge())); } if (paymentRequestDocument.getProrateBy().equals(OLEConstants.MANUAL_PRORATE) && items.getItemSurcharge() != null) { items.setItemUnitPrice(newUnitPriceList.get(j).add(items.getItemSurcharge())); } j++; } } if (paymentRequestDocument.getProrateBy().equals(OLEConstants.MANUAL_PRORATE)) { if (totalSurCharge.compareTo(addChargeItem) != 0) { GlobalVariables.getMessageMap().putError(PurapConstants.ITEM_TAB_ERROR_PROPERTY, OLEKeyConstants.ERROR_PAYMENT_REQUEST_TOTAL_MISMATCH); } } LOG.debug("Leaving Calculation for ProrateItemSurcharge"); }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * The natural logarithm.//from w w w. j a v a 2 s . com * * @param n The main argument, a strictly positive integer. * @param mc The requirements on the precision. * @return ln(n). */ static public BigDecimal log(int n, final MathContext mc) { /* the value is undefined if x is negative. */ if (n <= 0) { throw new ArithmeticException("Cannot take log of negative " + n); } else if (n == 1) { return BigDecimal.ZERO; } else if (n == 2) { if (mc.getPrecision() < LOG2.precision()) { return LOG2.round(mc); } else { /* Broadhurst \protect\vrule width0pt\protect\href{http://arxiv.org/abs/math/9803067}{arXiv:math/9803067} * Error propagation: the error in log(2) is twice the error in S(2,-5,...). */ int[] a = { 2, -5, -2, -7, -2, -5, 2, -3 }; BigDecimal S = broadhurstBBP(2, 1, a, new MathContext(1 + mc.getPrecision())); S = S.multiply(new BigDecimal(8)); S = sqrt(divideRound(S, 3)); return S.round(mc); } } else if (n == 3) { /* summation of a series roughly proportional to (7/500)^k. Estimate count * of terms to estimate the precision (drop the favorable additional * 1/k here): 0.013^k <= 10^(-precision), so k*log10(0.013) <= -precision * so k>= precision/1.87. */ int kmax = (int) (mc.getPrecision() / 1.87); MathContext mcloc = new MathContext(mc.getPrecision() + 1 + (int) (Math.log10(kmax * 0.693 / 1.098))); BigDecimal log3 = multiplyRound(log(2, mcloc), 19); /* log3 is roughly 1, so absolute and relative error are the same. The * result will be divided by 12, so a conservative error is the one * already found in mc */ double eps = prec2err(1.098, mc.getPrecision()) / kmax; Rational r = new Rational(7153, 524288); Rational pk = new Rational(7153, 524288); for (int k = 1;; k++) { Rational tmp = pk.divide(k); if (tmp.doubleValue() < eps) { break; } /* how many digits of tmp do we need in the sum? */ mcloc = new MathContext(err2prec(tmp.doubleValue(), eps)); BigDecimal c = pk.divide(k).BigDecimalValue(mcloc); if (k % 2 != 0) { log3 = log3.add(c); } else { log3 = log3.subtract(c); } pk = pk.multiply(r); } log3 = divideRound(log3, 12); return log3.round(mc); } else if (n == 5) { /* summation of a series roughly proportional to (7/160)^k. Estimate count * of terms to estimate the precision (drop the favorable additional * 1/k here): 0.046^k <= 10^(-precision), so k*log10(0.046) <= -precision * so k>= precision/1.33. */ int kmax = (int) (mc.getPrecision() / 1.33); MathContext mcloc = new MathContext(mc.getPrecision() + 1 + (int) (Math.log10(kmax * 0.693 / 1.609))); BigDecimal log5 = multiplyRound(log(2, mcloc), 14); /* log5 is roughly 1.6, so absolute and relative error are the same. The * result will be divided by 6, so a conservative error is the one * already found in mc */ double eps = prec2err(1.6, mc.getPrecision()) / kmax; Rational r = new Rational(759, 16384); Rational pk = new Rational(759, 16384); for (int k = 1;; k++) { Rational tmp = pk.divide(k); if (tmp.doubleValue() < eps) { break; } /* how many digits of tmp do we need in the sum? */ mcloc = new MathContext(err2prec(tmp.doubleValue(), eps)); BigDecimal c = pk.divide(k).BigDecimalValue(mcloc); log5 = log5.subtract(c); pk = pk.multiply(r); } log5 = divideRound(log5, 6); return log5.round(mc); } else if (n == 7) { /* summation of a series roughly proportional to (1/8)^k. Estimate count * of terms to estimate the precision (drop the favorable additional * 1/k here): 0.125^k <= 10^(-precision), so k*log10(0.125) <= -precision * so k>= precision/0.903. */ int kmax = (int) (mc.getPrecision() / 0.903); MathContext mcloc = new MathContext( mc.getPrecision() + 1 + (int) (Math.log10(kmax * 3 * 0.693 / 1.098))); BigDecimal log7 = multiplyRound(log(2, mcloc), 3); /* log7 is roughly 1.9, so absolute and relative error are the same. */ double eps = prec2err(1.9, mc.getPrecision()) / kmax; Rational r = new Rational(1, 8); Rational pk = new Rational(1, 8); for (int k = 1;; k++) { Rational tmp = pk.divide(k); if (tmp.doubleValue() < eps) { break; } /* how many digits of tmp do we need in the sum? */ mcloc = new MathContext(err2prec(tmp.doubleValue(), eps)); BigDecimal c = pk.divide(k).BigDecimalValue(mcloc); log7 = log7.subtract(c); pk = pk.multiply(r); } return log7.round(mc); } else { /* At this point one could either forward to the log(BigDecimal) signature (implemented) * or decompose n into Ifactors and use an implemenation of all the prime bases. * Estimate of the result; convert the mc argument to an absolute error eps * log(n+errn) = log(n)+errn/n = log(n)+eps */ double res = Math.log((double) n); double eps = prec2err(res, mc.getPrecision()); /* errn = eps*n, convert absolute error in result to requirement on absolute error in input */ eps *= n; /* Convert this absolute requirement of error in n to a relative error in n */ final MathContext mcloc = new MathContext(1 + err2prec((double) n, eps)); /* Padd n with a number of zeros to trigger the required accuracy in * the standard signature method */ BigDecimal nb = scalePrec(new BigDecimal(n), mcloc); return log(nb); } }
From source file:org.egov.works.services.AbstractEstimateService.java
public Map<String, List> addApprovedEstimateResultList(final List<BudgetFolioDetail> budgetFolioResultList, final List<BudgetUsage> budgetUsageList, final BigDecimal totalGrantPerc) { int srlNo = 1; Double cumulativeTotal = 0.00D; BigDecimal balanceAvailable = BigDecimal.ZERO; final Map<String, List> budgetFolioMap = new HashMap<String, List>(); for (final BudgetUsage budgetUsage : budgetUsageList) { final BudgetFolioDetail budgetFolioDetail = new BudgetFolioDetail(); budgetFolioDetail.setSrlNo(srlNo++); final AbstractEstimate estimate = find("from AbstractEstimate ae where ae.estimateNumber=?", budgetUsage.getReferenceNumber()); if (estimate != null) { budgetFolioDetail.setEstimateNo(estimate.getEstimateNumber()); budgetFolioDetail.setNameOfWork(estimate.getName()); budgetFolioDetail.setWorkValue(estimate.getTotalAmount().getValue()); budgetFolioDetail.setEstimateDate(sdf.format(estimate.getEstimateDate())); }/* w ww.j av a 2 s . c om*/ budgetFolioDetail.setBudgetApprNo(budgetUsage.getAppropriationnumber()); budgetFolioDetail.setCumulativeTotal(cumulativeTotal); balanceAvailable = totalGrantPerc.subtract(new BigDecimal(cumulativeTotal)); budgetFolioDetail.setBalanceAvailable(balanceAvailable); budgetFolioDetail.setAppDate(sdf.format(new Date(budgetUsage.getUpdatedTime().getTime()))); budgetFolioDetail.setAppType(getApporpriationType(budgetUsage.getId())); budgetFolioResultList.add(budgetFolioDetail); if (budgetUsage.getReleasedAmount() > 0) { cumulativeTotal = cumulativeTotal - budgetUsage.getReleasedAmount(); budgetFolioDetail.setAppropriatedValue(0.0 - budgetUsage.getReleasedAmount()); } else { cumulativeTotal = cumulativeTotal + budgetUsage.getConsumedAmount(); budgetFolioDetail.setAppropriatedValue(budgetUsage.getConsumedAmount()); } } final List calculatedValuesList = new ArrayList(); calculatedValuesList.add(cumulativeTotal); calculatedValuesList.add(totalGrantPerc.subtract(new BigDecimal(cumulativeTotal))); budgetFolioMap.put("budgetFolioList", budgetFolioResultList); budgetFolioMap.put("calculatedValues", calculatedValuesList); return budgetFolioMap; }