@Test
  public void testDisruptorCommandBusRepositoryNotAvailableOutsideOfInvokerThread() {
    DisruptorCommandBus commandBus = new DisruptorCommandBus(eventStore, eventBus);
    Repository<Aggregate> repository =
        commandBus.createRepository(new GenericAggregateFactory<Aggregate>(Aggregate.class));

    AggregateAnnotationCommandHandler<Aggregate> handler =
        new AggregateAnnotationCommandHandler<Aggregate>(Aggregate.class, repository);
    AggregateAnnotationCommandHandler.subscribe(handler, commandBus);
    DefaultCommandGateway gateway = new DefaultCommandGateway(commandBus);

    // Create the aggregate
    String aggregateId = "" + System.currentTimeMillis();
    gateway.sendAndWait(new CreateCommandAndEvent(aggregateId));

    // Load the aggretate from the repository -- from "worker" thread
    UnitOfWork uow = DefaultUnitOfWork.startAndGet();
    try {
      Aggregate aggregate = repository.load(aggregateId);
      fail("Expected IllegalStateException");
    } catch (IllegalStateException e) {
      assertTrue(e.getMessage().contains("DisruptorCommandBus"));
    } finally {
      uow.rollback();
    }
  }
示例#2
0
  @CommandHandler
  public void deleteLocation(DeleteLocationCommand command) {
    checkDeleteLocation(command.getLocationId());

    Location location = repository.load(command.getLocationId());
    location.delete(command);
  }
  @Test
  public void testCreateOrder() throws InterruptedException {
    OrderId orderId = new OrderId();
    commandGateway.send(new CreateOrderCommand(orderId, "TestOrder"));

    UnitOfWork unitOfWork = unitOfWorkProvider.get();
    Assert.assertEquals(
        "Order is not created", orderRepository.load(orderId).getIdentifier(), orderId);
    unitOfWork.commit();

    ItemId itemId1 = new ItemId();
    commandGateway.send(new AddOrderItemCommand(orderId, itemId1, 10));

    final AtomicBoolean injectionSuccessful = new AtomicBoolean();
    commandGateway.send(
        new RemoveOrderItemCommand(orderId, itemId1),
        new CommandCallback<Boolean>() {
          @Override
          public void onSuccess(Boolean result) {
            injectionSuccessful.set(true);
          }

          @Override
          public void onFailure(Throwable cause) {
            logger.error("Error", cause);
          }
        });

    Assert.assertTrue(
        "Injection into @CommandHandler method is not successful", injectionSuccessful.get());
  }
示例#4
0
  @CommandHandler
  public void createLocation(CreateLocationCommand command) {
    checkUniqueName(command.getLocationId(), command.getName(), command.getBusinessUnitId());
    checkInactiveDate(command.getInactiveDate());

    Location location = new Location(command);
    repository.add(location);
  }
 @CommandHandler
 public void handleSellOrder(CreateSellOrderCommand command) {
   OrderBook orderBook = repository.load(command.getOrderBookId(), null);
   orderBook.addSellOrder(
       command.getOrderId(),
       command.getTransactionId(),
       command.getTradeCount(),
       command.getItemPrice(),
       command.getPortfolioId());
 }
    @Override
    public Object handle(CommandMessage<StubCommand> command, UnitOfWork unitOfWork)
        throws Throwable {
      if (ExceptionCommand.class.isAssignableFrom(command.getPayloadType())) {
        throw ((ExceptionCommand) command.getPayload()).getException();
      } else if (CreateCommand.class.isAssignableFrom(command.getPayloadType())) {
        StubAggregate aggregate =
            new StubAggregate(command.getPayload().getAggregateIdentifier().toString());
        repository.add(aggregate);
        aggregate.doSomething();
      } else {
        StubAggregate aggregate = repository.load(command.getPayload().getAggregateIdentifier());
        if (ErrorCommand.class.isAssignableFrom(command.getPayloadType())) {
          aggregate.createFailingEvent();
        } else {
          aggregate.doSomething();
        }
      }

      return Void.TYPE;
    }
 @CommandHandler
 public void handle(GenerateTimesheet command) {
   Map<Integer, TimeEntry> timeEntries =
       timeEntryService.generateTimeEntries(
           HolidayCalendar.BELGIUM, command.getYear(), command.getMonthOfYear());
   TimesheetAR timesheetAR =
       new TimesheetAR(
           command.getTimesheetId(),
           command.getSsn(),
           command.getYear(),
           command.getMonthOfYear(),
           timeEntries);
   timesheetARRepository.add(timesheetAR);
 }
 @Override
 public Object handle(CommandMessage<?> command, UnitOfWork unitOfWork) throws Exception {
   repository.load(aggregateIdentifier.toString()).doSomething();
   return null;
 }
 private T loadAggregate(CommandMessage<?> command) {
   VersionedAggregateIdentifier iv = commandTargetResolver.resolveTarget(command);
   return repository.load(iv.getIdentifier(), iv.getVersion());
 }
 @CommandHandler
 void handle(RegisterTimeEntry command) {
   TimesheetAR timesheetAR = timesheetARRepository.load(command.getTimesheetId());
   timesheetAR.register(command.getTimeEntry());
 }
 @CommandHandler
 public void handleCreateOrderBook(CreateOrderBookCommand command) {
   OrderBook orderBook = new OrderBook(command.getOrderBookIdentifier());
   repository.add(orderBook);
 }
 @Override
 public Object handle(CommandMessage<StubCommand> command, UnitOfWork unitOfWork)
     throws Throwable {
   repository.load(command.getPayload().getAggregateIdentifier()).doSomething();
   return null;
 }
