Search in sources :

Example 6 with MonetaryException

use of javax.money.MonetaryException in project jsr354-ri by JavaMoney.

the class ECBAbstractRateProvider method getExchangeRate.

@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);
    }
}
Also used : ExchangeRateBuilder(org.javamoney.moneta.convert.ExchangeRateBuilder) ExchangeRate(javax.money.convert.ExchangeRate) MonetaryException(javax.money.MonetaryException)

Example 7 with MonetaryException

use of javax.money.MonetaryException in project jsr354-ri by JavaMoney.

the class ECBAbstractRateProvider method findExchangeRate.

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.");
    }
}
Also used : LoaderService(org.javamoney.moneta.spi.LoaderService) CurrencyUnit(javax.money.CurrencyUnit) SAXParserFactory(javax.xml.parsers.SAXParserFactory) ProviderContext(javax.money.convert.ProviderContext) Level(java.util.logging.Level) LoaderListener(org.javamoney.moneta.spi.LoaderService.LoaderListener) Map(java.util.Map) SAXParser(javax.xml.parsers.SAXParser) ExchangeRate(javax.money.convert.ExchangeRate) AbstractRateProvider(org.javamoney.moneta.spi.AbstractRateProvider) Monetary(javax.money.Monetary) MathContext(java.math.MathContext) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) MonetaryException(javax.money.MonetaryException) ConversionQuery(javax.money.convert.ConversionQuery) ExchangeRateBuilder(org.javamoney.moneta.convert.ExchangeRateBuilder) DefaultNumberValue(org.javamoney.moneta.spi.DefaultNumberValue) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) Stream(java.util.stream.Stream) CurrencyConversionException(javax.money.convert.CurrencyConversionException) LocalDate(java.time.LocalDate) DateTimeFormatter(java.time.format.DateTimeFormatter) Comparator(java.util.Comparator) Bootstrap(javax.money.spi.Bootstrap) InputStream(java.io.InputStream) ExchangeRate(javax.money.convert.ExchangeRate) LocalDate(java.time.LocalDate) MonetaryException(javax.money.MonetaryException)

Example 8 with MonetaryException

use of javax.money.MonetaryException in project jsr354-ri by JavaMoney.

the class DefaultMonetaryAmountsSingletonQuerySpi method getAmountFactories.

/**
 * (non-Javadoc)
 *
 * @see javax.money.spi.MonetaryAmountsSingletonQuerySpi#getAmountFactories(javax.money.MonetaryAmountFactoryQuery)
 */
@Override
public Collection<MonetaryAmountFactory<?>> getAmountFactories(MonetaryAmountFactoryQuery factoryQuery) {
    Objects.requireNonNull(factoryQuery);
    List<MonetaryAmountFactory<?>> factories = new ArrayList<>();
    // first check for explicit type
    for (@SuppressWarnings("unchecked") MonetaryAmountFactoryProviderSpi<? extends MonetaryAmount> factory : Bootstrap.getServices(MonetaryAmountFactoryProviderSpi.class)) {
        if (factory.getQueryInclusionPolicy() == QueryInclusionPolicy.NEVER) {
            continue;
        }
        if (factoryQuery.getTargetType() == factory.getAmountType()) {
            if (isPrecisionOK(factoryQuery, factory.getMaximalMonetaryContext())) {
                factories.add(factory.createMonetaryAmountFactory());
            } else {
                throw new MonetaryException("Incompatible context required=" + factoryQuery + ", maximal=" + factory.getMaximalMonetaryContext());
            }
        }
    }
    List<MonetaryAmountFactoryProviderSpi<? extends MonetaryAmount>> selection = new ArrayList<>();
    for (@SuppressWarnings("unchecked") MonetaryAmountFactoryProviderSpi<? extends MonetaryAmount> factory : Bootstrap.getServices(MonetaryAmountFactoryProviderSpi.class)) {
        if (factory.getQueryInclusionPolicy() == QueryInclusionPolicy.DIRECT_REFERENCE_ONLY || factory.getQueryInclusionPolicy() == QueryInclusionPolicy.NEVER) {
            continue;
        }
        if (isPrecisionOK(factoryQuery, factory.getMaximalMonetaryContext())) {
            selection.add(factory);
        }
    }
    if (selection.isEmpty()) {
        // fall back, add all selections, ignore flavor
        for (@SuppressWarnings("unchecked") MonetaryAmountFactoryProviderSpi<? extends MonetaryAmount> factory : Bootstrap.getServices(MonetaryAmountFactoryProviderSpi.class)) {
            if (factory.getQueryInclusionPolicy() == QueryInclusionPolicy.DIRECT_REFERENCE_ONLY || factory.getQueryInclusionPolicy() == QueryInclusionPolicy.NEVER) {
                continue;
            }
            if (isPrecisionOK(factoryQuery, factory.getMaximalMonetaryContext())) {
                selection.add(factory);
            }
        }
    }
    if (selection.size() == 1) {
        factories.add(selection.get(0).createMonetaryAmountFactory());
    }
    MonetaryContext context = createContext(factoryQuery);
    factories.forEach(f -> f.setContext(context));
    selection.sort(CONTEXT_COMPARATOR);
    factories.add(selection.get(0).createMonetaryAmountFactory());
    return factories;
}
Also used : MonetaryAmount(javax.money.MonetaryAmount) MonetaryAmountFactoryProviderSpi(javax.money.spi.MonetaryAmountFactoryProviderSpi) ArrayList(java.util.ArrayList) MonetaryAmountFactory(javax.money.MonetaryAmountFactory) MonetaryContext(javax.money.MonetaryContext) MonetaryException(javax.money.MonetaryException)

Example 9 with MonetaryException

use of javax.money.MonetaryException in project jsr354-ri by JavaMoney.

