Example #1
0
  @Test
  public void useTransactionTest() throws Exception {
    // Performing admin operations to create dataset instance
    // keyValueTable is a system dataset module
    Id.DatasetInstance myTableInstance = Id.DatasetInstance.from(namespace, "myTable");
    dsFramework.addInstance("keyValueTable", myTableInstance, DatasetProperties.EMPTY);

    Assert.assertTrue(feedManager.createFeed(FEED1));
    try {
      Cancellable cancellable =
          notificationService.subscribe(
              FEED1,
              new NotificationHandler<String>() {
                private int received = 0;

                @Override
                public Type getNotificationType() {
                  return String.class;
                }

                @Override
                public void received(
                    final String notification, NotificationContext notificationContext) {
                  notificationContext.execute(
                      new TxRunnable() {
                        @Override
                        public void run(DatasetContext context) throws Exception {
                          KeyValueTable table = context.getDataset("myTable");
                          table.write("foo", String.format("%s-%d", notification, received++));
                        }
                      },
                      TxRetryPolicy.maxRetries(5));
                }
              });
      TimeUnit.SECONDS.sleep(2);

      try {
        notificationService.publish(FEED1, "foobar");
        // Waiting for the subscriber to receive that notification
        TimeUnit.SECONDS.sleep(2);

        KeyValueTable table =
            dsFramework.getDataset(myTableInstance, DatasetDefinition.NO_ARGUMENTS, null);
        Assert.assertNotNull(table);
        Transaction tx1 = txManager.startShort(100);
        table.startTx(tx1);
        Assert.assertEquals("foobar-0", Bytes.toString(table.read("foo")));
        Assert.assertTrue(table.commitTx());
        txManager.canCommit(tx1, table.getTxChanges());
        txManager.commit(tx1);
        table.postTxCommit();
      } finally {
        cancellable.cancel();
      }
    } finally {
      dsFramework.deleteInstance(myTableInstance);
      feedManager.deleteFeed(FEED1);
    }
  }