示例#13
0
  private void executeBuying(ExecuteBuyOrderCommand buyCommand) {
    OrderBook orderBook = orderBookRepository.load(buyCommand.getOrderBookId());

    // buying price >= current buying price
    if (orderBook.getHighestBuyPrice().compareTo(buyCommand.getItemPrice()) >= 0) {
      return;
    }

    // refresh current buy price
    orderBook.resetHighestBuyPrice(buyCommand.getOrderId().toString(), buyCommand.getItemPrice());

    // buying price >= than the current highest selling  price
    logger.info("Executing Buying order {}", buyCommand);

    boolean done = true;
    do {
      final List<Order> sellOrders =
          orderExecutorHelper.findAscPendingOrdersByPriceTime(
              buyCommand.getPlaceDate(),
              buyCommand.getItemPrice(),
              buyCommand.getOrderBookId(),
              100);

      // no selling order matched
      if (isEmpty(sellOrders)) {
        return;
      }

      for (Order sellOrder : sellOrders) {
        // should not happen here, coz the repo does not return the right result
        if (sellOrder.getItemPrice().compareTo(buyCommand.getItemPrice()) > 0) {
          logger.warn(
              "Strange here, why sell orders from repo have price greater than current buy price!");
          break;
        }

        final Order buyOrder = orderExecutorHelper.findBuyOrder(buyCommand.getOrderId());

        BigMoney matchedTradePrice = sellOrder.getItemPrice();
        BigMoney matchedTradeAmount =
            min(sellOrder.getItemRemaining(), buyOrder.getItemRemaining());

        final BigMoney executedMoney =
            convertTo(matchedTradeAmount, matchedTradePrice).toBigMoney();

        BigMoney buyCommission =
            orderExecutorHelper.calcExecutedBuyCommission(
                buyOrder, matchedTradePrice, matchedTradeAmount);
        BigMoney sellCommission =
            orderExecutorHelper.calcExecutedSellCommission(
                sellOrder, matchedTradePrice, matchedTradeAmount);

        if (logger.isDebugEnabled()) {
          logger.debug(
              "Executing orders with amount {}, price {}, buy commission {}, sell commission {}, total money {}: highest buying order {}, lowest selling order {}",
              matchedTradeAmount,
              matchedTradePrice,
              buyCommission,
              sellCommission,
              executedMoney,
              sellOrder,
              buyOrder);
          orderBook.executeBuying(
              matchedTradeAmount,
              matchedTradePrice,
              executedMoney,
              buyOrder.getPrimaryKey(),
              sellOrder.getPrimaryKey(),
              buyCommission,
              sellCommission,
              buyOrder.getTransactionId(),
              sellOrder.getTransactionId(),
              buyOrder.getPortfolioId(),
              sellOrder.getPortfolioId(),
              buyCommand.getPlaceDate());
        }

        orderExecutorHelper.recordTraded(
            buyOrder,
            sellOrder,
            buyCommission,
            sellCommission,
            matchedTradeAmount,
            matchedTradeAmount,
            buyCommand.getPlaceDate());

        if (buyOrder.getItemRemaining().toMoney(RoundingMode.HALF_EVEN).isNegativeOrZero()) {
          done = true;
          break;
        }
      }
    } while (!done);

    orderExecutorHelper.refresh(orderBook);
  }