Search in sources :

Example 46 with CurrencyUnit

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

the class CurrenciesTest method testGetCurrencyString.

/**
 * Test method for
 * {@link javax.money.Monetary#getCurrency(java.lang.String, String...)} .
 */
@Test
public void testGetCurrencyString() {
    CurrencyUnit cur = Monetary.getCurrency("CHF");
    assertNotNull(cur);
    Currency jdkCurrency = Currency.getInstance("CHF");
    assertEquals(jdkCurrency.getCurrencyCode(), cur.getCurrencyCode());
    assertEquals(jdkCurrency.getNumericCode(), cur.getNumericCode());
    assertEquals(jdkCurrency.getDefaultFractionDigits(), cur.getDefaultFractionDigits());
}
Also used : CurrencyUnit(javax.money.CurrencyUnit) Currency(java.util.Currency) Test(org.testng.annotations.Test)

Example 47 with CurrencyUnit

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

the class IMFRateProvider method loadRatesTSV.

@SuppressWarnings("unchecked")
private void loadRatesTSV(InputStream inputStream) throws IOException, ParseException {
    Map<CurrencyUnit, List<ExchangeRate>> newCurrencyToSdr = new HashMap<>();
    Map<CurrencyUnit, List<ExchangeRate>> newSdrToCurrency = new HashMap<>();
    NumberFormat f = new DecimalFormat("#0.0000000000");
    f.setGroupingUsed(false);
    BufferedReader pr = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
    String line = pr.readLine();
    if (line.contains("Request Rejected")) {
        throw new IOException("Request has been rejected by IMF server.");
    }
    // int lineType = 0;
    boolean currencyToSdr = true;
    // SDRs per Currency unit (2)
    // 
    // Currency January 31, 2013 January 30, 2013 January 29, 2013
    // January 28, 2013 January 25, 2013
    // Euro 0.8791080000 0.8789170000 0.8742470000 0.8752180000
    // 0.8768020000
    // Currency units per SDR(3)
    // 
    // Currency January 31, 2013 January 30, 2013 January 29, 2013
    // January 28, 2013 January 25, 2013
    // Euro 1.137520 1.137760 1.143840 1.142570 1.140510
    List<LocalDate> timestamps = null;
    while (line != null) {
        if (line.trim().isEmpty()) {
            line = pr.readLine();
            continue;
        }
        if (line.startsWith("SDRs per Currency unit")) {
            currencyToSdr = false;
            line = pr.readLine();
            continue;
        } else if (line.startsWith("Currency units per SDR")) {
            currencyToSdr = true;
            line = pr.readLine();
            continue;
        } else if (line.startsWith("Currency")) {
            timestamps = readTimestamps(line);
            line = pr.readLine();
            continue;
        }
        String[] parts = line.split("\\t");
        CurrencyUnit currency = currenciesByName.get(parts[0]);
        if (currency == null) {
            LOGGER.finest("Uninterpretable data from IMF data feed: " + parts[0]);
            line = pr.readLine();
            continue;
        }
        Double[] values = parseValues(parts);
        for (int i = 0; i < values.length; i++) {
            if (values[i] == null) {
                continue;
            }
            LocalDate fromTS = timestamps != null ? timestamps.get(i) : null;
            if (fromTS == null) {
                continue;
            }
            RateType rateType = RateType.HISTORIC;
            if (fromTS.equals(LocalDate.now())) {
                rateType = RateType.DEFERRED;
            }
            if (currencyToSdr) {
                // Currency -> SDR
                ExchangeRate rate = new ExchangeRateBuilder(ConversionContextBuilder.create(CONTEXT, rateType).set(fromTS).build()).setBase(currency).setTerm(SDR).setFactor(new DefaultNumberValue(1d / values[i])).build();
                List<ExchangeRate> rates = newCurrencyToSdr.get(currency);
                if (rates == null) {
                    rates = new ArrayList<>(5);
                    newCurrencyToSdr.put(currency, rates);
                }
                rates.add(rate);
            } else {
                // SDR -> Currency
                ExchangeRate rate = new ExchangeRateBuilder(ConversionContextBuilder.create(CONTEXT, rateType).set(fromTS).set("LocalTime", fromTS.toString()).build()).setBase(SDR).setTerm(currency).setFactor(DefaultNumberValue.of(1d / values[i])).build();
                List<ExchangeRate> rates = newSdrToCurrency.get(currency);
                if (rates == null) {
                    rates = new ArrayList<>(5);
                    newSdrToCurrency.put(currency, rates);
                }
                rates.add(rate);
            }
        }
        line = pr.readLine();
    }
    // Cast is save, since contained DefaultExchangeRate is Comparable!
    for (List<ExchangeRate> list : newSdrToCurrency.values()) {
        Collections.sort(List.class.cast(list));
    }
    for (List<ExchangeRate> list : newCurrencyToSdr.values()) {
        Collections.sort(List.class.cast(list));
    }
    this.sdrToCurrency = newSdrToCurrency;
    this.currencyToSdr = newCurrencyToSdr;
    for (Map.Entry<CurrencyUnit, List<ExchangeRate>> entry : this.sdrToCurrency.entrySet()) {
        LOGGER.finest("SDR -> " + entry.getKey().getCurrencyCode() + ": " + entry.getValue());
    }
    for (Map.Entry<CurrencyUnit, List<ExchangeRate>> entry : this.currencyToSdr.entrySet()) {
        LOGGER.finest(entry.getKey().getCurrencyCode() + " -> SDR: " + entry.getValue());
    }
}
Also used : DefaultNumberValue(org.javamoney.moneta.spi.DefaultNumberValue) ExchangeRate(javax.money.convert.ExchangeRate) HashMap(java.util.HashMap) DecimalFormat(java.text.DecimalFormat) ArrayList(java.util.ArrayList) List(java.util.List) RateType(javax.money.convert.RateType) CurrencyUnit(javax.money.CurrencyUnit) InputStreamReader(java.io.InputStreamReader) IOException(java.io.IOException) ExchangeRateBuilder(org.javamoney.moneta.convert.ExchangeRateBuilder) BufferedReader(java.io.BufferedReader) HashMap(java.util.HashMap) Map(java.util.Map) NumberFormat(java.text.NumberFormat)

