javax.money.CurrencyUnit Java Examples

The following examples show how to use javax.money.CurrencyUnit. 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: ExchangeExample.java    From javamoney-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
	ExchangeRateProvider imfRateProvider = MonetaryConversions
			.getExchangeRateProvider("IMF");
	ExchangeRateProvider ecbRateProvider = MonetaryConversions
			.getExchangeRateProvider("ECB");

	CurrencyUnit euro = Monetary.getCurrency("EUR");
	CurrencyUnit dollar = Monetary.getCurrency(Locale.US);

	CurrencyConversion ecbDollarConvertion = ecbRateProvider
			.getCurrencyConversion(dollar);

	CurrencyConversion imfDollarConvertion = imfRateProvider
			.getCurrencyConversion(dollar);

	MonetaryAmount money = Money.of(10, euro);
	System.out.println(money.with(ecbDollarConvertion));
	System.out.println(money.with(imfDollarConvertion));
}
 
Example #2
Source File: CurrenciesTest.java    From jsr354-ri with Apache License 2.0 6 votes vote down vote up
/**
 * Test equals and hashCode methods for
 * {@link javax.money.CurrencyUnit}s.
 */
@Test
public void testEqualsHashCode() {
	String currencyCode = "USD";
	CurrencyUnit cur1 = Monetary.getCurrency(currencyCode, "default");
	CurrencyUnit cur2 = CurrencyUnitBuilder.of(currencyCode, "equals-hashCode-test")
               .setDefaultFractionDigits(2)
               .build(false);

	assertNotSame(cur1, cur2);
	assertNotEquals(cur1.getContext().getProviderName(), cur2.getContext().getProviderName());
	assertEquals(cur1, cur2);
	assertEquals(cur2, cur1);
	assertEquals(cur1.hashCode(), cur2.hashCode());
	assertEquals(cur1.hashCode(), currencyCode.hashCode());
	assertEquals(cur2.hashCode(), currencyCode.hashCode());
}
 
Example #3
Source File: ECBRateReadingHandler.java    From jsr354-ri with Apache License 2.0 6 votes vote down vote up
@Override
public void startElement(String uri, String localName, String qName,
                         Attributes attributes) throws SAXException {
    if ("Cube".equals(qName)) {
        if (Objects.nonNull(attributes.getValue("time"))) {

            this.localDate = LocalDate.parse(attributes.getValue("time")).atStartOfDay().toLocalDate();
        } else if (Objects.nonNull(attributes.getValue("currency"))) {
            // read data <Cube currency="USD" rate="1.3349"/>
            CurrencyUnit tgtCurrency = Monetary
                    .getCurrency(attributes.getValue("currency"));
            addRate(tgtCurrency, this.localDate, BigDecimal.valueOf(Double
                    .parseDouble(attributes.getValue("rate"))));
        }
    }
    super.startElement(uri, localName, qName, attributes);
}
 
Example #4
Source File: PrecisionContextRoundedOperatorTest.java    From jsr354-ri with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRoundedMonetaryOperatorWhenTheImplementationIsMoney() {
	int scale = 4;
	MathContext mathContext = new MathContext(scale, RoundingMode.HALF_EVEN);

	CurrencyUnit real = Monetary.getCurrency("BRL");
	MonetaryAmount money = Money.of(BigDecimal.valueOf(35.34567), real);

	PrecisionContextRoundedOperator monetaryOperator = PrecisionContextRoundedOperator.of(mathContext);
	MonetaryAmount result = monetaryOperator.apply(money);
	assertTrue(RoundedMoney.class.isInstance(result));
	assertEquals(result.getCurrency(), real);
	assertEquals(result.getNumber().getPrecision(), scale);
	assertEquals(BigDecimal.valueOf(35.35), result.getNumber().numberValue(BigDecimal.class));



}
 
Example #5
Source File: MonetaryFormatsTest.java    From jsr354-ri with Apache License 2.0 6 votes vote down vote up
/**
 * Test related to https://github.com/JavaMoney/jsr354-ri/issues/294
 */
