@Test
  public void testDisallowed() throws Exception {
    final InvocationContext context = mock(InvocationContext.class);

    final Invocation invocation = mock(Invocation.class);
    when(invocation.getInvocationContext()).thenReturn(context);

    CashRepository cashRepository = mock(CashRepository.class);
    final CoinReceiveCash cash1 = new CoinReceiveCash();
    cash1.confirm(BigMoney.of(CurrencyUnit.of("BTC"), BigDecimal.TEN), new Date());
    final CoinReceiveCash cash2 = new CoinReceiveCash();
    cash2.confirm(BigMoney.of(CurrencyUnit.of("BTC"), BigDecimal.ONE), new Date());
    when(cashRepository.findByDueDate(any(Date.class))).thenReturn(ImmutableList.of(cash1, cash2));

    DueDateService dateService = mock(DueDateService.class);

    final GlobalMaxAmountPerDayExecutingInterceptor interceptor =
        new GlobalMaxAmountPerDayExecutingInterceptor("BTC 10");
    interceptor.setCashRepository(cashRepository);
    interceptor.setService(dateService);

    final ValidationCode validationCode = interceptor.intercept(invocation);

    assertThat(validationCode, is(ValidationCode.EXCEEDED_GLOBAL_MAX_AMOUNT_PER_DAY));

    verify(dateService).computeDueDate(any(Date.class));
    verify(invocation, never()).invoke();
  }
  @Test
  public void testAllowed() throws Exception {
    final InvocationContext context = mock(InvocationContext.class);

    final Invocation invocation = mock(Invocation.class);
    when(invocation.getInvocationContext()).thenReturn(context);

    CashRepository cashRepository = mock(CashRepository.class);
    final CoinReceiveCash cash1 = new CoinReceiveCash();
    cash1.confirm(BigMoney.of(CurrencyUnit.of("BTC"), BigDecimal.TEN), new Date());
    final CoinReceiveCash cash2 = new CoinReceiveCash();
    cash2.confirm(BigMoney.of(CurrencyUnit.of("BTC"), BigDecimal.ONE), new Date());
    when(cashRepository.findByDueDate(any(Date.class)))
        .thenReturn(ImmutableList.of(cash1), ImmutableList.of(cash2));

    DueDateService dateService = mock(DueDateService.class);

    final GlobalMaxAmountPerDayExecutingInterceptor interceptor =
        new GlobalMaxAmountPerDayExecutingInterceptor("BTC 10");
    interceptor.setCashRepository(cashRepository);
    interceptor.setService(dateService);

    final ValidationCode validationCode1 = interceptor.intercept(invocation);
    final ValidationCode validationCode2 = interceptor.intercept(invocation);

    assertThat(validationCode1, anyOf(nullValue(), is(ValidationCode.SUCCESSFUL)));
    assertThat(validationCode2, anyOf(nullValue(), is(ValidationCode.SUCCESSFUL)));

    verify(invocation, times(2)).invoke();
    verify(dateService, times(2)).computeDueDate(any(Date.class));
    verify(invocation, times(2)).invoke();
  }
 @Override
 public Long toNonNullValue(Money value) {
   if (!currencyUnit.equals(value.getCurrencyUnit())) {
     throw new IllegalStateException(
         "Expected currency "
             + currencyUnit.getCurrencyCode()
             + " but was "
             + value.getCurrencyUnit());
   }
   return value.getAmountMinorLong();
 }
Beispiel #4
0
    @Override
    public boolean equals(Object o) {
      if (this == o) return true;
      if (o == null || getClass() != o.getClass()) return false;

      Pair pair = (Pair) o;

      return day.equals(pair.day) && unit.equals(pair.unit);
    }
  @Override
  public void open(Serializable serializable) throws Exception {
    if (null == serializable) {
      logger.trace("Starting a new checkpoint");
      checkpoint = new BasicBatchCheckpoint();
    } else {
      checkpoint = (BasicBatchCheckpoint) serializable;
      logger.trace("Checkpoint available: {}", checkpoint);
    }

    CurrencyUnit fromCurrency = CurrencyUnit.of(from);

    logger.trace("Building http client");

    logger.trace("Listing currently registered currencies");
    List<CurrencyUnit> registeredCurrencies = CurrencyUnit.registeredCurrencies();
    StringBuilder conversionsToAsk = new StringBuilder();
    int current = 0;
    for (CurrencyUnit to : registeredCurrencies) {
      if (fromCurrency.equals(to)) {
        continue;
      }
      logger.debug("Would ask the provider from convert {} into {}", fromCurrency, to);

      if (current > 0) {
        conversionsToAsk.append("+");
      }

      conversionsToAsk.append(fromCurrency).append(to).append("=X");
      current++;
    }
    String url = BASE_URL + conversionsToAsk.toString();
    logger.trace("URL to call: {}", url);

    logger.trace("Preparing reader");
    reader = new BufferedReader(new InputStreamReader(new URL(url).openStream()));
  }
