org.joda.money.CurrencyUnit Java Examples

The following examples show how to use org.joda.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: PremiumListUtils.java    From nomulus with Apache License 2.0 6 votes vote down vote up
public static PremiumList parseToPremiumList(String name, String inputData) {
  List<String> inputDataPreProcessed =
      Splitter.on('\n').omitEmptyStrings().splitToList(inputData);

  ImmutableMap<String, PremiumListEntry> prices =
      new google.registry.model.registry.label.PremiumList.Builder()
          .setName(name)
          .build()
          .parse(inputDataPreProcessed);
  ImmutableSet<CurrencyUnit> currencies =
      prices.values().stream()
          .map(e -> e.getValue().getCurrencyUnit())
          .distinct()
          .collect(toImmutableSet());
  checkArgument(
      currencies.size() == 1,
      "The Cloud SQL schema requires exactly one currency, but got: %s",
      ImmutableSortedSet.copyOf(currencies));
  CurrencyUnit currency = Iterables.getOnlyElement(currencies);

  Map<String, BigDecimal> priceAmounts =
      Maps.transformValues(prices, ple -> ple.getValue().getAmount());
  return PremiumList.create(name, currency, priceAmounts);
}
 
Example #2
Source File: TaxCalculationRepositoryTest.java    From batchers with Apache License 2.0 6 votes vote down vote up
@Test
public void givenOneEmployeeWithTaxAndPaycheck_whenGettingSum_theSumIsCorrect() {
    //ARRANGE
    Employee employee = anEmployee();
    employeeRepository.save(employee);

    TaxCalculation tax = new TaxCalculationTestBuilder()
            .withEmployee(employee)
            .build();
    taxCalculationRepository.save(tax);

    PayCheck payCheck = PayCheck.from(1l, tax, null);
    payCheckRepository.save(payCheck);

    //ACT
    Money successSum = taxCalculationRepository.getSuccessSum(tax.getYear(), tax.getMonth());
    Money failedSum = taxCalculationRepository.getFailedSum(tax.getYear(), tax.getMonth());

    //ASSERT
    assertThat(successSum).isEqualTo(tax.getTax());
    assertThat(failedSum).isEqualTo(Money.zero(CurrencyUnit.EUR));
}
 
Example #3
Source File: ConsoleRegistrarCreatorAction.java    From nomulus with Apache License 2.0 6 votes vote down vote up
private static ImmutableMap<CurrencyUnit, String> parseBillingAccount(String billingAccount) {
  try {
    return LINE_SPLITTER.splitToList(billingAccount).stream()
        .map(ENTRY_SPLITTER::splitToList)
        .peek(
            list ->
                checkState(
                    list.size() == 2,
                    "Can't parse line %s. The format should be [currency]=[account ID]",
                    list))
        .collect(
            toImmutableMap(
                list -> CurrencyUnit.of(Ascii.toUpperCase(list.get(0))), list -> list.get(1)));
  } catch (Throwable e) {
    throw new RuntimeException("Error parsing billing accounts - " + e.getMessage(), e);
  }
}
 
Example #4
Source File: RetryConfigTest.java    From batchers with Apache License 2.0 6 votes vote down vote up
@Test
public void whenRetryCallbackFails_retryTimeIsExponential() throws TaxWebServiceNonFatalException {
    long start = System.currentTimeMillis();

    when(retryCallback.doWithRetry(any(RetryContext.class)))
            .thenThrow(new TaxWebServiceNonFatalException(new EmployeeTestBuilder().build(), Money.of(CurrencyUnit.EUR, 10), null, null, "boe"))
            .thenThrow(new TaxWebServiceNonFatalException(new EmployeeTestBuilder().build(), Money.of(CurrencyUnit.EUR, 10), null, null, "boe"))
            .thenReturn(any());

    retryTemplate.execute(retryCallback);

    verify(retryCallback, times(3)).doWithRetry(any(RetryContext.class));

    long end = System.currentTimeMillis();
    long duration = end - start;
    assertThat(duration).isGreaterThanOrEqualTo(300);
}
 