@Test
public void testParse_amount_without_currency_code_but_with_currency_in_context() {
    CurrencyUnit eur = Monetary.getCurrency("EUR");
    AmountFormatQuery formatQuery = AmountFormatQueryBuilder.of(GERMANY)
        .set(CurrencyUnit.class, eur)
        .build();
    MonetaryAmountFormat format = MonetaryFormats.getAmountFormat(formatQuery);
    try {
        MonetaryAmount parsedAmount = format.parse("0.01");
        assertSame(parsedAmount.getCurrency(), eur);
        assertEquals(parsedAmount.getNumber().doubleValueExact(), 0.01D);
        assertEquals(parsedAmount.toString(), "EUR 0.01");
    } catch (MonetaryParseException e) {
        assertEquals(e.getMessage(), "Error parsing CurrencyUnit: no input.");
        assertEquals(e.getErrorIndex(), -1);
    }
}
 
Example #6
Source File: ConfigurableCurrencyUnitProviderTest.java    From jsr354-ri with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that searching by numeric code is supported by {@link ConfigurableCurrencyUnitProvider}.
 */
@Test
public void testSearchByNumericCurrencyCode() {
    CurrencyUnit usd = CurrencyUnitBuilder.of("USD", "search-test")
                    .setNumericCode(840)
                    .setDefaultFractionDigits(2)
                    .build(false);
    CurrencyUnit eur = CurrencyUnitBuilder.of("EUR", "search-test")
                    .setNumericCode(978)
                    .setDefaultFractionDigits(2)
                    .build(false);
    
    ConfigurableCurrencyUnitProvider.registerCurrencyUnit(usd);
    ConfigurableCurrencyUnitProvider.registerCurrencyUnit(eur);
    try {
        CurrencyQuery query = CurrencyQueryBuilder.of()
            .setProviderName(ConfigurableCurrencyUnitProvider.class.getSimpleName())
            .setNumericCodes(840)
            .build();
        CurrencyUnit currency = Monetary.getCurrency(query);
        assertEquals(usd, currency);
    } finally {
        ConfigurableCurrencyUnitProvider.removeCurrencyUnit(usd.getCurrencyCode());
        ConfigurableCurrencyUnitProvider.removeCurrencyUnit(eur.getCurrencyCode());
    }
}
 
Example #7
Source File: BasicOperations.java    From javamoney-examples with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
	CurrencyUnit dollar = Monetary.getCurrency(Locale.US);
       MonetaryAmount money = Money.of(120, dollar);
       MonetaryAmount money2 = Money.of(50, dollar);
       System.out.println(money.add(money2));
       System.out.println(money.subtract(money2));
       System.out.println(money.multiply(2));
       System.out.println(money.divide(2));
       System.out.println(money.isEqualTo(money2));
       System.out.println(money.isGreaterThan(money2));
       System.out.println(money.isGreaterThanOrEqualTo(money2));
       System.out.println(money.isGreaterThanOrEqualTo(money2));
       System.out.println(money.isLessThan(money2));
       System.out.println(money.isLessThanOrEqualTo(money2));
       System.out.println(money.isNegative());
       System.out.println(money.isNegativeOrZero());
}
 
Example #8
Source File: MonetaryAmountSerializer.java    From jackson-datatype-money with MIT License 6 votes vote down vote up
@Override
public void acceptJsonFormatVisitor(final JsonFormatVisitorWrapper wrapper, final JavaType hint)
        throws JsonMappingException {

    @Nullable final JsonObjectFormatVisitor visitor = wrapper.expectObjectFormat(hint);

    if (visitor == null) {
        return;
    }

    final SerializerProvider provider = wrapper.getProvider();

    visitor.property(names.getAmount(),
            provider.findValueSerializer(writer.getType()),
            provider.constructType(writer.getType()));

    visitor.property(names.getCurrency(),
            provider.findValueSerializer(CurrencyUnit.class),
            provider.constructType(CurrencyUnit.class));

    visitor.optionalProperty(names.getFormatted(),
            provider.findValueSerializer(String.class),
            provider.constructType(String.class));
}
 
Example #9
Source File: MonetaryOperatorsTest.java    From jsr354-ri with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRoundingUsingScale() {
	CurrencyUnit euro = Monetary.getCurrency("EUR");
	MonetaryAmount money = Money.parse("EUR 2.355432");
	MonetaryAmount result = MonetaryOperators.rounding(4).apply(money);
	assertNotNull(result);
	assertEquals(result.getCurrency(), euro);
	assertEquals(2.3554d, result.getNumber().doubleValue());
}
 