Example 48 with CurrencyUnit

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

the class JDKCurrencyProvider method getCurrencies.

/**
 * Return a {@link CurrencyUnit} instances matching the given
 * {@link javax.money.CurrencyContext}.
 *
 * @param currencyQuery the {@link javax.money.CurrencyContext} containing the parameters determining the query. not null.
 * @return the corresponding {@link CurrencyUnit}, or null, if no such unit
 * is provided by this provider.
 */
public Set<CurrencyUnit> getCurrencies(CurrencyQuery currencyQuery) {
    Set<CurrencyUnit> result = new HashSet<>();
    if (!currencyQuery.getCurrencyCodes().isEmpty()) {
        for (String code : currencyQuery.getCurrencyCodes()) {
            CurrencyUnit cu = CACHED.get(code);
            if (cu != null) {
                result.add(cu);
            }
        }
        return result;
    }
    if (!currencyQuery.getCountries().isEmpty()) {
        for (Locale country : currencyQuery.getCountries()) {
            CurrencyUnit cu = getCurrencyUnit(country);
            if (cu != null) {
                result.add(cu);
            }
        }
        return result;
    }
    if (!currencyQuery.getNumericCodes().isEmpty()) {
        for (Integer numCode : currencyQuery.getNumericCodes()) {
            List<CurrencyUnit> cus = getCurrencyUnits(numCode);
            result.addAll(cus);
        }
        return result;
    }
    // No constraints defined, return all.
    result.addAll(CACHED.values());
    return result;
}
Also used : CurrencyUnit(javax.money.CurrencyUnit)

Example 49 with CurrencyUnit

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

the class JDKCurrencyProvider method loadCurrencies.

private static Map<String, CurrencyUnit> loadCurrencies() {
    Set<Currency> availableCurrencies = Currency.getAvailableCurrencies();
    Map<String, CurrencyUnit> result = new HashMap<>(availableCurrencies.size());
    for (Currency jdkCurrency : availableCurrencies) {
        CurrencyUnit cu = new JDKCurrencyAdapter(jdkCurrency);
        result.put(cu.getCurrencyCode(), cu);
    }
    return Collections.unmodifiableMap(result);
}
Also used : CurrencyUnit(javax.money.CurrencyUnit)

Example 50 with CurrencyUnit

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

the class ToStringMonetaryAmountFormat method parserMonetaryAmount.

private ParserMonetaryAmount parserMonetaryAmount(CharSequence text) {
    String[] array = Objects.requireNonNull(text).toString().split(" ");
    if (array.length != 2) {
        throw new MonetaryParseException("An error happened when try to parse the Monetary Amount.", text, 0);
    }
    CurrencyUnit currencyUnit = Monetary.getCurrency(array[0]);
    BigDecimal number = new BigDecimal(array[1]);
    return new ParserMonetaryAmount(currencyUnit, number);
}
Also used : CurrencyUnit(javax.money.CurrencyUnit) MonetaryParseException(javax.money.format.MonetaryParseException) BigDecimal(java.math.BigDecimal)

Aggregations

CurrencyUnit (javax.money.CurrencyUnit)116 Test (org.testng.annotations.Test)78 MonetaryAmount (javax.money.MonetaryAmount)57 BigDecimal (java.math.BigDecimal)14 Currency (java.util.Currency)8 MonetaryException (javax.money.MonetaryException)6 ExchangeRate (javax.money.convert.ExchangeRate)6 RoundedMoney (org.javamoney.moneta.RoundedMoney)6 IOException (java.io.IOException)5 MathContext (java.math.MathContext)5 MonetaryParseException (javax.money.format.MonetaryParseException)5 Money (org.javamoney.moneta.Money)4 ExchangeRateBuilder (org.javamoney.moneta.convert.ExchangeRateBuilder)3 DefaultNumberValue (org.javamoney.moneta.spi.DefaultNumberValue)3 Test (org.junit.Test)3 BufferedReader (java.io.BufferedReader)2 InputStreamReader (java.io.InputStreamReader)2 LocalDate (java.time.LocalDate)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2