Example #5
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 #6
Source File: TaxCalculationRepositoryTest.java    From batchers with Apache License 2.0 6 votes vote down vote up
@Test
public void givenOneEmployeeWithTaxAndNoPaycheck_whenGettingSum_theSumIsCorrect() {
    //ARRANGE
    Employee employee = anEmployee();
    employeeRepository.save(employee);

    TaxCalculation tax = new TaxCalculationTestBuilder()
            .withEmployee(employee)
            .build();
    taxCalculationRepository.save(tax);

    //ACT
    Money successSum = taxCalculationRepository.getSuccessSum(tax.getYear(), tax.getMonth());
    Money failedSum = taxCalculationRepository.getFailedSum(tax.getYear(), tax.getMonth());

    //ASSERT
    assertThat(successSum).isEqualTo(Money.zero(CurrencyUnit.EUR));
    assertThat(failedSum).isEqualTo(tax.getTax());
}
 
Example #7
Source File: UpdateRegistrarCommandTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testSuccess_billingAccountMap_partialUpdate() throws Exception {
  createTlds("foo");
  persistResource(
      loadRegistrar("NewRegistrar")
          .asBuilder()
          .setBillingAccountMap(
              ImmutableMap.of(CurrencyUnit.USD, "abc123", CurrencyUnit.JPY, "789xyz"))
          .build());
  runCommand("--billing_account_map=JPY=123xyz", "--allowed_tlds=foo", "--force", "NewRegistrar");
  assertThat(loadRegistrar("NewRegistrar").getBillingAccountMap())
      .containsExactly(CurrencyUnit.JPY, "123xyz", CurrencyUnit.USD, "abc123");
}
 
Example #8
Source File: ForwardAvailableBalance.java    From banking-swift-messages-java with MIT License 5 votes vote down vote up
public static ForwardAvailableBalance of(GeneralField field) throws FieldNotationParseException {
    Preconditions.checkArgument(field.getTag().equals(FIELD_TAG_65), "unexpected field tag '%s'", field.getTag());

    List<String> subFields = SWIFT_NOTATION.parse(field.getContent());

    DebitCreditMark debitCreditMark = DebitCreditMark.ofFieldValue(subFields.get(0));
    LocalDate entryDate = LocalDate.parse(subFields.get(1), DATE_FORMATTER);
    CurrencyUnit amountCurrency = CurrencyUnit.of(subFields.get(2));
    BigDecimal amountValue = SwiftDecimalFormatter.parse(subFields.get(3));

    BigMoney amount = BigMoney.of(amountCurrency, amountValue);

    return new ForwardAvailableBalance(entryDate, debitCreditMark, amount);
}
 
Example #9
Source File: PersistentMoneyMajorAmountAndCurrency.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];
    Long amountMajorPart = (Long) convertedColumns[1];
    Money money = Money.ofMajor(currencyUnitPart, amountMajorPart);

    return money;
}
 
Example #10
Source File: FloorLimitIndicatorTest.java    From banking-swift-messages-java with MIT License 5 votes vote down vote up
@Test
public void getSignedAmount_WHEN_debit_transaction_THEN_return_negative_amount() throws Exception {
    // Given
    BigMoney amount = BigMoney.of(CurrencyUnit.EUR, 1);
    FloorLimitIndicator classUnderTest = new FloorLimitIndicator(
            DebitCreditMark.DEBIT,
            amount);

    // When
    Optional<BigMoney> signedAmount = classUnderTest.getSignedAmount();

    // Then
    assertThat(signedAmount).contains(amount.negated());
}
 
Example #11
Source File: OpeningBalance.java    From banking-swift-messages-java with MIT License 5 votes vote down vote up
public static OpeningBalance of(GeneralField field) throws FieldNotationParseException {
    Preconditions.checkArgument(field.getTag().equals(FIELD_TAG_60F) || field.getTag().equals(FIELD_TAG_60M), "unexpected field tag '%s'", field.getTag());
    Type type = field.getTag().equals(FIELD_TAG_60F) ? Type.OPENING : Type.INTERMEDIATE;

    List<String> subFields = SWIFT_NOTATION.parse(field.getContent());

    DebitCreditMark debitCreditMark = subFields.get(0) != null ? DebitCreditMark.ofFieldValue(subFields.get(0)) : null;
    LocalDate date = LocalDate.parse(subFields.get(1), DATE_FORMATTER);
    CurrencyUnit amountCurrency = CurrencyUnit.of(subFields.get(2));
    BigDecimal amountValue = SwiftDecimalFormatter.parse(subFields.get(3));
    BigMoney amount = BigMoney.of(amountCurrency, amountValue);

    return new OpeningBalance(type, date, debitCreditMark, amount);
}
 