Example #10
Source File: CurrenciesTest.java    From jsr354-ri with Apache License 2.0 5 votes vote down vote up
/**
 * Test method for {@link CurrencyUnit#toString()}
 * .
 */
@Test
public void testToString() {
	CurrencyUnit cur1 = Monetary.getCurrency("USD");
	String toString = cur1.toString();
	assertNotNull(toString);
	assertTrue(toString.contains("USD"), "Does not contain currency code.");
}
 
Example #11
Source File: ExchangeRateBuilderTest.java    From jsr354-ri with Apache License 2.0 5 votes vote down vote up
@Test
public void equalsTest() {
	DefaultNumberValue factor = new DefaultNumberValue(1.1);
	DefaultNumberValue bigDecimalFactor = new DefaultNumberValue(new BigDecimal("1.1"));
	CurrencyUnit EUR = Monetary.getCurrency("EUR");
	CurrencyUnit GBP = Monetary.getCurrency("GBP");
	ExchangeRate rate1 = new ExchangeRateBuilder("myprovider", RateType.ANY)
			.setBase(EUR)
			.setTerm(GBP)
			.setFactor(factor)
			.build();

	ExchangeRate rate2 = new ExchangeRateBuilder("myprovider", RateType.ANY)
			.setBase(EUR)
			.setTerm(GBP)
			.setFactor(factor)
			.build();

	ExchangeRate rate3 = new ExchangeRateBuilder("myprovider", RateType.ANY)
			.setBase(EUR)
			.setTerm(GBP)
			.setFactor(bigDecimalFactor)
			.build();

	assertEquals(rate1, rate2, "Rates with same factor");
	assertEquals(rate1, rate3, "Rates with numerically equal factor");
	assertEquals(rate1.hashCode(), rate2.hashCode(), "Hashes with same factor");
	assertEquals(rate1.hashCode(), rate3.hashCode(), "Hashes with numerically equal factor");
}
 
Example #12
Source File: SmokeTest.java    From javamoney-lib with Apache License 2.0 5 votes vote down vote up
@Test
public void testCurrencyAccess() {
    // Creating one
    CurrencyUnit currency = Monetary.getCurrency("INR");
    assertNotNull(currency);
    currency = Monetary.getCurrency("CDITest");
    assertNotNull(currency);
}
 
Example #13
Source File: CartViewModelFactory.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
@Inject
public CartViewModelFactory(final CurrencyUnit currency, final PriceFormatter priceFormatter, final ShippingInfoViewModelFactory shippingInfoViewModelFactory,
                            final PaymentInfoViewModelFactory paymentInfoViewModelFactory, final AddressViewModelFactory addressViewModelFactory,
                            final LineItemExtendedViewModelFactory lineItemExtendedViewModelFactory,
                            final DiscountCodeViewModelFactory discountCodeViewModelFactory) {
    super(currency, priceFormatter, shippingInfoViewModelFactory, paymentInfoViewModelFactory, addressViewModelFactory, discountCodeViewModelFactory);
    this.lineItemExtendedViewModelFactory = lineItemExtendedViewModelFactory;
}
 
Example #14
Source File: ConsoleUtils.java    From javamoney-examples with Apache License 2.0 5 votes vote down vote up
public static void printDetails(String title, CurrencyUnit cu) {
    if (cu == null) {
        System.out.println(title + " -> N/A");
    } else {
        System.out.println(title + " -> CurrencyUnit '" + cu.toString() + "':\n" +
                "  Class                 : " + cu.getClass().getName() + "\n" +
                "  Currency Code         : " + cu.getCurrencyCode() + "\n" +
                "  Num.Code              : " + cu.getNumericCode() + "\n" +
                "  DefaultFraction Digits: " + cu.getDefaultFractionDigits() + "\n" +
                "  Context               : " + cu.getContext());
    }
}
 
Example #15
Source File: MonetaryOperatorsTest.java    From jsr354-ri with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRoundingUsingRoundingMode() {
	CurrencyUnit euro = Monetary.getCurrency("EUR");
	MonetaryAmount money = Money.parse("EUR 2.355432");
	MonetaryAmount result = MonetaryOperators.rounding(RoundingMode.HALF_EVEN).apply(money);
	assertNotNull(result);
	assertEquals(result.getCurrency(), euro);
	assertEquals(2.36d, result.getNumber().doubleValue());
}
 
