/**
  * Access and test different Currency Conversions for the provider in place.
  *
  * <p>Test TCK providers, but also test implementation providers. Doing the ladder it is not
  * possible to test the rates quality, just that rates are returned if necessary.
  */
 @Test(
     description =
         "4.3.1 Access Conversion to term currency code XXX for all providers that support according "
             + "conversion, if"
             + "available a non-null CurrencyConversion must be provided.")
 @SpecAssertion(id = "431-A2", section = "4.3.1")
 public void testConversionsAreAvailable() {
   for (String providerName : MonetaryConversions.getConversionProviderNames()) {
     try {
       if (MonetaryConversions.isConversionAvailable("XXX", providerName)) {
         CurrencyConversion conv = MonetaryConversions.getConversion("XXX", providerName);
         AssertJUnit.assertNotNull(
             "CurrencyConversion returned from MonetaryConversions.getConversion(String, "
                 + "String...) should never be null: "
                 + providerName,
             conv);
         AssertJUnit.assertTrue(
             "CurrencyConversion is not flagged as available, "
                 + "though it was returned from MonetaryConversions.getConversion"
                 + "(String,"
                 + " String...): "
                 + providerName,
             MonetaryConversions.isConversionAvailable("XXX", providerName));
       }
     } catch (MonetaryException e) {
       AssertJUnit.assertFalse(
           "CurrencyConversion is not flagged as NOT available, though it is not accessible from "
               + "MonetaryConversions.getConversion(String, String...): "
               + providerName,
           MonetaryConversions.isConversionAvailable("XXX", providerName));
     }
   }
 }
 /**
  * Access and test different Currency Conversions for the provider in place.
  *
  * <p>Test TCK providers, but also test implementation providers. Doing the ladder it is not
  * possible to test the rates quality, just that rates are returned if necessary.
  */
 @Test(
     description =
         "4.3.1 Access Conversion by query to term currency XXX for all providers that support according "
             + "conversion, if"
             + "available a non-null CurrencyConversion must be provided.")
 @SpecAssertion(id = "431-A2", section = "4.3.1")
 public void testConversionsAreAvailableWithQuery() {
   for (String providerName : MonetaryConversions.getConversionProviderNames()) {
     ConversionQuery query =
         ConversionQueryBuilder.of().setTermCurrency("XXX").setProviderNames(providerName).build();
     try {
       if (MonetaryConversions.isConversionAvailable(query)) {
         CurrencyConversion conv = MonetaryConversions.getConversion(query);
         AssertJUnit.assertNotNull(
             "CurrencyConversion returned from MonetaryConversions.getConversion(ConversionQuery) must"
                 + " "
                 + "never be null: "
                 + providerName,
             conv);
         AssertJUnit.assertTrue(
             "CurrencyConversion is not flagged as available though it was returned from "
                 + "MonetaryConversions.getConversion(ConversionQuery): "
                 + providerName,
             MonetaryConversions.isConversionAvailable(query));
       }
     } catch (MonetaryException e) {
       // OK, possible!
       AssertJUnit.assertFalse(
           "CurrencyConversion is not flagged as not available, though it was not returned from "
               + "MonetaryConversions.getConversion(ConversionQuery): "
               + providerName,
           MonetaryConversions.isConversionAvailable(query));
     }
   }
 }
 /**
  * Test if all providers returns valid meta data.
  *
  * @see javax.money.convert.ProviderContext
  */
 @Test(
     description =
         "4.3.1 Test if all CurrencyConversion instances returns valid ConversionContext, accessed by "
             + "ConversionQuery/CurrencyUnit.")
 @SpecAssertion(id = "431-A3", section = "4.3.1")
 public void testProviderMetadata3WithContext() {
   for (String providerName : MonetaryConversions.getConversionProviderNames()) {
     ConversionQuery query =
         ConversionQueryBuilder.of()
             .setTermCurrency(Monetary.getCurrency("XXX"))
             .setProviderName(providerName)
             .build();
     if (MonetaryConversions.isConversionAvailable(query)) {
       CurrencyConversion conv = MonetaryConversions.getConversion(query);
       ConversionContext ctx = conv.getContext();
       AssertJUnit.assertNotNull(
           "ExchangeProvider must return a valid ProviderContext, but returned null: "
               + providerName,
           ctx);
       AssertJUnit.assertEquals(
           "ExchangeProvider's ProviderContext returns invalid name: " + providerName,
           providerName,
           ctx.getProviderName());
       AssertJUnit.assertNotNull(
           "ExchangeProvider's ProviderContext declares invalid RateTypes to be returned (null): "
               + providerName,
           ctx.getRateType());
     }
   }
 }
 /**
  * Test if all providers returns valid meta data.
  *
  * @see javax.money.convert.ProviderContext
  */
 @Test(
     description =
         "4.3.1 Test if all CurrencyConversion instances returns valid ConversionContext, accessed by "
             + "currency code.")
 @SpecAssertion(id = "431-A3", section = "4.3.1")
 public void testProviderMetadata2() {
   for (String providerName : MonetaryConversions.getConversionProviderNames()) {
     if (MonetaryConversions.isConversionAvailable("XXX", providerName)) {
       CurrencyConversion conv = MonetaryConversions.getConversion("XXX", providerName);
       ConversionContext ctx = conv.getContext();
       AssertJUnit.assertNotNull(
           "ExchangeProvider must return a valid ProviderContext, but returned null: "
               + providerName,
           ctx);
       AssertJUnit.assertEquals(
           "ExchangeProvider's ProviderContext returns invalid name: " + providerName,
           providerName,
           ctx.getProviderName());
       AssertJUnit.assertNotNull(
           "ExchangeProvider's ProviderContext declares invalid RateTypes to be returned (null): "
               + providerName,
           ctx.getRateType());
     }
   }
 }
 /**
  * Test if all providers returns valid meta data.
  *
  * @see javax.money.convert.ProviderContext
  */
 @Test(
     description =
         "4.3.1 Test if all ExchangeRateProvider instances returns valid ProviderContext.")
 @SpecAssertion(id = "431-A3", section = "4.3.1")
 public void testProviderMetadata() {
   for (String providerName : MonetaryConversions.getConversionProviderNames()) {
     ExchangeRateProvider prov = MonetaryConversions.getExchangeRateProvider(providerName);
     AssertJUnit.assertNotNull("Provider mot accessible: " + providerName, prov);
     ProviderContext ctx = prov.getContext();
     AssertJUnit.assertNotNull(
         "ExchangeProvider must return a valid ProviderContext, but returned null: "
             + providerName,
         ctx);
     AssertJUnit.assertEquals(
         "ExchangeProvider's ProviderContext returns invalid name: " + providerName,
         providerName,
         ctx.getProviderName());
     AssertJUnit.assertNotNull(
         "ExchangeProvider's ProviderContext declares invalid RateTypes to be returned (null): "
             + providerName,
         ctx.getRateTypes());
     AssertJUnit.assertFalse(
         "ExchangeProvider's ProviderContext declares empty RateTypes to be returned: "
             + providerName,
         ctx.getRateTypes().isEmpty());
   }
 }
 /** Access the conversion using the default conversion chain. */
 @Test(description = "4.3.1 Access and test conversion using the default provider chain.")
 @SpecAssertion(id = "431-A5", section = "4.3.1")
 public void testDefaultConversion() {
   ConversionQuery query =
       ConversionQueryBuilder.of().setTermCurrency(Monetary.getCurrency("USD")).build();
   CurrencyConversion conv = MonetaryConversions.getConversion(query);
   AssertJUnit.assertNotNull("No default CurrencyConversion returned for USD.", conv);
   query = ConversionQueryBuilder.of().setTermCurrency(Monetary.getCurrency("EUR")).build();
   conv = MonetaryConversions.getConversion(query);
   AssertJUnit.assertNotNull("No default CurrencyConversion returned for EUR.", conv);
 }
 /**
  * Access the default provider chain. Compare with entries from javamoney.properties. The chain
  * must not be empty!
  */
 @Test(description = "4.3.1 Access and test the default conversion provider chain.")
 @SpecAssertion(id = "431-A4", section = "4.3.1")
 public void testDefaultProviderChainIsDefined() {
   ExchangeRateProvider prov = MonetaryConversions.getExchangeRateProvider();
   AssertJUnit.assertNotNull("No default ExchangeRateProvider returned.", prov);
   // we cannot test more here...
 }
 /**
  * Access the default provider chain. Compare with entries from javamoney.properties. The chain
  * must not be empty!
  */
 @Test(
     description =
         "4.3.1 Access and test the default conversion provider chain, by accessing a default"
             + "CurrencyConversion for term currency code CHF.")
 @SpecAssertion(id = "431-A4", section = "4.3.1")
 public void testDefaultProviderChainIsDefinedDefault2() {
   CurrencyConversion conv = MonetaryConversions.getConversion("CHF");
   AssertJUnit.assertNotNull("No default CurrencyConversion returned.", conv);
   // we cannot test more here...
 }
 /** Bad case: Test access of an inexistent provider. Should throw a MonetaryException */
 @Test(
     expectedExceptions = MonetaryException.class,
     description =
         "4.3.1 Bad case: Access invalid "
             + "ExchangeRateProvider, expect MonetaryException thrown, using default provider chain.")
 @SpecAssertion(
     id = "431-A6",
     section = "4.3.1",
     note = "Accessing an invalid provider name, should throw a MonetaryException.")
 public void testUseInvalidProvider() {
   MonetaryConversions.getExchangeRateProvider("Dhdkjdhskljdsudgsdkjgjk sgdsjdg");
 }
 /**
  * Access the default provider chain. Compare with entries from javamoney.properties. The chain
  * must not be empty!
  */
 @Test(
     description =
         "4.3.1 Access and test the default conversion provider chain, by accessing a default"
             + "CurrencyConversion for ConversionQuery.")
 @SpecAssertion(id = "431-A4", section = "4.3.1")
 public void testDefaultProviderChainIsDefinedDefaultWithContext() {
   ConversionQuery query =
       ConversionQueryBuilder.of().setTermCurrency(Monetary.getCurrency("CHF")).build();
   CurrencyConversion conv = MonetaryConversions.getConversion(query);
   AssertJUnit.assertNotNull("No default CurrencyConversion returned.", conv);
   // we cannot test more here...
 }
 /**
  * Ensure at least one conversion provider is available.
  *
  * <p>Hint: ignore all TCK test providers, only count up productive providers.
  */
 @Test(
     description =
         "4.3.1 Ensure at least one conversion provider is available, TestRateProvider must be present.")
 @SpecAssertion(id = "431-A1", section = "4.3.1")
 public void testProvidersAvailable() {
   int providerCount = 0;
   for (String providername : MonetaryConversions.getConversionProviderNames()) {
     if (!"TestRateProvider".equals(providername)) {
       providerCount++;
     }
   }
   AssertJUnit.assertTrue(
       "At least one conversion provider must be available/registered.", providerCount > 0);
 }
