Java Code Examples for org.joda.money.Money#of()

The following examples show how to use org.joda.money.Money#of() . 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: JodaMoneyConverterTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void roundTripConversion() {
  Money money = Money.of(CurrencyUnit.USD, 100);
  TestEntity entity = new TestEntity(money);
  jpaTm().transact(() -> jpaTm().getEntityManager().persist(entity));
  List<?> result =
      jpaTm()
          .transact(
              () ->
                  jpaTm()
                      .getEntityManager()
                      .createNativeQuery(
                          "SELECT amount, currency FROM \"TestEntity\" WHERE name = 'id'")
                      .getResultList());
  assertThat(result.size()).isEqualTo(1);
  assertThat(Arrays.asList((Object[]) result.get(0)))
      .containsExactly(
          BigDecimal.valueOf(100).setScale(CurrencyUnit.USD.getDecimalPlaces()), "USD")
      .inOrder();
  TestEntity persisted =
      jpaTm().transact(() -> jpaTm().getEntityManager().find(TestEntity.class, "id"));
  assertThat(persisted.money).isEqualTo(money);
}
 
Example 2
Source File: JodaMoneySerializerTest.java    From batchers with Apache License 2.0 6 votes vote down vote up
@Test
public void testMoneySerialization() throws IOException {
    JodaMoneySerializer jodaMoneySerializer = new JodaMoneySerializer();
    Money value = Money.of(CurrencyUnit.EUR, 234.56);
    jodaMoneySerializer.serialize(value, jsonGenerator, null);

    verify(jsonGenerator).writeString("234.56 €");
}
 
Example 3
Source File: PersistentMoneyAmountAndCurrency.java    From jadira with Apache License 2.0 5 votes vote down vote up
@Override
protected Money fromConvertedColumns(Object[] convertedColumns) {

    CurrencyUnit currencyUnitPart = (CurrencyUnit) convertedColumns[0];
    BigDecimal amountPart = (BigDecimal) convertedColumns[1];
    Money money = Money.of(currencyUnitPart, amountPart);

    return money;
}
 
Example 4
Source File: FeesAndCredits.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private Money getTotalCostForType(FeeType type) {
  checkArgumentNotNull(type);
  return Money.of(
      currency,
      fees.stream()
          .filter(f -> f.getType() == type)
          .map(BaseFee::getCost)
          .reduce(zeroInCurrency(currency), BigDecimal::add));
}
 
Example 5
Source File: FeesAndCredits.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/** Returns the total cost of all fees and credits for the event. */
public Money getTotalCost() {
  return Money.of(
      currency,
      Streams.concat(fees.stream(), credits.stream())
          .map(BaseFee::getCost)
          .reduce(zeroInCurrency(currency), BigDecimal::add));
}
 
Example 6
Source File: OrderUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@DisplayName("given order with two items, when calculate total cost, then sum is returned")
@Test
void test0() throws Exception {
    // given
    OrderLine ol0 = new OrderLine(new Product(Money.of(CurrencyUnit.USD, 10.00)), 2);
    OrderLine ol1 = new OrderLine(new Product(Money.of(CurrencyUnit.USD, 5.00)), 10);
    Order order = new Order(Arrays.asList(ol0, ol1));

    // when
    Money totalCost = order.totalCost();

    // then
    assertThat(totalCost).isEqualTo(Money.of(CurrencyUnit.USD, 70.00));
}
 
Example 7
Source File: OrderUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@DisplayName("given order with three line items, when remove item, then total cost is updated")
@Test
void test3() throws Exception {
    // given
    OrderLine ol0 = new OrderLine(new Product(Money.of(CurrencyUnit.USD, 10.00)), 1);
    OrderLine ol1 = new OrderLine(new Product(Money.of(CurrencyUnit.USD, 20.00)), 1);
    OrderLine ol2 = new OrderLine(new Product(Money.of(CurrencyUnit.USD, 30.00)), 1);
    Order order = new Order(Arrays.asList(ol0, ol1, ol2));

    // when
    order.removeLineItem(1);

    // then
    assertThat(order.totalCost()).isEqualTo(Money.of(CurrencyUnit.USD, 40.00));
}
 
Example 8
Source File: TaxCalculatorService.java    From batchers with Apache License 2.0 5 votes vote down vote up
public Money calculateTax(Employee employee) {
    runningTimeService.sleep();
    double taxAmount = employee.getIncome() * 0.1;
    Money tax = Money.of(CurrencyUnit.EUR, taxAmount, RoundingMode.HALF_DOWN);

    return tax;
}
 
