示例#1
0
  @Test
  public void testRowUniquenessConstraint() throws Exception {
    RowUniquenessConstraint<String, String> unique =
        new RowUniquenessConstraint<String, String>(
                keyspace,
                UNIQUE_CF,
                "testRowUniquenessConstraint",
                UUIDStringSupplier.getInstance())
            .withConsistencyLevel(ConsistencyLevel.CL_ONE);
    RowUniquenessConstraint<String, String> unique2 =
        new RowUniquenessConstraint<String, String>(
                keyspace,
                UNIQUE_CF,
                "testRowUniquenessConstraint",
                UUIDStringSupplier.getInstance())
            .withConsistencyLevel(ConsistencyLevel.CL_ONE);

    try {
      unique.withData("abc").acquire();
      try {
        unique2.acquire();
        Assert.fail();
      } catch (Exception e) {
        LOG.info(e.getMessage());
      }

      String data = unique.readDataAsString();
      Assert.assertNotNull(data);
    } catch (Exception e) {
      e.printStackTrace();
      Assert.fail(e.getMessage());
      LOG.error(e.getMessage());
    } finally {
      unique.release();
    }

    try {
      String data = unique.readDataAsString();
      Assert.fail();
    } catch (Exception e) {
      LOG.info("", e);
    }
  }
  @Override
  public void acquireAndApplyMutation(Function<MutationBatch, Boolean> callback)
      throws NotUniqueException, Exception {
    try {
      // Phase 1: Write a unique column
      MutationBatch m = keyspace.prepareMutationBatch().setConsistencyLevel(consistencyLevel);
      if (data == null) {
        m.withRow(columnFamily, key).putEmptyColumn(uniqueColumn, ttl);
      } else {
        m.withRow(columnFamily, key).putColumn(uniqueColumn, data, ttl);
      }
      m.execute();

      // Phase 2: Read back all columns. There should be only 1
      ColumnList<C> result =
          keyspace
              .prepareQuery(columnFamily)
              .setConsistencyLevel(consistencyLevel)
              .getKey(key)
              .execute()
              .getResult();

      if (result.size() != 1) {
        throw new NotUniqueException(key.toString());
      }

      // Phase 3: Persist the uniqueness with
      m = keyspace.prepareMutationBatch().setConsistencyLevel(consistencyLevel);
      if (callback != null) callback.apply(m);

      if (data == null) {
        m.withRow(columnFamily, key).putEmptyColumn(uniqueColumn, null);
      } else {
        m.withRow(columnFamily, key).putColumn(uniqueColumn, data, null);
      }
      m.execute();
    } catch (Exception e) {
      release();
      throw e;
    }
  }