Example #12
Source File: TaxWebserviceCallResultRepositoryTest.java    From batchers with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    employee = anEmployee();
    employeeRepository.save(employee);


    january = new TaxCalculationTestBuilder()
            .withEmployee(employee)
            .withMonth(1)
            .withTax(10.0)
            .build();

    february = new TaxCalculationTestBuilder()
            .withEmployee(employee)
            .withMonth(2)
            .withTax(10.0)
            .build();

    List<TaxCalculation> taxCalculations = Arrays.asList(january, february);
    taxCalculations.forEach(taxCalculationRepository::save);

    januaryTry1 = TaxWebserviceCallResult.callFailed(january, new TaxWebServiceFatalException(new EmployeeTestBuilder().build(), Money.of(CurrencyUnit.EUR, 10), HttpStatus.BAD_REQUEST, null, "boe"));
    januaryTry2 = TaxWebserviceCallResult.callSucceeded(january);
    februaryTry1 = TaxWebserviceCallResult.callSucceeded(february);

    List<TaxWebserviceCallResult> taxWebserviceCallResults = Arrays.asList(januaryTry1, januaryTry2, februaryTry1);
    taxWebserviceCallResults.forEach(taxWebserviceCallResultRepository::save);
}
 
Example #13
Source File: OpeningBalanceTest.java    From banking-swift-messages-java with MIT License 5 votes vote down vote up
@Test
public void getSignedAmount_WHEN_debit_transaction_THEN_return_negative_amount() throws Exception {
    // Given
    BigMoney amount = BigMoney.of(CurrencyUnit.EUR, 1);
    OpeningBalance classUnderTest = new OpeningBalance(OpeningBalance.Type.OPENING, LocalDate.now(),
            DebitCreditMark.DEBIT,
            amount);

    // When
    BigMoney signedAmount = classUnderTest.getSignedAmount();

    // Then
    assertThat(signedAmount).isEqualTo(amount.negated());
}
 
Example #14
Source File: TransactionSummary.java    From banking-swift-messages-java with MIT License 5 votes vote down vote up
public static TransactionSummary of(GeneralField field) throws FieldNotationParseException {
    Preconditions.checkArgument(field.getTag().equals(FIELD_TAG_90D) || field.getTag().equals(FIELD_TAG_90C), "unexpected field tag '%s'", field.getTag());
    DebitCreditMark type = field.getTag().equals(FIELD_TAG_90D) ? DebitCreditMark.DEBIT : DebitCreditMark.CREDIT;

    List<String> subFields = SWIFT_NOTATION.parse(field.getContent());

    int transactionCount = Integer.parseInt(subFields.get(0));
    CurrencyUnit amountCurrency = CurrencyUnit.of(subFields.get(1));
    BigDecimal amountValue = SwiftDecimalFormatter.parse(subFields.get(2));
    BigMoney amount = BigMoney.of(amountCurrency, amountValue);

    return new TransactionSummary(type, transactionCount, amount);
}
 
Example #15
Source File: PersistentBigMoneyMinorAmountAndCurrency.java    From jadira with Apache License 2.0 5 votes vote down vote up
@Override
protected BigMoney fromConvertedColumns(Object[] convertedColumns) {

    CurrencyUnit currencyUnitPart = (CurrencyUnit) convertedColumns[0];
    Long amountMinorPart = (Long) convertedColumns[1];
    BigMoney money = BigMoney.ofMinor(currencyUnitPart, amountMinorPart);

    return money;
}
 