Example 9
Source File: OrderUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@DisplayName("given order with two line items, when add another line item, then total cost is updated")
@Test
void test2() throws Exception {
    // given
    OrderLine ol0 = new OrderLine(new Product(Money.of(CurrencyUnit.USD, 10.00)), 1);
    OrderLine ol1 = new OrderLine(new Product(Money.of(CurrencyUnit.USD, 5.00)), 1);
    Order order = new Order(Arrays.asList(ol0, ol1));

    // when
    order.addLineItem(new OrderLine(new Product(Money.of(CurrencyUnit.USD, 20.00)), 2));

    // then
    assertThat(order.totalCost()).isEqualTo(Money.of(CurrencyUnit.USD, 55));
}
 
Example 10
Source File: CallWebserviceProcessorTest.java    From batchers with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    employee = new EmployeeTestBuilder().build();
    Money money = Money.of(CurrencyUnit.EUR, 2000.0);
    taxCalculation = new TaxCalculationTestBuilder().withEmployee(employee).withTax(money).build();
    taxWebserviceCallResult = TaxWebserviceCallResult.callSucceeded(taxCalculation);
}
 
Example 11
Source File: BigDecimalColumnMoneyMapper.java    From jadira with Apache License 2.0 4 votes vote down vote up
@Override
public Money fromNonNullValue(BigDecimal val) {
    return Money.of(currencyUnit, val);
}
 
Example 12
Source File: OrderMongoIntegrationTest.java    From tutorials with MIT License 4 votes vote down vote up
private Order prepareTestOrderWithTwoLineItems() {
    OrderLine ol0 = new OrderLine(new Product(Money.of(CurrencyUnit.USD, 10.00)), 2);
    OrderLine ol1 = new OrderLine(new Product(Money.of(CurrencyUnit.USD, 5.00)), 10);
    return new Order(Arrays.asList(ol0, ol1));
}
 
Example 13
Source File: TaxCalculationTestBuilder.java    From batchers with Apache License 2.0 4 votes vote down vote up
public TaxCalculationTestBuilder withTax(double tax) {
    this.tax = Money.of(CurrencyUnit.EUR, tax);
    return this;
}
 
Example 14
Source File: TaxPaymentWebServiceFacadeTest.java    From batchers with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
    Money money = Money.of(CurrencyUnit.EUR, 2000.0);
    taxCalculation = new TaxCalculationTestBuilder().withTax(money).build();
    taxWebserviceCallResultValid = TaxWebserviceCallResult.callSucceeded(taxCalculation);
}
 
Example 15
Source File: MonthlyTaxForEmployeeTestBuilder.java    From batchers with Apache License 2.0 4 votes vote down vote up
public MonthlyTaxForEmployeeTestBuilder withTax(double tax) {
    this.tax = Money.of(CurrencyUnit.EUR, tax);
    return this;
}
 
Example 16
Source File: PremiumListDaoTest.java    From nomulus with Apache License 2.0 4 votes vote down vote up
private static Money moneyOf(CurrencyUnit unit, double amount) {
  return Money.of(unit, BigDecimal.valueOf(amount).setScale(unit.getDecimalPlaces()));
}
 
Example 17
Source File: JodaMoneyConverterTest.java    From nomulus with Apache License 2.0 4 votes vote down vote up
@Test
public void roundTripConversionWithComplexEntity() {
  Money myMoney = Money.of(CurrencyUnit.USD, 100);
  Money yourMoney = Money.of(CurrencyUnit.GBP, 80);
  ImmutableMap<String, Money> moneyMap =
      ImmutableMap.of(
          "uno", Money.of(CurrencyUnit.EUR, 500),
          "dos", Money.ofMajor(CurrencyUnit.JPY, 2000),
          "tres", Money.of(CurrencyUnit.GBP, 20));
  ComplexTestEntity entity = new ComplexTestEntity(moneyMap, myMoney, yourMoney);
  jpaTm().transact(() -> jpaTm().getEntityManager().persist(entity));
  List<?> result =
      jpaTm()
          .transact(
              () ->
                  jpaTm()
                      .getEntityManager()
                      .createNativeQuery(
                          "SELECT my_amount, my_currency, your_amount, your_currency FROM"
                              + " \"ComplexTestEntity\" WHERE name = 'id'")
                      .getResultList());
  assertThat(result.size()).isEqualTo(1);
  assertThat(Arrays.asList((Object[]) result.get(0)))
      .containsExactly(
          BigDecimal.valueOf(100).setScale(2), "USD", BigDecimal.valueOf(80).setScale(2), "GBP")
      .inOrder();
  result =
      jpaTm()
          .transact(
              () ->
                  jpaTm()
                      .getEntityManager()
                      .createNativeQuery(
                          "SELECT map_amount, map_currency FROM \"MoneyMap\""
                              + " WHERE entity_name = 'id' AND map_key = 'dos'")
                      .getResultList());
  ComplexTestEntity persisted =
      jpaTm().transact(() -> jpaTm().getEntityManager().find(ComplexTestEntity.class, "id"));
  assertThat(result.size()).isEqualTo(1);

  // Note that the amount has two decimal places even though JPY is supposed to have scale 0.
  // This is due to the unfournate fact that we need to accommodate differet currencies stored
  // in the same table so that the scale has to be set to the largest (2). When a Money field is
  // persisted in an entity, the entity should always have a @PostLoad callback to convert the
  // Money to the correct scale.
  assertThat(Arrays.asList((Object[]) result.get(0)))
      .containsExactly(BigDecimal.valueOf(2000).setScale(2), "JPY")
      .inOrder();
  // Make sure that the loaded entity contains the fields exactly as they are persisted.
  assertThat(persisted.myMoney).isEqualTo(myMoney);
  assertThat(persisted.yourMoney).isEqualTo(yourMoney);
  assertThat(persisted.moneyMap).containsExactlyEntriesIn(moneyMap);
}
 
