List of usage examples for java.math BigDecimal toString
@Override
public String toString()
From source file:com.salesmanager.core.module.impl.integration.payment.MonerisTransactionImpl.java
public GatewayTransactionVO refundTransaction(IntegrationKeys keys, IntegrationProperties props, MerchantStore store, Order order, GatewayTransactionVO trx, Customer customer, CoreModuleService cis, BigDecimal amount) throws TransactionException { try {/*from w w w .java 2 s . c o m*/ String uniqueOrderId = trx.getInternalGatewayOrderId(); String host = cis.getCoreModuleServiceDevDomain(); if (props.getProperties2().equals(String.valueOf(PaymentConstants.PRODUCTION_ENVIRONMENT))) { host = cis.getCoreModuleServiceProdDomain(); } String store_id = keys.getUserid(); String api_token = keys.getTransactionKey(); String order_id = trx.getInternalGatewayOrderId(); String amnt = amount.toString(); String txn_number = trx.getTransactionID(); String crypt = "7"; // For saving the amount in the transaction tables // order.setTotal(amount); HttpsPostRequest mpgReq = new HttpsPostRequest(host, store_id, api_token, new Refund(uniqueOrderId, amnt, txn_number, crypt)); log.debug(mpgReq.toString()); Receipt receipt = null; receipt = mpgReq.getReceipt(); /* * System.out.println("CardType = " + receipt.getCardType()); * System.out.println("TransAmount = " + receipt.getTransAmount()); * System.out.println("TxnNumber = " + receipt.getTxnNumber()); * System.out.println("ReceiptId = " + receipt.getReceiptId()); * System.out.println("TransType = " + receipt.getTransType()); * System.out.println("ReferenceNum = " + * receipt.getReferenceNum()); System.out.println("ResponseCode = " * + receipt.getResponseCode()); System.out.println("ISO = " + * receipt.getISO()); System.out.println("BankTotals = " + * receipt.getBankTotals()); System.out.println("Message = " + * receipt.getMessage()); System.out.println("AuthCode = " + * receipt.getAuthCode()); System.out.println("Complete = " + * receipt.getComplete()); System.out.println("TransDate = " + * receipt.getTransDate()); System.out.println("TransTime = " + * receipt.getTransTime()); System.out.println("Ticket = " + * receipt.getTicket()); System.out.println("TimedOut = " + * receipt.getTimedOut()); */ if (receipt.getComplete().equals("false")) { log.error("Cannot proceed to refund " + receipt.getMessage()); TransactionException e = new TransactionException( "Cannot proceed to refund " + receipt.getMessage()); e.setReason(receipt.getMessage()); throw e; } return this.parseResponse(PaymentConstants.REFUND, uniqueOrderId, mpgReq, order, amount, receipt); } catch (Exception e) { log.error("Error while processing the transaction" + e.getMessage()); // throw new Exception("Error while processing the transaction",e); TransactionException pe = new TransactionException( "Error while processing the transaction" + e.getMessage()); pe.setErrorcode("01"); throw pe; } }
From source file:com.konakart.bl.modules.payment.cyberpac.Cyberpac.java
/** * Return a payment details object for Cyberpac * // www .j a v a2 s . c o m * @param order * @param info * @return Returns information in a PaymentDetails object * @throws Exception */ public PaymentDetails getPaymentDetails(Order order, PaymentInfo info) throws Exception { StaticData sd = staticDataHM.get(getStoreId()); /* * The CyberpacZone zone, if greater than zero, should reference a GeoZone. If the * DeliveryAddress of the order isn't within that GeoZone, then we throw an exception */ if (sd.getZone() > 0) { checkZone(info, sd.getZone()); } // Get the scale for currency calculations int scale = new Integer(order.getCurrency().getDecimalPlaces()).intValue(); // Get the resource bundle ResourceBundle rb = getResourceBundle(mutex, bundleName, resourceBundleMap, info.getLocale()); if (rb == null) { throw new KKException( "A resource file cannot be found for the country " + info.getLocale().getCountry()); } PaymentDetails pDetails = new PaymentDetails(); pDetails.setCode(code); pDetails.setSortOrder(sd.getSortOrder()); pDetails.setPaymentType(PaymentDetails.BROWSER_PAYMENT_GATEWAY); pDetails.setDescription(rb.getString(MODULE_PAYMENT_CYBERPAC_TEXT_DESCRIPTION)); pDetails.setTitle(rb.getString(MODULE_PAYMENT_CYBERPAC_TEXT_TITLE)); // Return now if the full payment details aren't required. This happens when the manager // just wants a list of payment gateways to display in the UI. if (info.isReturnDetails() == false) { return pDetails; } pDetails.setPostOrGet("post"); pDetails.setRequestUrl(sd.getRequestUrl()); List<NameValue> parmList = new ArrayList<NameValue>(); /* * Parameters posted to gateway */ // Total BigDecimal total = null; for (int i = 0; i < order.getOrderTotals().length; i++) { OrderTotal ot = (OrderTotal) order.getOrderTotals()[i]; if (ot.getClassName().equals(OrderTotalMgr.ot_total)) { total = ot.getValue().setScale(scale, BigDecimal.ROUND_HALF_UP); } } if (total == null) { throw new KKException("An Order Total was not found in the order id = " + order.getId()); } parmList.add(new NameValue("Ds_Merchant_Amount", total.toString())); // Currency String currCode = null; if (order.getCurrency().getCode().equalsIgnoreCase("EUR")) { currCode = "978"; } else if (order.getCurrency().getCode().equalsIgnoreCase("USD")) { currCode = "840"; } else if (order.getCurrency().getCode().equalsIgnoreCase("GBP")) { currCode = "826"; } else if (order.getCurrency().getCode().equalsIgnoreCase("JPY")) { currCode = "392"; } else { throw new KKException("The currency with code = " + order.getCurrency().getCode() + " is not supported by the Cyberpac payment gateway."); } String ds_Merchant_Currency = currCode; parmList.add(new NameValue("Ds_Merchant_Currency", ds_Merchant_Currency)); // Various String ds_Merchant_Order = Integer.toString(order.getId()); parmList.add(new NameValue("Ds_Merchant_Order", ds_Merchant_Order)); parmList.add(new NameValue("Ds_Merchant_ProductDescription", rb.getString(MODULE_PAYMENT_CYBERPAC_CUSTOMER_MSG) + " " + order.getId())); parmList.add(new NameValue("Ds_Merchant_Cardholder", order.getBillingName())); String ds_Merchant_MerchantCode = sd.getMerchantCode(); parmList.add(new NameValue("Ds_Merchant_MerchantCode", ds_Merchant_MerchantCode)); parmList.add(new NameValue("Ds_Merchant_MerchantURL", sd.getCallbackUrl())); if (sd.getRedirectKOUrl() != null && sd.getRedirectKOUrl().length() > 0) { parmList.add(new NameValue("Ds_Merchant_UrlKO", sd.getRedirectKOUrl())); } if (sd.getRedirectOKUrl() != null && sd.getRedirectOKUrl().length() > 0) { parmList.add(new NameValue("Ds_Merchant_UrlOK", sd.getRedirectOKUrl())); } String lang = "001"; // Default Spanish Castellano String langCode = order.getLocale().substring(0, 2); if (order.getLocale().equalsIgnoreCase("ca_ES")) { lang = "003"; } else if (langCode.equalsIgnoreCase("en")) { lang = "002"; } else if (langCode.equalsIgnoreCase("fr")) { lang = "004"; } else if (langCode.equalsIgnoreCase("de")) { lang = "005"; } else if (langCode.equalsIgnoreCase("it")) { lang = "007"; } else if (langCode.equalsIgnoreCase("pt")) { lang = "009"; } else if (order.getLocale().equalsIgnoreCase("eu_ES")) { lang = "013"; } else if (langCode.equalsIgnoreCase("ru")) { lang = "014"; } parmList.add(new NameValue("Ds_Merchant_ConsumerLanguage", lang)); parmList.add(new NameValue("Ds_Merchant_Terminal", sd.getTerminalNumber())); if (sd.getTransactionType() != null && sd.getTransactionType().length() > 0) { parmList.add(new NameValue("Ds_Merchant_TransactionType", sd.getTransactionType())); } else { parmList.add(new NameValue("Ds_Merchant_TransactionType", "2")); } // Data passed to us in callback. Need to create a session SSOTokenIf ssoToken = new SSOToken(); String sessionId = getEng().login(sd.getCallbackUsername(), sd.getCallbackPassword()); if (sessionId == null) { throw new KKException( "Unable to log into the engine using the Cyberpac Callback Username and Password"); } ssoToken.setSessionId(sessionId); ssoToken.setCustom1(String.valueOf(order.getId())); // Save the SSOToken with a valid sessionId and the order id in custom1 String uuid = getEng().saveSSOToken(ssoToken); parmList.add(new NameValue("Ds_Merchant_MerchantData", uuid)); // Sign the data // Digest=SHA-1(Ds_Merchant_Amount + Ds_Merchant_Order +Ds_Merchant_MerchantCode // + DS_Merchant_Currency + SECRET CODE) String ds_Merchant_Amount = (total.multiply(new BigDecimal(100))).toString(); String stringToSign = ds_Merchant_Amount + ds_Merchant_Order + ds_Merchant_MerchantCode + ds_Merchant_Currency + sd.getSecretSigningCode(); MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] digest = md.digest(stringToSign.getBytes("UTF8")); String hexEncodedDigest = (Hex.encodeHex(digest)).toString(); parmList.add(new NameValue("Ds_Merchant_MerchantSignature", hexEncodedDigest)); if (log.isDebugEnabled()) { StringBuffer str = new StringBuffer(); str.append("Parameters to sign:").append("\n"); str.append("Ds_Merchant_Amount = ").append(ds_Merchant_Amount).append("\n"); str.append("Ds_Merchant_Order = ").append(ds_Merchant_Order).append("\n"); str.append("Ds_Merchant_MerchantCode = ").append(ds_Merchant_MerchantCode).append("\n"); str.append("Ds_Merchant_Currency = ").append(ds_Merchant_Currency).append("\n"); str.append("Secret Code = ").append(sd.getSecretSigningCode()).append("\n"); str.append("String to sign = ").append(stringToSign).append("\n"); str.append("SHA-1 result = ").append(hexEncodedDigest).append("\n"); log.debug(str); } // Put the parameters into an array NameValue[] nvArray = new NameValue[parmList.size()]; parmList.toArray(nvArray); pDetails.setParameters(nvArray); if (log.isDebugEnabled()) { log.debug(pDetails.toString()); } return pDetails; }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * The square root.//from w ww . j a v a 2s . c o m * * @param x the non-negative argument. * @return the square root of the BigDecimal rounded to the precision implied by x. */ static public BigDecimal sqrt(final BigDecimal x) { if (x.compareTo(BigDecimal.ZERO) < 0) { throw new ArithmeticException("negative argument " + x.toString() + " of square root"); } return root(2, x); }
From source file:org.openvpms.esci.adapter.map.invoice.InvoiceMapperImpl.java
/** * Returns the package size.//from ww w . j a v a 2 s. c o m * * @param line the invoice line * @param pkg the expected package, or <tt>null</tt> if it is not known * @return the package size, or <tt>0</tt> if it is not known * @throws ESCIAdapterException if the package size is incorrectly specified */ private int getPackageSize(UBLInvoiceLine line, Package pkg) { int result; BigDecimal packageSize = line.getPackSizeNumeric(); int expectedSize = (pkg != null) ? pkg.getPackageSize() : 0; int invoiceSize; try { invoiceSize = packageSize.intValueExact(); } catch (ArithmeticException exception) { ErrorContext context = new ErrorContext(line, "PackSizeNumeric"); String intValue = Integer.toString(packageSize.intValue()); throw new ESCIAdapterException(ESCIAdapterMessages.ublInvalidValue(context.getPath(), context.getType(), context.getID(), intValue, packageSize.toString())); } if (expectedSize != 0) { if (invoiceSize != 0 && invoiceSize != expectedSize) { log.warn("Different package size received for invoice. Expected package size=" + expectedSize + ", invoiced package size=" + invoiceSize); // TODO - log context } result = expectedSize; } else { result = invoiceSize; } return result; }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * The inverse hyperbolic cosine./*from w w w . j ava 2s . com*/ * * @param x The argument. * @return The arccosh(x) . */ static public BigDecimal acosh(final BigDecimal x) { if (x.compareTo(BigDecimal.ONE) < 0) { throw new ArithmeticException("Out of range argument cosh " + x.toString()); } else if (x.compareTo(BigDecimal.ONE) == 0) { return BigDecimal.ZERO; } else { BigDecimal xhighpr = scalePrec(x, 2); /* arccosh(x) = log(x+sqrt(x^2-1)) */ BigDecimal logx = log(sqrt(xhighpr.pow(2).subtract(BigDecimal.ONE)).add(xhighpr)); /* The absolute error in arcsinh x is err(x)/sqrt(x^2-1) */ double xDbl = x.doubleValue(); double eps = 0.5 * x.ulp().doubleValue() / Math.sqrt(xDbl * xDbl - 1.); MathContext mc = new MathContext(err2prec(logx.doubleValue(), eps)); return logx.round(mc); } }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * The integer root.//from w w w . j a va2s . c o m * * @param n the positive argument. * @param x the non-negative argument. * @return The n-th root of the BigDecimal rounded to the precision implied by x, x^(1/n). */ static public BigDecimal root(final int n, final BigDecimal x) { if (x.compareTo(BigDecimal.ZERO) < 0) { throw new ArithmeticException("negative argument " + x.toString() + " of root"); } if (n <= 0) { throw new ArithmeticException("negative power " + n + " of root"); } if (n == 1) { return x; } /* start the computation from a double precision estimate */ BigDecimal s = new BigDecimal(Math.pow(x.doubleValue(), 1.0 / n)); /* this creates nth with nominal precision of 1 digit */ final BigDecimal nth = new BigDecimal(n); /* Specify an internal accuracy within the loop which is * slightly larger than what is demanded by eps below. */ final BigDecimal xhighpr = scalePrec(x, 2); MathContext mc = new MathContext(2 + x.precision()); /* Relative accuracy of the result is eps. */ final double eps = x.ulp().doubleValue() / (2 * n * x.doubleValue()); for (;;) { /* s = s -(s/n-x/n/s^(n-1)) = s-(s-x/s^(n-1))/n; test correction s/n-x/s for being * smaller than the precision requested. The relative correction is (1-x/s^n)/n, */ BigDecimal c = xhighpr.divide(s.pow(n - 1), mc); c = s.subtract(c); MathContext locmc = new MathContext(c.precision()); c = c.divide(nth, locmc); s = s.subtract(c); if (Math.abs(c.doubleValue() / s.doubleValue()) < eps) { break; } } return s.round(new MathContext(err2prec(eps))); }
From source file:org.mifos.accounts.servicefacade.WebTierAccountServiceFacade.java
@Override public void applyHistoricalAdjustment(String globalAccountNum, Integer paymentId, String adjustmentNote, Short personnelId, AdjustedPaymentDto adjustedPaymentDto) { try {/*from w w w . ja v a2 s . c o m*/ AccountBO accountBO = accountBusinessService.findBySystemId(globalAccountNum); accountBO.setUserContext(getUserContext()); checkPermissionForAdjustment(accountBO); PersonnelBO personnelBO = personnelPersistence.findPersonnelById(personnelId); AccountPaymentEntity accountPaymentEntity = accountBO.findPaymentById(paymentId); if (accountPaymentEntity == null) { throw new AccountException(AccountExceptionConstants.CANNOTADJUST); } monthClosingServiceFacade.validateTransactionDate(accountPaymentEntity.getPaymentDate()); PaymentDto otherTransferPayment = accountPaymentEntity.getOtherTransferPaymentDto(); transactionHelper.flushAndClearSession(); //flush to avoid proxy casting problems transactionHelper.startTransaction(); Integer newSavingsPaymentId = null; if (otherTransferPayment != null) { SavingsAdjustmentDto savingsAdjustment = new SavingsAdjustmentDto( otherTransferPayment.getAccountId().longValue(), (adjustedPaymentDto == null) ? 0 : Double.valueOf(adjustedPaymentDto.getAmount()), adjustmentNote, otherTransferPayment.getPaymentId(), (adjustedPaymentDto == null) ? otherTransferPayment.getPaymentDate() : new LocalDate(adjustedPaymentDto.getPaymentDate())); PaymentDto newSavingsPayment = this.savingsServiceFacade.adjustTransaction(savingsAdjustment, true); newSavingsPaymentId = (newSavingsPayment == null) ? null : newSavingsPayment.getPaymentId(); } //reload after flush & clear accountBO = accountBusinessService.findBySystemId(globalAccountNum); accountBO.setUserContext(getUserContext()); AccountPaymentEntity adjustedPayment = null; Integer adjustedId; Stack<PaymentData> paymentsToBeReapplied = new Stack<PaymentData>(); Map<Integer, Stack<PaymentData>> memberPaymentsToBeReappliedMap = new HashMap<Integer, Stack<PaymentData>>(); if (accountBO.isGroupLoanAccount()) { for (LoanBO memberAccount : ((LoanBO) accountBO).getMemberAccounts()) { Stack<PaymentData> memberPaymentsToBeReapplied = new Stack<PaymentData>(); memberPaymentsToBeReappliedMap.put(memberAccount.getAccountId(), memberPaymentsToBeReapplied); } } do { adjustedPayment = accountBO.getLastPmntToBeAdjusted(); if (adjustedPayment == null) { break; } adjustedId = adjustedPayment.getPaymentId(); if (!accountPaymentEntity.getPaymentId().equals(adjustedId)) { PersonnelBO paymentCreator = (adjustedPayment.getCreatedByUser() == null) ? personnelBO : adjustedPayment.getCreatedByUser(); PaymentData paymentData = accountBO.createPaymentData(adjustedPayment.getAmount(), adjustedPayment.getPaymentDate(), adjustedPayment.getReceiptNumber(), adjustedPayment.getReceiptDate(), adjustedPayment.getPaymentType().getId(), paymentCreator); paymentData.setOtherTransferPayment(adjustedPayment.getOtherTransferPayment()); paymentsToBeReapplied.push(paymentData); // handling new Group Loan Members payments for (AccountPaymentEntity memberAdjustedPayment : adjustedPayment.getMemberPayments()) { PaymentData memberPaymentData = memberAdjustedPayment.getAccount().createPaymentData( memberAdjustedPayment.getAmount(), adjustedPayment.getPaymentDate(), adjustedPayment.getReceiptNumber(), adjustedPayment.getReceiptDate(), adjustedPayment.getPaymentType().getId(), paymentCreator); memberPaymentsToBeReappliedMap.get(memberAdjustedPayment.getAccount().getAccountId()) .push(memberPaymentData); } } transactionHelper.flushAndClearSession(); //reload after flush & clear accountBO = accountBusinessService.findBySystemId(globalAccountNum); accountBO.setUserContext(getUserContext()); accountBO.adjustLastPayment(adjustmentNote, personnelBO); legacyAccountDao.createOrUpdate(accountBO); //adjust New Group Loan member payments if (accountBO.isGroupLoanAccount()) { for (LoanBO memberAccount : ((LoanBO) accountBO).getMemberAccounts()) { AccountPaymentEntity memberPayment = memberAccount.getLastPmntToBeAdjusted(); if (memberPayment.getParentPaymentId() == null || !memberPayment.getParentPaymentId() .getPaymentId().equals(accountPaymentEntity.getPaymentId())) { continue; } memberAccount.setUserContext(getUserContext()); memberAccount.adjustLastPayment(adjustmentNote, personnelBO); legacyAccountDao.createOrUpdate(memberAccount); } } transactionHelper.flushSession(); } while (!accountPaymentEntity.getPaymentId().equals(adjustedId)); if (adjustedPaymentDto != null) { //reapply adjusted payment PersonnelBO paymentCreator = (accountPaymentEntity.getCreatedByUser() == null) ? personnelBO : accountPaymentEntity.getCreatedByUser(); Money amount = new Money(accountBO.getCurrency(), adjustedPaymentDto.getAmount()); PaymentData paymentData = accountBO.createPaymentData(amount, adjustedPaymentDto.getPaymentDate(), accountPaymentEntity.getReceiptNumber(), accountPaymentEntity.getReceiptDate(), adjustedPaymentDto.getPaymentType(), paymentCreator); //new adjusted savings payment must be tied to this payment if (newSavingsPaymentId != null) { AccountPaymentEntity newSvngPayment = legacyAccountDao.findPaymentById(newSavingsPaymentId); paymentData.setOtherTransferPayment(newSvngPayment); } accountBO.applyPayment(paymentData); legacyAccountDao.createOrUpdate(accountBO); transactionHelper.flushSession(); // handling new Group Loan Members payments if (accountBO.isGroupLoanAccount()) { for (AdjustedPaymentDto adjustedMemberPayment : adjustedPaymentDto.getMemberPayments()) { AccountBO memberAccount = ((LoanBO) accountBO) .findMemberById(adjustedMemberPayment.getAccountId()); BigDecimal adjustedMemberPaymentAmount = BigDecimal.ZERO; if (!StringUtils.isBlank(adjustedMemberPayment.getAmount())) { adjustedMemberPaymentAmount = new BigDecimal(adjustedMemberPayment.getAmount()); } Money memberAmount = new Money(memberAccount.getCurrency(), adjustedMemberPaymentAmount.toString()); PaymentData memberPaymentData = memberAccount.createPaymentData(memberAmount, adjustedPaymentDto.getPaymentDate(), accountPaymentEntity.getReceiptNumber(), accountPaymentEntity.getReceiptDate(), adjustedPaymentDto.getPaymentType(), paymentCreator); memberPaymentData.setParentPayment(accountBO.getLastPmnt()); memberAccount.applyPayment(memberPaymentData); legacyAccountDao.createOrUpdate(memberAccount); } } } while (!paymentsToBeReapplied.isEmpty()) { PaymentData paymentData = paymentsToBeReapplied.pop(); //avoid lazy loading exception if (paymentData.getOtherTransferPayment() != null) { legacyAccountDao.updatePayment(paymentData.getOtherTransferPayment()); } accountBO.applyPayment(paymentData); legacyAccountDao.createOrUpdate(accountBO); transactionHelper.flushSession(); if (accountBO.isGroupLoanAccount()) { for (LoanBO memberAccount : ((LoanBO) accountBO).getMemberAccounts()) { PaymentData memberPaymentData = memberPaymentsToBeReappliedMap .get(memberAccount.getAccountId()).pop(); memberPaymentData.setParentPayment(accountBO.getLastPmnt()); memberAccount.applyPayment(memberPaymentData); legacyAccountDao.createOrUpdate(memberAccount); } } } transactionHelper.commitTransaction(); } catch (ServiceException e) { transactionHelper.rollbackTransaction(); throw new MifosRuntimeException(e); } catch (AccountException e) { transactionHelper.rollbackTransaction(); throw new MifosRuntimeException(e); } catch (PersistenceException e) { transactionHelper.rollbackTransaction(); throw new MifosRuntimeException(e); } catch (RuntimeException e) { transactionHelper.rollbackTransaction(); throw new MifosRuntimeException(e); } finally { transactionHelper.closeSession(); } }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * Power function.//from w w w. ja v a 2 s. c o m * * @param x Base of the power. * @param y Exponent of the power. * @return x^y. * The estimation of the relative error in the result is |log(x)*err(y)|+|y*err(x)/x| */ static public BigDecimal pow(final BigDecimal x, final BigDecimal y) { if (x.compareTo(BigDecimal.ZERO) < 0) { throw new ArithmeticException("Cannot power negative " + x.toString()); } else if (x.compareTo(BigDecimal.ZERO) == 0) { return BigDecimal.ZERO; } else { /* return x^y = exp(y*log(x)) ; */ BigDecimal logx = log(x); BigDecimal ylogx = y.multiply(logx); BigDecimal resul = exp(ylogx); /* The estimation of the relative error in the result is |log(x)*err(y)|+|y*err(x)/x| */ double errR = Math.abs(logx.doubleValue() * y.ulp().doubleValue() / 2.) + Math.abs(y.doubleValue() * x.ulp().doubleValue() / 2. / x.doubleValue()); MathContext mcR = new MathContext(err2prec(1.0, errR)); return resul.round(mcR); } }
From source file:org.nd4j.linalg.util.BigDecimalMath.java
/** * The trigonometric co-tangent.//from w w w . ja v a 2 s . c o m * * @param x the argument in radians. * @return the cot(x) */ static public BigDecimal cot(final BigDecimal x) { if (x.compareTo(BigDecimal.ZERO) == 0) { throw new ArithmeticException("Cannot take cot of zero " + x.toString()); } else if (x.compareTo(BigDecimal.ZERO) < 0) { return cot(x.negate()).negate(); } else { /* reduce modulo pi */ BigDecimal res = modpi(x); /* absolute error in the result is err(x)/sin^2(x) to lowest order */ final double xDbl = res.doubleValue(); final double xUlpDbl = x.ulp().doubleValue() / 2.; final double eps = xUlpDbl / 2. / Math.pow(Math.sin(xDbl), 2.); final BigDecimal xhighpr = scalePrec(res, 2); final BigDecimal xhighprSq = multiplyRound(xhighpr, xhighpr); MathContext mc = new MathContext(err2prec(xhighpr.doubleValue(), eps)); BigDecimal resul = BigDecimal.ONE.divide(xhighpr, mc); /* x^(2i-1) */ BigDecimal xpowi = xhighpr; Bernoulli b = new Bernoulli(); /* 2^(2i) */ BigInteger fourn = new BigInteger("4"); /* (2i)! */ BigInteger fac = BigInteger.ONE; for (int i = 1;; i++) { Rational f = b.at(2 * i); fac = fac.multiply(new BigInteger("" + (2 * i))).multiply(new BigInteger("" + (2 * i - 1))); f = f.multiply(fourn).divide(fac); BigDecimal c = multiplyRound(xpowi, f); if (i % 2 == 0) { resul = resul.add(c); } else { resul = resul.subtract(c); } if (Math.abs(c.doubleValue()) < 0.1 * eps) { break; } fourn = fourn.shiftLeft(2); xpowi = multiplyRound(xpowi, xhighprSq); } mc = new MathContext(err2prec(resul.doubleValue(), eps)); return resul.round(mc); } }
From source file:com.citrix.cpbm.portal.fragment.controllers.AbstractSubscriptionController.java
@RequestMapping(value = "/taxable_amount", method = RequestMethod.GET) @ResponseBody// ww w. jav a 2 s .co m public String getTaxableAmount(@RequestParam("amount") final String amount) { logger.debug("getTaxableAmount method starting..."); BigDecimal taxableAmount = BigDecimal.ZERO; try { if (amount != null) { taxableAmount = billingAdminService.getTaxableAmount(new BigDecimal(amount)); } } catch (Exception e) { logger.error("Failed to get taxable amount", e); } logger.debug("getTaxableAmount method end"); return taxableAmount.toString(); }