javax.money.convert.ExchangeRate Java Examples

The following examples show how to use javax.money.convert.ExchangeRate. 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 vote down vote up
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: YahooRateReadingHandler.java    From javamoney-lib with Apache License 2.0 6 votes vote down vote up
private void addRate(YahooQuoteItemInformation information) {

        final ExchangeRateBuilder builder = new ExchangeRateBuilder(
        		ConversionContextBuilder.create(context, RateType.DEFERRED).build());
        builder.setBase(YahooAbstractRateProvider.BASE_CURRENCY);
        builder.setTerm(information.getCurrency());
        builder.setFactor(DefaultNumberValue.of(information.getValue()));
        final ExchangeRate exchangeRate = builder.build();

        Map<String, ExchangeRate> rateMap = this.excangeRates.get(information.getLocalDate());
        if (Objects.isNull(rateMap)) {
            synchronized (this.excangeRates) {
                rateMap = Optional.ofNullable(this.excangeRates.get(information.getLocalDate())).orElse(new ConcurrentHashMap<>());
                this.excangeRates.putIfAbsent(information.getLocalDate(), rateMap);
            }
        }
        rateMap.put(information.getCurrency().getCurrencyCode(), exchangeRate);

    }
 
Example #3
Source File: USFederalReserveRateProvider.java    From javamoney-lib with Apache License 2.0 6 votes vote down vote up
@Override
public void newDataLoaded(String resourceId, InputStream is) {
    final int oldSize = this.rates.size();
    try {
        Map<LocalDate, Map<String, ExchangeRate>> newRates = new HashMap<>();
        SAXParser parser = saxParserFactory.newSAXParser();
        parser.parse(is, new USFederalReserveRateReadingHandler(newRates, getContext()));

        //Remove any older rates so the map continually only has one week of rates cached
        Set<LocalDate> existingDates = new HashSet<>(rates.keySet());
        rates.putAll(newRates);
        for(LocalDate ld : existingDates) {
            if(!newRates.containsKey(ld)) {
                rates.remove(ld);
            }
        }
        int newSize = this.rates.size();
        loadState = "Loaded " + resourceId + " exchange rates for days:" + (newSize - oldSize);
        LOG.info(loadState);
    } catch (Exception e) {
        loadState = "Last Error during data load: " + e.getMessage();
        LOG.log(Level.FINEST, "Error during data load.", e);
    } finally{
        loadLock.countDown();
    }
}
 
Example #4
Source File: USFederalReserveRateReadingHandler.java    From javamoney-lib with Apache License 2.0 6 votes vote down vote up
private void addRate(CurrencyUnit term, LocalDate localDate, Number rate, boolean inverse) {
    RateType rateType = RateType.HISTORIC;
    ExchangeRateBuilder builder =
        new ExchangeRateBuilder(ConversionContextBuilder.create(context, rateType).set(localDate).build());
    builder.setBase(inverse ? term : USFederalReserveRateProvider.BASE_CURRENCY);
    builder.setTerm(inverse ? USFederalReserveRateProvider.BASE_CURRENCY : term);
    builder.setFactor(DefaultNumberValue.of(rate));
    ExchangeRate exchangeRate = builder.build();
    if(inverse) {
        exchangeRate = USFederalReserveRateProvider.reverse(exchangeRate);
    }
    Map<String, ExchangeRate> rateMap = this.historicRates.get(localDate);
    if (Objects.isNull(rateMap)) {
        synchronized (this.historicRates) {
            rateMap = Optional.ofNullable(this.historicRates.get(localDate)).orElse(new ConcurrentHashMap<>());
            this.historicRates.putIfAbsent(localDate, rateMap);
        }
    }
    rateMap.put(term.getCurrencyCode(), exchangeRate);
}
 