Beispiel #6
0
  private Stream<PostponingReasons> getPostponingReasonsStream(
      String sql, boolean doDistinctAfterFirstStream) {
    final AccumulationContext context = new AccumulationContext();
    final LazyResultSetIterator<Pair> iterator =
        LazyResultSetIterator.<Pair>of(
            Common.getRsSupplier(jdbcConnector, sql, "streamAllPostponingReasons"),
            Common.getMappingSqlFunction(
                rs ->
                    new Pair(
                        sqlDialect.translateFromDb(rs.getObject(1), UtcDay.class),
                        CurrencyUnit.ofNumericCode(rs.getInt(2))),
                sql,
                "streamAllPostponingReasons"),
            sql);
    Stream<Pair> stream = iterator.stream();
    if (doDistinctAfterFirstStream) {
      stream = stream.distinct();
    }
    return stream
        .filter(
            pair -> {
              if (context.builder == null) {
                context.builder = ImmutableSet.builder();
                context.currentDay = pair.day;
                context.builder.add(pair.unit);
                return false;
              }

              if (!pair.day.equals(context.currentDay)) {
                return true;
              } else {
                context.builder.add(pair.unit);
                return false;
              }
            })
        .map(
            pair -> {
              final PostponingReasons postponingReasons =
                  new PostponingReasons(context.currentDay, context.builder.build());
              if (iterator.hasNext()) {
                context.builder = ImmutableSet.builder();
                context.currentDay = pair.day;
                context.builder.add(pair.unit);
              }
              return postponingReasons;
            });
  }
Beispiel #7
0
  /**
   * Adapts a Transaction[] to a Trades Object
   *
   * @param transactions The Bitstamp transactions
   * @param tradableIdentifier The tradeable identifier (e.g. BTC in BTC/USD)
   * @param currency The currency (e.g. USD in BTC/USD)
   * @return The XChange Trades
   */
  public static Trades adaptTrades(
      BitstampTransaction[] transactions, String tradableIdentifier, String currency) {

    List<Trade> trades = new ArrayList<Trade>();
    for (BitstampTransaction tx : transactions) {
      trades.add(
          new Trade(
              null,
              tx.getAmount(),
              tradableIdentifier,
              currency,
              BigMoney.of(CurrencyUnit.of(currency), tx.getPrice()),
              DateUtils.fromMillisUtc(tx.getDate() * 1000L),
              tx.getTid()));
    }

    return new Trades(trades);
  }
  @Override
  public Object readItem() throws Exception {
    logger.trace("Reading item");
    String line = reader.readLine();
    if (null != line) {
      String[] parts = line.split(",");
      String left = parts[0];
      CurrencyUnit to = currencyAdapter.adapt(left.substring(4, 7));
      BigDecimal rate = bigDecimalAdapter.adapt(parts[1]);
      ExchangeRate exchangeRate =
          new ExchangeRate(CurrencyUnit.of(from), to, rate, LocalDate.now());

      checkpoint.incrementAndGet();
      logger.trace("Item read: {}", exchangeRate);
      return exchangeRate;
    } else {
      return null;
    }
  }
Beispiel #9
0
/** @author Adam Winciorek */
public class WageTest {

  private static final CurrencyUnit UNIT = CurrencyUnit.of("PLN");

  @Test
  public void shouldCalculateCorrectNetValue() {
    Wage wage = new Wage(Money.of(UNIT, 750), new WageMetadata(19, Money.of(UNIT, 1200)));
    Assert.assertEquals(Money.of(UNIT, 607.50), wage.calculateNetValue());
  }

  @Test
  public void shouldCalculateCorrectNetIncome() {
    Wage wage = new Wage(Money.of(UNIT, 750), new WageMetadata(19, Money.of(UNIT, 1200)));
    Assert.assertEquals(Money.of(UNIT, -592.50), wage.calculateNetIncome());
  }

  @Test
  public void shouldCalculateCorrectTaxAmount() {
    Wage wage = new Wage(Money.of(UNIT, 750), new WageMetadata(19, Money.of(UNIT, 1200)));
    Assert.assertEquals(Money.of(UNIT, 142.5), wage.calculateTaxAmount());
  }
}
Beispiel #10
0
 public CurrencyUnit getCurrencyUnit() {
   return CurrencyUnit.of(transactionCurrency);
 }
Beispiel #11
0
 @Override
 public int hashCode() {
   int result = day.hashCode();
   result = 31 * result + unit.hashCode();
   return result;
 }