浏览代码

ZOOKEEPER-3992: addWatch api should check the null watch

```
public void addWatch(String basePath, Watcher watcher, AddWatchMode mode)
        throws KeeperException, InterruptedException {
    PathUtils.validatePath(basePath);
    String serverPath = prependChroot(basePath);

    RequestHeader h = new RequestHeader();
    h.setType(ZooDefs.OpCode.addWatch);
    AddWatchRequest request = new AddWatchRequest(serverPath, mode.getMode());
    ReplyHeader r = cnxn.submitRequest(h, request, new ErrorResponse(),
```
we need to validateWatcher(watcher) to avoid the case:
```
zk.addWatch("/a/b", null, PERSISTENT_RECURSIVE);
```

Author: Matteo Minardi <matteo.minardi@diennea.com>

Reviewers: Enrico Olivelli <eolivelli@apache.org>, Damien Diederen <ddiederen@apache.org>

Closes #1529 from mino181295/fix/ZOOKEEPER-3992/addwatch-check-null
Matteo Minardi 4 年之前
父节点
当前提交
c9a1b595f9

+ 2 - 0
zookeeper-server/src/main/java/org/apache/zookeeper/ZooKeeper.java

@@ -2806,6 +2806,7 @@ public class ZooKeeper implements AutoCloseable {
     public void addWatch(String basePath, Watcher watcher, AddWatchMode mode)
             throws KeeperException, InterruptedException {
         PathUtils.validatePath(basePath);
+        validateWatcher(watcher);
         String serverPath = prependChroot(basePath);
 
         RequestHeader h = new RequestHeader();
@@ -2857,6 +2858,7 @@ public class ZooKeeper implements AutoCloseable {
             Object ctx
     ) {
         PathUtils.validatePath(basePath);
+        validateWatcher(watcher);
         String serverPath = prependChroot(basePath);
 
         RequestHeader h = new RequestHeader();

+ 15 - 0
zookeeper-server/src/test/java/org/apache/zookeeper/test/PersistentWatcherTest.java

@@ -21,6 +21,7 @@ package org.apache.zookeeper.test;
 import static org.apache.zookeeper.AddWatchMode.PERSISTENT;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 import java.io.IOException;
 import java.util.concurrent.BlockingQueue;
@@ -62,6 +63,20 @@ public class PersistentWatcherTest extends ClientBase {
         }
     }
 
+    @Test
+    public void testNullWatch()
+            throws IOException, InterruptedException, KeeperException {
+        try (ZooKeeper zk = createClient(new CountdownWatcher(), hostPort)) {
+            assertThrows(IllegalArgumentException.class, () -> {
+                zk.addWatch("/a/b", null, PERSISTENT);
+            });
+            assertThrows(IllegalArgumentException.class, () -> {
+                AsyncCallback.VoidCallback cb = (rc, path, ctx) -> {};
+                zk.addWatch("/a/b", null, PERSISTENT, cb, null);
+            });
+        }
+    }
+
     @Test
     public void testDefaultWatcher()
             throws IOException, InterruptedException, KeeperException {