Example #5
Source File: YahooAbstractRateProvider.java    From javamoney-lib with Apache License 2.0 6 votes vote down vote up
@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 #6
Source File: USFederalReserveRateProvider.java    From javamoney-lib with Apache License 2.0 6 votes vote down vote up
@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 #7
Source File: YahooAbstractRateProvider.java    From javamoney-lib with Apache License 2.0 6 votes vote down vote up
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 #8
Source File: DefaultExchangeRate.java    From jsr354-ri with Apache License 2.0 6 votes vote down vote up
@Override
public int hashCode() {
    // Numerically equal factors should produce the same hash code, so hash a normalized
    // version of the factor rather than the NumberValue object.
    BigDecimal normalizedFactor = factor.numberValue(BigDecimal.class).stripTrailingZeros();

    // The exchange rate chain includes a reference to "this" if the caller doesn't explicitly
    // set a chain in the builder, so we can't naively hash the chain or we'll get infinite
    // recursion.
    int chainHash = 0;
    for (ExchangeRate chainedRate : chain) {
        if (chainedRate == this) {
            // Use a constant to represent the presence of this object in the chain.
            chainHash = Objects.hash(chainHash, "this");
        } else {
            chainHash = Objects.hash(chainHash, chainedRate);
        }
    }

    return Objects.hash(base, conversionContext, normalizedFactor, term, chainHash);
}
 
Example #9
Source File: AbstractCurrencyConversion.java    From jsr354-ri with Apache License 2.0 6 votes vote down vote up
/**
 * Method that converts the source {@link MonetaryAmount} to an
 * {@link MonetaryAmount} based on the {@link ExchangeRate} of this
 * conversion.
 * @param amount The source amount
 * @return The converted amount, never null.
 * @throws CurrencyConversionException if conversion failed, or the required data is not available.
 * @see #getExchangeRate(MonetaryAmount)
 */
@Override
public MonetaryAmount apply(MonetaryAmount amount) {
    if (termCurrency.equals(Objects.requireNonNull(amount).getCurrency())) {
        return amount;
    }
    ExchangeRate rate = getExchangeRate(amount);
    if (Objects.isNull(rate) || !amount.getCurrency().equals(rate.getBaseCurrency())) {
        throw new CurrencyConversionException(amount.getCurrency(),
                this.termCurrency, null);
    }

    NumberValue factor = rate.getFactor();
    factor = roundFactor(amount, factor);

    Integer scale = rate.getContext().get(KEY_SCALE, Integer.class);
    if(Objects.isNull(scale) || scale < 0) {
    	return amount.multiply(factor).getFactory().setCurrency(rate.getCurrency()).create();
    } else {
    	return amount.multiply(factor).getFactory().setCurrency(rate.getCurrency()).create().with(MonetaryOperators.rounding(scale));
    }
}
 
Example #10
Source File: CompoundRateProvider.java    From jsr354-ri with Apache License 2.0 6 votes vote down vote up
@Override
public ExchangeRate getExchangeRate(ConversionQuery conversionQuery) {
    for (ExchangeRateProvider prov : this.providers) {
        try {
            if (prov.isAvailable(conversionQuery)) {
                ExchangeRate rate = prov.getExchangeRate(conversionQuery);
                if (Objects.nonNull(rate)) {
                    return rate;
                }
            }
        } catch (Exception e) {
            throw new CurrencyConversionException(conversionQuery.getBaseCurrency(), conversionQuery.getCurrency(), null,
                "Rate Provider did not return data though at check before data was flagged as available," +
                    " provider=" + prov.getContext().getProviderName() + ", query=" + conversionQuery, e);
        }
    }
    throw new CurrencyConversionException(conversionQuery.getBaseCurrency(), conversionQuery.getCurrency(), null,
            "All delegate providers failed to deliver rate, providers=" + this.providers +
                    ", query=" + conversionQuery);
}
 
