diff --git a/src/main/java/com/justinsb/etcd/EtcdClient.java b/src/main/java/com/justinsb/etcd/EtcdClient.java index babc363..a874dc4 100644 --- a/src/main/java/com/justinsb/etcd/EtcdClient.java +++ b/src/main/java/com/justinsb/etcd/EtcdClient.java @@ -145,6 +145,17 @@ public EtcdResult cas(String key, String prevValue, String value) throws EtcdCli return set0(key, data, new int[] { 200, 412 }, 101); } + /** + * Sets a key to a new value, depending on the previous existence of the key + */ + public EtcdResult cas(String key, Boolean prevExist, String value) throws EtcdClientException { + List data = Lists.newArrayList(); + data.add(new BasicNameValuePair("value", value)); + data.add(new BasicNameValuePair("prevExist", prevExist.toString())); + + return set0(key, data, new int[] { 200, 201, 412 }, 105); + } + /** * Watches the given subtree */ diff --git a/src/test/java/com/justinsb/etcd/SmokeTest.java b/src/test/java/com/justinsb/etcd/SmokeTest.java index ee42189..a7ef699 100644 --- a/src/test/java/com/justinsb/etcd/SmokeTest.java +++ b/src/test/java/com/justinsb/etcd/SmokeTest.java @@ -136,6 +136,32 @@ public void testCAS() throws Exception { Assert.assertEquals("world", result.node.value); } + @Test + public void testCASPrevValue() throws Exception { + String key = prefix + "/cas"; + + EtcdResult result; + + result = this.client.set(key, "hello"); + result = this.client.get(key); + Assert.assertEquals("hello", result.node.value); + + result = this.client.cas(key, false, "world"); + Assert.assertEquals(true, result.isError()); + + result = this.client.get(key); + Assert.assertEquals("hello", result.node.value); + + result = this.client.delete(key); + Assert.assertEquals(false, result.isError()); + + result = this.client.cas(key, false, "world"); + Assert.assertEquals(false, result.isError()); + + result = this.client.get(key); + Assert.assertEquals("world", result.node.value); + } + @Test public void testWatchPrefix() throws Exception { String key = prefix + "/watch";