private BigDecimal applyFee(boolean buy, BigDecimal price, BigDecimal transactionFee) { return (transactionFee.compareTo(BigDecimal.ZERO) == 0) ? price : price .multiply( (buy) ? BigDecimal.ONE.add(transactionFee) : BigDecimal.ONE.subtract(transactionFee)) .setScale(2, BigDecimal.ROUND_HALF_EVEN); }
private BigDecimal calcularDividendo() { // Dos apuestas de MONTO_APUESTA donde solo 1 es acertada. BigDecimal montoApostado = MONTO_APUESTA.multiply(new BigDecimal(2)); BigDecimal porcentajeARepartir = BigDecimal.ONE.subtract(BolsasApuestasManager.porcentajeComisionHipodromo); BigDecimal totalARepartir = montoApostado.multiply(porcentajeARepartir); BigDecimal dividendo = totalARepartir.divide(MONTO_APUESTA, 2, BigDecimal.ROUND_CEILING); if (BigDecimal.ONE.compareTo(dividendo) > 0) { dividendo = BigDecimal.ONE.setScale(2); } return dividendo; }
public PercentType[] toRGB() { PercentType red = null; PercentType green = null; PercentType blue = null; BigDecimal h = hue.divide(new BigDecimal(100), 10, BigDecimal.ROUND_HALF_UP); BigDecimal s = saturation.divide(new BigDecimal(100)); int h_int = h.multiply(new BigDecimal(5)) .divide(new BigDecimal(3), 10, BigDecimal.ROUND_HALF_UP) .intValue(); BigDecimal f = h.multiply(new BigDecimal(5)) .divide(new BigDecimal(3), 10, BigDecimal.ROUND_HALF_UP) .remainder(BigDecimal.ONE); PercentType a = new PercentType(value.multiply(BigDecimal.ONE.subtract(s))); PercentType b = new PercentType(value.multiply(BigDecimal.ONE.subtract(s.multiply(f)))); PercentType c = new PercentType( value.multiply(BigDecimal.ONE.subtract((BigDecimal.ONE.subtract(f)).multiply(s)))); if (h_int == 0 || h_int == 6) { red = getBrightness(); green = c; blue = a; } else if (h_int == 1) { red = b; green = getBrightness(); blue = a; } else if (h_int == 2) { red = a; green = getBrightness(); blue = c; } else if (h_int == 3) { red = a; green = b; blue = getBrightness(); } else if (h_int == 4) { red = c; green = a; blue = getBrightness(); } else if (h_int == 5) { red = getBrightness(); green = a; blue = b; } else { throw new RuntimeException(); } return new PercentType[] {red, green, blue}; }
@Override public DecimalAmount invert() { return bd.compareTo(BigDecimal.ZERO) == 0 ? new DecimalAmount(BigDecimal.ZERO) : new DecimalAmount(BigDecimal.ONE.divide(bd, mc)); }
@Test(timeout = 5000L) public void powDoubleIntTen() { for (int i = -325; i < 311; i++) assertEquals(Double.parseDouble("1e" + i), pow(10.0, i), EXACT); for (int i = -325; i < 311; i++) assertEquals(BigDecimal.ONE.scaleByPowerOfTen(i).doubleValue(), pow(10.0, i), EXACT); }
@Override public BigDecimal getCurrencyValue(CurrencyForm currencyForm) throws NoCurrenciesException { Criteria fromCriteria = Criteria.where("timestamp") .is(currencyForm.getTimestamp()) .and("currencyCode") .is(currencyForm.getFromCurrencyCode()); List<MongoCurrency> fromCurrencies = currencyMongoDao.query(fromCriteria); Criteria toCriteria = Criteria.where("timestamp") .is(currencyForm.getTimestamp()) .and("currencyCode") .is(currencyForm.getToCurrencyCode()); List<MongoCurrency> toCurrencies = currencyMongoDao.query(toCriteria); if (fromCurrencies.isEmpty() || toCurrencies.isEmpty()) { throw new NoCurrenciesException( currencyForm.getFromCurrencyCode(), currencyForm.getToCurrencyCode(), currencyForm.getTimestamp()); } MongoCurrency fromCurrency = fromCurrencies.get(0); MongoCurrency toCurrency = toCurrencies.get(0); BigDecimal fromCurrencyInUsd = BigDecimal.ONE .divide(fromCurrency.getValue(), 10, BigDecimal.ROUND_HALF_UP) .multiply(currencyForm.getAmountFrom()); return fromCurrencyInUsd.multiply(toCurrency.getValue()); }
@Override public void write(WriteBuffer buff, Object obj) { if (!isBigDecimal(obj)) { super.write(buff, obj); return; } BigDecimal x = (BigDecimal) obj; if (BigDecimal.ZERO.equals(x)) { buff.put((byte) TAG_BIG_DECIMAL_0); } else if (BigDecimal.ONE.equals(x)) { buff.put((byte) TAG_BIG_DECIMAL_1); } else { int scale = x.scale(); BigInteger b = x.unscaledValue(); int bits = b.bitLength(); if (bits < 64) { if (scale == 0) { buff.put((byte) TAG_BIG_DECIMAL_SMALL); } else { buff.put((byte) TAG_BIG_DECIMAL_SMALL_SCALED).putVarInt(scale); } buff.putVarLong(b.longValue()); } else { byte[] bytes = b.toByteArray(); buff.put((byte) TYPE_BIG_DECIMAL).putVarInt(scale).putVarInt(bytes.length).put(bytes); } } }
static Map<Integer, Double> getPageRanks(Graph g, int iterations) { // this is a map of userID tp their current page rank Map<Integer, Double> pageRanks = new TreeMap<Integer, Double>(); Map<Integer, Double> tempPageRanks = new TreeMap<Integer, Double>(); double d = 0.85000000; // dampening factor is .85 for (Integer userID : g.users.keySet()) { pageRanks.put(userID, BigDecimal.ONE.doubleValue()); } // calculate the page rank i = iterations times for (int i = 0; i < iterations; i++) { // calculate the page rank for every vertex at that iteration tempPageRanks = new TreeMap<Integer, Double>(); for (Integer userID : g.users.keySet()) { double x = 0.0; // by summing over all of userID's followers for (Integer followerID : g.followers.get(userID).keySet()) { // the page rank from the previous iteration of each follower double followerPR = pageRanks.get(followerID); // divided by the number of that follower's friends double numFriendsOfFollower = (double) g.friends.get(followerID).size(); x += (double) followerPR / numFriendsOfFollower; } // save the page rank tempPageRanks.put(userID, 0.1500000 + (d * x)); } // update the page ranks all at once pageRanks = tempPageRanks; } return pageRanks; }
@Override public ByteBuffer write(ByteBuffer buff, Object obj) { if (!isBigDecimal(obj)) { return super.write(buff, obj); } BigDecimal x = (BigDecimal) obj; if (BigDecimal.ZERO.equals(x)) { buff.put((byte) TAG_BIG_DECIMAL_0); } else if (BigDecimal.ONE.equals(x)) { buff.put((byte) TAG_BIG_DECIMAL_1); } else { int scale = x.scale(); BigInteger b = x.unscaledValue(); int bits = b.bitLength(); if (bits < 64) { if (scale == 0) { buff.put((byte) TAG_BIG_DECIMAL_SMALL); } else { buff.put((byte) TAG_BIG_DECIMAL_SMALL_SCALED); DataUtils.writeVarInt(buff, scale); } DataUtils.writeVarLong(buff, b.longValue()); } else { buff.put((byte) TYPE_BIG_DECIMAL); DataUtils.writeVarInt(buff, scale); byte[] bytes = b.toByteArray(); DataUtils.writeVarInt(buff, bytes.length); buff = DataUtils.ensureCapacity(buff, bytes.length); buff.put(bytes); } } return buff; }
public static List<Map<String, BigDecimal>> getPackageSplit( DispatchContext dctx, List<Map<String, Object>> shippableItemInfo, BigDecimal maxWeight) { // create the package list w/ the first package List<Map<String, BigDecimal>> packages = FastList.newInstance(); if (UtilValidate.isNotEmpty(shippableItemInfo)) { for (Map<String, Object> itemInfo : shippableItemInfo) { long pieces = ((Long) itemInfo.get("piecesIncluded")).longValue(); BigDecimal totalQuantity = (BigDecimal) itemInfo.get("quantity"); BigDecimal totalWeight = (BigDecimal) itemInfo.get("weight"); String productId = (String) itemInfo.get("productId"); // sanity check if (pieces < 1) { pieces = 1; // can NEVER be less than one } BigDecimal weight = totalWeight.divide(BigDecimal.valueOf(pieces), generalRounding); for (int z = 1; z <= totalQuantity.intValue(); z++) { BigDecimal partialQty = pieces > 1 ? BigDecimal.ONE.divide(BigDecimal.valueOf(pieces), generalRounding) : BigDecimal.ONE; for (long x = 0; x < pieces; x++) { if (weight.compareTo(maxWeight) >= 0) { Map<String, BigDecimal> newPackage = FastMap.newInstance(); newPackage.put(productId, partialQty); packages.add(newPackage); } else if (totalWeight.compareTo(BigDecimal.ZERO) > 0) { // create the first package if (packages.size() == 0) { packages.add(FastMap.<String, BigDecimal>newInstance()); } // package loop boolean addedToPackage = false; for (Map<String, BigDecimal> packageMap : packages) { if (!addedToPackage) { BigDecimal packageWeight = calcPackageWeight(dctx, packageMap, shippableItemInfo, weight); if (packageWeight.compareTo(maxWeight) <= 0) { BigDecimal qty = packageMap.get(productId); qty = UtilValidate.isEmpty(qty) ? BigDecimal.ZERO : qty; packageMap.put(productId, qty.add(partialQty)); addedToPackage = true; } } } if (!addedToPackage) { Map<String, BigDecimal> packageMap = FastMap.newInstance(); packageMap.put(productId, partialQty); packages.add(packageMap); } } } } } } return packages; }
public static void main(String argv[]) { for (int i = -10; i < 10; i++) { BigDecimal bd = BigDecimal.ONE.scaleByPowerOfTen(i); BigDecimal expected; if (!bd.equals(expected = new BigDecimal(BigInteger.ONE, -i))) { throw new RuntimeException( "Unexpected result " + bd.toString() + "; expected " + expected.toString()); } bd = BigDecimal.ONE.negate().scaleByPowerOfTen(i); if (!bd.equals(expected = new BigDecimal(BigInteger.ONE.negate(), -i))) { throw new RuntimeException( "Unexpected result " + bd.toString() + "; expected " + expected.toString()); } } }
/** * Calculates the value of the first argument raised to the power of the second argument. * * @param base the base * @param expornent the exponent * @return the value <tt>a<sup>b</sup></tt> in <tt>BigDecimal</tt> */ private BigDecimal pow(double base, int expornent) { BigDecimal value; if (expornent > 0) { value = new BigDecimal(new Double(base).toString()).pow(expornent); } else { value = BigDecimal.ONE.divide(new BigDecimal(new Double(base).toString()).pow(-expornent)); } return value; }
@Test public void ensureCorrectWorkingDurationForAssumptionDayForBadenWuerttemberg() { BigDecimal workingDuration = publicHolidaysService.getWorkingDurationOfDate( new DateMidnight(2015, DateTimeConstants.AUGUST, 15), FederalState.BADEN_WUERTTEMBERG); Assert.assertEquals("Wrong working duration", BigDecimal.ONE.setScale(1), workingDuration); }
@Test public void ensureCorrectWorkingDurationForWorkDay() { DateMidnight testDate = new DateMidnight(2013, DateTimeConstants.NOVEMBER, 27); BigDecimal workingDuration = publicHolidaysService.getWorkingDurationOfDate(testDate, state); Assert.assertEquals("Wrong working duration", BigDecimal.ONE.setScale(1), workingDuration); }
/** * Normalize the vector so its L2 Norm is 1 WARNING: This function uses norm() which loses the * BigDecimal precision and range in VectorType * * @param v vector to compute norm of * @return normalized input vector * @throws ZeroNormException if norm(v) less than Double.MIN_VALUE */ public static VectorType normalize(VectorType v) { VectorType vout = new VectorType(); double normv = norm(v); if (normv < Double.MIN_VALUE) { throw new ZeroNormException("Can't normalize vector with zero magnitude."); } BigDecimal normInv = BigDecimal.ONE.divide(BigDecimal.valueOf(norm(v))); vout.setI(v.getI().multiply(normInv)); vout.setJ(v.getJ().multiply(normInv)); vout.setK(v.getK().multiply(normInv)); return vout; }
@Test public final void shouldConvertNullToOne() { // given BigDecimal notNullDecimal = BigDecimal.TEN; // when BigDecimal fromNullRes = BigDecimalUtils.convertNullToOne(null); BigDecimal fromNotNullRes = BigDecimalUtils.convertNullToOne(notNullDecimal); // then Assert.assertEquals(0, notNullDecimal.compareTo(fromNotNullRes)); Assert.assertEquals(0, BigDecimal.ONE.compareTo(fromNullRes)); }
@Test public void ensureWorkingDurationForNewYearsEveCanBeConfiguredToAWorkingDurationOfFullDay() { Settings settings = new Settings(); settings.getWorkingTimeSettings().setWorkingDurationForNewYearsEve(DayLength.FULL); Mockito.when(settingsService.getSettings()).thenReturn(settings); DateMidnight testDate = new DateMidnight(2013, DateTimeConstants.DECEMBER, 31); BigDecimal workingDuration = publicHolidaysService.getWorkingDurationOfDate(testDate, state); Assert.assertEquals("Wrong working duration", BigDecimal.ONE.setScale(1), workingDuration); }
public enum TradeType { BUY(BigDecimal.ONE), SELL(BigDecimal.ONE.negate()); private final BigDecimal multiplier; TradeType(BigDecimal multiplier) { this.multiplier = multiplier; } /** @return the multiplier */ public BigDecimal getMultiplier() { return multiplier; } }
/** * Builds a '1' times ten to the specified power with any trailing zeros stripped. * * <p>Examples: * * <ul> * <li>0 == 1 * <li>-1 == .1 * <li>3 = 1000 * </ul> * * @param scale * @return */ protected static BigDecimal oneTimesTenToThePower(int power) { if (power == 0) { return BigDecimal.ONE.stripTrailingZeros(); } else if (power < 0) { power = power * -1; String numStr; numStr = "." + StringUtils.repeat("0", power - 1); numStr = numStr + "1"; return new BigDecimal(numStr).stripTrailingZeros(); } else { String numStr; numStr = StringUtils.repeat("0", power); numStr = "1" + numStr; return new BigDecimal(numStr).stripTrailingZeros(); } }
public BigDecimal calculate( MonetaryAmount annuity, MonetaryAmount paymentOrCashFlows, Rate rate, int periods) { MonetaryAmount pvAnnuity = PresentValueAnnuity.of().calculate(annuity, rate, periods); return new BigDecimal( String.valueOf( Math.log( BigDecimal.ONE .subtract( pvAnnuity .divide(paymentOrCashFlows.getNumber()) .getNumber() .numberValue(BigDecimal.class)) .pow(-1) .doubleValue()) / Math.log(1 + rate.get().doubleValue()))); }
/** * Weight units * * @author Stefan Laubenberger * @version 0.1.0, 2013-07-31 * @since 0.0.1 */ @XmlRootElement(name = "weight") public enum Weight implements Unit<Weight> { MILLIGRAM( Constants.FACTOR_MILLIGRAM_TO_GRAM.multiply( Constants.FACTOR_GRAM_TO_KILOGRAM, Constants.DEFAULT_MATHCONTEXT)), // $JUnit$ GRAM(Constants.FACTOR_GRAM_TO_KILOGRAM), // $JUnit$ KILOGRAM(BigDecimal.ONE), // $JUnit$ OUNCE( Constants.FACTOR_OUNCE_TO_GRAM.multiply( Constants.FACTOR_GRAM_TO_KILOGRAM, Constants.DEFAULT_MATHCONTEXT)), // $JUnit$ POUND(Constants.FACTOR_POUND_TO_KILOGRAM), // $JUnit$ TON( BigDecimal.ONE.divide( Constants.FACTOR_TON_TO_KILOGRAM, Constants.DEFAULT_MATHCONTEXT)); // $JUnit$ final BigDecimal factor; Weight(final BigDecimal factor) { this.factor = factor; } BigDecimal getFactor() { return factor; } /* * Implemented methods */ @Override public BigDecimal convertTo(final Weight toUnit, final Number value) { // $JUnit$ if (null == toUnit) { throw new RuntimeExceptionIsNull("toUnit"); // $NON-NLS-1$ } if (null == value) { throw new RuntimeExceptionIsNull("value"); // $NON-NLS-1$ } final BigDecimal internalValue = new BigDecimal(value.toString()); return toUnit == this ? internalValue : internalValue .divide(factor, Constants.DEFAULT_MATHCONTEXT) .multiply(toUnit.factor, Constants.DEFAULT_MATHCONTEXT); } }
/** * This method tries to represent a BigDecimal using only BigInteger. It can be used for * implementing {@link #makeNumber(BigDecimal)} when the current theory supports only integers. */ protected final TFormulaInfo decimalAsInteger(BigDecimal val) { if (val.scale() <= 0) { // actually an integral number return makeNumberImpl(convertBigDecimalToBigInteger(val)); } else { // represent x.y by xy / (10^z) where z is the number of digits in y // (the "scale" of a BigDecimal) BigDecimal n = val.movePointRight(val.scale()); // this is "xy" BigInteger numerator = convertBigDecimalToBigInteger(n); BigDecimal d = BigDecimal.ONE.scaleByPowerOfTen(val.scale()); // this is "10^z" BigInteger denominator = convertBigDecimalToBigInteger(d); assert denominator.signum() > 0; return linearDivide(makeNumberImpl(numerator), makeNumberImpl(denominator)); } }
private BigDecimal getAvancement(SQLRowAccessor r) { Collection<? extends SQLRowAccessor> rows = r.getReferentRows(r.getTable().getTable("TR_COMMANDE_CLIENT")); long totalFact = 0; long total = r.getLong("T_HT"); for (SQLRowAccessor row : rows) { if (!row.isForeignEmpty("ID_SAISIE_VENTE_FACTURE")) { SQLRowAccessor rowFact = row.getForeign("ID_SAISIE_VENTE_FACTURE"); Long l = rowFact.getLong("T_HT"); totalFact += l; } } if (total > 0) { return new BigDecimal(totalFact) .divide(new BigDecimal(total), DecimalUtils.HIGH_PRECISION) .movePointRight(2) .setScale(2, RoundingMode.HALF_UP); } else { return BigDecimal.ONE.movePointRight(2); } }
@AfterViews public void afterViews() { assetPair = (AssetPair) getArguments().getSerializable(Constants.EXTRA_ASSET_PAIR); price = BigDecimal.valueOf(getArguments().getDouble(Constants.EXTRA_RATE_PRICE)); if (assetPair != null) { if (assetPair.getInverted()) { accurancy = assetPair.getInvertedAccuracy(); if (price.compareTo(BigDecimal.ZERO) != 0) { price = BigDecimal.ONE.divide(price, accurancy, RoundingMode.HALF_EVEN); } mainName = assetPair.getQuotingAssetId(); subName = assetPair.getBaseAssetId(); } else { accurancy = assetPair.getAccuracy(); mainName = assetPair.getBaseAssetId(); subName = assetPair.getQuotingAssetId(); } } actionBar.setTitle(mainName + "/" + subName); if (getArguments().getSerializable(Constants.EXTRA_DESCRIPTION) != null) { if (getArguments().getSerializable(Constants.EXTRA_RATE_PRICE) != null) { price = (BigDecimal) getArguments().getSerializable(Constants.EXTRA_RATE_PRICE); btnBuy.setText( String.format(getString(R.string.buy_rate), mainName, subName) + " " + LykkeUtils.getStriped(accurancy, price)); btnSell.setText( String.format(getString(R.string.sell_at_price), mainName, subName) + " " + LykkeUtils.getStriped(accurancy, price)); } onSuccess(getArguments().getSerializable(Constants.EXTRA_DESCRIPTION)); } else { setUpVisibility(View.VISIBLE, View.GONE); btnBuy.setVisibility(View.GONE); btnSell.setVisibility(View.GONE); getInfoFromServer(); } }
/** * Compute the value, in radians, of the arctangent of the inverse of the supplied integer to the * specified number of digits after the decimal point. The value is computed using the power * series expansion for the arc tangent: * * <p>arctan(x) = x - (x^3)/3 + (x^5)/5 - (x^7)/7 + (x^9)/9 ... */ public static BigDecimal arctan(int inverseX, int scale) { BigDecimal result, numer, term; BigDecimal invX = BigDecimal.valueOf(inverseX); BigDecimal invX2 = BigDecimal.valueOf(inverseX * inverseX); numer = BigDecimal.ONE.divide(invX, scale, roundingMode); result = numer; int i = 1; do { numer = numer.divide(invX2, scale, roundingMode); int denom = 2 * i + 1; term = numer.divide(BigDecimal.valueOf(denom), scale, roundingMode); if ((i % 2) != 0) { result = result.subtract(term); } else { result = result.add(term); } i++; } while (term.compareTo(BigDecimal.ZERO) != 0); return result; }
@Override public void onSuccess(Object result) { try { if (getActivity() != null) { if (result instanceof DescriptionResult) { resultData = (DescriptionResult) result; setUpVisibility(View.GONE, View.VISIBLE); btnBuy.setVisibility(View.VISIBLE); btnSell.setVisibility(View.VISIBLE); if (((DescriptionResult) result).getAssetClass() == null) { linearAssetName.setVisibility(View.GONE); viewAssetClass.setVisibility(View.GONE); } else { tvAssetClass.setText(((DescriptionResult) result).getAssetClass()); } if (((DescriptionResult) result).getDescription() == null) { linearDescription.setVisibility(View.GONE); viewDescription.setVisibility(View.GONE); } else { tvDescription.setText(((DescriptionResult) result).getDescription()); } if (((DescriptionResult) result).getIssuerName() == null) { linearIssuerName.setVisibility(View.GONE); viewIssuerName.setVisibility(View.GONE); } else { tvIssuerName.setText(((DescriptionResult) result).getIssuerName()); } if (((DescriptionResult) result).getNumberOfCoins() == null) { linearNumberOfCoins.setVisibility(View.GONE); viewNumberOfCoins.setVisibility(View.GONE); } else { tvNumberOfCoins.setText(((DescriptionResult) result).getNumberOfCoins()); } if (((DescriptionResult) result).getMarketCapitalization() == null) { linearMarketCapitalization.setVisibility(View.GONE); viewMarketCapitalization.setVisibility(View.GONE); } else { tvMarketCapitalization.setText(((DescriptionResult) result).getMarketCapitalization()); } if (((DescriptionResult) result).getAssetDescriptionUrl() == null) { linearDescriptionUrl.setVisibility(View.GONE); viewDescriptionUrl.setVisibility(View.GONE); } else { Spannable s = (Spannable) Html.fromHtml(((DescriptionResult) result).getAssetDescriptionUrl()); for (URLSpan u : s.getSpans(0, s.length(), URLSpan.class)) { s.setSpan( new UnderlineSpan() { public void updateDrawState(TextPaint tp) { tp.setUnderlineText(false); } }, s.getSpanStart(u), s.getSpanEnd(u), 0); } tvDescriptionUrl.setMovementMethod(LinkMovementMethod.getInstance()); tvDescriptionUrl.setLinksClickable(true); tvDescriptionUrl.setText(s); } Resources r = getResources(); float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 20, r.getDisplayMetrics()); float pxMargin = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3, r.getDisplayMetrics()); linearPop.removeAllViews(); for (int i = 0; i < Integer.parseInt(((DescriptionResult) result).getPopIndex()); i++) { ImageView imageView = new ImageView(getActivity()); imageView.setImageResource(R.drawable.star); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(Math.round(px), Math.round(px)); lp.setMargins(Math.round(pxMargin), 0, Math.round(pxMargin), 0); imageView.setLayoutParams(lp); linearPop.addView(imageView); } if (Integer.parseInt(((DescriptionResult) result).getPopIndex()) == 0) { linearPopularity.setVisibility(View.GONE); } handler.post(run); } else if (result instanceof RateResult) { if (((RateResult) result).getRate() != null && ((RateResult) result).getRate().getAsk() != null && getActivity() != null) { price = BigDecimal.valueOf(((RateResult) result).getRate().getAsk()); if (assetPair.getInverted()) { price = BigDecimal.ONE.divide(price, accurancy, RoundingMode.HALF_EVEN); } btnBuy.setText( String.format(getString(R.string.buy_rate), mainName, subName) + " " + LykkeUtils.getStriped(accurancy, price)); } if (((RateResult) result).getRate() != null && ((RateResult) result).getRate().getBid() != null && getActivity() != null) { bid = BigDecimal.valueOf(((RateResult) result).getRate().getBid()); if (assetPair.getInverted()) { bid = BigDecimal.ONE.divide(bid, accurancy, RoundingMode.HALF_EVEN); } btnSell.setText( String.format(getString(R.string.sell_at_price), mainName, subName) + " " + LykkeUtils.getStriped(accurancy, bid)); } } } } catch (NullPointerException ex) { } }
protected boolean createTransactionFromChargeApplication( StepExecution<RatingTicket> stepExecution, ChargeApplication chargeApplication) { TaskExecution<RatingTicket> taskExecution = stepExecution.getTaskExecution(); try { Integer usageQuantity = chargeApplication.getQuantity(); if (usageQuantity == null) usageQuantity = 0; PricePlanMatrix ratePrice = (PricePlanMatrix) stepExecution.getParameter(VertinaConstants.RATE_PLAN); DiscountPlanMatrix discountPrice = (DiscountPlanMatrix) stepExecution.getParameter(VertinaConstants.DISCOUNT_PLAN); BigDecimal unitPrice1 = chargeApplication.getAmountWithoutTax(); boolean overriddenPrice = (unitPrice1 != null); if (!overriddenPrice) { if (ratePrice == null) { logger.error( "Error getting pricePlan for ChargeCode=" + chargeApplication.getChargeCode()); setNotAccepted(stepExecution, "ERROR_GETTING_PRICE"); return false; } else { logger.info( "found ratePrice:" + ratePrice.getId() + " price=" + ratePrice.getAmountWithoutTax() + " price2=" + ratePrice.getAmountWithoutTax2()); unitPrice1 = ratePrice.getAmountWithoutTax(); } } if (unitPrice1 == null) { unitPrice1 = BigDecimal.ZERO; } BigDecimal unitPrice2 = chargeApplication.getAmount2(); if (unitPrice2 == null && ratePrice != null && ratePrice.getAmountWithoutTax2() != null) { unitPrice2 = ratePrice.getAmountWithoutTax2(); } if (unitPrice2 == null) { unitPrice2 = BigDecimal.ZERO; } BigDecimal unitPriceRatio = BigDecimal.ONE; // subscription prorata if (ApplicationTypeEnum.PRORATA_SUBSCRIPTION.equals(chargeApplication.getApplicationType())) { try { if ("1".equals(chargeApplication.getParameter3())) { unitPriceRatio = new BigDecimal(chargeApplication.getParameter1()); } unitPrice1 = unitPrice1.multiply(unitPriceRatio); unitPrice2 = unitPrice2.multiply(unitPriceRatio); } catch (Exception e) { // TODO reject on failure? logger.error("Error calculating unit prices.", e); } } if (ApplicationTypeEnum.PRORATA_TERMINATION.equals(chargeApplication.getApplicationType())) { try { unitPriceRatio = new BigDecimal(chargeApplication.getParameter1()); unitPrice1 = unitPrice1.multiply(unitPriceRatio); unitPrice2 = unitPrice2.multiply(unitPriceRatio); } catch (Exception e) { // TODO reject on failure? logger.error("Error calculating unit prices.", e); } } Provider provider = chargeApplication.getProvider(); if (provider.getRounding() != null && provider.getRounding() > 0) { unitPrice1 = NumberUtils.round(unitPrice1, provider.getRounding()); unitPrice2 = NumberUtils.round(unitPrice2, provider.getRounding()); } BigDecimal amount1 = new BigDecimal(usageQuantity).multiply(unitPrice1); BigDecimal amount2 = new BigDecimal(usageQuantity).multiply(unitPrice2); BigDecimal amount1Discounted = BigDecimal.ZERO; BigDecimal amount2Discounted = BigDecimal.ZERO; if (overriddenPrice && discountPrice != null) { try { BigDecimal discount = BigDecimal.ONE.subtract(discountPrice.getPercent().divide(HUNDRED)); amount1Discounted = amount1.multiply(discount); amount2Discounted = amount2.multiply(discount); } catch (Exception e) { // TODO reject on failure? logger.error("Error calculating discount.", e); } } else { amount1Discounted = amount1; amount2Discounted = amount2; } BigDecimal amount1Tax = BigDecimal.ZERO; BigDecimal amount2Tax = BigDecimal.ZERO; if (chargeApplication.getTaxPercent() != null) { amount1Tax = amount1Discounted.multiply(chargeApplication.getTaxPercent()).divide(HUNDRED); amount2Tax = amount2Discounted.multiply(chargeApplication.getTaxPercent().divide(HUNDRED)); } RatedTransaction transaction = new RatedTransaction(); transaction.setProvider(chargeApplication.getProvider()); transaction.setChargeApplication(chargeApplication); // FIXME: Too many requests to get the wallet : copy wallet in // chargeApplication transaction.setWallet(chargeApplication.getSubscription().getUserAccount().getWallet()); transaction.setUsageCode(chargeApplication.getChargeCode()); transaction.setDescription( chargeApplication.getDescription() + (chargeApplication.getParameter2() == null ? "" : (" " + chargeApplication.getParameter2()))); transaction.setUsageDate(chargeApplication.getApplicationDate()); transaction.setUsageQuantity(usageQuantity); transaction.setUnitPrice1(unitPrice1); transaction.setUnitPrice2(unitPrice2); transaction.setUnitPriceRatio(unitPriceRatio); transaction.setDiscountPercent(discountPrice != null ? discountPrice.getPercent() : null); transaction.setInvoiceSubCategory(chargeApplication.getInvoiceSubCategory()); transaction.setTaxCode(chargeApplication.getTaxCode()); transaction.setTaxPercent(chargeApplication.getTaxPercent()); BigDecimal amount1WithTax = amount1Tax.add(amount1Discounted); BigDecimal amount2WithTax = amount2Tax.add(amount2Discounted); if (provider.getRounding() != null && provider.getRounding() > 0) { amount1Discounted = NumberUtils.round(amount1Discounted, provider.getRounding()); amount1WithTax = NumberUtils.round(amount1WithTax, provider.getRounding()); amount2Discounted = NumberUtils.round(amount2Discounted, provider.getRounding()); amount2WithTax = NumberUtils.round(amount2WithTax, provider.getRounding()); } transaction.setAmount1(amount1); transaction.setAmount1WithoutTax(amount1Discounted); // en transaction.setAmount1Tax(amount1Tax); transaction.setAmount1WithTax(amount1WithTax); transaction.setAmount2(amount2); transaction.setAmount2WithoutTax(amount2Discounted); transaction.setAmount2Tax(amount2Tax); transaction.setAmount2WithTax(amount2WithTax); transaction.setProvider(chargeApplication.getProvider()); transaction.setParameter1(chargeApplication.getCriteria1()); transaction.setParameter2(chargeApplication.getCriteria2()); transaction.setParameter3(chargeApplication.getCriteria3()); transaction.setParameter4(RatingTicket.sdf.format(chargeApplication.getSubscriptionDate())); transaction.setParameter5( chargeApplication.getAmountWithoutTax() != null ? chargeApplication.getAmountWithoutTax().toString() : null); transaction.setStatus(RatedTransactionStatusEnum.OPEN); putToTaskExecutionListContextParameter( VertinaConstants.LIST_OF_TRANSACTIONS_KEY, transaction, taskExecution); putToTaskExecutionListContextParameter( VertinaConstants.PROCESSED_CHARGE_APPLICATIONS_KEY, chargeApplication, taskExecution); } catch (Exception e) { logger.error("Error creating RatedTransaction", e); setNotAccepted(stepExecution, "ERROR_CREATING_TRANSACTION"); return false; } return true; }
protected boolean updateTransaction( StepExecution<RatingTicket> stepExecution, RatedTransaction transaction) { TaskExecution<RatingTicket> taskExecution = stepExecution.getTaskExecution(); RatingTicket ticket = stepExecution.getTicket(); try { PricePlanMatrix ratePrice = (PricePlanMatrix) stepExecution.getParameter(VertinaConstants.RATE_PLAN); DiscountPlanMatrix discountPrice = (DiscountPlanMatrix) stepExecution.getParameter(VertinaConstants.DISCOUNT_PLAN); BigDecimal unitPrice1 = ticket.amountWithoutTax; boolean overriddenPrice = (unitPrice1 != null); if (!overriddenPrice) { if (ratePrice == null) { logger.error("Error getting pricePlan for ChargeCode=" + ticket.chargeCode); setNotAccepted(stepExecution, "ERROR_GETTING_PRICE"); return false; } else { logger.info( "found ratePrice:" + ratePrice.getId() + " price=" + ratePrice.getAmountWithoutTax() + " price2=" + ratePrice.getAmountWithoutTax2()); unitPrice1 = ratePrice.getAmountWithoutTax(); } if (unitPrice1 == null) { unitPrice1 = BigDecimal.ZERO; } BigDecimal unitPrice2 = ticket.amount2; if (unitPrice2 == null && ratePrice != null && ratePrice.getAmountWithoutTax2() != null) { unitPrice2 = ratePrice.getAmountWithoutTax2(); } if (unitPrice2 == null) { unitPrice2 = BigDecimal.ZERO; } unitPrice1 = unitPrice1.multiply(transaction.getUnitPriceRatio()); unitPrice2 = unitPrice2.multiply(transaction.getUnitPriceRatio()); unitPrice1 = unitPrice1.setScale(4, RoundingMode.HALF_UP); BigDecimal amount1 = new BigDecimal(transaction.getUsageQuantity()).multiply(unitPrice1); unitPrice2 = unitPrice2.setScale(4, RoundingMode.HALF_UP); BigDecimal amount2 = new BigDecimal(transaction.getUsageQuantity()).multiply(unitPrice2); BigDecimal amount1Discounted = BigDecimal.ZERO; BigDecimal amount2Discounted = BigDecimal.ZERO; if (overriddenPrice && discountPrice != null) { try { BigDecimal discount = BigDecimal.ONE.subtract(discountPrice.getPercent().divide(HUNDRED)); amount1Discounted = amount1.multiply(discount); amount2Discounted = amount2.multiply(discount); } catch (Exception e) { // TODO reject on failure? logger.error("Error calculating discount.", e); } } else { amount1Discounted = amount1; amount2Discounted = amount2; } BigDecimal amount1Tax = BigDecimal.ZERO; BigDecimal amount2Tax = BigDecimal.ZERO; if (transaction.getTaxPercent() != null) { amount1Tax = amount1Discounted.multiply(transaction.getTaxPercent()).divide(HUNDRED); amount2Tax = amount2Discounted.multiply(transaction.getTaxPercent().divide(HUNDRED)); } BigDecimal amount1WithTax = amount1Tax.add(amount1Discounted); BigDecimal amount2WithTax = amount2Tax.add(amount2Discounted); Provider provider = transaction.getProvider(); if (provider != null && (provider.getRounding() != null && provider.getRounding() > 0)) { amount1Discounted = NumberUtils.round(amount1Discounted, provider.getRounding()); amount1WithTax = NumberUtils.round(amount1WithTax, provider.getRounding()); amount2Discounted = NumberUtils.round(amount2Discounted, provider.getRounding()); amount2WithTax = NumberUtils.round(amount2WithTax, provider.getRounding()); } transaction.setUnitPrice1(unitPrice1); transaction.setUnitPrice2(unitPrice2); transaction.setDiscountPercent(discountPrice != null ? discountPrice.getPercent() : null); transaction.setAmount1(amount1); transaction.setAmount1WithoutTax(amount1Discounted); // en transaction.setAmount1Tax(amount1Tax); transaction.setAmount1WithTax(amount1WithTax); transaction.setAmount2(amount2); transaction.setAmount2WithoutTax(amount2Discounted); transaction.setAmount2Tax(amount2Tax); transaction.setAmount2WithTax(amount2WithTax); } transaction.setStatus(RatedTransactionStatusEnum.OPEN); putToTaskExecutionListContextParameter( VertinaConstants.LIST_OF_TRANSACTIONS_KEY, transaction, taskExecution); } catch (Exception e) { logger.error("Error updating RatedTransaction", e); setNotAccepted(stepExecution, "ERROR_UPDATING_TRANSACTION"); return false; } return true; }
private void test( final BigDecimal valueToSplit, final int childrenCount, final MathContext mathContext) { final String info = "ValueToSplit=" + valueToSplit + ", childrenCount=" + childrenCount + ", mathContext=" + mathContext; final int precision = mathContext.getPrecision(); final BigDecimal splitValueExpected = valueToSplit.divide(BigDecimal.valueOf(childrenCount), mathContext); // Delta: tolerated difference between calculated split value and actual split value // i.e. 1^(-precision) = 1/(1^precision) ... because BigDecimal does not support negative powers final BigDecimal splitValueExpectedDelta = BigDecimal.ONE.divide(BigDecimal.ONE.pow(precision)); // Example: For ValueToSplit=100, childrenCount=33, precision=2 // splitValueExpected = 0.03 // splitValueExpectedDelta = 1^(-2) = 0.01 final MutableAttributeSplitRequest request = createRequest(valueToSplit, childrenCount); BigDecimal splitValueSUM = BigDecimal.ZERO; for (int index = 0; index < childrenCount; index++) { // // Update request current index request.setAttributeStorageCurrent(request.getAttributeStorages().get(index)); request.setAttributeStorageCurrentIndex(index); // // Execute splitting final IAttributeSplitResult result = splitter.split(request); // // Get and check split value final BigDecimal splitValue = (BigDecimal) result.getSplitValue(); assertEquals( "Invalid split value on index=" + index + "\n" + info, splitValueExpected, // expected splitValue, // actual splitValueExpectedDelta // delta ); // // Update SUM of split values splitValueSUM = splitValueSUM.add(splitValue); // // Update: request's ValueToSplit = last split remaining value final BigDecimal remainingValue = (BigDecimal) result.getRemainingValue(); final BigDecimal remainingValueExpected = valueToSplit.subtract(splitValueSUM); assertEquals( "Invalid remaining value on index=" + index + "\n" + info, remainingValueExpected, // expected remainingValue, // actual BigDecimal.ZERO // delta=exact ); request.setValueToSplit(remainingValue); } // // Assume: sum of all split values shall be the same as initial value to split Assert.assertThat( "Invalid splitValues SUM" + "\n" + info, splitValueSUM, // actual Matchers.comparesEqualTo(valueToSplit) // expected ); }
/** * Calculate the number of bytes required to encode the given value. * * @param v the value * @param handler the data handler for lobs * @return the number of bytes required to store this value */ public static int getValueLen(Value v, DataHandler handler) { if (v == ValueNull.INSTANCE) { return 1; } switch (v.getType()) { case Value.BOOLEAN: return 1; case Value.BYTE: return 2; case Value.SHORT: return 3; case Value.INT: { int x = v.getInt(); if (x < 0) { return 1 + getVarIntLen(-x); } else if (x < 16) { return 1; } else { return 1 + getVarIntLen(x); } } case Value.LONG: { long x = v.getLong(); if (x < 0) { return 1 + getVarLongLen(-x); } else if (x < 8) { return 1; } else { return 1 + getVarLongLen(x); } } case Value.DOUBLE: { double x = v.getDouble(); if (x == 1.0d) { return 1; } long d = Double.doubleToLongBits(x); if (d == ValueDouble.ZERO_BITS) { return 1; } return 1 + getVarLongLen(Long.reverse(d)); } case Value.FLOAT: { float x = v.getFloat(); if (x == 1.0f) { return 1; } int f = Float.floatToIntBits(x); if (f == ValueFloat.ZERO_BITS) { return 1; } return 1 + getVarIntLen(Integer.reverse(f)); } case Value.STRING: { String s = v.getString(); int len = s.length(); if (len < 32) { return 1 + getStringWithoutLengthLen(s, len); } return 1 + getStringLen(s); } case Value.STRING_IGNORECASE: case Value.STRING_FIXED: return 1 + getStringLen(v.getString()); case Value.DECIMAL: { BigDecimal x = v.getBigDecimal(); if (BigDecimal.ZERO.equals(x)) { return 1; } else if (BigDecimal.ONE.equals(x)) { return 1; } int scale = x.scale(); BigInteger b = x.unscaledValue(); int bits = b.bitLength(); if (bits <= 63) { if (scale == 0) { return 1 + getVarLongLen(b.longValue()); } return 1 + getVarIntLen(scale) + getVarLongLen(b.longValue()); } byte[] bytes = b.toByteArray(); return 1 + getVarIntLen(scale) + getVarIntLen(bytes.length) + bytes.length; } case Value.TIME: if (SysProperties.STORE_LOCAL_TIME) { long nanos = ((ValueTime) v).getNanos(); long millis = nanos / 1000000; nanos -= millis * 1000000; return 1 + getVarLongLen(millis) + getVarLongLen(nanos); } return 1 + getVarLongLen(DateTimeUtils.getTimeLocalWithoutDst(v.getTime())); case Value.DATE: { if (SysProperties.STORE_LOCAL_TIME) { long dateValue = ((ValueDate) v).getDateValue(); return 1 + getVarLongLen(dateValue); } long x = DateTimeUtils.getTimeLocalWithoutDst(v.getDate()); return 1 + getVarLongLen(x / MILLIS_PER_MINUTE); } case Value.TIMESTAMP: { if (SysProperties.STORE_LOCAL_TIME) { ValueTimestamp ts = (ValueTimestamp) v; long dateValue = ts.getDateValue(); long nanos = ts.getNanos(); long millis = nanos / 1000000; nanos -= millis * 1000000; return 1 + getVarLongLen(dateValue) + getVarLongLen(millis) + getVarLongLen(nanos); } Timestamp ts = v.getTimestamp(); return 1 + getVarLongLen(DateTimeUtils.getTimeLocalWithoutDst(ts)) + getVarIntLen(ts.getNanos()); } case Value.JAVA_OBJECT: { byte[] b = v.getBytesNoCopy(); return 1 + getVarIntLen(b.length) + b.length; } case Value.BYTES: { byte[] b = v.getBytesNoCopy(); int len = b.length; if (len < 32) { return 1 + b.length; } return 1 + getVarIntLen(b.length) + b.length; } case Value.UUID: return 1 + LENGTH_LONG + LENGTH_LONG; case Value.BLOB: case Value.CLOB: { int len = 1; ValueLob lob = (ValueLob) v; byte[] small = lob.getSmall(); if (small == null) { len += getVarIntLen(-1); len += getVarIntLen(lob.getTableId()); len += getVarLongLen(lob.getLobId()); len += getVarLongLen(lob.getPrecision()); } else { len += getVarIntLen(small.length); len += small.length; } return len; } case Value.ARRAY: { Value[] list = ((ValueArray) v).getList(); int len = 1 + getVarIntLen(list.length); for (Value x : list) { len += getValueLen(x, handler); } return len; } case Value.RESULT_SET: { int len = 1; try { ResultSet rs = ((ValueResultSet) v).getResultSet(); rs.beforeFirst(); ResultSetMetaData meta = rs.getMetaData(); int columnCount = meta.getColumnCount(); len += getVarIntLen(columnCount); for (int i = 0; i < columnCount; i++) { len += getStringLen(meta.getColumnName(i + 1)); len += getVarIntLen(meta.getColumnType(i + 1)); len += getVarIntLen(meta.getPrecision(i + 1)); len += getVarIntLen(meta.getScale(i + 1)); } while (rs.next()) { len++; for (int i = 0; i < columnCount; i++) { int t = DataType.convertSQLTypeToValueType(meta.getColumnType(i + 1)); Value val = DataType.readValue(null, rs, i + 1, t); len += getValueLen(val, handler); } } len++; rs.beforeFirst(); } catch (SQLException e) { throw DbException.convert(e); } return len; } default: throw DbException.throwInternalError("type=" + v.getType()); } }