javax.money.MonetaryException Java Examples
The following examples show how to use
javax.money.MonetaryException.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ECBAbstractRateProvider.java From jsr354-ri with Apache License 2.0 | 7 votes |
private RateResult findExchangeRate(ConversionQuery conversionQuery) { LocalDate[] dates = getQueryDates(conversionQuery); if (dates == null) { Comparator<LocalDate> comparator = Comparator.naturalOrder(); LocalDate date = this.rates.keySet().stream() .max(comparator) .orElseThrow(() -> new MonetaryException("There is not more recent exchange rate to rate on ECBRateProvider.")); return new RateResult(this.rates.get(date)); } else { for (LocalDate localDate : dates) { Map<String, ExchangeRate> targets = this.rates.get(localDate); if(Objects.nonNull(targets)) { return new RateResult(targets); } } String datesOnErros = Stream.of(dates).map(date -> date.format(DateTimeFormatter.ISO_LOCAL_DATE)).collect(Collectors.joining(",")); throw new MonetaryException("There is not exchange on day " + datesOnErros + " to rate to rate on ECBRateProvider."); } }
Example #2
Source File: IMFHistoricRateProviderTest.java From jsr354-ri with Apache License 2.0 | 6 votes |
@Test(expectedExceptions = MonetaryException.class) public void shouldReturnErrorWhenFindFromHistoricalUsingPeriod() { LocalDate localDate = YearMonth.of(2011, Month.JANUARY).atDay(9); ConversionQuery conversionQuery = ConversionQueryBuilder.of() .setTermCurrency(EURO) .set(withDaysBetween(localDate.minusDays(1), localDate)) .build(); CurrencyConversion currencyConversion = provider .getCurrencyConversion(conversionQuery); assertNotNull(currencyConversion); MonetaryAmount money = Money.of(BigDecimal.TEN, DOLLAR); currencyConversion.apply(money); fail(); }
Example #3
Source File: USFederalReserveRateReadingHandler.java From javamoney-lib with Apache License 2.0 | 6 votes |
@Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if ("description".equals(qName)) { descriptionNode = true; } else if ("dc:date".equals(qName)) { dcDateNode = true; } else if ("cb:value".equals(qName)) { cbValueNode = true; String units = attributes.getValue("units"); if (attributes.getValue("units") != null) { Matcher matcher = unitsPattern.matcher(units); if (matcher.find()) { try { this.currencyCode = matcher.group(1); } catch (MonetaryException me) { // ignore...currency index not an actual currency } } } } super.startElement(uri, localName, qName, attributes); }
Example #4
Source File: YahooAbstractRateProvider.java From javamoney-lib with Apache License 2.0 | 6 votes |
@Override public ExchangeRate getExchangeRate(ConversionQuery conversionQuery) { Objects.requireNonNull(conversionQuery); try { if (loadLock.await(30, TimeUnit.SECONDS)) { if (rates.isEmpty()) { return null; } RateResult result = findExchangeRate(conversionQuery); ExchangeRateBuilder builder = getBuilder(conversionQuery, result.date); ExchangeRate sourceRate = result.targets.get(conversionQuery.getBaseCurrency() .getCurrencyCode()); ExchangeRate target = result.targets .get(conversionQuery.getCurrency().getCurrencyCode()); return createExchangeRate(conversionQuery, builder, sourceRate, target); }else{ throw new MonetaryException("Failed to load currency conversion data: " + loadState); } } catch(InterruptedException e){ throw new MonetaryException("Failed to load currency conversion data: Load task has been interrupted.", e); } }
Example #5
Source File: YahooAbstractRateProvider.java From javamoney-lib with Apache License 2.0 | 6 votes |
private RateResult findExchangeRate(ConversionQuery conversionQuery) { LocalDate[] dates = getQueryDates(conversionQuery); if (dates == null) { Comparator<LocalDate> comparator = Comparator.naturalOrder(); LocalDate date = this.rates.keySet().stream().sorted(comparator.reversed()).findFirst().orElseThrow(() -> new MonetaryException("There is not more recent exchange rate to rate on ECBRateProvider.")); return new RateResult(date, this.rates.get(date)); } else { for (LocalDate localDate : dates) { Map<String, ExchangeRate> targets = this.rates.get(localDate); if(Objects.nonNull(targets)) { return new RateResult(localDate, targets); } } String datesOnErros = Stream.of(dates).map(date -> date.format(DateTimeFormatter.ISO_LOCAL_DATE)).collect(Collectors.joining(",")); throw new MonetaryException("There is not exchange on day " + datesOnErros + " to rate to rate on ECBRateProvider."); } }
Example #6
Source File: IMFAbstractRateProvider.java From jsr354-ri with Apache License 2.0 | 6 votes |
private ExchangeRate getExchangeRate(List<ExchangeRate> rates,final LocalDate[] dates) { if (Objects.isNull(rates) ) { return null; } if (Objects.isNull(dates)) { return rates.stream() .max(COMPARATOR_EXCHANGE_BY_LOCAL_DATE) .orElseThrow(() -> new MonetaryException("There is not more recent exchange rate to rate on IMFRateProvider.")); } else { for (LocalDate localDate : dates) { Predicate<ExchangeRate> filter = rate -> rate.getContext().get(LocalDate.class).equals(localDate); Optional<ExchangeRate> exchangeRateOptional = rates.stream().filter(filter).findFirst(); if(exchangeRateOptional.isPresent()) { return exchangeRateOptional.get(); } } String datesOnErros = Stream.of(dates).map(date -> date.format(DateTimeFormatter.ISO_LOCAL_DATE)).collect(Collectors.joining(",")); throw new MonetaryException("There is not exchange on day " + datesOnErros + " to rate to rate on IFMRateProvider."); } }
Example #7
Source File: ECBHistoric90RateProviderTest.java From jsr354-ri with Apache License 2.0 | 6 votes |
@Test(expectedExceptions = MonetaryException.class) public void shouldSetTimeInLocalDateTime() { LocalDate localDate = YearMonth.of(2014, Month.JANUARY).atDay(9); ConversionQuery conversionQuery = ConversionQueryBuilder.of() .setTermCurrency(EURO).set(localDate).build(); CurrencyConversion currencyConversion = provider .getCurrencyConversion(conversionQuery); assertNotNull(currencyConversion); MonetaryAmount money = Money.of(BigDecimal.TEN, DOLLAR); MonetaryAmount result = currencyConversion.apply(money); assertEquals(result.getCurrency(), EURO); assertTrue(result.getNumber().doubleValue() > 0); }
Example #8
Source File: ECBHistoric90RateProviderTest.java From jsr354-ri with Apache License 2.0 | 6 votes |
@Test(expectedExceptions = MonetaryException.class) public void shouldReturnErrorWhenFindFromHistoricalUsingPeriod() { LocalDate localDate = YearMonth.of(2011, Month.JANUARY).atDay(9); ConversionQuery conversionQuery = ConversionQueryBuilder.of() .setTermCurrency(EURO) .set(withDaysBetween(localDate.minusDays(1), localDate)) .build(); CurrencyConversion currencyConversion = provider .getCurrencyConversion(conversionQuery); assertNotNull(currencyConversion); MonetaryAmount money = Money.of(BigDecimal.TEN, DOLLAR); currencyConversion.apply(money); fail(); }
Example #9
Source File: USFederalReserveRateProvider.java From javamoney-lib with Apache License 2.0 | 6 votes |
@Override public ExchangeRate getExchangeRate(ConversionQuery conversionQuery) { Objects.requireNonNull(conversionQuery); try { if (loadLock.await(30, TimeUnit.SECONDS)) { if (rates.isEmpty()) { return null; } RateResult result = findExchangeRate(conversionQuery); ExchangeRateBuilder builder = getBuilder(conversionQuery, result.date); ExchangeRate sourceRate = result.targets.get(conversionQuery.getBaseCurrency().getCurrencyCode()); ExchangeRate target = result.targets.get(conversionQuery.getCurrency().getCurrencyCode()); return createExchangeRate(conversionQuery, builder, sourceRate, target); }else{ throw new MonetaryException("Failed to load currency conversion data: " + loadState); } } catch(InterruptedException e){ throw new MonetaryException("Failed to load currency conversion data: Load task has been interrupted.", e); } }
Example #10
Source File: ECBAbstractRateProvider.java From jsr354-ri with Apache License 2.0 | 6 votes |
@Override public ExchangeRate getExchangeRate(ConversionQuery conversionQuery) { Objects.requireNonNull(conversionQuery); try { if (loadLock.await(30, TimeUnit.SECONDS)) { if (rates.isEmpty()) { return null; } RateResult result = findExchangeRate(conversionQuery); ExchangeRateBuilder builder = getBuilder(conversionQuery); ExchangeRate sourceRate = result.targets.get(conversionQuery.getBaseCurrency() .getCurrencyCode()); ExchangeRate target = result.targets .get(conversionQuery.getCurrency().getCurrencyCode()); return createExchangeRate(conversionQuery, builder, sourceRate, target); }else{ throw new MonetaryException("Failed to load currency conversion data: " + loadState); } } catch(InterruptedException e){ throw new MonetaryException("Failed to load currency conversion data: Load task has been interrupted.", e); } }
Example #11
Source File: DefaultMonetaryConversionsSingletonSpi.java From jsr354-ri with Apache License 2.0 | 6 votes |
private Collection<String> getProvidersToUse(ConversionQuery query) { List<String> providersToUse = new ArrayList<>(); List<String> providerNames = query.getProviderNames(); if (providerNames.isEmpty()) { providerNames = getDefaultProviderChain(); if (providerNames.isEmpty()) { throw new IllegalStateException("No default provider chain available."); } } for (String provider : providerNames) { ExchangeRateProvider prov = this.conversionProviders.get(provider); if (prov == null) { throw new MonetaryException("Invalid ExchangeRateProvider (not found): " + provider); } providersToUse.add(provider); } return providersToUse; }
Example #12
Source File: DefaultMonetaryConversionsSingletonSpi.java From jsr354-ri with Apache License 2.0 | 6 votes |
@Override public ExchangeRateProvider getExchangeRateProvider(String... providers) { List<ExchangeRateProvider> provInstances = new ArrayList<>(); for (String provName : providers) { ExchangeRateProvider prov = Optional.ofNullable( this.conversionProviders.get(provName)) .orElseThrow( () -> new MonetaryException( "Unsupported conversion/rate provider: " + provName)); provInstances.add(prov); } if (provInstances.size() == 1) { return provInstances.get(0); } return new CompoundRateProvider(provInstances); }
Example #13
Source File: DefaultMonetaryConversionsSingletonSpi.java From jsr354-ri with Apache License 2.0 | 6 votes |
@Override public ExchangeRateProvider getExchangeRateProvider(ConversionQuery conversionQuery) { Collection<String> providers = getProvidersToUse(conversionQuery); List<ExchangeRateProvider> provInstances = new ArrayList<>(); for (String provName : providers) { ExchangeRateProvider prov = Optional.ofNullable( this.conversionProviders.get(provName)) .orElseThrow( () -> new MonetaryException( "Unsupported conversion/rate provider: " + provName)); provInstances.add(prov); } if (provInstances.isEmpty()) { throw new MonetaryException("No such providers: " + conversionQuery); } if (provInstances.size() == 1) { return provInstances.get(0); } return new CompoundRateProvider(provInstances); }
Example #14
Source File: BuildableCurrencyUnit.java From jsr354-ri with Apache License 2.0 | 6 votes |
/** * Constructor, called from the Builder. * * @param builder the builder, never null. */ BuildableCurrencyUnit(CurrencyUnitBuilder builder) { Objects.requireNonNull(builder.currencyCode, "currencyCode required"); if (builder.numericCode < -1) { throw new MonetaryException("numericCode must be >= -1"); } if (builder.defaultFractionDigits < 0) { throw new MonetaryException("defaultFractionDigits must be >= 0"); } if (builder.currencyContext == null) { throw new MonetaryException("currencyContext must be != null"); } this.defaultFractionDigits = builder.defaultFractionDigits; this.numericCode = builder.numericCode; this.currencyCode = builder.currencyCode; this.currencyContext = builder.currencyContext; }
Example #15
Source File: DefaultMonetaryAmountsSingletonSpi.java From jsr354-ri with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") @Override public <T extends MonetaryAmount> MonetaryAmountFactory<T> getAmountFactory(Class<T> amountType) { MonetaryAmountFactoryProviderSpi<T> f = MonetaryAmountFactoryProviderSpi.class.cast(factories.get(amountType)); if (Objects.nonNull(f)) { return f.createMonetaryAmountFactory(); } throw new MonetaryException("No matching MonetaryAmountFactory found, type=" + amountType.getName()); }
Example #16
Source File: DefaultMonetaryAmountsSingletonSpi.java From jsr354-ri with Apache License 2.0 | 5 votes |
@Override public Class<? extends MonetaryAmount> getDefaultAmountType() { if (Objects.isNull(configuredDefaultAmountType)) { for (MonetaryAmountFactoryProviderSpi<?> f : Bootstrap.getServices(MonetaryAmountFactoryProviderSpi.class)) { if (f.getQueryInclusionPolicy() == MonetaryAmountFactoryProviderSpi.QueryInclusionPolicy.ALWAYS) { configuredDefaultAmountType = f.getAmountType(); break; } } } return Optional.ofNullable(configuredDefaultAmountType) .orElseThrow(() -> new MonetaryException("No MonetaryAmountFactoryProviderSpi registered.")); }
Example #17
Source File: MoneyUtilsTest.java From jsr354-ri with Apache License 2.0 | 5 votes |
@Test public void testCheckAmountParameter() { CurrencyUnit dollar = Monetary.getCurrency("USD"); CurrencyUnit real = Monetary.getCurrency("BRL"); checkAmountParameter(FastMoney.of(0, "USD"), dollar); expectThrows(MonetaryException.class, () -> checkAmountParameter(FastMoney.of(0, "USD"), real)); }
Example #18
Source File: ECBHistoric90RateProviderTest.java From jsr354-ri with Apache License 2.0 | 5 votes |
@Test(expectedExceptions = MonetaryException.class) public void shouldReturnErrorWhenDoesNotFindTheExchangeRate() { LocalDate localDate = YearMonth.of(2011, Month.JANUARY).atDay(9); ConversionQuery conversionQuery = ConversionQueryBuilder.of() .set(localDate).setTermCurrency(EURO).build(); CurrencyConversion currencyConversion = provider .getCurrencyConversion(conversionQuery); assertNotNull(currencyConversion); MonetaryAmount money = Money.of(BigDecimal.TEN, DOLLAR); currencyConversion.apply(money); fail(); }
Example #19
Source File: IMFHistoricRateProviderTest.java From jsr354-ri with Apache License 2.0 | 5 votes |
@Test(expectedExceptions = MonetaryException.class) public void shouldReturnErrorWhenDoesNotFindTheExchangeRate() { LocalDate localDate = YearMonth.of(2011, Month.JANUARY).atDay(9); ConversionQuery conversionQuery = ConversionQueryBuilder.of() .set(localDate).setTermCurrency(EURO).build(); CurrencyConversion currencyConversion = provider .getCurrencyConversion(conversionQuery); assertNotNull(currencyConversion); MonetaryAmount money = Money.of(BigDecimal.TEN, DOLLAR); currencyConversion.apply(money); fail(); }
Example #20
Source File: DefaultResourceCache.java From jsr354-ri with Apache License 2.0 | 5 votes |
@Override public byte[] read(String resourceId) { File f = this.cachedResources.get(resourceId); if (Objects.isNull(f)) { return null; } try { return Files.readAllBytes(f.toPath()); } catch (IOException exception) { throw new MonetaryException("An error on retrieve the resource id: " + resourceId, exception); } }
Example #21
Source File: USFederalReserveRateProvider.java From javamoney-lib with Apache License 2.0 | 5 votes |
private RateResult findExchangeRate(ConversionQuery conversionQuery) { LocalDate[] dates = getQueryDates(conversionQuery); if (dates == null) { Comparator<LocalDate> comparator = Comparator.naturalOrder(); LocalDate date = this.rates .keySet() .stream() .sorted(comparator.reversed()) .findFirst() .orElseThrow( () -> new MonetaryException("There is not more recent exchange rate to rate on " + getDataId())); return new RateResult(date, this.rates.get(date)); } else { for (LocalDate localDate : dates) { Map<String, ExchangeRate> targets = this.rates.get(localDate); if (Objects.nonNull(targets)) { return new RateResult(localDate, targets); } } String datesOnErros = Stream.of(dates).map(date -> date.format(DateTimeFormatter.ISO_LOCAL_DATE)) .collect(Collectors.joining(",")); throw new MonetaryException("There is not exchange on day " + datesOnErros + " to rate to rate on " + getDataId() + "."); } }
Example #22
Source File: BalloonLoanPayment.java From javamoney-lib with Apache License 2.0 | 5 votes |
/** * Private constructor. * * @param rateAndPeriods the target rate and periods, not null. */ private BalloonLoanPayment(RateAndPeriods rateAndPeriods, MonetaryAmount balloonAmount) { super(rateAndPeriods); if(rateAndPeriods.getPeriods()==0){ throw new MonetaryException("Period cannot be 0."); } this.balloonAmount = Objects.requireNonNull(balloonAmount); }
Example #23
Source File: BalloonLoanPayment.java From javamoney-lib with Apache License 2.0 | 5 votes |
@Override public MonetaryAmount apply(MonetaryAmount amountPV) { if(!balloonAmount.getCurrency().equals(amountPV.getCurrency())){ throw new MonetaryException("Currency mismatch: " + balloonAmount.getCurrency() + " <> "+amountPV.getCurrency()); } return calculate(amountPV, balloonAmount, rateAndPeriods); }
Example #24
Source File: DoublingTime.java From javamoney-lib with Apache License 2.0 | 5 votes |
/** * This function returns the number of periods required to double an amount * with continuous compounding, given a rate. * * @param rate the rate * @return the big decimal */ public static BigDecimal calculate(Rate rate) { if(rate.get().signum()==0){ throw new MonetaryException("Cannot calculate DoublingTime with a rate=zero"); } return new BigDecimal(Math.log(2.0d), CalculationContext.mathContext()) .divide( BigDecimal.valueOf( Math.log(1.0d + rate.get().doubleValue()) ), CalculationContext.mathContext()); }
Example #25
Source File: DoublingTimeSimple.java From javamoney-lib with Apache License 2.0 | 5 votes |
/** * This function returns the number of periods required to double an amount * with continuous compounding, given a rate. * * @param rate the rate * @return the big decimal */ public static BigDecimal calculate(Rate rate) { if(rate.get().signum()==0){ throw new MonetaryException("Cannot calculate DoublingTimeSimple with a rate=zero"); } return CalculationContext.one(). divide(rate.get(), CalculationContext.mathContext()); }
Example #26
Source File: FutureValueGrowingAnnuity.java From javamoney-lib with Apache License 2.0 | 5 votes |
/** * Constructor. * * @param discountRate The discount rate, not null. * @param growthRate The growth rate, not null. * @param periods the target periods, >= 0. */ private FutureValueGrowingAnnuity(Rate discountRate, Rate growthRate, int periods) { this.discountRate = Objects.requireNonNull(discountRate); this.growthRate = Objects.requireNonNull(growthRate); if(discountRate.equals(growthRate)){ throw new MonetaryException("Discount rate and growth rate cannot be the same."); } if (periods < 0) { throw new MonetaryException("Periods < 0"); } this.periods = periods; }
Example #27
Source File: FutureValueGrowingAnnuity.java From javamoney-lib with Apache License 2.0 | 5 votes |
/** * Performs the calculation. * * @param firstPayment the first payment * @param discountRate The rate perperiod, not null. If the rate is less than 0, the result will be zero. * @param growthRate The growth rate, not null. * @param periods the target periods, >= 0. * @return the resulting amount, never null. */ public static MonetaryAmount calculate(MonetaryAmount firstPayment, Rate discountRate, Rate growthRate, int periods) { if(discountRate.equals(growthRate)){ throw new MonetaryException("Discount rate and growth rate cannot be the same."); } if(discountRate.get().signum()<0){ return firstPayment.getFactory().setNumber(0.0d).create(); } BigDecimal num = CalculationContext.one().add(discountRate.get()).pow(periods) .subtract(CalculationContext.one().add(growthRate.get()).pow(periods)); BigDecimal denum = discountRate.get().subtract(growthRate.get()); return firstPayment.multiply(num.divide(denum, CalculationContext.mathContext())); }
Example #28
Source File: BalloonLoanPaymentTest.java From javamoney-lib with Apache License 2.0 | 5 votes |
/** * Calculate zero periods. * * @throws Exception the exception */ @Test(expected=MonetaryException.class) public void calculate_zeroPeriods() throws Exception { BalloonLoanPayment.of( RateAndPeriods.of(0.05,0), Money.of(5, "CHF") ); }
Example #29
Source File: FutureValueGrowingAnnuityTest.java From javamoney-lib with Apache License 2.0 | 5 votes |
/** * Of invalid with equal rates. * * @throws Exception the exception */ @Test(expected = MonetaryException.class) public void of_InvalidWithEqualRates() throws Exception { FutureValueGrowingAnnuity val = FutureValueGrowingAnnuity.of( Rate.of(0.05), Rate.of(0.05), 0 ); }
Example #30
Source File: ConversionAggregatorTest.java From jsr354-ri with Apache License 2.0 | 4 votes |
@Test(expectedExceptions = MonetaryException.class) public void shouldSumMoneratyExceptionWhenHasDifferenctsCurrencies() { Stream<MonetaryAmount> stream = streamCurrencyDifferent(); stream.reduce(sum()).get(); }