Example #11
Source File: ExchangeRateBuilderTest.java    From jsr354-ri with Apache License 2.0 6 votes vote down vote up
@Test
public void testNumberInsignificanceForRates(){
	ExchangeRate rateFromString = new ExchangeRateBuilder(ConversionContext.HISTORIC_CONVERSION)
			.setBase(Monetary.getCurrency("USD"))
			.setTerm(Monetary.getCurrency("EUR"))
			.setFactor(DefaultNumberValue.of(new BigDecimal("1.1")))
			.build();

	ExchangeRate rateFromDouble = new ExchangeRateBuilder(ConversionContext.HISTORIC_CONVERSION)
			.setBase(Monetary.getCurrency("USD"))
			.setTerm(Monetary.getCurrency("EUR"))
			.setFactor(DefaultNumberValue.of(1.1))
			.build();

	assertEquals(rateFromDouble, rateFromString, "Rates are not equal for same factor.");
}
 
Example #12
Source File: ECBAbstractRateProvider.java    From jsr354-ri with Apache License 2.0 6 votes vote down vote up
@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 #13
Source File: MonetaryConversionTest.java    From jsr354-ri with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetExchangeRateProvider_Chained()
		throws InterruptedException {
	ExchangeRateProvider prov = MonetaryConversions
			.getExchangeRateProvider("ECB");
	assertTrue(Objects.nonNull(prov));
	assertEquals(ECBCurrentRateProvider.class, prov.getClass());
	// Test rate provided by IMF (derived)
	Thread.sleep(5000L); // wait for provider to load...
	ExchangeRate r = prov.getExchangeRate(Monetary.getCurrency("USD"),
			Monetary.getCurrency("INR"));
	assertTrue(Objects.nonNull(r));
	assertTrue(r.isDerived());
	// Test rate provided by ECB
	r = prov.getExchangeRate(Monetary.getCurrency("EUR"),
			Monetary.getCurrency("CHF"));
	assertTrue(Objects.nonNull(r));
	assertFalse(r.isDerived());
}
 
Example #14
Source File: IMFAbstractRateProvider.java    From jsr354-ri with Apache License 2.0 6 votes vote down vote up
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 #15
Source File: IMFHistoricRateProvider.java    From jsr354-ri with Apache License 2.0 6 votes vote down vote up
@Override
public ExchangeRate getExchangeRate(ConversionQuery conversionQuery) {
	LocalDate[] times = getQueryDates(conversionQuery);
	if(Objects.isNull(times)) {
		return super.getExchangeRate(conversionQuery);
	}

	for (YearMonth yearMonth : Stream.of(times).map(YearMonth::from)
			.collect(Collectors.toSet())) {

		if(!cachedHistoric.contains(yearMonth)){
			Map<IMFHistoricalType, InputStream> resources = IMFRemoteSearch.INSTANCE.getResources(yearMonth,
					getContext().get("User-Agent", String.class));
			loadFromRemote(resources);
			cachedHistoric.add(yearMonth);
		}
	}
	return super.getExchangeRate(conversionQuery);
}
 
Example #16
Source File: MonetaryConversionTest.java    From jsr354-ri with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetExchangeRateProvider_Chained()
		throws InterruptedException {
	ExchangeRateProvider prov = MonetaryConversions
			.getExchangeRateProvider("IMF");
	assertTrue(Objects.nonNull(prov));
	assertEquals(IMFRateProvider.class, prov.getClass());
	// Test rate provided by IMF (derived)
	Thread.sleep(5000L); // wait for provider to load...
	ExchangeRate exchangeRate = prov.getExchangeRate(Monetary.getCurrency("USD"),
			Monetary.getCurrency("INR"));
	assertTrue(Objects.nonNull(exchangeRate));
	assertTrue(exchangeRate.isDerived());
	// Test rate provided by ECB
	exchangeRate = prov.getExchangeRate(Monetary.getCurrency("EUR"),
			Monetary.getCurrency("CHF"));
	assertTrue(Objects.nonNull(exchangeRate));
	assertTrue(exchangeRate.isDerived());
}
 