Example #16
Source File: ClosingBalance.java    From banking-swift-messages-java with MIT License 5 votes vote down vote up
public static ClosingBalance of(GeneralField field) throws FieldNotationParseException {
    Preconditions.checkArgument(field.getTag().equals(FIELD_TAG_62F) || field.getTag().equals(FIELD_TAG_62M), "unexpected field tag '%s'", field.getTag());
    Type type = field.getTag().equals(FIELD_TAG_62F) ? Type.CLOSING : Type.INTERMEDIATE;

    List<String> subFields = SWIFT_NOTATION.parse(field.getContent());

    DebitCreditMark debitCreditMark = DebitCreditMark.ofFieldValue(subFields.get(0));
    LocalDate date = LocalDate.parse(subFields.get(1), DATE_FORMATTER);
    CurrencyUnit amountCurrency = CurrencyUnit.of(subFields.get(2));
    BigDecimal amountValue = SwiftDecimalFormatter.parse(subFields.get(3));
    BigMoney amount = BigMoney.of(amountCurrency, amountValue);

    return new ClosingBalance(type, date, debitCreditMark, amount);
}
 
Example #17
Source File: TaxPaymentWebServiceTest.java    From batchers with Apache License 2.0 5 votes vote down vote up
@Test(expected = TaxWebServiceNonFatalException.class)
public void testProcess_UnexpectedServerExceptionOccurs_ExceptionIsRethrown() throws Exception {
    whenCallingTheWebservice().thenThrow(aServerErrorException());

    Employee employee = new EmployeeTestBuilder().build();

    taxPaymentWebService.doWebserviceCallToTaxService(employee, Money.of(CurrencyUnit.EUR, 2000.0));
}
 
Example #18
Source File: ClosingBalanceTest.java    From banking-swift-messages-java with MIT License 5 votes vote down vote up
@Test
public void getSignedAmount_WHEN_credit_transaction_THEN_return_positive_amount() throws Exception {
    // Given
    BigMoney amount = BigMoney.of(CurrencyUnit.EUR, 1);
    ClosingBalance classUnderTest = new ClosingBalance(ClosingBalance.Type.CLOSING, LocalDate.now(),
            DebitCreditMark.CREDIT,
            amount);

    // When
    BigMoney signedAmount = classUnderTest.getSignedAmount();

    // Then
    assertThat(signedAmount).isEqualTo(amount);
}
 
Example #19
Source File: JodaMoneyConverterTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@PostLoad
void setCurrencyScale() {
  moneyMap
      .entrySet()
      .forEach(
          entry -> {
            Money money = entry.getValue();
            if (!money.toBigMoney().isCurrencyScale()) {
              CurrencyUnit currency = money.getCurrencyUnit();
              BigDecimal amount = money.getAmount().setScale(currency.getDecimalPlaces());
              entry.setValue(Money.of(currency, amount));
            }
          });
}
 
Example #20
Source File: CurrencyUnitAdapter.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/** Parses a string into a {@link CurrencyUnit} object. */
@Override
public CurrencyUnit unmarshal(String currency) throws UnknownCurrencyException {
  try {
    return CurrencyUnit.of(nullToEmpty(currency).trim());
  } catch (IllegalArgumentException e) {
    throw new UnknownCurrencyException();
  }
}
 
Example #21
Source File: AmountBasedDiscountPolicy.java    From tutorials with MIT License 5 votes vote down vote up
@Override
public double discount(Order order) {
    if (order.totalCost()
        .isGreaterThan(Money.of(CurrencyUnit.USD, 500.00))) {
        return 0.10;
    } else
        return 0;
}
 
Example #22
Source File: UpdateRegistrarCommandTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testSuccess_billingAccountMap_onlyAppliesToRealRegistrar() throws Exception {
  createTlds("foo");
  assertThat(loadRegistrar("NewRegistrar").getBillingAccountMap()).isEmpty();
  runCommand("--billing_account_map=JPY=789xyz", "--allowed_tlds=foo", "--force", "NewRegistrar");
  assertThat(loadRegistrar("NewRegistrar").getBillingAccountMap())
      .containsExactly(CurrencyUnit.JPY, "789xyz");
}
 
Example #23
Source File: UpdateRegistrarCommandTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void testSuccess_billingAccountMap() throws Exception {
  assertThat(loadRegistrar("NewRegistrar").getBillingAccountMap()).isEmpty();
  runCommand("--billing_account_map=USD=abc123,JPY=789xyz", "--force", "NewRegistrar");
  assertThat(loadRegistrar("NewRegistrar").getBillingAccountMap())
      .containsExactly(CurrencyUnit.USD, "abc123", CurrencyUnit.JPY, "789xyz");
}
 
