Search in sources :

Example 1 with TxnResponse

use of com.coreos.jetcd.api.TxnResponse in project jetcd by coreos.

the class KVTest method testTxn.

@Test
public void testTxn() throws Exception {
    ByteString sampleKey = ByteString.copyFrom("txn_key", "UTF-8");
    ByteString sampleValue = ByteString.copyFrom("xyz", "UTF-8");
    ByteString cmpValue = ByteString.copyFrom("abc", "UTF-8");
    ByteString putValue = ByteString.copyFrom("XYZ", "UTF-8");
    ByteString putValueNew = ByteString.copyFrom("ABC", "UTF-8");
    ListenableFuture<PutResponse> feature = kvClient.put(sampleKey, sampleValue);
    try {
        // put the original txn key value pair
        PutResponse putResp = feature.get();
        // construct txn operation
        Cmp cmp = new Cmp(sampleKey, Cmp.Op.GREATER, CmpTarget.value(cmpValue));
        Txn txn = Txn.newBuilder().If(cmp).Then(Op.put(sampleKey, putValue, PutOption.DEFAULT)).Else(Op.put(sampleKey, putValueNew, PutOption.DEFAULT)).build();
        ListenableFuture<TxnResponse> txnResp = kvClient.commit(txn);
        txnResp.get();
        // get the value
        RangeResponse getResp = kvClient.get(sampleKey).get();
        test.assertEquals(getResp.getKvsList().size(), 1);
        test.assertEquals(getResp.getKvs(0).getValue().toStringUtf8(), "XYZ");
    } catch (Exception e) {
    // empty
    }
}
Also used : DeleteRangeResponse(com.coreos.jetcd.api.DeleteRangeResponse) RangeResponse(com.coreos.jetcd.api.RangeResponse) ByteString(com.google.protobuf.ByteString) Cmp(com.coreos.jetcd.op.Cmp) Txn(com.coreos.jetcd.op.Txn) TxnResponse(com.coreos.jetcd.api.TxnResponse) PutResponse(com.coreos.jetcd.api.PutResponse) ExecutionException(java.util.concurrent.ExecutionException) Test(org.testng.annotations.Test) BeforeTest(org.testng.annotations.BeforeTest)

Aggregations

DeleteRangeResponse (com.coreos.jetcd.api.DeleteRangeResponse)1 PutResponse (com.coreos.jetcd.api.PutResponse)1 RangeResponse (com.coreos.jetcd.api.RangeResponse)1 TxnResponse (com.coreos.jetcd.api.TxnResponse)1 Cmp (com.coreos.jetcd.op.Cmp)1 Txn (com.coreos.jetcd.op.Txn)1 ByteString (com.google.protobuf.ByteString)1 ExecutionException (java.util.concurrent.ExecutionException)1 BeforeTest (org.testng.annotations.BeforeTest)1 Test (org.testng.annotations.Test)1