Example #17
Source File: MonetaryConversionTest.java    From javamoney-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetExchangeRateProvider_Chained()
		throws InterruptedException {
	ExchangeRateProvider prov = MonetaryConversions
			.getExchangeRateProvider("ECB", "IMF");
	assertTrue(prov != null);
	assertEquals(CompoundRateProvider.class, prov.getClass());
	// Test rate provided by IMF (derived)
	Thread.sleep(5000L); // wait for provider to load...
	ExchangeRate r = prov.getExchangeRate(Monetary.getCurrency("USD"),
			Monetary.getCurrency("INR"));
	assertTrue(r != null);
	assertTrue(r.isDerived());
	// Test rate provided by ECB
	r = prov.getExchangeRate(Monetary.getCurrency("EUR"),
			Monetary.getCurrency("CHF"));
	assertTrue(r != null);
	assertFalse(r.isDerived());
}
 
Example #18
Source File: MonetaryConversionTest.java    From javamoney-examples with Apache License 2.0 6 votes vote down vote up
@Test
public void testGetExchangeRateProvider_Chained()
		throws InterruptedException {
	ExchangeRateProvider prov = MonetaryConversions
			.getExchangeRateProvider("ECB", "IMF");
	assertTrue(Objects.nonNull(prov));
	assertEquals(CompoundRateProvider.class, prov.getClass());
	// Test rate provided by IMF (derived)
	Thread.sleep(5000L); // wait for provider to load...
	ExchangeRate r = prov.getExchangeRate(Monetary.getCurrency("USD"),
			Monetary.getCurrency("INR"));
	assertTrue(Objects.nonNull(r));
	assertTrue(r.isDerived());
	// Test rate provided by ECB
	r = prov.getExchangeRate(Monetary.getCurrency("EUR"),
			Monetary.getCurrency("CHF"));
	assertTrue(Objects.nonNull(r));
	assertFalse(r.isDerived());
}
 
Example #19
Source File: MonetaryConversionTest.java    From javamoney-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetExchangeRateDefault() {
	ExchangeRateProvider prov = MonetaryConversions
			.getExchangeRateProvider();
	assertTrue(Objects.nonNull(prov));
	ExchangeRate rate = prov.getExchangeRate("CHF", "EUR");
	assertNotNull(rate);
}
 
Example #20
Source File: MonetaryConversionTest.java    From jsr354-ri with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetExchangeRateDefault() {
	ExchangeRateProvider prov = MonetaryConversions
			.getExchangeRateProvider();
	assertTrue(Objects.nonNull(prov));
	ExchangeRate rate = prov.getExchangeRate("CHF", "EUR");
	assertNotNull(rate);
}
 
Example #21
Source File: MonetaryConversionTest.java    From javamoney-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetExchangeRateDefault() {
	ExchangeRateProvider prov = MonetaryConversions
			.getExchangeRateProvider();
	assertTrue(prov != null);
	ExchangeRate rate = prov.getExchangeRate("CHF", "EUR");
	assertNotNull(rate);
}
 
Example #22
Source File: KnowmExchangeRateProvider.java    From consensusj with Apache License 2.0 5 votes vote down vote up
private ExchangeRate buildExchangeRate(CurrencyUnitPair pair, Ticker ticker) {
    return new ExchangeRateBuilder(name, RateType.DEFERRED)
            .setBase(pair.getBase())
            .setTerm(pair.getTarget())
            .setFactor(DefaultNumberValue.of(ticker.getLast()))
            .build();
}
 
Example #23
Source File: ECBAbstractRateProvider.java    From jsr354-ri with Apache License 2.0 5 votes vote down vote up
private ExchangeRate reverse(ExchangeRate rate) {
    if (Objects.isNull(rate)) {
        throw new IllegalArgumentException("Rate null is not reversible.");
    }
    return new ExchangeRateBuilder(rate).setRate(rate).setBase(rate.getCurrency()).setTerm(rate.getBaseCurrency())
            .setFactor(divide(DefaultNumberValue.ONE, rate.getFactor(), MathContext.DECIMAL64)).build();
}
 