Example 18
Source File: DomainFlowUtils.java    From nomulus with Apache License 2.0 4 votes vote down vote up
/**
 * Validates that non-zero fees are acked (i.e. they are specified and the amount matches).
 *
 * <p>This is used directly by update operations, i.e. those that otherwise don't have implicit
 * costs, and is also used as a helper method to validate if fees are required for operations that
 * do have implicit costs, e.g. creates and renews.
 */
public static void validateFeesAckedIfPresent(
    final Optional<? extends FeeTransformCommandExtension> feeCommand,
    FeesAndCredits feesAndCredits)
    throws EppException {
  // Check for the case where a fee command extension was required but not provided.
  // This only happens when the total fees are non-zero and include custom fees requiring the
  // extension.
  if (!feeCommand.isPresent()) {
    if (!feesAndCredits.getEapCost().isZero()) {
      throw new FeesRequiredDuringEarlyAccessProgramException(feesAndCredits.getEapCost());
    }
    if (feesAndCredits.getTotalCost().isZero() || !feesAndCredits.isFeeExtensionRequired()) {
      return;
    }
    throw new FeesRequiredForNonFreeOperationException(feesAndCredits.getTotalCost());
  }

  List<Fee> fees = feeCommand.get().getFees();
  // The schema guarantees that at least one fee will be present.
  checkState(!fees.isEmpty());
  BigDecimal total = zeroInCurrency(feeCommand.get().getCurrency());
  for (Fee fee : fees) {
    if (!fee.hasDefaultAttributes()) {
      throw new UnsupportedFeeAttributeException();
    }
    total = total.add(fee.getCost());
  }
  for (Credit credit : feeCommand.get().getCredits()) {
    if (!credit.hasDefaultAttributes()) {
      throw new UnsupportedFeeAttributeException();
    }
    total = total.add(credit.getCost());
  }

  Money feeTotal;
  try {
    feeTotal = Money.of(feeCommand.get().getCurrency(), total);
  } catch (ArithmeticException e) {
    throw new CurrencyValueScaleException();
  }

  if (!feeTotal.getCurrencyUnit().equals(feesAndCredits.getCurrency())) {
    throw new CurrencyUnitMismatchException();
  }
  // If more than one fees are required, always validate individual fees.
  ImmutableMap<FeeType, Money> expectedFeeMap =
      buildFeeMap(feesAndCredits.getFees(), feesAndCredits.getCurrency());
  if (expectedFeeMap.size() > 1) {
    ImmutableMap<FeeType, Money> providedFeeMap =
        buildFeeMap(feeCommand.get().getFees(), feeCommand.get().getCurrency());
    for (FeeType type : expectedFeeMap.keySet()) {
      if (!providedFeeMap.containsKey(type)) {
        throw new FeesMismatchException(type);
      }
      Money expectedCost = expectedFeeMap.get(type);
      if (!providedFeeMap.get(type).isEqual(expectedCost)) {
        throw new FeesMismatchException(type, expectedCost);
      }
    }
  }
  // Checking if total amount is expected. Extra fees that we are not expecting may be passed in.
  // Or if there is only a single fee type expected.
  if (!feeTotal.equals(feesAndCredits.getTotalCost())) {
    throw new FeesMismatchException(feesAndCredits.getTotalCost());
  }
}
 
Example 19
Source File: MoneyTypeHandler.java    From Java-API-Test-Examples with Apache License 2.0 2 votes vote down vote up
/**
 *  处理 CNY 人民币
 * @param value
 * @return
 */
private Money parseMoney(Long value) {
    return Money.of(CurrencyUnit.of("CNY"), value / 100.0);
}
 
Example 20
Source File: MoneyTypeHandler.java    From Java-API-Test-Examples with Apache License 2.0 2 votes vote down vote up
/**
 *  处理 CNY 人民币
 * @param value
 * @return
 */
private Money parseMoney(Long value) {
    return Money.of(CurrencyUnit.of("CNY"), value / 100.0);
}