Example #24
Source File: Registrar.java    From nomulus with Apache License 2.0 5 votes vote down vote up
public Builder setBillingAccountMap(@Nullable Map<CurrencyUnit, String> billingAccountMap) {
  if (billingAccountMap == null) {
    getInstance().billingAccountMap = null;
  } else {
    getInstance().billingAccountMap =
        billingAccountMap
            .entrySet()
            .stream()
            .collect(toImmutableMap(Map.Entry::getKey, BillingAccountEntry::new));
  }
  return this;
}
 
Example #25
Source File: PersistentBigMoneyMajorAmountAndCurrency.java    From jadira with Apache License 2.0 5 votes vote down vote up
@Override
protected BigMoney fromConvertedColumns(Object[] convertedColumns) {

    CurrencyUnit currencyUnitPart = (CurrencyUnit) convertedColumns[0];
    Long amountMajorPart = (Long) convertedColumns[1];

    BigMoney theMoney = BigMoney.ofMajor(currencyUnitPart, amountMajorPart);
    if (theMoney.getScale() < currencyUnitPart.getDecimalPlaces()) {
    	theMoney = theMoney.withCurrencyScale();
    }

    return theMoney;
}
 
Example #26
Source File: PersistentBigMoneyAmountAndCurrencyAsInteger.java    From jadira with Apache License 2.0 5 votes vote down vote up
@Override
protected BigMoney fromConvertedColumns(Object[] convertedColumns) {

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

    return money;
}
 
Example #27
Source File: TaxPaymentWebServiceFacadeTest.java    From batchers with Apache License 2.0 5 votes vote down vote up
@Test
public void whenPreviousCallResultIsFailed_andCallReturnsException_exceptionIsReturned() throws Exception {
    when(taxWebserviceCallResultRepository.findSuccessfulByTaxCalculation(taxCalculation)).thenReturn(null);
    when(taxServiceCallResultCallable.call()).thenThrow(new TaxWebServiceNonFatalException(new EmployeeTestBuilder().build(), Money.of(CurrencyUnit.EUR, 10), HttpStatus.INTERNAL_SERVER_ERROR, null, "boe"));

    expectExceptionWithMessage(TaxWebServiceNonFatalException.class, "Paying the taxes for employee with id null with amount EUR 10.00 failed because of boe");

    taxPaymentWebServiceFacade.callTaxService(taxCalculation, taxServiceCallResultCallable);
}
 
Example #28
Source File: PremiumListTest.java    From nomulus with Apache License 2.0 5 votes vote down vote up
@Test
public void bloomFilter_worksCorrectly() {
  BloomFilter<String> bloomFilter =
      PremiumList.create("testname", CurrencyUnit.USD, TEST_PRICES).getBloomFilter();
  ImmutableSet.of("silver", "gold", "palladium")
      .forEach(l -> assertThat(bloomFilter.mightContain(l)).isTrue());
  ImmutableSet.of("dirt", "pyrite", "zirconia")
      .forEach(l -> assertThat(bloomFilter.mightContain(l)).isFalse());
}
 
Example #29
Source File: DomainFlowUtils.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private static ImmutableMap<FeeType, Money> buildFeeMap(List<Fee> fees, CurrencyUnit currency)
    throws ParameterValuePolicyErrorException {
  ImmutableMultimap.Builder<FeeType, Money> mapBuilder =
      new ImmutableMultimap.Builder<FeeType, Money>().orderKeysBy(Comparator.naturalOrder());
  for (Fee fee : fees) {
    mapBuilder.put(getOrParseType(fee), Money.of(currency, fee.getCost()));
  }
  return mapBuilder
      .build()
      .asMap()
      .entrySet()
      .stream()
      .collect(toImmutableMap(Entry::getKey, entry -> Money.total(entry.getValue())));
}
 
Example #30
Source File: PersistentMoneyMajorAmountAndCurrencyAsInteger.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];
    Long amountMajorPart = (Long) convertedColumns[1];
    Money money = Money.ofMajor(currencyUnitPart, amountMajorPart);

    return money;
}