Example #16
Source File: ConvertMinorPartQueryTest.java    From jsr354-ri with Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = ArithmeticException.class)
public void shouldReturnWhenTheValueIsBiggerThanLong() {
	CurrencyUnit real = Monetary.getCurrency("BRL");
	MonetaryAmount monetaryAmount = Money.of(Long.MAX_VALUE, real);
	query.queryFrom(monetaryAmount.add(Money.of(10, real)));
	fail();
}
 
Example #17
Source File: ConversionOperatorsTest.java    From jsr354-ri with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldExchangeCurrencyPositiveValue() {
	CurrencyUnit real = Monetary.getCurrency("BRL");
	MonetaryAmount money = Money.parse("EUR 2.35");
	MonetaryAmount result = ConversionOperators.exchange(real).apply(money);
	assertNotNull(result);
	assertEquals(result.getCurrency(), real);
	assertEquals(2.35d, result.getNumber().doubleValue());
}
 
Example #18
Source File: ConversionOperators.java    From jsr354-ri with Apache License 2.0 5 votes vote down vote up
/**
 * of the summary of the MonetaryAmount
 * @param currencyUnit
 *            the target {@link javax.money.CurrencyUnit}
 * @return the MonetarySummaryStatistics
 */
public static Collector<MonetaryAmount, MonetarySummaryStatistics, MonetarySummaryStatistics> summarizingMonetary(
		CurrencyUnit currencyUnit, ExchangeRateProvider provider) {

	Supplier<MonetarySummaryStatistics> supplier = () -> new ExchangeRateMonetarySummaryStatistics(
			currencyUnit, provider);
	return Collector.of(supplier, MonetarySummaryStatistics::accept,
			MonetarySummaryStatistics::combine);
}
 
Example #19
Source File: LocalizationModule.java    From commercetools-sunrise-java with Apache License 2.0 5 votes vote down vote up
@Override
protected void configure() {
    bind(Locale.class)
            .toProvider(LocaleFromUrlProvider.class)
            .in(RequestScoped.class);

    bind(CountryCode.class)
            .toProvider(CountryFromSessionProvider.class)
            .in(RequestScoped.class);

    bind(CurrencyUnit.class)
            .toProvider(CurrencyFromCountryProvider.class)
            .in(RequestScoped.class);
}
 
Example #20
Source File: AmountEntry.java    From javamoney-examples with Apache License 2.0 5 votes vote down vote up
public AmountEntry(String title) {
	super("AmountEntry.fxml");
	amountTitle.setText(title);
	numberType.getItems().add("BigDecimal");
	numberType.getItems().add("Long");
       for(CurrencyUnit cu: Monetary.getCurrencies()){
           codeBox.getItems().add(cu.getCurrencyCode());
       }
       Collections.sort(codeBox.getItems());
       codeBox.getSelectionModel().select("CHF");
}
 
Example #21
Source File: ConsoleUtils.java    From javamoney-examples with Apache License 2.0 5 votes vote down vote up
public static void printDetails(CurrencyUnit cu) {
    if (cu == null) {
        System.out.println("N/A");
    } else {
        System.out.println("CurrencyUnit '" + cu.toString() + "':\n" +
                "  Class                 : " + cu.getClass().getName() + "\n" +
                "  Currency Code         : " + cu.getCurrencyCode() + "\n" +
                "  Num.Code              : " + cu.getNumericCode() + "\n" +
                "  DefaultFraction Digits: " + cu.getDefaultFractionDigits() + "\n" +
                "  Context               : " + cu.getContext());
    }
}
 
Example #22
Source File: MonetarySummaryMap.java    From jsr354-ri with Apache License 2.0 5 votes vote down vote up
@Override
public MonetarySummaryStatistics putIfAbsent(CurrencyUnit key,
                                             MonetarySummaryStatistics value) {
    MonetarySummaryStatistics v = statisticsMap.get(key);
    if (Objects.isNull(v)) {
        v = put(key, value);
    }
    return v;
}
 
Example #23
Source File: CurrencyUnitDeserializerTest.java    From jackson-datatype-money with MIT License 5 votes vote down vote up
@Test
void shouldDeserialize() throws IOException {
    final CurrencyUnit actual = unit.readValue("\"EUR\"", CurrencyUnit.class);
    final CurrencyUnit expected = CurrencyUnitBuilder.of("EUR", "default").build();

    assertThat(actual, is(expected));
}
 