the class CurrencyToken method parse.

/**
 * Parses a currency from the given {@link ParseContext}. Depending on the
 * current {@link CurrencyStyle} it interprets the next non empty token,
 * either as
 * <ul>
 * <li>currency code
 * <li>currency symbol
 * </ul>
 * Parsing of localized currency names or numeric code is not supported.
 *
 * @throws UnsupportedOperationException if the {@link CurrencyStyle} is configured to us currency
 *                                       names, or numeric codes for formatting.
 */
@Override
public void parse(ParseContext context) throws MonetaryParseException {
    String token = context.lookupNextToken();
    while (Objects.nonNull(token)) {
        if (token.trim().isEmpty()) {
            context.consume(token);
            token = context.lookupNextToken();
            continue;
        }
        break;
    }
    if (token == null) {
        throw new MonetaryException("Error parsing CurrencyUnit: no input.");
    }
    try {
        CurrencyUnit cur;
        switch(style) {
            case CODE:
                if (!Monetary.isCurrencyAvailable(token)) {
                    // Perhaps blank is missing between currency code and number...
                    String subCurrency = parseCurrencyCode(token);
                    cur = Monetary.getCurrency(subCurrency);
                    context.consume(subCurrency);
                } else {
                    cur = Monetary.getCurrency(token);
                    context.consume(token);
                }
                break;
            case SYMBOL:
                if (token.startsWith("$")) {
                    throw new MonetaryParseException("$ is not a unique currency symbol.", token, context.getErrorIndex());
                } else if (token.startsWith("€")) {
                    cur = Monetary.getCurrency("EUR");
                    context.consume("€");
                } else if (token.startsWith("£")) {
                    cur = Monetary.getCurrency("GBP");
                    context.consume("£");
                } else {
                    cur = Monetary.getCurrency(token);
                    context.consume(token);
                }
                context.setParsedCurrency(cur);
                break;
            case NAME:
            case NUMERIC_CODE:
            default:
                throw new UnsupportedOperationException("Not yet implemented");
        }
        if (Objects.nonNull(cur)) {
            context.setParsedCurrency(cur);
        }
    } catch (Exception e) {
        throw new MonetaryException("Error parsing CurrencyUnit.", e);
    }
}
Also used : CurrencyUnit(javax.money.CurrencyUnit) MonetaryParseException(javax.money.format.MonetaryParseException) MonetaryException(javax.money.MonetaryException) IOException(java.io.IOException) MonetaryParseException(javax.money.format.MonetaryParseException) MonetaryException(javax.money.MonetaryException)

Example 10 with MonetaryException

use of javax.money.MonetaryException in project jsr354-ri by JavaMoney.

the class IMFAbstractRateProvider method getExchangeRate.

private ExchangeRate getExchangeRate(List<ExchangeRate> rates, final LocalDate[] dates) {
    if (Objects.isNull(rates)) {
        return null;
    }
    if (Objects.isNull(dates)) {
        return rates.stream().sorted(COMPARATOR_EXCHANGE_BY_LOCAL_DATE.reversed()).findFirst().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.");
    }
}
Also used : CurrencyContextBuilder(javax.money.CurrencyContextBuilder) CurrencyUnit(javax.money.CurrencyUnit) HashMap(java.util.HashMap) Currency(java.util.Currency) ProviderContext(javax.money.convert.ProviderContext) LoaderListener(org.javamoney.moneta.spi.LoaderService.LoaderListener) Locale(java.util.Locale) RateIMFResult(org.javamoney.moneta.convert.internal.imf.IMFRateReadingHandler.RateIMFResult) Map(java.util.Map) ExchangeRate(javax.money.convert.ExchangeRate) AbstractRateProvider(org.javamoney.moneta.spi.AbstractRateProvider) Monetary(javax.money.Monetary) CurrencyUnitBuilder(org.javamoney.moneta.CurrencyUnitBuilder) Predicate(java.util.function.Predicate) MonetaryException(javax.money.MonetaryException) ConversionQuery(javax.money.convert.ConversionQuery) ExchangeRateBuilder(org.javamoney.moneta.convert.ExchangeRateBuilder) Logger(java.util.logging.Logger) Collectors(java.util.stream.Collectors) ConversionContext(javax.money.convert.ConversionContext) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Stream(java.util.stream.Stream) LocalDate(java.time.LocalDate) DateTimeFormatter(java.time.format.DateTimeFormatter) Optional(java.util.Optional) Comparator(java.util.Comparator) Collections(java.util.Collections) InputStream(java.io.InputStream) ExchangeRate(javax.money.convert.ExchangeRate) LocalDate(java.time.LocalDate) MonetaryException(javax.money.MonetaryException)

Aggregations

MonetaryException (javax.money.MonetaryException)18 ArrayList (java.util.ArrayList)8 CurrencyUnit (javax.money.CurrencyUnit)8 ExchangeRateProvider (javax.money.convert.ExchangeRateProvider)7 ExchangeRate (javax.money.convert.ExchangeRate)6 ExchangeRateBuilder (org.javamoney.moneta.convert.ExchangeRateBuilder)6 CompoundRateProvider (org.javamoney.moneta.spi.CompoundRateProvider)4 LocalDate (java.time.LocalDate)3 IOException (java.io.IOException)2 InputStream (java.io.InputStream)2 DateTimeFormatter (java.time.format.DateTimeFormatter)2 Comparator (java.util.Comparator)2 Map (java.util.Map)2 Objects (java.util.Objects)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 TimeUnit (java.util.concurrent.TimeUnit)2 Logger (java.util.logging.Logger)2 Collectors (java.util.stream.Collectors)2 Stream (java.util.stream.Stream)2 Monetary (javax.money.Monetary)2