Example #24
Source File: ECBAbstractRateProvider.java    From jsr354-ri with Apache License 2.0 5 votes vote down vote up
private ExchangeRate createExchangeRate(ConversionQuery query,
                                        ExchangeRateBuilder builder, ExchangeRate sourceRate,
                                        ExchangeRate target) {

    if (areBothBaseCurrencies(query)) {
        builder.setFactor(DefaultNumberValue.ONE);
        return builder.build();
    } else if (BASE_CURRENCY_CODE.equals(query.getCurrency().getCurrencyCode())) {
        if (Objects.isNull(sourceRate)) {
            return null;
        }
        return reverse(sourceRate);
    } else if (BASE_CURRENCY_CODE.equals(query.getBaseCurrency()
            .getCurrencyCode())) {
        return target;
    } else {

        ExchangeRate rate1 = getExchangeRate(
                query.toBuilder().setTermCurrency(Monetary.getCurrency(BASE_CURRENCY_CODE)).build());
        ExchangeRate rate2 = getExchangeRate(
                query.toBuilder().setBaseCurrency(Monetary.getCurrency(BASE_CURRENCY_CODE))
                        .setTermCurrency(query.getCurrency()).build());
        if (Objects.nonNull(rate1) && Objects.nonNull(rate2)) {
            builder.setFactor(multiply(rate1.getFactor(), rate2.getFactor()));
            builder.setRateChain(rate1, rate2);
            return builder.build();
        }
        throw new CurrencyConversionException(query.getBaseCurrency(),
                query.getCurrency(), sourceRate.getContext());
    }
}
 
Example #25
Source File: USFederalReserveRateProvider.java    From javamoney-lib with Apache License 2.0 5 votes vote down vote up
protected static ExchangeRate reverse(ExchangeRate rate) {
    if (Objects.isNull(rate)) {
        throw new IllegalArgumentException("Rate null is not reversible.");
    }
    return new ExchangeRateBuilder(rate).setRate(rate).setBase(rate.getCurrency()).setTerm(rate.getBaseCurrency())
        .setFactor(divide(DefaultNumberValue.ONE, rate.getFactor(), MathContext.DECIMAL64)).build();
}
 
Example #26
Source File: ExchangeRateBuilderTest.java    From jsr354-ri with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCreateExchangeRateFromExchangeRate() {
	ExchangeRate rate = new ExchangeRateBuilder(ConversionContext.ANY_CONVERSION).setBase(CURRENCY)
			.setTerm(CURRENCY).setFactor(NUMBER_FACTOR).build();

	ExchangeRate rate2 = new ExchangeRateBuilder(rate).build();

	assertEquals(rate.getContext(), rate2.getContext());
	assertEquals(rate.getBaseCurrency(), rate2.getBaseCurrency());
	assertEquals(rate.getFactor(), rate2.getFactor());
}
 
Example #27
Source File: ExchangeRateBuilderTest.java    From jsr354-ri with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCreateExchangeRate() {
	ExchangeRate rate = new ExchangeRateBuilder(ConversionContext.ANY_CONVERSION).setBase(CURRENCY)
			.setTerm(CURRENCY).setFactor(NUMBER_FACTOR).build();

	assertEquals(rate.getContext(), ConversionContext.ANY_CONVERSION);
	assertEquals(rate.getBaseCurrency(), CURRENCY);
	assertEquals(rate.getFactor(), NUMBER_FACTOR);
}
 
Example #28
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 #29
Source File: YahooAbstractRateProvider.java    From javamoney-lib with Apache License 2.0 5 votes vote down vote up
private ExchangeRate reverse(ExchangeRate rate) {
    if (Objects.isNull(rate)) {
        throw new IllegalArgumentException("Rate null is not reversible.");
    }

    return new ExchangeRateBuilder(rate).setRate(rate).setBase(rate.getCurrency())
    		.setTerm(rate.getBaseCurrency()).setContext(getExchangeContext(DIGIT_FRACTION_KEY))
            .setFactor(divide(DefaultNumberValue.ONE, rate.getFactor(), MathContext.DECIMAL64)).build();
}
 
Example #30
Source File: ExchangeRateSimpleTest.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"));

    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");
}