Example #24
Source File: GeeConCurrencyProvider.java    From javamoney-examples with Apache License 2.0 5 votes vote down vote up
@Override
public Set<CurrencyUnit> getCurrencies(CurrencyQuery query) {
    if(Boolean.TRUE.equals(query.getBoolean("GeeCon"))) {
        return currencies;
    }
    return Collections.emptySet();
}
 
Example #25
Source File: CurrencyUnitSchemaSerializerTest.java    From jackson-datatype-money with MIT License 5 votes vote down vote up
@Test
void shouldSerializeJsonSchema() throws Exception {
    JsonSchemaGenerator generator = new JsonSchemaGenerator(unit);
    JsonSchema jsonSchema = generator.generateSchema(CurrencyUnit.class);
    final String actual = unit.writeValueAsString(jsonSchema);
    final String expected = "{\"type\":\"string\"}";

    assertThat(actual, is(expected));
}
 
Example #26
Source File: ScaleRoundedOperatorTest.java    From jsr354-ri with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRoundedMonetaryOperatorWhenTheImplementationIsMoney() {
	int scale = 4;

	CurrencyUnit real = Monetary.getCurrency("BRL");
	MonetaryAmount money = Money.of(BigDecimal.valueOf(35.34567), real);

	ScaleRoundedOperator monetaryOperator = ScaleRoundedOperator.of(scale, RoundingMode.HALF_EVEN);
	MonetaryAmount result = monetaryOperator.apply(money);
	assertTrue(RoundedMoney.class.isInstance(result));
	assertEquals(result.getCurrency(), real);
	assertEquals(result.getNumber().getScale(), scale);
	assertEquals(BigDecimal.valueOf(35.3457), result.getNumber().numberValue(BigDecimal.class));

}
 
Example #27
Source File: ConversionAggregatorTest.java    From jsr354-ri with Apache License 2.0 5 votes vote down vote up
@Test
public void groupByCurrencyUnitTest() {
    Map<CurrencyUnit, List<MonetaryAmount>> groupBy = currencies().collect(
            groupByCurrencyUnit());
    assertEquals(3, groupBy.entrySet().size());
    assertEquals(3, groupBy.get(BRAZILIAN_REAL).size());
    assertEquals(3, groupBy.get(DOLLAR).size());
    assertEquals(3, groupBy.get(EURO).size());
}
 
Example #28
Source File: ConsoleUtils.java    From javamoney-examples with Apache License 2.0 5 votes vote down vote up
public static void printDetails(CurrencyUnit cu) {
    if (cu == null) {
        System.out.println("N/A");
    } else {
        System.out.println("CurrencyUnit '" + cu.toString() + "':\n" +
                "  Class                 : " + cu.getClass().getName() + "\n" +
                "  Currency Code         : " + cu.getCurrencyCode() + "\n" +
                "  Num.Code              : " + cu.getNumericCode() + "\n" +
                "  DefaultFraction Digits: " + cu.getDefaultFractionDigits() + "\n" +
                "  Context               : " + cu.getContext());
    }
}
 
Example #29
Source File: MonetaryFunctionsAggregatorTest.java    From jsr354-ri with Apache License 2.0 5 votes vote down vote up
@Test
public void groupBySummarizingMonetaryTest() {
    GroupMonetarySummaryStatistics group = currenciesToSummary().collect(
            groupBySummarizingMonetary());
    Map<CurrencyUnit, MonetarySummaryStatistics> mapSummary = group.get();
    assertEquals(mapSummary.keySet().size(), 3);
}
 
Example #30
Source File: ConsoleUtils.java    From javamoney-examples with Apache License 2.0 5 votes vote down vote up
public static void printDetails(CurrencyUnit cu) {
    if (cu == null) {
        System.out.println("N/A");
    } else {
        System.out.println("CurrencyUnit '" + cu.toString() + "':\n" +
                "  Class                 : " + cu.getClass().getName() + "\n" +
                "  Currency Code         : " + cu.getCurrencyCode() + "\n" +
                "  Num.Code              : " + cu.getNumericCode() + "\n" +
                "  DefaultFraction Digits: " + cu.getDefaultFractionDigits() + "\n" +
                "  Context               : " + cu.getContext());
    }
}