Пример #12
0
  public static void main(String[] args) {
    // getting CurrencyUnit by currency code and locale
    CurrencyUnit euro = Monetary.getCurrency("EUR");
    CurrencyUnit dollar = Monetary.getCurrency(Locale.US);

    System.out.println("getting CurrencyUnit by currency code and locale");
    System.out.printf("%s\n", euro);
    System.out.printf("%s\n", dollar);

    // getting MonetaryAmount by currency code and CurrencyUnit, without using Money (implementation
    // class)
    MonetaryAmount fiveEuro = Money.of(5, euro);
    MonetaryAmount twelveEuro = Money.of(new BigDecimal("12"), euro);
    MonetaryAmount tenDollar = Money.of(10, "USD");
    MonetaryAmount tenPound =
        Monetary.getDefaultAmountFactory().setNumber(10).setCurrency("GBP").create();

    System.out.println();
    System.out.println(
        "getting MonetaryAmount by currency code and CurrencyUnit, without using Money (implementation class)");
    System.out.printf("5 EUR: %s\n", fiveEuro);
    System.out.printf("12 EUR: %s\n", twelveEuro);
    System.out.printf("10 USD: %s\n", tenDollar);
    System.out.printf("10 GBP: %s\n", tenPound);

    // getting currency, the numeric amount and precision
    MonetaryAmount amount = Money.of(123.45, euro);

    System.out.println();
    System.out.println("getting currency, the numeric amount and precision");
    System.out.printf("123.45 EUR (currency): %s\n", amount.getCurrency());
    System.out.printf("123.45 EUR (long): %s\n", amount.getNumber().longValue());
    System.out.printf("123.45 EUR (number): %s\n", amount.getNumber());
    System.out.printf(
        "123.45 EUR (fractionNumerator): %s\n", amount.getNumber().getAmountFractionNumerator());
    System.out.printf(
        "123.45 EUR (fractionDenominator): %s\n",
        amount.getNumber().getAmountFractionDenominator());
    System.out.printf(
        "123.45 EUR (amount, BigDecimal): %s\n", amount.getNumber().numberValue(BigDecimal.class));

    // aritmetic
    MonetaryAmount seventeenEuros = fiveEuro.add(twelveEuro);
    MonetaryAmount sevenEuros = twelveEuro.subtract(fiveEuro);
    MonetaryAmount tenEuro = fiveEuro.multiply(2);
    MonetaryAmount twoPointFiveEuro = fiveEuro.divide(2);

    System.out.println();
    System.out.println("aritmetic");
    System.out.printf("5 EUR + 12 EUR: %s\n", seventeenEuros);
    System.out.printf("12 EUR - 5 EUR: %s\n", sevenEuros);
    System.out.printf("5 EUR * 2: %s\n", tenEuro);
    System.out.printf("5 EUR / 2: %s\n", twoPointFiveEuro);

    // negative
    MonetaryAmount minusSevenEuro = fiveEuro.subtract(twelveEuro);

    System.out.println();
    System.out.println("negative");
    System.out.printf("5 EUR - 12 EUR: %s\n", minusSevenEuro);

    // Note that MonetaryAmounts need to have the same CurrencyUnit to do mathematical operations
    // this fails with: javax.money.MonetaryException: Currency mismatch: EUR/USD
    // fiveEuro.add(tenDollar);

    // comparing
    System.out.println();
    System.out.println("comparing");
    System.out.printf("7€ < 10€: %s\n", sevenEuros.isLessThan(tenEuro));
    System.out.printf("7€ > 10€: %s\n", sevenEuros.isGreaterThan(tenEuro));
    System.out.printf("10 > 7€: %s\n", tenEuro.isGreaterThan(sevenEuros));

    // rounding
    MonetaryAmount euros = Money.of(12.34567, "EUR");
    MonetaryAmount roundedEuros = euros.with(Monetary.getDefaultRounding());

    System.out.println();
    System.out.println("rounding");
    System.out.printf("12.34567 EUR redondeados: %s\n", roundedEuros);

    // streams
    List<MonetaryAmount> amounts = new ArrayList<>();
    amounts.add(Money.of(2, "EUR"));
    amounts.add(Money.of(7, "USD"));
    amounts.add(Money.of(18, "USD"));
    amounts.add(Money.of(42, "USD"));
    amounts.add(Money.of(13.37, "GBP"));

    // filter
    List<MonetaryAmount> onlyDollars =
        amounts.stream().filter(MonetaryFunctions.isCurrency(dollar)).collect(Collectors.toList());

    System.out.println();
    System.out.println("filter");
    System.out.printf("Solo USD: %s\n", onlyDollars);

    List<MonetaryAmount> euroAndDollar =
        amounts
            .stream()
            .filter(MonetaryFunctions.isCurrency(euro, dollar))
            .collect(Collectors.toList());

    System.out.printf("Solo EUR y USD: %s\n", euroAndDollar);

    List<MonetaryAmount> greaterThanTenDollar =
        amounts
            .stream()
            .filter(MonetaryFunctions.isCurrency(dollar))
            .filter(MonetaryFunctions.isGreaterThan(tenDollar))
            .collect(Collectors.toList());

    System.out.printf("Solo USD y mayores que 10: %s\n", greaterThanTenDollar);

    List<MonetaryAmount> sortedByAmount =
        onlyDollars.stream().sorted(MonetaryFunctions.sortNumber()).collect(Collectors.toList());

    System.out.printf("Solo USD y ordenados: %s\n", sortedByAmount);

    // grouping
    Map<CurrencyUnit, List<MonetaryAmount>> groupedByCurrency =
        amounts.stream().collect(MonetaryFunctions.groupByCurrencyUnit());

    System.out.println();
    System.out.println("grouping");
    System.out.printf("Agrupación por divisa: %s\n", groupedByCurrency);

    // reduction
    List<MonetaryAmount> euroAmounts = new ArrayList<>();
    euroAmounts.add(Money.of(7.5, "EUR"));
    euroAmounts.add(Money.of(10, "EUR"));
    euroAmounts.add(Money.of(12, "EUR"));

    Optional<MonetaryAmount> max = euroAmounts.stream().reduce(MonetaryFunctions.max());
    Optional<MonetaryAmount> min = euroAmounts.stream().reduce(MonetaryFunctions.min());
    Optional<MonetaryAmount> sum = euroAmounts.stream().reduce(MonetaryFunctions.sum());

    System.out.println();
    System.out.println("reduction");
    System.out.printf("Máximo %s, mínimo %s, suma %s\n", max.get(), min.get(), sum.get());

    // exchange rates
    ExchangeRateProvider exchangeRateProviderECB =
        MonetaryConversions.getExchangeRateProvider("ECB");
    ExchangeRateProvider exchangeRateProviderOER =
        MonetaryConversions.getExchangeRateProvider("OER");
    ExchangeRate exchangeRateECB = exchangeRateProviderECB.getExchangeRate("USD", "EUR");
    ExchangeRate exchangeRateOER = exchangeRateProviderOER.getExchangeRate("USD", "EUR");

    System.out.println();
    System.out.println("exchange rates");
    System.out.printf(
        "Ratio de conversión de USD a EUR (ECB, European Central Bank): %f\n",
        exchangeRateECB.getFactor().doubleValue());
    System.out.printf(
        "Ratio de conversión de USD a EUR (OER, Open Exchange Rates): %f\n",
        exchangeRateOER.getFactor().doubleValue());

    // conversion
    CurrencyConversion toEuroECB = MonetaryConversions.getConversion("EUR", "ECB");
    CurrencyConversion toEuroOER = MonetaryConversions.getConversion("EUR", "OER");
    MonetaryAmount tenDollarToEuroECB = tenDollar.with(toEuroECB);
    MonetaryAmount tenDollarToEuroOER = tenDollar.with(toEuroOER);

    System.out.println();
    System.out.println("conversion");
    System.out.printf("10 USD son %s EUR (ECB)\n", tenDollarToEuroECB);
    System.out.printf("10 USD son %s EUR (OER)\n", tenDollarToEuroOER);

    // formating
    MonetaryAmountFormat spainFormat = MonetaryFormats.getAmountFormat(new Locale("es", "ES"));
    MonetaryAmountFormat usFormat = MonetaryFormats.getAmountFormat(new Locale("en", "US"));
    MonetaryAmount fiveThousandEuro = Money.of(5000, euro);

    System.out.println();
    System.out.println("formating");
    System.out.printf(
        "Formato de 5000 EUR localizado en España: %s\n", spainFormat.format(fiveThousandEuro));
    System.out.printf(
        "Formato de 5000 EUR localizado en Estados Unidos: %s\n",
        usFormat.format(fiveThousandEuro));

    // parsing
    MonetaryAmount twelvePointFiveEuro = spainFormat.parse("12,50 EUR");

    System.out.println();
    System.out.println("parsing");
    System.out.printf("Analizando «12,50 EUR» es %s\n", spainFormat.format(twelvePointFiveEuro));

    // custom exchange rates provider
    ExchangeRateProvider customExchangeRateProvider =
        MonetaryConversions.getExchangeRateProvider("OER");
    ExchangeRate customExchangeRate = customExchangeRateProvider.getExchangeRate("USD", "EUR");

    System.out.println();
    System.out.println("custom exchange rates");
    System.out.printf(
        "Ratio de conversión de USD a EUR: %f\n", customExchangeRate.getFactor().doubleValue());
  }