Ver Fonte

ZOOKEEPER-3475: Enable Checkstyle configuration on zookeeper-server

- [x] org/apache/zookeeper
- [x] org/apache/zookeeper/admin
- [x] org/apache/zookeeper/cli
- [x] org/apache/zookeeper/client
- [x] org/apache/zookeeper/common
- [x] org/apache/zookeeper/jmx
- [x] org/apache/zookeeper/metrics
- [x] org/apache/zookeeper/metrics/impl
- [x] org/apache/zookeeper/server
- [x] org/apache/zookeeper/server/admin
- [x] org/apache/zookeeper/server/auth
- [x] org/apache/zookeeper/server/command
- [x] org/apache/zookeeper/server/metric
- [x] org/apache/zookeeper/server/persistence
- [x] org/apache/zookeeper/server/quorum
- [x] org/apache/zookeeper/server/quorum/auth
- [x] org/apache/zookeeper/server/quorum/flexible
- [x] org/apache/zookeeper/server/util
- [x] org/apache/zookeeper/server/watch
- [x] org/apache/zookeeper/test
- [x] org/apache/zookeeper/util
- [x] org/apache/zookeeper/version/util

Author: tison <wander4096@gmail.com>

Reviewers: Brian Nixon <nixon@fb.com>, Enrico Olivelli <eolivelli@gmail.com>, Michael Han <hanm@apache.org>

Closes #1049 from TisonKun/ZOOKEEPER-3475
tison há 5 anos atrás
pai
commit
fe940cdd8f
100 ficheiros alterados com 3542 adições e 3089 exclusões
  1. 9 0
      checkstyleSuppressions.xml
  2. 7 6
      zookeeper-it/src/test/java/org/apache/zookeeper/test/system/GenerateLoad.java
  3. 1 1
      zookeeper-it/src/test/java/org/apache/zookeeper/test/system/InstanceContainer.java
  4. 15 15
      zookeeper-it/src/test/java/org/apache/zookeeper/test/system/InstanceManager.java
  5. 8 8
      zookeeper-it/src/test/java/org/apache/zookeeper/test/system/SimpleClient.java
  6. 10 10
      zookeeper-it/src/test/java/org/apache/zookeeper/test/system/SimpleSysTest.java
  7. 21 21
      zookeeper-recipes/zookeeper-recipes-queue/src/test/java/org/apache/zookeeper/recipes/queue/DistributedQueueTest.java
  8. 32 0
      zookeeper-server/pom.xml
  9. 39 22
      zookeeper-server/src/main/java/org/apache/zookeeper/AsyncCallback.java
  10. 315 312
      zookeeper-server/src/main/java/org/apache/zookeeper/ClientCnxn.java
  11. 19 21
      zookeeper-server/src/main/java/org/apache/zookeeper/ClientCnxnSocket.java
  12. 36 41
      zookeeper-server/src/main/java/org/apache/zookeeper/ClientCnxnSocketNIO.java
  13. 40 43
      zookeeper-server/src/main/java/org/apache/zookeeper/ClientCnxnSocketNetty.java
  14. 9 8
      zookeeper-server/src/main/java/org/apache/zookeeper/ClientWatchManager.java
  15. 49 43
      zookeeper-server/src/main/java/org/apache/zookeeper/CreateMode.java
  16. 3 2
      zookeeper-server/src/main/java/org/apache/zookeeper/DigestWatcher.java
  17. 31 41
      zookeeper-server/src/main/java/org/apache/zookeeper/Environment.java
  18. 16 20
      zookeeper-server/src/main/java/org/apache/zookeeper/JLineZNodeCompleter.java
  19. 253 187
      zookeeper-server/src/main/java/org/apache/zookeeper/KeeperException.java
  20. 59 60
      zookeeper-server/src/main/java/org/apache/zookeeper/Login.java
  21. 75 63
      zookeeper-server/src/main/java/org/apache/zookeeper/MultiOperationRecord.java
  22. 90 82
      zookeeper-server/src/main/java/org/apache/zookeeper/MultiResponse.java
  23. 77 31
      zookeeper-server/src/main/java/org/apache/zookeeper/Op.java
  24. 68 29
      zookeeper-server/src/main/java/org/apache/zookeeper/OpResult.java
  25. 4 5
      zookeeper-server/src/main/java/org/apache/zookeeper/Quotas.java
  26. 27 28
      zookeeper-server/src/main/java/org/apache/zookeeper/SaslClientCallbackHandler.java
  27. 16 5
      zookeeper-server/src/main/java/org/apache/zookeeper/SaslServerPrincipal.java
  28. 9 10
      zookeeper-server/src/main/java/org/apache/zookeeper/ServerAdminClient.java
  29. 399 408
      zookeeper-server/src/main/java/org/apache/zookeeper/Shell.java
  30. 4 4
      zookeeper-server/src/main/java/org/apache/zookeeper/StatsTrack.java
  31. 3 1
      zookeeper-server/src/main/java/org/apache/zookeeper/Testable.java
  32. 6 5
      zookeeper-server/src/main/java/org/apache/zookeeper/Transaction.java
  33. 12 13
      zookeeper-server/src/main/java/org/apache/zookeeper/Version.java
  34. 13 11
      zookeeper-server/src/main/java/org/apache/zookeeper/WatchDeregistration.java
  35. 14 14
      zookeeper-server/src/main/java/org/apache/zookeeper/WatchedEvent.java
  36. 78 58
      zookeeper-server/src/main/java/org/apache/zookeeper/Watcher.java
  37. 36 27
      zookeeper-server/src/main/java/org/apache/zookeeper/ZKUtil.java
  38. 49 49
      zookeeper-server/src/main/java/org/apache/zookeeper/ZooDefs.java
  39. 282 202
      zookeeper-server/src/main/java/org/apache/zookeeper/ZooKeeper.java
  40. 65 72
      zookeeper-server/src/main/java/org/apache/zookeeper/ZooKeeperMain.java
  41. 5 6
      zookeeper-server/src/main/java/org/apache/zookeeper/ZooKeeperTestable.java
  42. 12 12
      zookeeper-server/src/main/java/org/apache/zookeeper/ZookeeperBanner.java
  43. 70 33
      zookeeper-server/src/main/java/org/apache/zookeeper/admin/ZooKeeperAdmin.java
  44. 24 23
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/AclParser.java
  45. 3 1
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/AddAuthCommand.java
  46. 17 14
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/CliCommand.java
  47. 3 1
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/CliException.java
  48. 4 1
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/CliParseException.java
  49. 10 8
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/CliWrapperException.java
  50. 5 5
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/CloseCommand.java
  51. 3 1
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/CommandNotFoundException.java
  52. 17 10
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/CreateCommand.java
  53. 20 10
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/DelQuotaCommand.java
  54. 8 7
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/DeleteAllCommand.java
  55. 12 6
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/DeleteCommand.java
  56. 7 6
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/GetAclCommand.java
  57. 4 1
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/GetAllChildrenNumberCommand.java
  58. 12 7
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/GetCommand.java
  59. 15 9
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/GetConfigCommand.java
  60. 5 3
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/GetEphemeralsCommand.java
  61. 18 16
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/ListQuotaCommand.java
  62. 14 9
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/Ls2Command.java
  63. 12 6
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/LsCommand.java
  64. 4 1
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/MalformedCommandException.java
  65. 4 1
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/MalformedPathException.java
  66. 30 29
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/ReconfigCommand.java
  67. 5 4
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/RemoveWatchesCommand.java
  68. 9 3
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/SetAclCommand.java
  69. 9 3
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/SetCommand.java
  70. 35 26
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/SetQuotaCommand.java
  71. 15 11
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/StatCommand.java
  72. 4 3
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/StatPrinter.java
  73. 4 3
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/SyncCommand.java
  74. 3 1
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/VersionCommand.java
  75. 12 12
      zookeeper-server/src/main/java/org/apache/zookeeper/client/ConnectStringParser.java
  76. 23 20
      zookeeper-server/src/main/java/org/apache/zookeeper/client/FourLetterWordMain.java
  77. 20 20
      zookeeper-server/src/main/java/org/apache/zookeeper/client/HostProvider.java
  78. 43 50
      zookeeper-server/src/main/java/org/apache/zookeeper/client/StaticHostProvider.java
  79. 6 7
      zookeeper-server/src/main/java/org/apache/zookeeper/client/ZKClientConfig.java
  80. 91 100
      zookeeper-server/src/main/java/org/apache/zookeeper/client/ZooKeeperSaslClient.java
  81. 9 12
      zookeeper-server/src/main/java/org/apache/zookeeper/common/AtomicFileOutputStream.java
  82. 13 9
      zookeeper-server/src/main/java/org/apache/zookeeper/common/AtomicFileWritingIdiom.java
  83. 2 1
      zookeeper-server/src/main/java/org/apache/zookeeper/common/ClientX509Util.java
  84. 13 22
      zookeeper-server/src/main/java/org/apache/zookeeper/common/FileChangeWatcher.java
  85. 9 7
      zookeeper-server/src/main/java/org/apache/zookeeper/common/FileKeyStoreLoader.java
  86. 11 12
      zookeeper-server/src/main/java/org/apache/zookeeper/common/FileKeyStoreLoaderBuilderProvider.java
  87. 10 11
      zookeeper-server/src/main/java/org/apache/zookeeper/common/IOUtils.java
  88. 10 5
      zookeeper-server/src/main/java/org/apache/zookeeper/common/JKSFileLoader.java
  89. 6 6
      zookeeper-server/src/main/java/org/apache/zookeeper/common/KeyStoreFileType.java
  90. 3 1
      zookeeper-server/src/main/java/org/apache/zookeeper/common/KeyStoreLoader.java
  91. 2 1
      zookeeper-server/src/main/java/org/apache/zookeeper/common/NetUtils.java
  92. 11 12
      zookeeper-server/src/main/java/org/apache/zookeeper/common/NettyUtils.java
  93. 10 7
      zookeeper-server/src/main/java/org/apache/zookeeper/common/PEMFileLoader.java
  94. 10 5
      zookeeper-server/src/main/java/org/apache/zookeeper/common/PKCS12FileLoader.java
  95. 346 345
      zookeeper-server/src/main/java/org/apache/zookeeper/common/PathTrie.java
  96. 104 112
      zookeeper-server/src/main/java/org/apache/zookeeper/common/PathUtils.java
  97. 2 1
      zookeeper-server/src/main/java/org/apache/zookeeper/common/QuorumX509Util.java
  98. 36 39
      zookeeper-server/src/main/java/org/apache/zookeeper/common/SSLContextAndOptions.java
  99. 8 5
      zookeeper-server/src/main/java/org/apache/zookeeper/common/StandardTypeFileKeyStoreLoader.java
  100. 11 9
      zookeeper-server/src/main/java/org/apache/zookeeper/common/StringUtils.java

+ 9 - 0
checkstyleSuppressions.xml

@@ -23,4 +23,13 @@
     <suppress checks=".*" files=".+[\\/]generated-sources[\\/].+\.java" />
     <suppress checks=".*" files=".+[\\/]generated-test-sources[\\/].+\.java" />
     <suppress checks="LineLength" files=".+[\\/]jute[\\/].+\.java"/>
+
+    <!-- TODO ZOOKEEPER-3508 -->
+    <suppress checks="LineLength" files=".+[\\/]zookeeper-server[\\/].+\.java"/>
+
+    <!-- TODO ZOOKEEPER-3507 -->
+    <suppress checks=".*Name.*" files=".+[\\/]zookeeper-server[\\/].+\.java"/>
+
+    <!-- TODO ZOOKEEPER-3469 -->
+    <suppress checks="Javadoc.+" files=".+[\\/]zookeeper-server[\\/].+\.java"/>
 </suppressions>

+ 7 - 6
zookeeper-it/src/test/java/org/apache/zookeeper/test/system/GenerateLoad.java

@@ -70,7 +70,7 @@ public class GenerateLoad {
     volatile static long currentInterval;
 
     static long lastChange;
-    
+
     static PrintStream sf;
     static PrintStream tf;
     static {
@@ -86,7 +86,8 @@ public class GenerateLoad {
     synchronized static void add(long time, int count, Socket s) {
         long interval = time / INTERVAL;
         if (currentInterval == 0 || currentInterval > interval) {
-            System.out.println("Dropping " + count + " for " + new Date(time)
+            System.out.println(
+                "Dropping " + count + " for " + new Date(time)
                     + " " + currentInterval + ">" + interval);
             return;
         }
@@ -269,7 +270,7 @@ public class GenerateLoad {
     static public class GeneratorInstance implements Instance {
 
         byte bytes[];
-        
+
         int percentage = -1;
 
         int errors;
@@ -287,7 +288,7 @@ public class GenerateLoad {
         int wlatency;
 
         int outstanding;
-        
+
         volatile boolean alive;
 
         class ZooKeeperThread extends Thread implements Watcher, DataCallback,
@@ -556,7 +557,7 @@ public class GenerateLoad {
 
     private static boolean leaderOnly;
     private static boolean leaderServes;
-    
+
     private static String []processOptions(String args[]) {
         ArrayList<String> newArgs = new ArrayList<String>();
         for(String a: args) {
@@ -571,7 +572,7 @@ public class GenerateLoad {
         }
         return newArgs.toArray(new String[0]);
     }
-    
+
     /**
      * @param args
      * @throws InterruptedException

+ 1 - 1
zookeeper-it/src/test/java/org/apache/zookeeper/test/system/InstanceContainer.java

@@ -242,7 +242,7 @@ public class InstanceContainer implements Watcher, AsyncCallback.ChildrenCallbac
             Instance i = instances.remove(child);
             if (i == null) {
                 // Start up a new instance
-                byte data[] = null;
+                byte[] data = null;
                 String myNode = assignmentsNode + '/' + child;
                 while(true) {
                     try {

+ 15 - 15
zookeeper-it/src/test/java/org/apache/zookeeper/test/system/InstanceManager.java

@@ -47,7 +47,7 @@ import org.apache.zookeeper.common.Time;
  *    * ready: this znode indicates that the InstanceManager is running
  *    * available: the children of this znode are ephemeral nodes representing
  *                 running InstanceContainers
- *    * assignments: there will be a child under this znode for each available 
+ *    * assignments: there will be a child under this znode for each available
  *                   InstanceContainer. those znodes will have a child for each
  *                   assigned instance
  *    * reports: there will be a child under this znode for each instance that is
@@ -114,21 +114,21 @@ public class InstanceManager implements AsyncCallback.ChildrenCallback, Watcher
             InterruptedException {
         try {
             zk.create(prefixNode, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
-        } catch(NodeExistsException e) { /* this is ok */ } 
+        } catch(NodeExistsException e) { /* this is ok */ }
         try {
             zk.create(assignmentsNode, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
-        } catch(NodeExistsException e) { /* this is ok */ } 
-        try { 
+        } catch(NodeExistsException e) { /* this is ok */ }
+        try {
             zk.create(statusNode, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
-        } catch(NodeExistsException e) { /* this is ok */ } 
-        try { 
+        } catch(NodeExistsException e) { /* this is ok */ }
+        try {
             zk.create(reportsNode, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
-        } catch(NodeExistsException e) { /* this is ok */ } 
+        } catch(NodeExistsException e) { /* this is ok */ }
         try {
             zk.create(readyNode, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
-        } catch(NodeExistsException e) { /* this is ok */ } 
+        } catch(NodeExistsException e) { /* this is ok */ }
     }
-    
+
     synchronized public void processResult(int rc, String path, Object ctx,
             List<String> children) {
         if (rc != KeeperException.Code.OK.intValue()) {
@@ -159,7 +159,7 @@ public class InstanceManager implements AsyncCallback.ChildrenCallback, Watcher
         }
         assignments = newAssignments;
     }
-    
+
     public void process(WatchedEvent event) {
         if (event.getPath().equals(statusNode)) {
             zk.getChildren(statusNode, this, this, null);
@@ -224,7 +224,7 @@ public class InstanceManager implements AsyncCallback.ChildrenCallback, Watcher
         }
         throw lastException;
     }
-    
+
     public void reconfigureInstance(String name, String params) throws NoAssignmentException, InterruptedException, KeeperException {
         if (LOG.isDebugEnabled()) {
             LOG.debug("Reconfiguring " + name + " with " + params);
@@ -246,7 +246,7 @@ public class InstanceManager implements AsyncCallback.ChildrenCallback, Watcher
             throw lastException;
         }
     }
-    
+
     private void doDelete(String path) throws InterruptedException, KeeperException {
         KeeperException lastException = null;
         for(int i = 0; i < maxTries; i++) {
@@ -270,11 +270,11 @@ public class InstanceManager implements AsyncCallback.ChildrenCallback, Watcher
         doDelete(assignmentsNode + '/' + assigned.container + '/' + name);
         doDelete(reportsNode + '/' + name);
     }
-    
+
     synchronized boolean isAlive(String name) {
         return instanceToAssignment.get(name) != null;
     }
-    
+
     public void resetStatus(String name) throws InterruptedException, KeeperException {
         KeeperException lastException = null;
         for(int i = 0; i < maxTries; i++) {
@@ -295,7 +295,7 @@ public class InstanceManager implements AsyncCallback.ChildrenCallback, Watcher
 
     public String getStatus(String name, long timeout) throws KeeperException, InterruptedException {
         Stat stat = new Stat();
-        byte data[] = null;
+        byte[] data = null;
         long endTime = Time.currentElapsedTime() + timeout;
         KeeperException lastException = null;
         for(int i = 0; i < maxTries && endTime > Time.currentElapsedTime(); i++) {

+ 8 - 8
zookeeper-it/src/test/java/org/apache/zookeeper/test/system/SimpleClient.java

@@ -29,7 +29,7 @@ import org.apache.zookeeper.ZooDefs.Ids;
 import org.apache.zookeeper.data.Stat;
 
 /**
- * The client that gets spawned for the SimpleSysTest 
+ * The client that gets spawned for the SimpleSysTest
  *
  */
 public class SimpleClient implements Instance, Watcher, AsyncCallback.DataCallback, StringCallback, StatCallback {
@@ -38,7 +38,7 @@ public class SimpleClient implements Instance, Watcher, AsyncCallback.DataCallba
     ZooKeeper zk;
     transient int index;
     transient String myPath;
-    byte data[];
+    byte[] data;
     boolean createdEphemeral;
     public void configure(String params) {
         String parts[] = params.split(" ");
@@ -46,7 +46,7 @@ public class SimpleClient implements Instance, Watcher, AsyncCallback.DataCallba
         this.index = Integer.parseInt(parts[0]);
         myPath = "/simpleCase/" + index;
     }
-    
+
     public void start() {
         try {
             zk = new ZooKeeper(hostPort, 15000, this);
@@ -58,7 +58,7 @@ public class SimpleClient implements Instance, Watcher, AsyncCallback.DataCallba
             e.printStackTrace();
         }
     }
-    
+
     public void stop() {
         try {
             if (zk != null) {
@@ -73,7 +73,7 @@ public class SimpleClient implements Instance, Watcher, AsyncCallback.DataCallba
             zk.getData("/simpleCase", true, this, null);
         }
     }
-    
+
     public void processResult(int rc, String path, Object ctx, byte[] data,
             Stat stat) {
         if (rc != 0) {
@@ -91,9 +91,9 @@ public class SimpleClient implements Instance, Watcher, AsyncCallback.DataCallba
             } else {
                 zk.setData(myPath, data, -1, this, null);
             }
-        }            
+        }
     }
-    
+
     public void processResult(int rc, String path, Object ctx, String name) {
         if (rc != 0) {
             zk.create(myPath, data, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, this, null);
@@ -108,7 +108,7 @@ public class SimpleClient implements Instance, Watcher, AsyncCallback.DataCallba
     public String toString() {
         return SimpleClient.class.getName() + "[" + index + "] using " + hostPort;
     }
-    
+
     Reporter r;
     public void setReporter(Reporter r) {
         this.r = r;

+ 10 - 10
zookeeper-it/src/test/java/org/apache/zookeeper/test/system/SimpleSysTest.java

@@ -45,7 +45,7 @@ public class SimpleSysTest extends BaseSysTest implements Watcher {
     int maxTries = 10;
     boolean connected;
     final private static Logger LOG = LoggerFactory.getLogger(SimpleSysTest.class);
-    
+
     synchronized private boolean waitForConnect(ZooKeeper zk, long timeout) throws InterruptedException {
         connected = (zk.getState() == States.CONNECTED);
         long end = Time.currentElapsedTime() + timeout;
@@ -55,7 +55,7 @@ public class SimpleSysTest extends BaseSysTest implements Watcher {
         }
         return connected;
     }
-    
+
     /**
      * This test checks the following:
      * 1) All clients connect successfully
@@ -63,7 +63,7 @@ public class SimpleSysTest extends BaseSysTest implements Watcher {
      * 3) All servers are restarted and cluster stays alive
      * 4) Clients see a change by the server
      * 5) Clients' ephemeral nodes are cleaned up
-     * 
+     *
      * @throws Exception
      */
     @Test
@@ -77,7 +77,7 @@ public class SimpleSysTest extends BaseSysTest implements Watcher {
         waitForConnect(zk, 10000);
         zk.create("/simpleCase", "orig".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
         startClients();
-        
+
         // Check that all clients connect properly
         for(int i = 0; i < getClientCount(); i++) {
             for(int j = 0; j < maxTries; j++) {
@@ -92,7 +92,7 @@ public class SimpleSysTest extends BaseSysTest implements Watcher {
                 }
             }
         }
-        
+
         // Kill half the servers, make a change, restart the dead
         // servers, and then bounce the other servers one by one
         for(int i = 0; i < getServerCount(); i++) {
@@ -120,11 +120,11 @@ public class SimpleSysTest extends BaseSysTest implements Watcher {
         } catch(ConnectionLossException e) {
             Assert.assertTrue("Servers didn't bounce", waitForConnect(zk, 15000));
         }
-        
+
         // check that the change has propagated to everyone
         for(int i = 0; i < getClientCount(); i++) {
             for(int j = 0; j < maxTries; j++) {
-                byte data[] = zk.getData("/simpleCase/" + i, false, stat);
+                byte[] data = zk.getData("/simpleCase/" + i, false, stat);
                 if (new String(data).equals("new")) {
                     break;
                 }
@@ -134,10 +134,10 @@ public class SimpleSysTest extends BaseSysTest implements Watcher {
                 Thread.sleep(1000);
             }
         }
-        
+
         // send out the kill signal
         zk.setData("/simpleCase", "die".getBytes(), -1);
-        
+
         // watch for everyone to die
         for(int i = 0; i < getClientCount(); i++) {
             try {
@@ -152,7 +152,7 @@ public class SimpleSysTest extends BaseSysTest implements Watcher {
                 // Great this is what we were hoping for!
             }
         }
-        
+
         stopClients();
         stopServers();
     }

+ 21 - 21
zookeeper-recipes/zookeeper-recipes-queue/src/test/java/org/apache/zookeeper/recipes/queue/DistributedQueueTest.java

@@ -42,8 +42,8 @@ public class DistributedQueueTest extends ClientBase {
         String dir = "/testOffer1";
         String testString = "Hello World";
         final int num_clients = 1;
-        ZooKeeper clients[] = new ZooKeeper[num_clients];
-        DistributedQueue queueHandles[] = new DistributedQueue[num_clients];
+        ZooKeeper[] clients = new ZooKeeper[num_clients];
+        DistributedQueue[] queueHandles = new DistributedQueue[num_clients];
         for(int i=0; i < clients.length; i++){
             clients[i] = createClient();
             queueHandles[i] = new DistributedQueue(clients[i], dir, null);
@@ -51,7 +51,7 @@ public class DistributedQueueTest extends ClientBase {
 
         queueHandles[0].offer(testString.getBytes());
 
-        byte dequeuedBytes[] = queueHandles[0].remove();
+        byte[] dequeuedBytes = queueHandles[0].remove();
         Assert.assertEquals(new String(dequeuedBytes), testString);
     }
 
@@ -60,8 +60,8 @@ public class DistributedQueueTest extends ClientBase {
         String dir = "/testOffer2";
         String testString = "Hello World";
         final int num_clients = 2;
-        ZooKeeper clients[] = new ZooKeeper[num_clients];
-        DistributedQueue queueHandles[] = new DistributedQueue[num_clients];
+        ZooKeeper[] clients = new ZooKeeper[num_clients];
+        DistributedQueue[] queueHandles = new DistributedQueue[num_clients];
         for(int i=0; i < clients.length; i++){
             clients[i] = createClient();
             queueHandles[i] = new DistributedQueue(clients[i], dir, null);
@@ -69,7 +69,7 @@ public class DistributedQueueTest extends ClientBase {
 
         queueHandles[0].offer(testString.getBytes());
 
-        byte dequeuedBytes[] = queueHandles[1].remove();
+        byte[] dequeuedBytes = queueHandles[1].remove();
         Assert.assertEquals(new String(dequeuedBytes), testString);
     }
 
@@ -78,8 +78,8 @@ public class DistributedQueueTest extends ClientBase {
         String dir = "/testTake1";
         String testString = "Hello World";
         final int num_clients = 1;
-        ZooKeeper clients[] = new ZooKeeper[num_clients];
-        DistributedQueue queueHandles[] = new DistributedQueue[num_clients];
+        ZooKeeper[] clients = new ZooKeeper[num_clients];
+        DistributedQueue[] queueHandles = new DistributedQueue[num_clients];
         for(int i=0; i < clients.length; i++){
             clients[i] = createClient();
             queueHandles[i] = new DistributedQueue(clients[i], dir, null);
@@ -87,7 +87,7 @@ public class DistributedQueueTest extends ClientBase {
 
         queueHandles[0].offer(testString.getBytes());
 
-        byte dequeuedBytes[] = queueHandles[0].take();
+        byte[] dequeuedBytes = queueHandles[0].take();
         Assert.assertEquals(new String(dequeuedBytes), testString);
     }
 
@@ -98,8 +98,8 @@ public class DistributedQueueTest extends ClientBase {
         String dir = "/testRemove1";
         String testString = "Hello World";
         final int num_clients = 1;
-        ZooKeeper clients[] = new ZooKeeper[num_clients];
-        DistributedQueue queueHandles[] = new DistributedQueue[num_clients];
+        ZooKeeper[] clients = new ZooKeeper[num_clients];
+        DistributedQueue[] queueHandles = new DistributedQueue[num_clients];
         for(int i=0; i < clients.length; i++){
             clients[i] = createClient();
             queueHandles[i] = new DistributedQueue(clients[i], dir, null);
@@ -116,8 +116,8 @@ public class DistributedQueueTest extends ClientBase {
     public void createNremoveMtest(String dir,int n,int m) throws Exception{
         String testString = "Hello World";
         final int num_clients = 2;
-        ZooKeeper clients[] = new ZooKeeper[num_clients];
-        DistributedQueue queueHandles[] = new DistributedQueue[num_clients];
+        ZooKeeper[] clients = new ZooKeeper[num_clients];
+        DistributedQueue[] queueHandles = new DistributedQueue[num_clients];
         for(int i=0; i < clients.length; i++){
             clients[i] = createClient();
             queueHandles[i] = new DistributedQueue(clients[i], dir, null);
@@ -128,7 +128,7 @@ public class DistributedQueueTest extends ClientBase {
             queueHandles[0].offer(offerString.getBytes());
         }
 
-        byte data[] = null;
+        byte[] data = null;
         for(int i=0; i<m; i++){
             data=queueHandles[1].remove();
         }
@@ -147,8 +147,8 @@ public class DistributedQueueTest extends ClientBase {
     public void createNremoveMelementTest(String dir,int n,int m) throws Exception{
         String testString = "Hello World";
         final int num_clients = 2;
-        ZooKeeper clients[] = new ZooKeeper[num_clients];
-        DistributedQueue queueHandles[] = new DistributedQueue[num_clients];
+        ZooKeeper[] clients = new ZooKeeper[num_clients];
+        DistributedQueue[] queueHandles = new DistributedQueue[num_clients];
         for(int i=0; i < clients.length; i++){
             clients[i] = createClient();
             queueHandles[i] = new DistributedQueue(clients[i], dir, null);
@@ -159,7 +159,7 @@ public class DistributedQueueTest extends ClientBase {
             queueHandles[0].offer(offerString.getBytes());
         }
 
-        byte data[] = null;
+        byte[] data = null;
         for(int i=0; i<m; i++){
             data=queueHandles[1].remove();
         }
@@ -191,8 +191,8 @@ public class DistributedQueueTest extends ClientBase {
         String dir = "/testTakeWait1";
         final String testString = "Hello World";
         final int num_clients = 1;
-        final ZooKeeper clients[] = new ZooKeeper[num_clients];
-        final DistributedQueue queueHandles[] = new DistributedQueue[num_clients];
+        final ZooKeeper[] clients = new ZooKeeper[num_clients];
+        final DistributedQueue[] queueHandles = new DistributedQueue[num_clients];
         for(int i=0; i < clients.length; i++){
             clients[i] = createClient();
             queueHandles[i] = new DistributedQueue(clients[i], dir, null);
@@ -238,8 +238,8 @@ public class DistributedQueueTest extends ClientBase {
         String dir = "/testTakeWait2";
         final String testString = "Hello World";
         final int num_clients = 1;
-        final ZooKeeper clients[] = new ZooKeeper[num_clients];
-        final DistributedQueue queueHandles[] = new DistributedQueue[num_clients];
+        final ZooKeeper[] clients = new ZooKeeper[num_clients];
+        final DistributedQueue[] queueHandles = new DistributedQueue[num_clients];
         for(int i=0; i < clients.length; i++){
             clients[i] = createClient();
             queueHandles[i] = new DistributedQueue(clients[i], dir, null);

+ 32 - 0
zookeeper-server/pom.xml

@@ -290,6 +290,38 @@
           </systemPropertyVariables>
         </configuration>
       </plugin>
+
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-checkstyle-plugin</artifactId>
+        <version>3.1.0</version>
+        <dependencies>
+          <dependency>
+            <groupId>com.puppycrawl.tools</groupId>
+            <artifactId>checkstyle</artifactId>
+            <version>${checkstyle.version}</version>
+          </dependency>
+        </dependencies>
+        <configuration>
+          <configLocation>checkstyle-strict.xml</configLocation>
+          <suppressionsLocation>checkstyleSuppressions.xml</suppressionsLocation>
+          <encoding>UTF-8</encoding>
+          <consoleOutput>true</consoleOutput>
+          <failOnViolation>true</failOnViolation>
+          <includeResources>false</includeResources>
+          <includeTestSourceDirectory>true</includeTestSourceDirectory>
+          <includeTestResources>false</includeTestResources>
+        </configuration>
+        <executions>
+          <execution>
+            <id>checkstyle</id>
+            <phase>validate</phase>
+            <goals>
+              <goal>check</goal>
+            </goals>
+          </execution>
+        </executions>
+      </plugin>
     </plugins>
   </build>
 

+ 39 - 22
zookeeper-server/src/main/java/org/apache/zookeeper/AsyncCallback.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,10 +15,10 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper;
 
 import java.util.List;
-
 import org.apache.yetus.audience.InterfaceAudience;
 import org.apache.zookeeper.data.ACL;
 import org.apache.zookeeper.data.Stat;
@@ -38,6 +38,7 @@ public interface AsyncCallback {
      */
     @InterfaceAudience.Public
     interface StatCallback extends AsyncCallback {
+
         /**
          * Process the result of the asynchronous call.
          * <p>
@@ -65,21 +66,24 @@ public interface AsyncCallback {
          * @param stat {@link org.apache.zookeeper.data.Stat} object of
          *             the node on given path.
          */
-        public void processResult(int rc, String path, Object ctx, Stat stat);
+        void processResult(int rc, String path, Object ctx, Stat stat);
+
     }
 
-    /*
-    *  This callback is used to get all children node number of the node.
-    * */
+    /**
+     *  This callback is used to get all children node number of the node.
+     */
     @InterfaceAudience.Public
     interface AllChildrenNumberCallback extends AsyncCallback {
+
         /**
          *
          * @param rc      The return code or the result of the call.
          * @param ctx     Whatever context object that we passed to asynchronous calls.
          * @param number  the number of children nodes under a specific path
          */
-        public void processResult(int rc, String path, Object ctx, int number);
+        void processResult(int rc, String path, Object ctx, int number);
+
     }
 
     /**
@@ -87,6 +91,7 @@ public interface AsyncCallback {
      */
     @InterfaceAudience.Public
     interface DataCallback extends AsyncCallback {
+
         /**
          * Process the result of asynchronous calls.
          * <p>
@@ -111,8 +116,8 @@ public interface AsyncCallback {
          * @param stat {@link org.apache.zookeeper.data.Stat} object of
          *             the node on given path.
          */
-        public void processResult(int rc, String path, Object ctx, byte data[],
-                Stat stat);
+        void processResult(int rc, String path, Object ctx, byte[] data, Stat stat);
+
     }
 
     /**
@@ -120,6 +125,7 @@ public interface AsyncCallback {
      */
     @InterfaceAudience.Public
     interface ACLCallback extends AsyncCallback {
+
         /**
          * Process the result of the asynchronous call.
          * <p>
@@ -144,8 +150,8 @@ public interface AsyncCallback {
          * @param stat {@link org.apache.zookeeper.data.Stat} object of
          *             the node on given path.
          */
-        public void processResult(int rc, String path, Object ctx,
-                List<ACL> acl, Stat stat);
+        void processResult(int rc, String path, Object ctx, List<ACL> acl, Stat stat);
+
     }
 
     /**
@@ -153,6 +159,7 @@ public interface AsyncCallback {
      */
     @InterfaceAudience.Public
     interface ChildrenCallback extends AsyncCallback {
+
         /**
          * Process the result of the asynchronous call.
          * <p>
@@ -175,8 +182,8 @@ public interface AsyncCallback {
          * @param children An unordered array of children of the node on
          *                 given path.
          */
-        public void processResult(int rc, String path, Object ctx,
-                List<String> children);
+        void processResult(int rc, String path, Object ctx, List<String> children);
+
     }
 
     /**
@@ -184,6 +191,7 @@ public interface AsyncCallback {
      */
     @InterfaceAudience.Public
     interface Children2Callback extends AsyncCallback {
+
         /**
          * Process the result of the asynchronous call.
          * See {@link org.apache.zookeeper.AsyncCallback.ChildrenCallback}.
@@ -197,8 +205,8 @@ public interface AsyncCallback {
          * @param stat     {@link org.apache.zookeeper.data.Stat} object of
          *                 the node on given path.
          */
-        public void processResult(int rc, String path, Object ctx,
-                List<String> children, Stat stat);
+        void processResult(int rc, String path, Object ctx, List<String> children, Stat stat);
+
     }
 
     /**
@@ -206,6 +214,7 @@ public interface AsyncCallback {
      */
     @InterfaceAudience.Public
     interface Create2Callback extends AsyncCallback {
+
         /**
          * Process the result of the asynchronous call.
          * See {@link org.apache.zookeeper.AsyncCallback.StringCallback}.
@@ -220,8 +229,8 @@ public interface AsyncCallback {
          * @param stat {@link org.apache.zookeeper.data.Stat} object of
          *             the node on given path.
          */
-        public void processResult(int rc, String path, Object ctx,
-        		String name, Stat stat);
+        void processResult(int rc, String path, Object ctx, String name, Stat stat);
+
     }
 
     /**
@@ -229,6 +238,7 @@ public interface AsyncCallback {
      */
     @InterfaceAudience.Public
     interface StringCallback extends AsyncCallback {
+
         /**
          * Process the result of the asynchronous call.
          * <p>
@@ -262,7 +272,8 @@ public interface AsyncCallback {
          *             On success, <i>name</i> and <i>path</i> are usually
          *             equal, unless a sequential node has been created.
          */
-        public void processResult(int rc, String path, Object ctx, String name);
+        void processResult(int rc, String path, Object ctx, String name);
+
     }
 
     /**
@@ -273,6 +284,7 @@ public interface AsyncCallback {
      */
     @InterfaceAudience.Public
     interface VoidCallback extends AsyncCallback {
+
         /**
          * Process the result of the asynchronous call.
          * <p>
@@ -305,7 +317,8 @@ public interface AsyncCallback {
          * @param ctx  Whatever context object that we passed to
          *             asynchronous calls.
          */
-        public void processResult(int rc, String path, Object ctx);
+        void processResult(int rc, String path, Object ctx);
+
     }
 
     /**
@@ -315,6 +328,7 @@ public interface AsyncCallback {
      */
     @InterfaceAudience.Public
     interface MultiCallback extends AsyncCallback {
+
         /**
          * Process the result of the asynchronous call.
          * <p>
@@ -339,8 +353,8 @@ public interface AsyncCallback {
          *                  One result for each operation,
          *                  and the order matches that of input.
          */
-        public void processResult(int rc, String path, Object ctx,
-                List<OpResult> opResults);
+        void processResult(int rc, String path, Object ctx, List<OpResult> opResults);
+
     }
 
     /**
@@ -348,12 +362,15 @@ public interface AsyncCallback {
      * a single getEphemerals call.
      */
     interface EphemeralsCallback extends AsyncCallback {
+
         /**
          *
          * @param rc      The return code or the result of the call.
          * @param ctx     Whatever context object that we passed to asynchronous calls.
          * @param paths   The path that we passed to asynchronous calls.
          */
-        public void processResult(int rc, Object ctx, List<String> paths);
+        void processResult(int rc, Object ctx, List<String> paths);
+
     }
+
 }

Diff do ficheiro suprimidas por serem muito extensas
+ 315 - 312
zookeeper-server/src/main/java/org/apache/zookeeper/ClientCnxn.java


+ 19 - 21
zookeeper-server/src/main/java/org/apache/zookeeper/ClientCnxnSocket.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -26,12 +26,11 @@ import java.text.MessageFormat;
 import java.util.Queue;
 import java.util.concurrent.LinkedBlockingDeque;
 import java.util.concurrent.atomic.AtomicLong;
-
 import org.apache.jute.BinaryInputArchive;
 import org.apache.zookeeper.ClientCnxn.Packet;
 import org.apache.zookeeper.client.ZKClientConfig;
-import org.apache.zookeeper.common.ZKConfig;
 import org.apache.zookeeper.common.Time;
+import org.apache.zookeeper.common.ZKConfig;
 import org.apache.zookeeper.proto.ConnectResponse;
 import org.apache.zookeeper.server.ByteBufferInputStream;
 import org.slf4j.Logger;
@@ -40,12 +39,13 @@ import org.slf4j.LoggerFactory;
 /**
  * A ClientCnxnSocket does the lower level communication with a socket
  * implementation.
- * 
+ *
  * This code has been moved out of ClientCnxn so that a Netty implementation can
  * be provided as an alternative to the NIO socket code.
- * 
+ *
  */
 abstract class ClientCnxnSocket {
+
     private static final Logger LOG = LoggerFactory.getLogger(ClientCnxnSocket.class);
 
     protected boolean initialized;
@@ -76,8 +76,7 @@ abstract class ClientCnxnSocket {
      */
     protected long sessionId;
 
-    void introduce(ClientCnxn.SendThread sendThread, long sessionId,
-                   LinkedBlockingDeque<Packet> outgoingQueue) {
+    void introduce(ClientCnxn.SendThread sendThread, long sessionId, LinkedBlockingDeque<Packet> outgoingQueue) {
         this.sendThread = sendThread;
         this.sessionId = sessionId;
         this.outgoingQueue = outgoingQueue;
@@ -131,8 +130,7 @@ abstract class ClientCnxnSocket {
                 buf.append(Integer.toHexString(b) + ",");
             }
             buf.append("]");
-            LOG.trace("readConnectResult " + incomingBuffer.remaining() + " "
-                    + buf.toString());
+            LOG.trace("readConnectResult " + incomingBuffer.remaining() + " " + buf.toString());
         }
         ByteBufferInputStream bbis = new ByteBufferInputStream(incomingBuffer);
         BinaryInputArchive bbia = BinaryInputArchive.getArchive(bbis);
@@ -150,8 +148,7 @@ abstract class ClientCnxnSocket {
         }
 
         this.sessionId = conRsp.getSessionId();
-        sendThread.onConnected(conRsp.getTimeOut(), this.sessionId,
-                conRsp.getPasswd(), isRO);
+        sendThread.onConnected(conRsp.getTimeOut(), this.sessionId, conRsp.getPasswd(), isRO);
     }
 
     abstract boolean isConnected();
@@ -208,9 +205,10 @@ abstract class ClientCnxnSocket {
      * @throws IOException
      * @throws InterruptedException
      */
-    abstract void doTransport(int waitTimeOut, Queue<Packet> pendingQueue,
-            ClientCnxn cnxn)
-            throws IOException, InterruptedException;
+    abstract void doTransport(
+        int waitTimeOut,
+        Queue<Packet> pendingQueue,
+        ClientCnxn cnxn) throws IOException, InterruptedException;
 
     /**
      * Close the socket.
@@ -232,15 +230,15 @@ abstract class ClientCnxnSocket {
 
     protected void initProperties() throws IOException {
         try {
-            packetLen = clientConfig.getInt(ZKConfig.JUTE_MAXBUFFER,
-                    ZKClientConfig.CLIENT_MAX_PACKET_LENGTH_DEFAULT);
-            LOG.info("{} value is {} Bytes", ZKConfig.JUTE_MAXBUFFER,
-                    packetLen);
+            packetLen = clientConfig.getInt(
+                ZKConfig.JUTE_MAXBUFFER,
+                ZKClientConfig.CLIENT_MAX_PACKET_LENGTH_DEFAULT);
+            LOG.info("{} value is {} Bytes", ZKConfig.JUTE_MAXBUFFER, packetLen);
         } catch (NumberFormatException e) {
             String msg = MessageFormat.format(
-                    "Configured value {0} for property {1} can not be parsed to int",
-                    clientConfig.getProperty(ZKConfig.JUTE_MAXBUFFER),
-                    ZKConfig.JUTE_MAXBUFFER);
+                "Configured value {0} for property {1} can not be parsed to int",
+                clientConfig.getProperty(ZKConfig.JUTE_MAXBUFFER),
+                ZKConfig.JUTE_MAXBUFFER);
             LOG.error(msg);
             throw new IOException(msg);
         }

+ 36 - 41
zookeeper-server/src/main/java/org/apache/zookeeper/ClientCnxnSocketNIO.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -30,7 +30,6 @@ import java.util.Iterator;
 import java.util.Queue;
 import java.util.Set;
 import java.util.concurrent.LinkedBlockingDeque;
-
 import org.apache.zookeeper.ClientCnxn.EndOfStreamException;
 import org.apache.zookeeper.ClientCnxn.Packet;
 import org.apache.zookeeper.ZooDefs.OpCode;
@@ -39,8 +38,8 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 public class ClientCnxnSocketNIO extends ClientCnxnSocket {
-    private static final Logger LOG = LoggerFactory
-            .getLogger(ClientCnxnSocketNIO.class);
+
+    private static final Logger LOG = LoggerFactory.getLogger(ClientCnxnSocketNIO.class);
 
     private final Selector selector = Selector.open();
 
@@ -59,13 +58,12 @@ public class ClientCnxnSocketNIO extends ClientCnxnSocket {
     boolean isConnected() {
         return sockKey != null;
     }
-    
+
     /**
      * @throws InterruptedException
      * @throws IOException
      */
-    void doIO(Queue<Packet> pendingQueue, ClientCnxn cnxn)
-      throws InterruptedException, IOException {
+    void doIO(Queue<Packet> pendingQueue, ClientCnxn cnxn) throws InterruptedException, IOException {
         SocketChannel sock = (SocketChannel) sockKey.channel();
         if (sock == null) {
             throw new IOException("Socket is null!");
@@ -73,10 +71,9 @@ public class ClientCnxnSocketNIO extends ClientCnxnSocket {
         if (sockKey.isReadable()) {
             int rc = sock.read(incomingBuffer);
             if (rc < 0) {
-                throw new EndOfStreamException(
-                        "Unable to read additional data from server sessionid 0x"
-                                + Long.toHexString(sessionId)
-                                + ", likely server has closed socket");
+                throw new EndOfStreamException("Unable to read additional data from server sessionid 0x"
+                                               + Long.toHexString(sessionId)
+                                               + ", likely server has closed socket");
             }
             if (!incomingBuffer.hasRemaining()) {
                 incomingBuffer.flip();
@@ -86,8 +83,7 @@ public class ClientCnxnSocketNIO extends ClientCnxnSocket {
                 } else if (!initialized) {
                     readConnectResult();
                     enableRead();
-                    if (findSendablePacket(outgoingQueue,
-                            sendThread.tunnelAuthInProgress()) != null) {
+                    if (findSendablePacket(outgoingQueue, sendThread.tunnelAuthInProgress()) != null) {
                         // Since SASL authentication has completed (if client is configured to do so),
                         // outgoing packets waiting in the outgoingQueue can now be sent.
                         enableWrite();
@@ -105,16 +101,15 @@ public class ClientCnxnSocketNIO extends ClientCnxnSocket {
             }
         }
         if (sockKey.isWritable()) {
-            Packet p = findSendablePacket(outgoingQueue,
-                    sendThread.tunnelAuthInProgress());
+            Packet p = findSendablePacket(outgoingQueue, sendThread.tunnelAuthInProgress());
 
             if (p != null) {
                 updateLastSend();
                 // If we already started writing p, p.bb will already exist
                 if (p.bb == null) {
-                    if ((p.requestHeader != null) &&
-                            (p.requestHeader.getType() != OpCode.ping) &&
-                            (p.requestHeader.getType() != OpCode.auth)) {
+                    if ((p.requestHeader != null)
+                        && (p.requestHeader.getType() != OpCode.ping)
+                        && (p.requestHeader.getType() != OpCode.auth)) {
                         p.requestHeader.setXid(cnxn.getXid());
                     }
                     p.createBB();
@@ -124,8 +119,8 @@ public class ClientCnxnSocketNIO extends ClientCnxnSocket {
                     sentCount.getAndIncrement();
                     outgoingQueue.removeFirstOccurrence(p);
                     if (p.requestHeader != null
-                            && p.requestHeader.getType() != OpCode.ping
-                            && p.requestHeader.getType() != OpCode.auth) {
+                        && p.requestHeader.getType() != OpCode.ping
+                        && p.requestHeader.getType() != OpCode.auth) {
                         synchronized (pendingQueue) {
                             pendingQueue.add(p);
                         }
@@ -157,8 +152,7 @@ public class ClientCnxnSocketNIO extends ClientCnxnSocket {
         }
     }
 
-    private Packet findSendablePacket(LinkedBlockingDeque<Packet> outgoingQueue,
-                                      boolean tunneledAuthInProgres) {
+    private Packet findSendablePacket(LinkedBlockingDeque<Packet> outgoingQueue, boolean tunneledAuthInProgres) {
         if (outgoingQueue.isEmpty()) {
             return null;
         }
@@ -221,7 +215,7 @@ public class ClientCnxnSocketNIO extends ClientCnxnSocket {
         }
         sockKey = null;
     }
- 
+
     @Override
     void close() {
         try {
@@ -232,7 +226,7 @@ public class ClientCnxnSocketNIO extends ClientCnxnSocket {
             LOG.warn("Ignoring exception during selector close", e);
         }
     }
-    
+
     /**
      * create a socket channel.
      * @return the created socket channel
@@ -249,25 +243,24 @@ public class ClientCnxnSocketNIO extends ClientCnxnSocket {
 
     /**
      * register with the selection and connect
-     * @param sock the {@link SocketChannel} 
+     * @param sock the {@link SocketChannel}
      * @param addr the address of remote host
      * @throws IOException
      */
-    void registerAndConnect(SocketChannel sock, InetSocketAddress addr) 
-    throws IOException {
+    void registerAndConnect(SocketChannel sock, InetSocketAddress addr) throws IOException {
         sockKey = sock.register(selector, SelectionKey.OP_CONNECT);
         boolean immediateConnect = sock.connect(addr);
         if (immediateConnect) {
             sendThread.primeConnection();
         }
     }
-    
+
     @Override
     void connect(InetSocketAddress addr) throws IOException {
         SocketChannel sock = createSock();
         try {
-           registerAndConnect(sock, addr);
-      } catch (IOException e) {
+            registerAndConnect(sock, addr);
+        } catch (IOException e) {
             LOG.error("Unable to open socket to " + addr);
             sock.close();
             throw e;
@@ -283,7 +276,7 @@ public class ClientCnxnSocketNIO extends ClientCnxnSocket {
 
     /**
      * Returns the address to which the socket is connected.
-     * 
+     *
      * @return ip address of the remote side of the connection or null if not
      *         connected
      */
@@ -294,7 +287,7 @@ public class ClientCnxnSocketNIO extends ClientCnxnSocket {
 
     /**
      * Returns the local address to which the socket is bound.
-     * 
+     *
      * @return ip address of the remote side of the connection or null if not
      *         connected
      */
@@ -302,7 +295,7 @@ public class ClientCnxnSocketNIO extends ClientCnxnSocket {
     SocketAddress getLocalSocketAddress() {
         return localSocketAddress;
     }
-    
+
     private void updateSocketAddresses() {
         Socket socket = ((SocketChannel) sockKey.channel()).socket();
         localSocketAddress = socket.getLocalSocketAddress();
@@ -322,10 +315,12 @@ public class ClientCnxnSocketNIO extends ClientCnxnSocket {
     private synchronized void wakeupCnxn() {
         selector.wakeup();
     }
-    
+
     @Override
-    void doTransport(int waitTimeOut, Queue<Packet> pendingQueue, ClientCnxn cnxn)
-            throws IOException, InterruptedException {
+    void doTransport(
+        int waitTimeOut,
+        Queue<Packet> pendingQueue,
+        ClientCnxn cnxn) throws IOException, InterruptedException {
         selector.select(waitTimeOut);
         Set<SelectionKey> selected;
         synchronized (this) {
@@ -348,8 +343,7 @@ public class ClientCnxnSocketNIO extends ClientCnxnSocket {
             }
         }
         if (sendThread.getZkState().isConnected()) {
-            if (findSendablePacket(outgoingQueue,
-                    sendThread.tunnelAuthInProgress()) != null) {
+            if (findSendablePacket(outgoingQueue, sendThread.tunnelAuthInProgress()) != null) {
                 enableWrite();
             }
         }
@@ -363,8 +357,8 @@ public class ClientCnxnSocketNIO extends ClientCnxnSocket {
         // sockKey may be concurrently accessed by multiple
         // threads. We use tmp here to avoid a race condition
         SelectionKey tmp = sockKey;
-        if (tmp!=null) {
-           ((SocketChannel) tmp.channel()).socket().close();
+        if (tmp != null) {
+            ((SocketChannel) tmp.channel()).socket().close();
         }
     }
 
@@ -387,7 +381,7 @@ public class ClientCnxnSocketNIO extends ClientCnxnSocket {
         }
     }
 
-    synchronized private void enableRead() {
+    private synchronized void enableRead() {
         int i = sockKey.interestOps();
         if ((i & SelectionKey.OP_READ) == 0) {
             sockKey.interestOps(i | SelectionKey.OP_READ);
@@ -413,4 +407,5 @@ public class ClientCnxnSocketNIO extends ClientCnxnSocket {
         ByteBuffer pbb = p.bb;
         sock.write(pbb);
     }
+
 }

+ 40 - 43
zookeeper-server/src/main/java/org/apache/zookeeper/ClientCnxnSocketNetty.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -18,22 +18,7 @@
 
 package org.apache.zookeeper;
 
-import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.net.SocketAddress;
-import java.util.Iterator;
-import java.util.Queue;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.Semaphore;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicReference;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReentrantLock;
-
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLEngine;
-
+import static org.apache.zookeeper.common.X509Exception.SSLContextException;
 import io.netty.bootstrap.Bootstrap;
 import io.netty.buffer.ByteBuf;
 import io.netty.buffer.ByteBufAllocator;
@@ -51,6 +36,20 @@ import io.netty.channel.socket.SocketChannel;
 import io.netty.handler.ssl.SslHandler;
 import io.netty.util.concurrent.Future;
 import io.netty.util.concurrent.GenericFutureListener;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.SocketAddress;
+import java.util.Iterator;
+import java.util.Queue;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Semaphore;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLEngine;
 import org.apache.zookeeper.ClientCnxn.EndOfStreamException;
 import org.apache.zookeeper.ClientCnxn.Packet;
 import org.apache.zookeeper.client.ZKClientConfig;
@@ -60,14 +59,13 @@ import org.apache.zookeeper.common.X509Util;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import static org.apache.zookeeper.common.X509Exception.SSLContextException;
-
 /**
  * ClientCnxnSocketNetty implements ClientCnxnSocket abstract methods.
  * It's responsible for connecting to server, reading/writing network traffic and
  * being a layer between network data and higher level packets.
  */
 public class ClientCnxnSocketNetty extends ClientCnxnSocket {
+
     private static final Logger LOG = LoggerFactory.getLogger(ClientCnxnSocketNetty.class);
 
     private final EventLoopGroup eventLoopGroup;
@@ -79,8 +77,7 @@ public class ClientCnxnSocketNetty extends ClientCnxnSocket {
     private final AtomicBoolean needSasl = new AtomicBoolean();
     private final Semaphore waitSasl = new Semaphore(0);
 
-    private static final AtomicReference<ByteBufAllocator> TEST_ALLOCATOR =
-            new AtomicReference<>(null);
+    private static final AtomicReference<ByteBufAllocator> TEST_ALLOCATOR = new AtomicReference<>(null);
 
     ClientCnxnSocketNetty(ZKClientConfig clientConfig) throws IOException {
         this.clientConfig = clientConfig;
@@ -131,12 +128,11 @@ public class ClientCnxnSocketNetty extends ClientCnxnSocket {
     void connect(InetSocketAddress addr) throws IOException {
         firstConnect = new CountDownLatch(1);
 
-        Bootstrap bootstrap = new Bootstrap()
-                .group(eventLoopGroup)
-                .channel(NettyUtils.nioOrEpollSocketChannel())
-                .option(ChannelOption.SO_LINGER, -1)
-                .option(ChannelOption.TCP_NODELAY, true)
-                .handler(new ZKClientPipelineFactory(addr.getHostString(), addr.getPort()));
+        Bootstrap bootstrap = new Bootstrap().group(eventLoopGroup)
+                                             .channel(NettyUtils.nioOrEpollSocketChannel())
+                                             .option(ChannelOption.SO_LINGER, -1)
+                                             .option(ChannelOption.TCP_NODELAY, true)
+                                             .handler(new ZKClientPipelineFactory(addr.getHostString(), addr.getPort()));
         bootstrap = configureBootstrapAllocator(bootstrap);
         bootstrap.validate();
 
@@ -261,10 +257,10 @@ public class ClientCnxnSocketNetty extends ClientCnxnSocket {
     }
 
     @Override
-    void doTransport(int waitTimeOut,
-                     Queue<Packet> pendingQueue,
-                     ClientCnxn cnxn)
-            throws IOException, InterruptedException {
+    void doTransport(
+        int waitTimeOut,
+        Queue<Packet> pendingQueue,
+        ClientCnxn cnxn) throws IOException, InterruptedException {
         try {
             if (!firstConnect.await(waitTimeOut, TimeUnit.MILLISECONDS)) {
                 return;
@@ -286,9 +282,7 @@ public class ClientCnxnSocketNetty extends ClientCnxnSocket {
             // channel disconnection happened
             if (disconnected.get()) {
                 addBack(head);
-                throw new EndOfStreamException("channel for sessionid 0x"
-                        + Long.toHexString(sessionId)
-                        + " is lost");
+                throw new EndOfStreamException("channel for sessionid 0x" + Long.toHexString(sessionId) + " is lost");
             }
             if (head != null) {
                 doWrite(pendingQueue, head, cnxn);
@@ -337,9 +331,7 @@ public class ClientCnxnSocketNetty extends ClientCnxnSocket {
         p.createBB();
         updateLastSend();
         final ByteBuf writeBuffer = Unpooled.wrappedBuffer(p.bb);
-        final ChannelFuture result = doFlush
-                ? channel.writeAndFlush(writeBuffer)
-                : channel.write(writeBuffer);
+        final ChannelFuture result = doFlush ? channel.writeAndFlush(writeBuffer) : channel.write(writeBuffer);
         result.addListener(onSendPktDoneListener);
         return result;
     }
@@ -357,9 +349,9 @@ public class ClientCnxnSocketNetty extends ClientCnxnSocket {
         boolean anyPacketsSent = false;
         while (true) {
             if (p != WakeupPacket.getInstance()) {
-                if ((p.requestHeader != null) &&
-                        (p.requestHeader.getType() != ZooDefs.OpCode.ping) &&
-                        (p.requestHeader.getType() != ZooDefs.OpCode.auth)) {
+                if ((p.requestHeader != null)
+                    && (p.requestHeader.getType() != ZooDefs.OpCode.ping)
+                    && (p.requestHeader.getType() != ZooDefs.OpCode.auth)) {
                     p.requestHeader.setXid(cnxn.getXid());
                     synchronized (pendingQueue) {
                         pendingQueue.add(p);
@@ -408,9 +400,9 @@ public class ClientCnxnSocketNetty extends ClientCnxnSocket {
         }
     }
 
-
     // *************** <END> CientCnxnSocketNetty </END> ******************
     private static class WakeupPacket {
+
         private static final Packet instance = new Packet(null, null, null, null, null);
 
         protected WakeupPacket() {
@@ -420,6 +412,7 @@ public class ClientCnxnSocketNetty extends ClientCnxnSocket {
         public static Packet getInstance() {
             return instance;
         }
+
     }
 
     /**
@@ -427,6 +420,7 @@ public class ClientCnxnSocketNetty extends ClientCnxnSocket {
      * connection implementation.
      */
     private class ZKClientPipelineFactory extends ChannelInitializer<SocketChannel> {
+
         private SSLContext sslContext = null;
         private SSLEngine sslEngine = null;
         private String host;
@@ -459,6 +453,7 @@ public class ClientCnxnSocketNetty extends ClientCnxnSocket {
             pipeline.addLast("ssl", new SslHandler(sslEngine));
             LOG.info("SSL handler added for channel: {}", pipeline.channel());
         }
+
     }
 
     /**
@@ -466,6 +461,7 @@ public class ClientCnxnSocketNetty extends ClientCnxnSocket {
      * place. It mainly handles read traffic and helps synchronize connection state.
      */
     private class ZKClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
+
         AtomicBoolean channelClosed = new AtomicBoolean(false);
 
         @Override
@@ -491,8 +487,7 @@ public class ClientCnxnSocketNetty extends ClientCnxnSocket {
             updateNow();
             while (buf.isReadable()) {
                 if (incomingBuffer.remaining() > buf.readableBytes()) {
-                    int newLimit = incomingBuffer.position()
-                            + buf.readableBytes();
+                    int newLimit = incomingBuffer.position() + buf.readableBytes();
                     incomingBuffer.limit(newLimit);
                 }
                 buf.readBytes(incomingBuffer);
@@ -527,6 +522,7 @@ public class ClientCnxnSocketNetty extends ClientCnxnSocket {
             LOG.warn("Exception caught", cause);
             cleanup();
         }
+
     }
 
     /**
@@ -548,4 +544,5 @@ public class ClientCnxnSocketNetty extends ClientCnxnSocket {
     static void clearTestAllocator() {
         TEST_ALLOCATOR.set(null);
     }
+
 }

+ 9 - 8
zookeeper-server/src/main/java/org/apache/zookeeper/ClientWatchManager.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -23,18 +23,19 @@ import java.util.Set;
 /**
  */
 public interface ClientWatchManager {
+
     /**
-     * Return a set of watchers that should be notified of the event. The 
-     * manager must not notify the watcher(s), however it will update it's 
-     * internal structure as if the watches had triggered. The intent being 
-     * that the callee is now responsible for notifying the watchers of the 
+     * Return a set of watchers that should be notified of the event. The
+     * manager must not notify the watcher(s), however it will update it's
+     * internal structure as if the watches had triggered. The intent being
+     * that the callee is now responsible for notifying the watchers of the
      * event, possibly at some later time.
-     * 
+     *
      * @param state event state
      * @param type event type
      * @param path event path
      * @return may be empty set but must not be null
      */
-    public Set<Watcher> materialize(Watcher.Event.KeeperState state,
-        Watcher.Event.EventType type, String path);
+    Set<Watcher> materialize(Watcher.Event.KeeperState state, Watcher.Event.EventType type, String path);
+
 }

+ 49 - 43
zookeeper-server/src/main/java/org/apache/zookeeper/CreateMode.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,6 +15,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper;
 
 import org.apache.yetus.audience.InterfaceAudience;
@@ -26,25 +27,25 @@ import org.slf4j.LoggerFactory;
  */
 @InterfaceAudience.Public
 public enum CreateMode {
-    
+
     /**
      * The znode will not be automatically deleted upon client's disconnect.
      */
-    PERSISTENT (0, false, false, false, false),
+    PERSISTENT(0, false, false, false, false),
     /**
-    * The znode will not be automatically deleted upon client's disconnect,
-    * and its name will be appended with a monotonically increasing number.
-    */
-    PERSISTENT_SEQUENTIAL (2, false, true, false, false),
+     * The znode will not be automatically deleted upon client's disconnect,
+     * and its name will be appended with a monotonically increasing number.
+     */
+    PERSISTENT_SEQUENTIAL(2, false, true, false, false),
     /**
      * The znode will be deleted upon the client's disconnect.
      */
-    EPHEMERAL (1, true, false, false, false),
+    EPHEMERAL(1, true, false, false, false),
     /**
      * The znode will be deleted upon the client's disconnect, and its name
      * will be appended with a monotonically increasing number.
      */
-    EPHEMERAL_SEQUENTIAL (3, true, true, false, false),
+    EPHEMERAL_SEQUENTIAL(3, true, true, false, false),
     /**
      * The znode will be a container node. Container
      * nodes are special purpose nodes useful for recipes such as leader, lock,
@@ -54,7 +55,7 @@ public enum CreateMode {
      * {@link org.apache.zookeeper.KeeperException.NoNodeException}
      * when creating children inside of this container node.
      */
-    CONTAINER (4, false, false, true, false),
+    CONTAINER(4, false, false, true, false),
     /**
      * The znode will not be automatically deleted upon client's disconnect.
      * However if the znode has not been modified within the given TTL, it
@@ -77,8 +78,7 @@ public enum CreateMode {
     private int flag;
     private boolean isTTL;
 
-    CreateMode(int flag, boolean ephemeral, boolean sequential,
-               boolean isContainer, boolean isTTL) {
+    CreateMode(int flag, boolean ephemeral, boolean sequential, boolean isContainer, boolean isTTL) {
         this.flag = flag;
         this.ephemeral = ephemeral;
         this.sequential = sequential;
@@ -86,11 +86,11 @@ public enum CreateMode {
         this.isTTL = isTTL;
     }
 
-    public boolean isEphemeral() { 
+    public boolean isEphemeral() {
         return ephemeral;
     }
 
-    public boolean isSequential() { 
+    public boolean isSequential() {
         return sequential;
     }
 
@@ -109,25 +109,31 @@ public enum CreateMode {
     /**
      * Map an integer value to a CreateMode value
      */
-    static public CreateMode fromFlag(int flag) throws KeeperException {
-        switch(flag) {
-        case 0: return CreateMode.PERSISTENT;
+    public static CreateMode fromFlag(int flag) throws KeeperException {
+        switch (flag) {
+        case 0:
+            return CreateMode.PERSISTENT;
 
-        case 1: return CreateMode.EPHEMERAL;
+        case 1:
+            return CreateMode.EPHEMERAL;
 
-        case 2: return CreateMode.PERSISTENT_SEQUENTIAL;
+        case 2:
+            return CreateMode.PERSISTENT_SEQUENTIAL;
 
-        case 3: return CreateMode.EPHEMERAL_SEQUENTIAL ;
+        case 3:
+            return CreateMode.EPHEMERAL_SEQUENTIAL;
 
-        case 4: return CreateMode.CONTAINER;
+        case 4:
+            return CreateMode.CONTAINER;
 
-        case 5: return CreateMode.PERSISTENT_WITH_TTL;
+        case 5:
+            return CreateMode.PERSISTENT_WITH_TTL;
 
-        case 6: return CreateMode.PERSISTENT_SEQUENTIAL_WITH_TTL;
+        case 6:
+            return CreateMode.PERSISTENT_SEQUENTIAL_WITH_TTL;
 
         default:
-            String errMsg = "Received an invalid flag value: " + flag
-                    + " to convert to a CreateMode";
+            String errMsg = "Received an invalid flag value: " + flag + " to convert to a CreateMode";
             LOG.error(errMsg);
             throw new KeeperException.BadArgumentsException(errMsg);
         }
@@ -136,31 +142,31 @@ public enum CreateMode {
     /**
      * Map an integer value to a CreateMode value
      */
-    static public CreateMode fromFlag(int flag, CreateMode defaultMode) {
-        switch(flag) {
-            case 0:
-                return CreateMode.PERSISTENT;
+    public static CreateMode fromFlag(int flag, CreateMode defaultMode) {
+        switch (flag) {
+        case 0:
+            return CreateMode.PERSISTENT;
 
-            case 1:
-                return CreateMode.EPHEMERAL;
+        case 1:
+            return CreateMode.EPHEMERAL;
 
-            case 2:
-                return CreateMode.PERSISTENT_SEQUENTIAL;
+        case 2:
+            return CreateMode.PERSISTENT_SEQUENTIAL;
 
-            case 3:
-                return CreateMode.EPHEMERAL_SEQUENTIAL;
+        case 3:
+            return CreateMode.EPHEMERAL_SEQUENTIAL;
 
-            case 4:
-                return CreateMode.CONTAINER;
+        case 4:
+            return CreateMode.CONTAINER;
 
-            case 5:
-                return CreateMode.PERSISTENT_WITH_TTL;
+        case 5:
+            return CreateMode.PERSISTENT_WITH_TTL;
 
-            case 6:
-                return CreateMode.PERSISTENT_SEQUENTIAL_WITH_TTL;
+        case 6:
+            return CreateMode.PERSISTENT_SEQUENTIAL_WITH_TTL;
 
-            default:
-                return defaultMode;
+        default:
+            return defaultMode;
         }
     }
 }

+ 3 - 2
zookeeper-server/src/main/java/org/apache/zookeeper/DigestWatcher.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -26,7 +26,8 @@ public interface DigestWatcher {
     /**
      * Called when the digest mismatch is found on a given zxid.
      *
-     * @param mismatchZxid the zxid when the digest mismatch happened. 
+     * @param mismatchZxid the zxid when the digest mismatch happened.
      */
     void process(long mismatchZxid);
+
 }

+ 31 - 41
zookeeper-server/src/main/java/org/apache/zookeeper/Environment.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -22,7 +22,6 @@ import java.net.InetAddress;
 import java.net.UnknownHostException;
 import java.util.ArrayList;
 import java.util.List;
-
 import org.slf4j.Logger;
 
 /**
@@ -30,26 +29,33 @@ import org.slf4j.Logger;
  *
  */
 public class Environment {
+
     public static final String JAAS_CONF_KEY = "java.security.auth.login.config";
 
     public static class Entry {
+
         private String k;
         private String v;
         public Entry(String k, String v) {
             this.k = k;
             this.v = v;
         }
-        public String getKey() { return k; }
-        public String getValue() { return v; }
-        
+        public String getKey() {
+            return k;
+        }
+        public String getValue() {
+            return v;
+        }
+
         @Override
         public String toString() {
             return k + "=" + v;
         }
+
     }
 
     private static void put(List<Entry> l, String k, String v) {
-        l.add(new Entry(k,v));
+        l.add(new Entry(k, v));
     }
 
     public static List<Entry> list() {
@@ -57,56 +63,40 @@ public class Environment {
         put(l, "zookeeper.version", Version.getFullVersion());
 
         try {
-            put(l, "host.name",
-                InetAddress.getLocalHost().getCanonicalHostName());
+            put(l, "host.name", InetAddress.getLocalHost().getCanonicalHostName());
         } catch (UnknownHostException e) {
             put(l, "host.name", "<NA>");
         }
 
-        put(l, "java.version",
-                System.getProperty("java.version", "<NA>"));
-        put(l, "java.vendor",
-                System.getProperty("java.vendor", "<NA>"));
-        put(l, "java.home",
-                System.getProperty("java.home", "<NA>"));
-        put(l, "java.class.path",
-                System.getProperty("java.class.path", "<NA>"));
-        put(l, "java.library.path",
-                System.getProperty("java.library.path", "<NA>"));
-        put(l, "java.io.tmpdir",
-                System.getProperty("java.io.tmpdir", "<NA>"));
-        put(l, "java.compiler",
-                System.getProperty("java.compiler", "<NA>"));
-        put(l, "os.name",
-                System.getProperty("os.name", "<NA>"));
-        put(l, "os.arch",
-                System.getProperty("os.arch", "<NA>"));
-        put(l, "os.version",
-                System.getProperty("os.version", "<NA>"));
-        put(l, "user.name",
-                System.getProperty("user.name", "<NA>"));
-        put(l, "user.home",
-                System.getProperty("user.home", "<NA>"));
-        put(l, "user.dir",
-                System.getProperty("user.dir", "<NA>"));
+        put(l, "java.version", System.getProperty("java.version", "<NA>"));
+        put(l, "java.vendor", System.getProperty("java.vendor", "<NA>"));
+        put(l, "java.home", System.getProperty("java.home", "<NA>"));
+        put(l, "java.class.path", System.getProperty("java.class.path", "<NA>"));
+        put(l, "java.library.path", System.getProperty("java.library.path", "<NA>"));
+        put(l, "java.io.tmpdir", System.getProperty("java.io.tmpdir", "<NA>"));
+        put(l, "java.compiler", System.getProperty("java.compiler", "<NA>"));
+        put(l, "os.name", System.getProperty("os.name", "<NA>"));
+        put(l, "os.arch", System.getProperty("os.arch", "<NA>"));
+        put(l, "os.version", System.getProperty("os.version", "<NA>"));
+        put(l, "user.name", System.getProperty("user.name", "<NA>"));
+        put(l, "user.home", System.getProperty("user.home", "<NA>"));
+        put(l, "user.dir", System.getProperty("user.dir", "<NA>"));
 
         // Get memory information.
         Runtime runtime = Runtime.getRuntime();
         int mb = 1024 * 1024;
-        put(l, "os.memory.free",
-               Long.toString(runtime.freeMemory() / mb) + "MB");
-        put(l, "os.memory.max",
-               Long.toString(runtime.maxMemory() / mb) + "MB");
-        put(l, "os.memory.total",
-               Long.toString(runtime.totalMemory() / mb) + "MB");
+        put(l, "os.memory.free", runtime.freeMemory() / mb + "MB");
+        put(l, "os.memory.max", runtime.maxMemory() / mb + "MB");
+        put(l, "os.memory.total", runtime.totalMemory() / mb + "MB");
 
         return l;
     }
-    
+
     public static void logEnv(String msg, Logger log) {
         List<Entry> env = Environment.list();
         for (Entry e : env) {
             log.info(msg + e.toString());
         }
     }
+
 }

+ 16 - 20
zookeeper-server/src/main/java/org/apache/zookeeper/JLineZNodeCompleter.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -20,67 +20,63 @@ package org.apache.zookeeper;
 
 import java.util.Collections;
 import java.util.List;
-
 import jline.console.completer.Completer;
 
 class JLineZNodeCompleter implements Completer {
+
     private ZooKeeper zk;
 
     public JLineZNodeCompleter(ZooKeeper zk) {
         this.zk = zk;
     }
 
-    @SuppressWarnings({ "unchecked", "rawtypes" })
+    @SuppressWarnings({"unchecked", "rawtypes"})
     public int complete(String buffer, int cursor, List candidates) {
         // Guarantee that the final token is the one we're expanding
-        buffer = buffer.substring(0,cursor);
+        buffer = buffer.substring(0, cursor);
         String token = "";
         if (!buffer.endsWith(" ")) {
             String[] tokens = buffer.split(" ");
             if (tokens.length != 0) {
-                token = tokens[tokens.length-1] ;
+                token = tokens[tokens.length - 1];
             }
         }
 
-        if (token.startsWith("/")){
-            return completeZNode( buffer, token, candidates);
+        if (token.startsWith("/")) {
+            return completeZNode(buffer, token, candidates);
         }
         return completeCommand(buffer, token, candidates);
     }
 
-    private int completeCommand(String buffer, String token,
-            List<String> candidates)
-    {
+    private int completeCommand(String buffer, String token, List<String> candidates) {
         for (String cmd : ZooKeeperMain.getCommands()) {
-            if (cmd.startsWith( token )) {
+            if (cmd.startsWith(token)) {
                 candidates.add(cmd);
             }
         }
-        return buffer.lastIndexOf(" ")+1;
+        return buffer.lastIndexOf(" ") + 1;
     }
 
-    private int completeZNode( String buffer, String token,
-            List<String> candidates)
-    {
+    private int completeZNode(String buffer, String token, List<String> candidates) {
         String path = token;
         int idx = path.lastIndexOf("/") + 1;
         String prefix = path.substring(idx);
         try {
             // Only the root path can end in a /, so strip it off every other prefix
-            String dir = idx == 1 ? "/" : path.substring(0,idx-1);
+            String dir = idx == 1 ? "/" : path.substring(0, idx - 1);
             List<String> children = zk.getChildren(dir, false);
             for (String child : children) {
                 if (child.startsWith(prefix)) {
-                    candidates.add( child );
+                    candidates.add(child);
                 }
             }
-        } catch( InterruptedException e) {
+        } catch (InterruptedException e) {
             return 0;
-        }
-        catch( KeeperException e) {
+        } catch (KeeperException e) {
             return 0;
         }
         Collections.sort(candidates);
         return candidates.size() == 0 ? buffer.length() : buffer.lastIndexOf("/") + 1;
     }
+
 }

+ 253 - 187
zookeeper-server/src/main/java/org/apache/zookeeper/KeeperException.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -18,17 +18,17 @@
 
 package org.apache.zookeeper;
 
-import org.apache.yetus.audience.InterfaceAudience;
-
 import java.util.ArrayList;
 import java.util.EnumSet;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import org.apache.yetus.audience.InterfaceAudience;
 
 @SuppressWarnings("serial")
 @InterfaceAudience.Public
 public abstract class KeeperException extends Exception {
+
     /**
      * All multi-requests that result in an exception retain the results
      * here so that it is possible to examine the problems in the catch
@@ -92,65 +92,65 @@ public abstract class KeeperException extends Exception {
      */
     public static KeeperException create(Code code) {
         switch (code) {
-            case SYSTEMERROR:
-                return new SystemErrorException();
-            case RUNTIMEINCONSISTENCY:
-                return new RuntimeInconsistencyException();
-            case DATAINCONSISTENCY:
-                return new DataInconsistencyException();
-            case CONNECTIONLOSS:
-                return new ConnectionLossException();
-            case MARSHALLINGERROR:
-                return new MarshallingErrorException();
-            case UNIMPLEMENTED:
-                return new UnimplementedException();
-            case OPERATIONTIMEOUT:
-                return new OperationTimeoutException();
-            case NEWCONFIGNOQUORUM:
-               return new NewConfigNoQuorum();
-            case RECONFIGINPROGRESS:
-               return new ReconfigInProgress();
-            case BADARGUMENTS:
-                return new BadArgumentsException();
-            case APIERROR:
-                return new APIErrorException();
-            case NONODE:
-                return new NoNodeException();
-            case NOAUTH:
-                return new NoAuthException();
-            case BADVERSION:
-                return new BadVersionException();
-            case NOCHILDRENFOREPHEMERALS:
-                return new NoChildrenForEphemeralsException();
-            case NODEEXISTS:
-                return new NodeExistsException();
-            case INVALIDACL:
-                return new InvalidACLException();
-            case AUTHFAILED:
-                return new AuthFailedException();
-            case NOTEMPTY:
-                return new NotEmptyException();
-            case SESSIONEXPIRED:
-                return new SessionExpiredException();
-            case INVALIDCALLBACK:
-                return new InvalidCallbackException();
-            case SESSIONMOVED:
-                return new SessionMovedException();
-            case NOTREADONLY:
-                return new NotReadOnlyException();
-            case EPHEMERALONLOCALSESSION:
-                return new EphemeralOnLocalSessionException();
-            case NOWATCHER:
-                return new NoWatcherException();
-            case RECONFIGDISABLED:
-                return new ReconfigDisabledException();
-            case SESSIONCLOSEDREQUIRESASLAUTH:
-                return new SessionClosedRequireAuthException();
-            case REQUESTTIMEOUT:
-                return new RequestTimeoutException();
-            case OK:
-            default:
-                throw new IllegalArgumentException("Invalid exception code");
+        case SYSTEMERROR:
+            return new SystemErrorException();
+        case RUNTIMEINCONSISTENCY:
+            return new RuntimeInconsistencyException();
+        case DATAINCONSISTENCY:
+            return new DataInconsistencyException();
+        case CONNECTIONLOSS:
+            return new ConnectionLossException();
+        case MARSHALLINGERROR:
+            return new MarshallingErrorException();
+        case UNIMPLEMENTED:
+            return new UnimplementedException();
+        case OPERATIONTIMEOUT:
+            return new OperationTimeoutException();
+        case NEWCONFIGNOQUORUM:
+            return new NewConfigNoQuorum();
+        case RECONFIGINPROGRESS:
+            return new ReconfigInProgress();
+        case BADARGUMENTS:
+            return new BadArgumentsException();
+        case APIERROR:
+            return new APIErrorException();
+        case NONODE:
+            return new NoNodeException();
+        case NOAUTH:
+            return new NoAuthException();
+        case BADVERSION:
+            return new BadVersionException();
+        case NOCHILDRENFOREPHEMERALS:
+            return new NoChildrenForEphemeralsException();
+        case NODEEXISTS:
+            return new NodeExistsException();
+        case INVALIDACL:
+            return new InvalidACLException();
+        case AUTHFAILED:
+            return new AuthFailedException();
+        case NOTEMPTY:
+            return new NotEmptyException();
+        case SESSIONEXPIRED:
+            return new SessionExpiredException();
+        case INVALIDCALLBACK:
+            return new InvalidCallbackException();
+        case SESSIONMOVED:
+            return new SessionMovedException();
+        case NOTREADONLY:
+            return new NotReadOnlyException();
+        case EPHEMERALONLOCALSESSION:
+            return new EphemeralOnLocalSessionException();
+        case NOWATCHER:
+            return new NoWatcherException();
+        case RECONFIGDISABLED:
+            return new ReconfigDisabledException();
+        case SESSIONCLOSEDREQUIRESASLAUTH:
+            return new SessionClosedRequireAuthException();
+        case REQUESTTIMEOUT:
+            return new RequestTimeoutException();
+        case OK:
+        default:
+            throw new IllegalArgumentException("Invalid exception code");
         }
     }
 
@@ -181,142 +181,143 @@ public abstract class KeeperException extends Exception {
     @Deprecated
     @InterfaceAudience.Public
     public interface CodeDeprecated {
+
         /**
          * @deprecated deprecated in 3.1.0, use {@link Code#OK} instead
          */
         @Deprecated
-        public static final int Ok = 0;
+        int Ok = 0;
 
         /**
          * @deprecated deprecated in 3.1.0, use {@link Code#SYSTEMERROR} instead
          */
         @Deprecated
-        public static final int SystemError = -1;
+        int SystemError = -1;
         /**
          * @deprecated deprecated in 3.1.0, use
          * {@link Code#RUNTIMEINCONSISTENCY} instead
          */
         @Deprecated
-        public static final int RuntimeInconsistency = -2;
+        int RuntimeInconsistency = -2;
         /**
          * @deprecated deprecated in 3.1.0, use {@link Code#DATAINCONSISTENCY}
          * instead
          */
         @Deprecated
-        public static final int DataInconsistency = -3;
+        int DataInconsistency = -3;
         /**
          * @deprecated deprecated in 3.1.0, use {@link Code#CONNECTIONLOSS}
          * instead
          */
         @Deprecated
-        public static final int ConnectionLoss = -4;
+        int ConnectionLoss = -4;
         /**
          * @deprecated deprecated in 3.1.0, use {@link Code#MARSHALLINGERROR}
          * instead
          */
         @Deprecated
-        public static final int MarshallingError = -5;
+        int MarshallingError = -5;
         /**
          * @deprecated deprecated in 3.1.0, use {@link Code#UNIMPLEMENTED}
          * instead
          */
         @Deprecated
-        public static final int Unimplemented = -6;
+        int Unimplemented = -6;
         /**
          * @deprecated deprecated in 3.1.0, use {@link Code#OPERATIONTIMEOUT}
          * instead
          */
         @Deprecated
-        public static final int OperationTimeout = -7;
+        int OperationTimeout = -7;
         /**
          * @deprecated deprecated in 3.1.0, use {@link Code#BADARGUMENTS}
          * instead
          */
         @Deprecated
-        public static final int BadArguments = -8;
+        int BadArguments = -8;
 
         @Deprecated
-        public static final int UnknownSession= -12;
+        int UnknownSession = -12;
 
         /**
          * @deprecated deprecated in 3.1.0, use {@link Code#NEWCONFIGNOQUORUM}
          * instead
          */
         @Deprecated
-        public static final int NewConfigNoQuorum = -13;
+        int NewConfigNoQuorum = -13;
 
         /**
          * @deprecated deprecated in 3.1.0, use {@link Code#RECONFIGINPROGRESS}
          * instead
          */
         @Deprecated
-        public static final int ReconfigInProgress= -14;
+        int ReconfigInProgress = -14;
 
         /**
          * @deprecated deprecated in 3.1.0, use {@link Code#APIERROR} instead
          */
         @Deprecated
-        public static final int APIError = -100;
+        int APIError = -100;
 
         /**
          * @deprecated deprecated in 3.1.0, use {@link Code#NONODE} instead
          */
         @Deprecated
-        public static final int NoNode = -101;
+        int NoNode = -101;
         /**
          * @deprecated deprecated in 3.1.0, use {@link Code#NOAUTH} instead
          */
         @Deprecated
-        public static final int NoAuth = -102;
+        int NoAuth = -102;
         /**
          * @deprecated deprecated in 3.1.0, use {@link Code#BADVERSION} instead
          */
         @Deprecated
-        public static final int BadVersion = -103;
+        int BadVersion = -103;
         /**
          * @deprecated deprecated in 3.1.0, use
          * {@link Code#NOCHILDRENFOREPHEMERALS}
          * instead
          */
         @Deprecated
-        public static final int NoChildrenForEphemerals = -108;
+        int NoChildrenForEphemerals = -108;
         /**
          * @deprecated deprecated in 3.1.0, use {@link Code#NODEEXISTS} instead
          */
         @Deprecated
-        public static final int NodeExists = -110;
+        int NodeExists = -110;
         /**
          * @deprecated deprecated in 3.1.0, use {@link Code#NOTEMPTY} instead
          */
         @Deprecated
-        public static final int NotEmpty = -111;
+        int NotEmpty = -111;
         /**
          * @deprecated deprecated in 3.1.0, use {@link Code#SESSIONEXPIRED} instead
          */
         @Deprecated
-        public static final int SessionExpired = -112;
+        int SessionExpired = -112;
         /**
          * @deprecated deprecated in 3.1.0, use {@link Code#INVALIDCALLBACK}
          * instead
          */
         @Deprecated
-        public static final int InvalidCallback = -113;
+        int InvalidCallback = -113;
         /**
          * @deprecated deprecated in 3.1.0, use {@link Code#INVALIDACL} instead
          */
         @Deprecated
-        public static final int InvalidACL = -114;
+        int InvalidACL = -114;
         /**
          * @deprecated deprecated in 3.1.0, use {@link Code#AUTHFAILED} instead
          */
         @Deprecated
-        public static final int AuthFailed = -115;
-        
+        int AuthFailed = -115;
+
         // This value will be used directly in {@link CODE#SESSIONMOVED}
-        // public static final int SessionMoved = -118;       
-        
+        // public static final int SessionMoved = -118;
+
         @Deprecated
-        public static final int EphemeralOnLocalSession = -120;
+        int EphemeralOnLocalSession = -120;
 
     }
 
@@ -326,78 +327,78 @@ public abstract class KeeperException extends Exception {
      * enum values are in all CAPS.
      */
     @InterfaceAudience.Public
-    public static enum Code implements CodeDeprecated {
+    public enum Code implements CodeDeprecated {
         /** Everything is OK */
-        OK (Ok),
+        OK(Ok),
 
         /** System and server-side errors.
          * This is never thrown by the server, it shouldn't be used other than
          * to indicate a range. Specifically error codes greater than this
          * value, but lesser than {@link #APIERROR}, are system errors.
          */
-        SYSTEMERROR (SystemError),
+        SYSTEMERROR(SystemError),
 
         /** A runtime inconsistency was found */
-        RUNTIMEINCONSISTENCY (RuntimeInconsistency),
+        RUNTIMEINCONSISTENCY(RuntimeInconsistency),
         /** A data inconsistency was found */
-        DATAINCONSISTENCY (DataInconsistency),
+        DATAINCONSISTENCY(DataInconsistency),
         /** Connection to the server has been lost */
-        CONNECTIONLOSS (ConnectionLoss),
+        CONNECTIONLOSS(ConnectionLoss),
         /** Error while marshalling or unmarshalling data */
-        MARSHALLINGERROR (MarshallingError),
+        MARSHALLINGERROR(MarshallingError),
         /** Operation is unimplemented */
-        UNIMPLEMENTED (Unimplemented),
+        UNIMPLEMENTED(Unimplemented),
         /** Operation timeout */
-        OPERATIONTIMEOUT (OperationTimeout),
+        OPERATIONTIMEOUT(OperationTimeout),
         /** Invalid arguments */
-        BADARGUMENTS (BadArguments),
-        /** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try 
+        BADARGUMENTS(BadArguments),
+        /** No quorum of new config is connected and up-to-date with the leader of last commmitted config - try
          *  invoking reconfiguration after new servers are connected and synced */
-        NEWCONFIGNOQUORUM (NewConfigNoQuorum),
+        NEWCONFIGNOQUORUM(NewConfigNoQuorum),
         /** Another reconfiguration is in progress -- concurrent reconfigs not supported (yet) */
-        RECONFIGINPROGRESS (ReconfigInProgress),
+        RECONFIGINPROGRESS(ReconfigInProgress),
         /** Unknown session (internal server use only) */
-        UNKNOWNSESSION (UnknownSession),
-        
+        UNKNOWNSESSION(UnknownSession),
+
         /** API errors.
          * This is never thrown by the server, it shouldn't be used other than
          * to indicate a range. Specifically error codes greater than this
          * value are API errors (while values less than this indicate a
          * {@link #SYSTEMERROR}).
          */
-        APIERROR (APIError),
+        APIERROR(APIError),
 
         /** Node does not exist */
-        NONODE (NoNode),
+        NONODE(NoNode),
         /** Not authenticated */
-        NOAUTH (NoAuth),
+        NOAUTH(NoAuth),
         /** Version conflict
-            In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
-        BADVERSION (BadVersion),
+         In case of reconfiguration: reconfig requested from config version X but last seen config has a different version Y */
+        BADVERSION(BadVersion),
         /** Ephemeral nodes may not have children */
-        NOCHILDRENFOREPHEMERALS (NoChildrenForEphemerals),
+        NOCHILDRENFOREPHEMERALS(NoChildrenForEphemerals),
         /** The node already exists */
-        NODEEXISTS (NodeExists),
+        NODEEXISTS(NodeExists),
         /** The node has children */
-        NOTEMPTY (NotEmpty),
+        NOTEMPTY(NotEmpty),
         /** The session has been expired by the server */
-        SESSIONEXPIRED (SessionExpired),
+        SESSIONEXPIRED(SessionExpired),
         /** Invalid callback specified */
-        INVALIDCALLBACK (InvalidCallback),
+        INVALIDCALLBACK(InvalidCallback),
         /** Invalid ACL specified */
-        INVALIDACL (InvalidACL),
+        INVALIDACL(InvalidACL),
         /** Client authentication failed */
-        AUTHFAILED (AuthFailed),
+        AUTHFAILED(AuthFailed),
         /** Session moved to another server, so operation is ignored */
-        SESSIONMOVED (-118),
+        SESSIONMOVED(-118),
         /** State-changing request is passed to read-only server */
-        NOTREADONLY (-119),
+        NOTREADONLY(-119),
         /** Attempt to create ephemeral node on a local session */
-        EPHEMERALONLOCALSESSION (EphemeralOnLocalSession),
+        EPHEMERALONLOCALSESSION(EphemeralOnLocalSession),
         /** Attempts to remove a non-existing watcher */
-        NOWATCHER (-121),
+        NOWATCHER(-121),
         /** Request not completed within max allowed time.*/
-        REQUESTTIMEOUT (-122),
+        REQUESTTIMEOUT(-122),
         /** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled. */
         RECONFIGDISABLED(-123),
         /** The session has been closed by server because server requires client to do SASL authentication,
@@ -405,12 +406,12 @@ public abstract class KeeperException extends Exception {
          *  (i.e. wrong credential used.). */
         SESSIONCLOSEDREQUIRESASLAUTH(-124);
 
-        private static final Map<Integer,Code> lookup
-            = new HashMap<Integer,Code>();
+        private static final Map<Integer, Code> lookup = new HashMap<Integer, Code>();
 
         static {
-            for(Code c : EnumSet.allOf(Code.class))
+            for (Code c : EnumSet.allOf(Code.class)) {
                 lookup.put(c.code, c);
+            }
         }
 
         private final int code;
@@ -422,7 +423,9 @@ public abstract class KeeperException extends Exception {
          * Get the int value for a particular Code.
          * @return error code as integer
          */
-        public int intValue() { return code; }
+        public int intValue() {
+            return code;
+        }
 
         /**
          * Get the Code value for a particular integer error code
@@ -436,64 +439,64 @@ public abstract class KeeperException extends Exception {
 
     static String getCodeMessage(Code code) {
         switch (code) {
-            case OK:
-                return "ok";
-            case SYSTEMERROR:
-                return "SystemError";
-            case RUNTIMEINCONSISTENCY:
-                return "RuntimeInconsistency";
-            case DATAINCONSISTENCY:
-                return "DataInconsistency";
-            case CONNECTIONLOSS:
-                return "ConnectionLoss";
-            case MARSHALLINGERROR:
-                return "MarshallingError";
-            case NEWCONFIGNOQUORUM:
-               return "NewConfigNoQuorum";
-            case RECONFIGINPROGRESS:
-               return "ReconfigInProgress";
-            case UNIMPLEMENTED:
-                return "Unimplemented";
-            case OPERATIONTIMEOUT:
-                return "OperationTimeout";
-            case BADARGUMENTS:
-                return "BadArguments";
-            case APIERROR:
-                return "APIError";
-            case NONODE:
-                return "NoNode";
-            case NOAUTH:
-                return "NoAuth";
-            case BADVERSION:
-                return "BadVersion";
-            case NOCHILDRENFOREPHEMERALS:
-                return "NoChildrenForEphemerals";
-            case NODEEXISTS:
-                return "NodeExists";
-            case INVALIDACL:
-                return "InvalidACL";
-            case AUTHFAILED:
-                return "AuthFailed";
-            case NOTEMPTY:
-                return "Directory not empty";
-            case SESSIONEXPIRED:
-                return "Session expired";
-            case INVALIDCALLBACK:
-                return "Invalid callback";
-            case SESSIONMOVED:
-                return "Session moved";
-            case NOTREADONLY:
-                return "Not a read-only call";
-            case EPHEMERALONLOCALSESSION:
-                return "Ephemeral node on local session";
-            case NOWATCHER:
-                return "No such watcher";
-            case RECONFIGDISABLED:
-                return "Reconfig is disabled";
-            case SESSIONCLOSEDREQUIRESASLAUTH:
-                return "Session closed because client failed to authenticate";
-            default:
-                return "Unknown error " + code;
+        case OK:
+            return "ok";
+        case SYSTEMERROR:
+            return "SystemError";
+        case RUNTIMEINCONSISTENCY:
+            return "RuntimeInconsistency";
+        case DATAINCONSISTENCY:
+            return "DataInconsistency";
+        case CONNECTIONLOSS:
+            return "ConnectionLoss";
+        case MARSHALLINGERROR:
+            return "MarshallingError";
+        case NEWCONFIGNOQUORUM:
+            return "NewConfigNoQuorum";
+        case RECONFIGINPROGRESS:
+            return "ReconfigInProgress";
+        case UNIMPLEMENTED:
+            return "Unimplemented";
+        case OPERATIONTIMEOUT:
+            return "OperationTimeout";
+        case BADARGUMENTS:
+            return "BadArguments";
+        case APIERROR:
+            return "APIError";
+        case NONODE:
+            return "NoNode";
+        case NOAUTH:
+            return "NoAuth";
+        case BADVERSION:
+            return "BadVersion";
+        case NOCHILDRENFOREPHEMERALS:
+            return "NoChildrenForEphemerals";
+        case NODEEXISTS:
+            return "NodeExists";
+        case INVALIDACL:
+            return "InvalidACL";
+        case AUTHFAILED:
+            return "AuthFailed";
+        case NOTEMPTY:
+            return "Directory not empty";
+        case SESSIONEXPIRED:
+            return "Session expired";
+        case INVALIDCALLBACK:
+            return "Invalid callback";
+        case SESSIONMOVED:
+            return "Session moved";
+        case NOTREADONLY:
+            return "Not a read-only call";
+        case EPHEMERALONLOCALSESSION:
+            return "Ephemeral node on local session";
+        case NOWATCHER:
+            return "No such watcher";
+        case RECONFIGDISABLED:
+            return "Reconfig is disabled";
+        case SESSIONCLOSEDREQUIRESASLAUTH:
+            return "Session closed because client failed to authenticate";
+        default:
+            return "Unknown error " + code;
         }
     }
 
@@ -565,9 +568,11 @@ public abstract class KeeperException extends Exception {
      */
     @InterfaceAudience.Public
     public static class APIErrorException extends KeeperException {
+
         public APIErrorException() {
             super(Code.APIERROR);
         }
+
     }
 
     /**
@@ -575,9 +580,11 @@ public abstract class KeeperException extends Exception {
      */
     @InterfaceAudience.Public
     public static class AuthFailedException extends KeeperException {
+
         public AuthFailedException() {
             super(Code.AUTHFAILED);
         }
+
     }
 
     /**
@@ -585,12 +592,14 @@ public abstract class KeeperException extends Exception {
      */
     @InterfaceAudience.Public
     public static class BadArgumentsException extends KeeperException {
+
         public BadArgumentsException() {
             super(Code.BADARGUMENTS);
         }
         public BadArgumentsException(String path) {
             super(Code.BADARGUMENTS, path);
         }
+
     }
 
     /**
@@ -598,12 +607,14 @@ public abstract class KeeperException extends Exception {
      */
     @InterfaceAudience.Public
     public static class BadVersionException extends KeeperException {
+
         public BadVersionException() {
             super(Code.BADVERSION);
         }
         public BadVersionException(String path) {
             super(Code.BADVERSION, path);
         }
+
     }
 
     /**
@@ -611,9 +622,11 @@ public abstract class KeeperException extends Exception {
      */
     @InterfaceAudience.Public
     public static class ConnectionLossException extends KeeperException {
+
         public ConnectionLossException() {
             super(Code.CONNECTIONLOSS);
         }
+
     }
 
     /**
@@ -621,9 +634,11 @@ public abstract class KeeperException extends Exception {
      */
     @InterfaceAudience.Public
     public static class DataInconsistencyException extends KeeperException {
+
         public DataInconsistencyException() {
             super(Code.DATAINCONSISTENCY);
         }
+
     }
 
     /**
@@ -631,12 +646,14 @@ public abstract class KeeperException extends Exception {
      */
     @InterfaceAudience.Public
     public static class InvalidACLException extends KeeperException {
+
         public InvalidACLException() {
             super(Code.INVALIDACL);
         }
         public InvalidACLException(String path) {
             super(Code.INVALIDACL, path);
         }
+
     }
 
     /**
@@ -644,9 +661,11 @@ public abstract class KeeperException extends Exception {
      */
     @InterfaceAudience.Public
     public static class InvalidCallbackException extends KeeperException {
+
         public InvalidCallbackException() {
             super(Code.INVALIDCALLBACK);
         }
+
     }
 
     /**
@@ -654,9 +673,11 @@ public abstract class KeeperException extends Exception {
      */
     @InterfaceAudience.Public
     public static class MarshallingErrorException extends KeeperException {
+
         public MarshallingErrorException() {
             super(Code.MARSHALLINGERROR);
         }
+
     }
 
     /**
@@ -664,9 +685,11 @@ public abstract class KeeperException extends Exception {
      */
     @InterfaceAudience.Public
     public static class NoAuthException extends KeeperException {
+
         public NoAuthException() {
             super(Code.NOAUTH);
         }
+
     }
 
     /**
@@ -674,32 +697,38 @@ public abstract class KeeperException extends Exception {
      */
     @InterfaceAudience.Public
     public static class NewConfigNoQuorum extends KeeperException {
+
         public NewConfigNoQuorum() {
             super(Code.NEWCONFIGNOQUORUM);
         }
+
     }
-    
+
     /**
      * @see Code#RECONFIGINPROGRESS
      */
     @InterfaceAudience.Public
     public static class ReconfigInProgress extends KeeperException {
+
         public ReconfigInProgress() {
             super(Code.RECONFIGINPROGRESS);
         }
+
     }
-    
+
     /**
      * @see Code#NOCHILDRENFOREPHEMERALS
      */
     @InterfaceAudience.Public
     public static class NoChildrenForEphemeralsException extends KeeperException {
+
         public NoChildrenForEphemeralsException() {
             super(Code.NOCHILDRENFOREPHEMERALS);
         }
         public NoChildrenForEphemeralsException(String path) {
             super(Code.NOCHILDRENFOREPHEMERALS, path);
         }
+
     }
 
     /**
@@ -707,12 +736,14 @@ public abstract class KeeperException extends Exception {
      */
     @InterfaceAudience.Public
     public static class NodeExistsException extends KeeperException {
+
         public NodeExistsException() {
             super(Code.NODEEXISTS);
         }
         public NodeExistsException(String path) {
             super(Code.NODEEXISTS, path);
         }
+
     }
 
     /**
@@ -720,12 +751,14 @@ public abstract class KeeperException extends Exception {
      */
     @InterfaceAudience.Public
     public static class NoNodeException extends KeeperException {
+
         public NoNodeException() {
             super(Code.NONODE);
         }
         public NoNodeException(String path) {
             super(Code.NONODE, path);
         }
+
     }
 
     /**
@@ -733,12 +766,14 @@ public abstract class KeeperException extends Exception {
      */
     @InterfaceAudience.Public
     public static class NotEmptyException extends KeeperException {
+
         public NotEmptyException() {
             super(Code.NOTEMPTY);
         }
         public NotEmptyException(String path) {
             super(Code.NOTEMPTY, path);
         }
+
     }
 
     /**
@@ -746,9 +781,11 @@ public abstract class KeeperException extends Exception {
      */
     @InterfaceAudience.Public
     public static class OperationTimeoutException extends KeeperException {
+
         public OperationTimeoutException() {
             super(Code.OPERATIONTIMEOUT);
         }
+
     }
 
     /**
@@ -756,9 +793,11 @@ public abstract class KeeperException extends Exception {
      */
     @InterfaceAudience.Public
     public static class RuntimeInconsistencyException extends KeeperException {
+
         public RuntimeInconsistencyException() {
             super(Code.RUNTIMEINCONSISTENCY);
         }
+
     }
 
     /**
@@ -766,9 +805,11 @@ public abstract class KeeperException extends Exception {
      */
     @InterfaceAudience.Public
     public static class SessionExpiredException extends KeeperException {
+
         public SessionExpiredException() {
             super(Code.SESSIONEXPIRED);
         }
+
     }
 
     /**
@@ -776,9 +817,11 @@ public abstract class KeeperException extends Exception {
      */
     @InterfaceAudience.Public
     public static class UnknownSessionException extends KeeperException {
+
         public UnknownSessionException() {
             super(Code.UNKNOWNSESSION);
         }
+
     }
 
     /**
@@ -786,9 +829,11 @@ public abstract class KeeperException extends Exception {
      */
     @InterfaceAudience.Public
     public static class SessionMovedException extends KeeperException {
+
         public SessionMovedException() {
             super(Code.SESSIONMOVED);
         }
+
     }
 
     /**
@@ -796,9 +841,11 @@ public abstract class KeeperException extends Exception {
      */
     @InterfaceAudience.Public
     public static class NotReadOnlyException extends KeeperException {
+
         public NotReadOnlyException() {
             super(Code.NOTREADONLY);
         }
+
     }
 
     /**
@@ -806,9 +853,11 @@ public abstract class KeeperException extends Exception {
      */
     @InterfaceAudience.Public
     public static class EphemeralOnLocalSessionException extends KeeperException {
+
         public EphemeralOnLocalSessionException() {
             super(Code.EPHEMERALONLOCALSESSION);
         }
+
     }
 
     /**
@@ -816,9 +865,11 @@ public abstract class KeeperException extends Exception {
      */
     @InterfaceAudience.Public
     public static class SystemErrorException extends KeeperException {
+
         public SystemErrorException() {
             super(Code.SYSTEMERROR);
         }
+
     }
 
     /**
@@ -826,9 +877,11 @@ public abstract class KeeperException extends Exception {
      */
     @InterfaceAudience.Public
     public static class UnimplementedException extends KeeperException {
+
         public UnimplementedException() {
             super(Code.UNIMPLEMENTED);
         }
+
     }
 
     /**
@@ -836,6 +889,7 @@ public abstract class KeeperException extends Exception {
      */
     @InterfaceAudience.Public
     public static class NoWatcherException extends KeeperException {
+
         public NoWatcherException() {
             super(Code.NOWATCHER);
         }
@@ -843,6 +897,7 @@ public abstract class KeeperException extends Exception {
         public NoWatcherException(String path) {
             super(Code.NOWATCHER, path);
         }
+
     }
 
     /**
@@ -850,28 +905,39 @@ public abstract class KeeperException extends Exception {
      */
     @InterfaceAudience.Public
     public static class ReconfigDisabledException extends KeeperException {
-        public ReconfigDisabledException() { super(Code.RECONFIGDISABLED); }
+
+        public ReconfigDisabledException() {
+            super(Code.RECONFIGDISABLED);
+        }
         public ReconfigDisabledException(String path) {
             super(Code.RECONFIGDISABLED, path);
         }
+
     }
 
     /**
      * @see Code#SESSIONCLOSEDREQUIRESASLAUTH
      */
     public static class SessionClosedRequireAuthException extends KeeperException {
-        public SessionClosedRequireAuthException() { super(Code.SESSIONCLOSEDREQUIRESASLAUTH); }
+
+        public SessionClosedRequireAuthException() {
+            super(Code.SESSIONCLOSEDREQUIRESASLAUTH);
+        }
         public SessionClosedRequireAuthException(String path) {
             super(Code.SESSIONCLOSEDREQUIRESASLAUTH, path);
         }
+
     }
 
     /**
      * @see Code#REQUESTTIMEOUT
      */
     public static class RequestTimeoutException extends KeeperException {
+
         public RequestTimeoutException() {
             super(Code.REQUESTTIMEOUT);
         }
+
     }
+
 }

+ 59 - 60
zookeeper-server/src/main/java/org/apache/zookeeper/Login.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -25,28 +25,26 @@ package org.apache.zookeeper;
  * See ZooKeeperSaslClient for client-side usage.
  */
 
+import java.util.Date;
+import java.util.Random;
+import java.util.Set;
+import javax.security.auth.Subject;
+import javax.security.auth.callback.CallbackHandler;
 import javax.security.auth.kerberos.KerberosPrincipal;
+import javax.security.auth.kerberos.KerberosTicket;
 import javax.security.auth.login.AppConfigurationEntry;
 import javax.security.auth.login.Configuration;
 import javax.security.auth.login.LoginContext;
 import javax.security.auth.login.LoginException;
-import javax.security.auth.callback.CallbackHandler;
-
 import org.apache.zookeeper.client.ZKClientConfig;
+import org.apache.zookeeper.common.Time;
 import org.apache.zookeeper.common.ZKConfig;
 import org.apache.zookeeper.server.ZooKeeperSaslServer;
-import org.apache.zookeeper.common.Time;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import javax.security.auth.kerberos.KerberosTicket;
-import javax.security.auth.Subject;
-
-import java.util.Date;
-import java.util.Random;
-import java.util.Set;
-
 public class Login {
+
     private static final String KINIT_COMMAND_DEFAULT = "/usr/bin/kinit";
     private static final Logger LOG = LoggerFactory.getLogger(Login.class);
     public CallbackHandler callbackHandler;
@@ -85,7 +83,7 @@ public class Login {
     /**
      * LoginThread constructor. The constructor starts the thread used to
      * periodically re-login to the Kerberos Ticket Granting Server.
-     * 
+     *
      * @param loginContextName
      *            name of section in JAAS file that will be use to login. Passed
      *            as first param to javax.security.auth.login.LoginContext().
@@ -98,25 +96,24 @@ public class Login {
      * @throws javax.security.auth.login.LoginException
      *             Thrown if authentication fails.
      */
-    public Login(final String loginContextName, CallbackHandler callbackHandler, final ZKConfig zkConfig)
-            throws LoginException {
-        this.zkConfig=zkConfig;
+    public Login(final String loginContextName, CallbackHandler callbackHandler, final ZKConfig zkConfig) throws LoginException {
+        this.zkConfig = zkConfig;
         this.callbackHandler = callbackHandler;
         login = login(loginContextName);
         this.loginContextName = loginContextName;
         subject = login.getSubject();
         isKrbTicket = !subject.getPrivateCredentials(KerberosTicket.class).isEmpty();
-        AppConfigurationEntry entries[] = Configuration.getConfiguration().getAppConfigurationEntry(loginContextName);
-        for (AppConfigurationEntry entry: entries) {
+        AppConfigurationEntry[] entries = Configuration.getConfiguration().getAppConfigurationEntry(loginContextName);
+        for (AppConfigurationEntry entry : entries) {
             // there will only be a single entry, so this for() loop will only be iterated through once.
             if (entry.getOptions().get("useTicketCache") != null) {
-                String val = (String)entry.getOptions().get("useTicketCache");
+                String val = (String) entry.getOptions().get("useTicketCache");
                 if (val.equals("true")) {
                     isUsingTicketCache = true;
                 }
             }
             if (entry.getOptions().get("principal") != null) {
-                principal = (String)entry.getOptions().get("principal");
+                principal = (String) entry.getOptions().get("principal");
             }
             break;
         }
@@ -148,21 +145,20 @@ public class Login {
                         Date expiryDate = new Date(expiry);
                         if ((isUsingTicketCache) && (tgt.getEndTime().equals(tgt.getRenewTill()))) {
                             Object[] logPayload = {expiryDate, principal, principal};
-                            LOG.error("The TGT cannot be renewed beyond the next expiry date: {}." +
-                                    "This process will not be able to authenticate new SASL connections after that " +
-                                    "time (for example, it will not be authenticate a new connection with a Zookeeper " +
-                                    "Quorum member).  Ask your system administrator to either increase the " +
-                                    "'renew until' time by doing : 'modprinc -maxrenewlife {}' within " +
-                                    "kadmin, or instead, to generate a keytab for {}. Because the TGT's " +
-                                    "expiry cannot be further extended by refreshing, exiting refresh thread now.", logPayload);
+                            LOG.error("The TGT cannot be renewed beyond the next expiry date: {}."
+                                      + "This process will not be able to authenticate new SASL connections after that "
+                                      + "time (for example, it will not be authenticate a new connection with a Zookeeper "
+                                      + "Quorum member).  Ask your system administrator to either increase the "
+                                      + "'renew until' time by doing : 'modprinc -maxrenewlife {}' within "
+                                      + "kadmin, or instead, to generate a keytab for {}. Because the TGT's "
+                                      + "expiry cannot be further extended by refreshing, exiting refresh thread now.", logPayload);
                             return;
                         }
                         // determine how long to sleep from looking at ticket's expiry.
                         // We should not allow the ticket to expire, but we should take into consideration
                         // MIN_TIME_BEFORE_RELOGIN. Will not sleep less than MIN_TIME_BEFORE_RELOGIN, unless doing so
                         // would cause ticket expiration.
-                        if ((nextRefresh > expiry) ||
-                                ((now + MIN_TIME_BEFORE_RELOGIN) > expiry)) {
+                        if ((nextRefresh > expiry) || ((now + MIN_TIME_BEFORE_RELOGIN) > expiry)) {
                             // expiry is before next scheduled refresh).
                             nextRefresh = now;
                         } else {
@@ -172,8 +168,8 @@ public class Login {
                                 Date newuntil = new Date(now + MIN_TIME_BEFORE_RELOGIN);
                                 Object[] logPayload = {until, newuntil, (MIN_TIME_BEFORE_RELOGIN / 1000)};
                                 LOG.warn("TGT refresh thread time adjusted from : {} to : {} since "
-                                        + "the former is sooner than the minimum refresh interval ("
-                                        + "{} seconds) from now.", logPayload);
+                                         + "the former is sooner than the minimum refresh interval ("
+                                         + "{} seconds) from now.", logPayload);
                             }
                             nextRefresh = Math.max(nextRefresh, now + MIN_TIME_BEFORE_RELOGIN);
                         }
@@ -181,8 +177,8 @@ public class Login {
                         if (nextRefresh > expiry) {
                             Object[] logPayload = {nextRefreshDate, expiryDate};
                             LOG.error("next refresh: {} is later than expiry {}."
-                                    + " This may indicate a clock skew problem. Check that this host and the KDC's "
-                                    + "hosts' clocks are in sync. Exiting refresh thread.", logPayload);
+                                      + " This may indicate a clock skew problem. Check that this host and the KDC's "
+                                      + "hosts' clocks are in sync. Exiting refresh thread.", logPayload);
                             return;
                         }
                     }
@@ -197,12 +193,11 @@ public class Login {
                             LOG.warn("TGT renewal thread has been interrupted and will exit.");
                             break;
                         }
-                    }
-                    else {
+                    } else {
                         LOG.error("nextRefresh:{} is in the past: exiting refresh thread. Check"
-                                + " clock sync between this host and KDC - (KDC's clock is likely ahead of this host)."
-                                + " Manual intervention will be required for this client to successfully authenticate."
-                                + " Exiting refresh thread.", nextRefreshDate);
+                                  + " clock sync between this host and KDC - (KDC's clock is likely ahead of this host)."
+                                  + " Manual intervention will be required for this client to successfully authenticate."
+                                  + " Exiting refresh thread.", nextRefreshDate);
                         break;
                     }
                     if (isUsingTicketCache) {
@@ -227,7 +222,8 @@ public class Login {
                                 } else {
                                     Object[] logPayload = {cmd, kinitArgs, e.toString(), e};
                                     LOG.warn("Could not renew TGT due to problem running shell command: '{}"
-                                            + " {}'; exception was:{}. Exiting refresh thread.", logPayload);
+                                             + " {}'; exception was:{}. Exiting refresh thread.",
+                                             logPayload);
                                     return;
                                 }
                             }
@@ -255,7 +251,7 @@ public class Login {
                             }
                         }
                     } catch (LoginException le) {
-                        LOG.error("Failed to refresh TGT: refresh thread exiting now.",le);
+                        LOG.error("Failed to refresh TGT: refresh thread exiting now.", le);
                         break;
                     }
                 }
@@ -292,12 +288,13 @@ public class Login {
 
     private synchronized LoginContext login(final String loginContextName) throws LoginException {
         if (loginContextName == null) {
-            throw new LoginException("loginContext name (JAAS file section header) was null. " +
-                    "Please check your java.security.login.auth.config (=" +
-                    System.getProperty("java.security.login.auth.config") +
-                    ") and your " + getLoginContextMessage());
+            throw new LoginException("loginContext name (JAAS file section header) was null. "
+                                     + "Please check your java.security.login.auth.config (="
+                                     + System.getProperty("java.security.login.auth.config")
+                                     + ") and your "
+                                     + getLoginContextMessage());
         }
-        LoginContext loginContext = new LoginContext(loginContextName,callbackHandler);
+        LoginContext loginContext = new LoginContext(loginContextName, callbackHandler);
         loginContext.login();
         LOG.info("{} successfully logged in.", loginContextName);
         return loginContext;
@@ -305,11 +302,15 @@ public class Login {
 
     private String getLoginContextMessage() {
         if (zkConfig instanceof ZKClientConfig) {
-            return ZKClientConfig.LOGIN_CONTEXT_NAME_KEY + "(=" + zkConfig.getProperty(
-                    ZKClientConfig.LOGIN_CONTEXT_NAME_KEY, ZKClientConfig.LOGIN_CONTEXT_NAME_KEY_DEFAULT) + ")";
+            return ZKClientConfig.LOGIN_CONTEXT_NAME_KEY
+                   + "(="
+                   + zkConfig.getProperty(ZKClientConfig.LOGIN_CONTEXT_NAME_KEY, ZKClientConfig.LOGIN_CONTEXT_NAME_KEY_DEFAULT)
+                   + ")";
         } else {
-            return ZooKeeperSaslServer.LOGIN_CONTEXT_NAME_KEY + "(=" + System.getProperty(
-                    ZooKeeperSaslServer.LOGIN_CONTEXT_NAME_KEY, ZooKeeperSaslServer.DEFAULT_LOGIN_CONTEXT_NAME) + ")";
+            return ZooKeeperSaslServer.LOGIN_CONTEXT_NAME_KEY
+                   + "(="
+                   + System.getProperty(ZooKeeperSaslServer.LOGIN_CONTEXT_NAME_KEY, ZooKeeperSaslServer.DEFAULT_LOGIN_CONTEXT_NAME)
+                   + ")";
         }
     }
 
@@ -319,24 +320,22 @@ public class Login {
         long expires = tgt.getEndTime().getTime();
         LOG.info("TGT valid starting at:        {}", tgt.getStartTime().toString());
         LOG.info("TGT expires:                  {}", tgt.getEndTime().toString());
-        long proposedRefresh = start + (long) ((expires - start) *
-                (TICKET_RENEW_WINDOW + (TICKET_RENEW_JITTER * rng.nextDouble())));
+        long proposedRefresh = start + (long) ((expires - start) * (TICKET_RENEW_WINDOW + (TICKET_RENEW_JITTER * rng.nextDouble())));
         if (proposedRefresh > expires) {
             // proposedRefresh is too far in the future: it's after ticket expires: simply return now.
             return Time.currentWallTime();
-        }
-        else {
+        } else {
             return proposedRefresh;
         }
     }
 
     private synchronized KerberosTicket getTGT() {
         Set<KerberosTicket> tickets = subject.getPrivateCredentials(KerberosTicket.class);
-        for(KerberosTicket ticket: tickets) {
+        for (KerberosTicket ticket : tickets) {
             KerberosPrincipal server = ticket.getServer();
             if (server.getName().equals("krbtgt/" + server.getRealm() + "@" + server.getRealm())) {
                 LOG.debug("Client principal is \"{}\".", ticket.getClient().getName());
-                LOG.debug("Server principal is \"{}\".",  ticket.getServer().getName());
+                LOG.debug("Server principal is \"{}\".", ticket.getServer().getName());
                 return ticket;
             }
         }
@@ -345,10 +344,10 @@ public class Login {
 
     private boolean hasSufficientTimeElapsed() {
         long now = Time.currentElapsedTime();
-        if (now - getLastLogin() < MIN_TIME_BEFORE_RELOGIN ) {
+        if (now - getLastLogin() < MIN_TIME_BEFORE_RELOGIN) {
             LOG.warn("Not attempting to re-login since the last re-login was "
-                    + "attempted less than {} seconds before.",
-                    (MIN_TIME_BEFORE_RELOGIN / 1000));
+                     + "attempted less than {} seconds before.",
+                     (MIN_TIME_BEFORE_RELOGIN / 1000));
             return false;
         }
         // register most recent relogin attempt
@@ -393,13 +392,12 @@ public class Login {
      * @throws javax.security.auth.login.LoginException on a failure
      */
     // c.f. HADOOP-6559
-    private synchronized void reLogin()
-            throws LoginException {
+    private synchronized void reLogin() throws LoginException {
         if (!isKrbTicket) {
             return;
         }
         LoginContext login = getLogin();
-        if (login  == null) {
+        if (login == null) {
             throw new LoginException("login must be done first");
         }
         if (!hasSufficientTimeElapsed()) {
@@ -419,4 +417,5 @@ public class Login {
             setLogin(login);
         }
     }
+
 }

+ 75 - 63
zookeeper-server/src/main/java/org/apache/zookeeper/MultiOperationRecord.java

@@ -17,15 +17,21 @@
 
 package org.apache.zookeeper;
 
-import org.apache.jute.InputArchive;
-import org.apache.jute.OutputArchive;
-import org.apache.jute.Record;
-import org.apache.zookeeper.proto.*;
-
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.List;
+import org.apache.jute.InputArchive;
+import org.apache.jute.OutputArchive;
+import org.apache.jute.Record;
+import org.apache.zookeeper.proto.CheckVersionRequest;
+import org.apache.zookeeper.proto.CreateRequest;
+import org.apache.zookeeper.proto.CreateTTLRequest;
+import org.apache.zookeeper.proto.DeleteRequest;
+import org.apache.zookeeper.proto.GetChildrenRequest;
+import org.apache.zookeeper.proto.GetDataRequest;
+import org.apache.zookeeper.proto.MultiHeader;
+import org.apache.zookeeper.proto.SetDataRequest;
 
 /**
  * Encodes a composite operation.  In the wire format, each operation
@@ -36,6 +42,7 @@ import java.util.List;
  * All of the operations must be from the same OpKind.
  */
 public class MultiOperationRecord implements Record, Iterable<Op> {
+
     private List<Op> ops = new ArrayList<Op>();
     private Op.OpKind opKind = null;
 
@@ -51,7 +58,7 @@ public class MultiOperationRecord implements Record, Iterable<Op> {
 
     @Override
     public Iterator<Op> iterator() {
-        return ops.iterator() ;
+        return ops.iterator();
     }
 
     public void add(Op op) throws IllegalArgumentException {
@@ -65,7 +72,7 @@ public class MultiOperationRecord implements Record, Iterable<Op> {
 
     /**
      * Returns the kind of the operations contained by the record.
-     * @return  The OpKind value of all the elements in the record.
+     * @return The OpKind value of all the elements in the record.
      */
     public Op.OpKind getOpKind() {
         return opKind;
@@ -75,8 +82,8 @@ public class MultiOperationRecord implements Record, Iterable<Op> {
         if (opKind == null) {
             opKind = ok;
         } else if (ok != opKind) {
-            throw new IllegalArgumentException("Mixing read and write operations (transactions)" +
-                      " is not allowed in a multi request.");
+            throw new IllegalArgumentException("Mixing read and write operations (transactions)"
+                                               + " is not allowed in a multi request.");
         }
     }
 
@@ -87,19 +94,19 @@ public class MultiOperationRecord implements Record, Iterable<Op> {
             MultiHeader h = new MultiHeader(op.getType(), false, -1);
             h.serialize(archive, tag);
             switch (op.getType()) {
-                case ZooDefs.OpCode.create:
-                case ZooDefs.OpCode.create2:
-                case ZooDefs.OpCode.createTTL:
-                case ZooDefs.OpCode.createContainer:
-                case ZooDefs.OpCode.delete:
-                case ZooDefs.OpCode.setData:
-                case ZooDefs.OpCode.check:
-                case ZooDefs.OpCode.getChildren:
-                case ZooDefs.OpCode.getData:
-                    op.toRequestRecord().serialize(archive, tag);
-                    break;
-                default:
-                    throw new IOException("Invalid type of op");
+            case ZooDefs.OpCode.create:
+            case ZooDefs.OpCode.create2:
+            case ZooDefs.OpCode.createTTL:
+            case ZooDefs.OpCode.createContainer:
+            case ZooDefs.OpCode.delete:
+            case ZooDefs.OpCode.setData:
+            case ZooDefs.OpCode.check:
+            case ZooDefs.OpCode.getChildren:
+            case ZooDefs.OpCode.getData:
+                op.toRequestRecord().serialize(archive, tag);
+                break;
+            default:
+                throw new IOException("Invalid type of op");
             }
         }
         new MultiHeader(-1, true, -1).serialize(archive, tag);
@@ -114,45 +121,45 @@ public class MultiOperationRecord implements Record, Iterable<Op> {
         try {
             while (!h.getDone()) {
                 switch (h.getType()) {
-                    case ZooDefs.OpCode.create:
-                    case ZooDefs.OpCode.create2:
-                    case ZooDefs.OpCode.createContainer:
-                        CreateRequest cr = new CreateRequest();
-                        cr.deserialize(archive, tag);
-                        add(Op.create(cr.getPath(), cr.getData(), cr.getAcl(), cr.getFlags()));
-                        break;
-                    case ZooDefs.OpCode.createTTL:
-                        CreateTTLRequest crTtl = new CreateTTLRequest();
-                        crTtl.deserialize(archive, tag);
-                        add(Op.create(crTtl.getPath(), crTtl.getData(), crTtl.getAcl(), crTtl.getFlags(), crTtl.getTtl()));
-                        break;
-                    case ZooDefs.OpCode.delete:
-                        DeleteRequest dr = new DeleteRequest();
-                        dr.deserialize(archive, tag);
-                        add(Op.delete(dr.getPath(), dr.getVersion()));
-                        break;
-                    case ZooDefs.OpCode.setData:
-                        SetDataRequest sdr = new SetDataRequest();
-                        sdr.deserialize(archive, tag);
-                        add(Op.setData(sdr.getPath(), sdr.getData(), sdr.getVersion()));
-                        break;
-                    case ZooDefs.OpCode.check:
-                        CheckVersionRequest cvr = new CheckVersionRequest();
-                        cvr.deserialize(archive, tag);
-                        add(Op.check(cvr.getPath(), cvr.getVersion()));
-                        break;
-                    case ZooDefs.OpCode.getChildren:
-                        GetChildrenRequest gcr = new GetChildrenRequest();
-                        gcr.deserialize(archive, tag);
-                        add(Op.getChildren(gcr.getPath()));
-                        break;
-                    case ZooDefs.OpCode.getData:
-                        GetDataRequest gdr = new GetDataRequest();
-                        gdr.deserialize(archive, tag);
-                        add(Op.getData(gdr.getPath()));
-                        break;
-                    default:
-                        throw new IOException("Invalid type of op");
+                case ZooDefs.OpCode.create:
+                case ZooDefs.OpCode.create2:
+                case ZooDefs.OpCode.createContainer:
+                    CreateRequest cr = new CreateRequest();
+                    cr.deserialize(archive, tag);
+                    add(Op.create(cr.getPath(), cr.getData(), cr.getAcl(), cr.getFlags()));
+                    break;
+                case ZooDefs.OpCode.createTTL:
+                    CreateTTLRequest crTtl = new CreateTTLRequest();
+                    crTtl.deserialize(archive, tag);
+                    add(Op.create(crTtl.getPath(), crTtl.getData(), crTtl.getAcl(), crTtl.getFlags(), crTtl.getTtl()));
+                    break;
+                case ZooDefs.OpCode.delete:
+                    DeleteRequest dr = new DeleteRequest();
+                    dr.deserialize(archive, tag);
+                    add(Op.delete(dr.getPath(), dr.getVersion()));
+                    break;
+                case ZooDefs.OpCode.setData:
+                    SetDataRequest sdr = new SetDataRequest();
+                    sdr.deserialize(archive, tag);
+                    add(Op.setData(sdr.getPath(), sdr.getData(), sdr.getVersion()));
+                    break;
+                case ZooDefs.OpCode.check:
+                    CheckVersionRequest cvr = new CheckVersionRequest();
+                    cvr.deserialize(archive, tag);
+                    add(Op.check(cvr.getPath(), cvr.getVersion()));
+                    break;
+                case ZooDefs.OpCode.getChildren:
+                    GetChildrenRequest gcr = new GetChildrenRequest();
+                    gcr.deserialize(archive, tag);
+                    add(Op.getChildren(gcr.getPath()));
+                    break;
+                case ZooDefs.OpCode.getData:
+                    GetDataRequest gdr = new GetDataRequest();
+                    gdr.deserialize(archive, tag);
+                    add(Op.getData(gdr.getPath()));
+                    break;
+                default:
+                    throw new IOException("Invalid type of op");
                 }
                 h.deserialize(archive, tag);
             }
@@ -164,8 +171,12 @@ public class MultiOperationRecord implements Record, Iterable<Op> {
 
     @Override
     public boolean equals(Object o) {
-        if (this == o) return true;
-        if (!(o instanceof MultiOperationRecord)) return false;
+        if (this == o) {
+            return true;
+        }
+        if (!(o instanceof MultiOperationRecord)) {
+            return false;
+        }
 
         MultiOperationRecord that = (MultiOperationRecord) o;
 
@@ -196,4 +207,5 @@ public class MultiOperationRecord implements Record, Iterable<Op> {
         }
         return h;
     }
+
 }

+ 90 - 82
zookeeper-server/src/main/java/org/apache/zookeeper/MultiResponse.java

@@ -17,21 +17,20 @@
 
 package org.apache.zookeeper;
 
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
 import org.apache.jute.InputArchive;
 import org.apache.jute.OutputArchive;
 import org.apache.jute.Record;
 import org.apache.zookeeper.proto.Create2Response;
 import org.apache.zookeeper.proto.CreateResponse;
+import org.apache.zookeeper.proto.ErrorResponse;
 import org.apache.zookeeper.proto.GetChildrenResponse;
 import org.apache.zookeeper.proto.GetDataResponse;
 import org.apache.zookeeper.proto.MultiHeader;
 import org.apache.zookeeper.proto.SetDataResponse;
-import org.apache.zookeeper.proto.ErrorResponse;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
 
 /**
  * Handles the response from a multi request.  Such a response consists of
@@ -41,6 +40,7 @@ import java.util.List;
  * with the corresponding operation in the original request list.
  */
 public class MultiResponse implements Record, Iterable<OpResult> {
+
     private List<OpResult> results = new ArrayList<OpResult>();
 
     public void add(OpResult x) {
@@ -61,36 +61,38 @@ public class MultiResponse implements Record, Iterable<OpResult> {
         archive.startRecord(this, tag);
 
         for (OpResult result : results) {
-            int err = result.getType() == ZooDefs.OpCode.error ? ((OpResult.ErrorResult)result).getErr() : 0;
+            int err = result.getType() == ZooDefs.OpCode.error ? ((OpResult.ErrorResult) result).getErr() : 0;
 
             new MultiHeader(result.getType(), false, err).serialize(archive, tag);
 
             switch (result.getType()) {
-                case ZooDefs.OpCode.create:
-                    new CreateResponse(((OpResult.CreateResult) result).getPath()).serialize(archive, tag);
-                    break;
-                case ZooDefs.OpCode.create2:
-                	OpResult.CreateResult createResult = (OpResult.CreateResult) result;
-                    new Create2Response(createResult.getPath(),
-                    		createResult.getStat()).serialize(archive, tag);
-                    break;
-                case ZooDefs.OpCode.delete:
-                case ZooDefs.OpCode.check:
-                    break;
-                case ZooDefs.OpCode.setData:
-                    new SetDataResponse(((OpResult.SetDataResult) result).getStat()).serialize(archive, tag);
-                    break;
-                case ZooDefs.OpCode.getChildren:
-                    new GetChildrenResponse(((OpResult.GetChildrenResult) result).getChildren()).serialize(archive, tag);
-                    break;
-                case ZooDefs.OpCode.getData:
-                    new GetDataResponse(((OpResult.GetDataResult) result).getData(),((OpResult.GetDataResult) result).getStat()).serialize(archive, tag);
-                    break;
-                case ZooDefs.OpCode.error:
-                    new ErrorResponse(((OpResult.ErrorResult) result).getErr()).serialize(archive, tag);
-                    break;
-                default:
-                    throw new IOException("Invalid type " + result.getType() + " in MultiResponse");
+            case ZooDefs.OpCode.create:
+                new CreateResponse(((OpResult.CreateResult) result).getPath()).serialize(archive, tag);
+                break;
+            case ZooDefs.OpCode.create2:
+                OpResult.CreateResult createResult = (OpResult.CreateResult) result;
+                new Create2Response(createResult.getPath(), createResult.getStat()).serialize(archive, tag);
+                break;
+            case ZooDefs.OpCode.delete:
+            case ZooDefs.OpCode.check:
+                break;
+            case ZooDefs.OpCode.setData:
+                new SetDataResponse(((OpResult.SetDataResult) result).getStat()).serialize(archive, tag);
+                break;
+            case ZooDefs.OpCode.getChildren:
+                new GetChildrenResponse(((OpResult.GetChildrenResult) result).getChildren()).serialize(archive, tag);
+                break;
+            case ZooDefs.OpCode.getData:
+                new GetDataResponse(
+                    ((OpResult.GetDataResult) result).getData(),
+                    ((OpResult.GetDataResult) result).getStat())
+                    .serialize(archive, tag);
+                break;
+            case ZooDefs.OpCode.error:
+                new ErrorResponse(((OpResult.ErrorResult) result).getErr()).serialize(archive, tag);
+                break;
+            default:
+                throw new IOException("Invalid type " + result.getType() + " in MultiResponse");
             }
         }
         new MultiHeader(-1, true, -1).serialize(archive, tag);
@@ -106,53 +108,53 @@ public class MultiResponse implements Record, Iterable<OpResult> {
         h.deserialize(archive, tag);
         while (!h.getDone()) {
             switch (h.getType()) {
-                case ZooDefs.OpCode.create:
-                    CreateResponse cr = new CreateResponse();
-                    cr.deserialize(archive, tag);
-                    results.add(new OpResult.CreateResult(cr.getPath()));
-                    break;
-
-                case ZooDefs.OpCode.create2:
-                    Create2Response cr2 = new Create2Response();
-                    cr2.deserialize(archive, tag);
-                    results.add(new OpResult.CreateResult(cr2.getPath(), cr2.getStat()));
-                    break;
-
-                case ZooDefs.OpCode.delete:
-                    results.add(new OpResult.DeleteResult());
-                    break;
-
-                case ZooDefs.OpCode.setData:
-                    SetDataResponse sdr = new SetDataResponse();
-                    sdr.deserialize(archive, tag);
-                    results.add(new OpResult.SetDataResult(sdr.getStat()));
-                    break;
-
-                case ZooDefs.OpCode.check:
-                    results.add(new OpResult.CheckResult());
-                    break;
-
-                case ZooDefs.OpCode.getChildren:
-                    GetChildrenResponse gcr = new GetChildrenResponse();
-                    gcr.deserialize(archive, tag);
-                    results.add(new OpResult.GetChildrenResult(gcr.getChildren()));
-                    break;
-
-                case ZooDefs.OpCode.getData:
-                    GetDataResponse gdr = new GetDataResponse();
-                    gdr.deserialize(archive, tag);
-                    results.add(new OpResult.GetDataResult(gdr.getData(), gdr.getStat()));
-                    break;
-
-                case ZooDefs.OpCode.error:
-                    //FIXME: need way to more cleanly serialize/deserialize exceptions
-                    ErrorResponse er = new ErrorResponse();
-                    er.deserialize(archive, tag);
-                    results.add(new OpResult.ErrorResult(er.getErr()));
-                    break;
-
-                default:
-                    throw new IOException("Invalid type " + h.getType() + " in MultiResponse");
+            case ZooDefs.OpCode.create:
+                CreateResponse cr = new CreateResponse();
+                cr.deserialize(archive, tag);
+                results.add(new OpResult.CreateResult(cr.getPath()));
+                break;
+
+            case ZooDefs.OpCode.create2:
+                Create2Response cr2 = new Create2Response();
+                cr2.deserialize(archive, tag);
+                results.add(new OpResult.CreateResult(cr2.getPath(), cr2.getStat()));
+                break;
+
+            case ZooDefs.OpCode.delete:
+                results.add(new OpResult.DeleteResult());
+                break;
+
+            case ZooDefs.OpCode.setData:
+                SetDataResponse sdr = new SetDataResponse();
+                sdr.deserialize(archive, tag);
+                results.add(new OpResult.SetDataResult(sdr.getStat()));
+                break;
+
+            case ZooDefs.OpCode.check:
+                results.add(new OpResult.CheckResult());
+                break;
+
+            case ZooDefs.OpCode.getChildren:
+                GetChildrenResponse gcr = new GetChildrenResponse();
+                gcr.deserialize(archive, tag);
+                results.add(new OpResult.GetChildrenResult(gcr.getChildren()));
+                break;
+
+            case ZooDefs.OpCode.getData:
+                GetDataResponse gdr = new GetDataResponse();
+                gdr.deserialize(archive, tag);
+                results.add(new OpResult.GetDataResult(gdr.getData(), gdr.getStat()));
+                break;
+
+            case ZooDefs.OpCode.error:
+                // TODO: need way to more cleanly serialize/deserialize exceptions
+                ErrorResponse er = new ErrorResponse();
+                er.deserialize(archive, tag);
+                results.add(new OpResult.ErrorResult(er.getErr()));
+                break;
+
+            default:
+                throw new IOException("Invalid type " + h.getType() + " in MultiResponse");
             }
             h.deserialize(archive, tag);
         }
@@ -165,8 +167,12 @@ public class MultiResponse implements Record, Iterable<OpResult> {
 
     @Override
     public boolean equals(Object o) {
-        if (this == o) return true;
-        if (!(o instanceof MultiResponse)) return false;
+        if (this == o) {
+            return true;
+        }
+        if (!(o instanceof MultiResponse)) {
+            return false;
+        }
 
         MultiResponse other = (MultiResponse) o;
 
@@ -182,8 +188,9 @@ public class MultiResponse implements Record, Iterable<OpResult> {
                 }
             }
             return !i.hasNext();
+        } else {
+            return other.results == null;
         }
-        else return other.results == null;
     }
 
     @Override
@@ -194,4 +201,5 @@ public class MultiResponse implements Record, Iterable<OpResult> {
         }
         return hash;
     }
+
 }

+ 77 - 31
zookeeper-server/src/main/java/org/apache/zookeeper/Op.java

@@ -17,6 +17,9 @@
 
 package org.apache.zookeeper;
 
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
 import org.apache.jute.Record;
 import org.apache.zookeeper.common.PathUtils;
 import org.apache.zookeeper.data.ACL;
@@ -30,10 +33,6 @@ import org.apache.zookeeper.proto.GetDataRequest;
 import org.apache.zookeeper.proto.SetDataRequest;
 import org.apache.zookeeper.server.EphemeralType;
 
-import java.util.Arrays;
-import java.util.Iterator;
-import java.util.List;
-
 /**
  * Represents a single operation in a multi-operation transaction.  Each operation can be a create, update,
  * delete, a version check or just read operations like getChildren or getData.
@@ -50,7 +49,11 @@ import java.util.List;
  */
 public abstract class Op {
 
-    public enum OpKind { TRANSACTION, READ }
+    public enum OpKind {
+        TRANSACTION,
+        READ
+    }
+
     private int type;
     private String path;
     private OpKind opKind;
@@ -177,7 +180,6 @@ public abstract class Op {
         return new SetData(path, data, version);
     }
 
-
     /**
      * Constructs an version check operation.  Arguments are as for the ZooKeeper.setData method except that
      * no data is provided since no update is intended.  The purpose for this is to allow read-modify-write
@@ -205,7 +207,7 @@ public abstract class Op {
     /**
      * Gets the integer type code for an Op.  This code should be as from ZooDefs.OpCode
      * @see ZooDefs.OpCode
-     * @return  The type code.
+     * @return The type code.
      */
     public int getType() {
         return type;
@@ -213,7 +215,7 @@ public abstract class Op {
 
     /**
      * Gets the path for an Op.
-     * @return  The path.
+     * @return The path.
      */
     public String getPath() {
         return path;
@@ -221,7 +223,7 @@ public abstract class Op {
 
     /**
      * Gets the kind of an Op.
-     * @return  The OpKind value.
+     * @return The OpKind value.
      */
     public OpKind getKind() {
         return opKind;
@@ -231,8 +233,8 @@ public abstract class Op {
      * Encodes an op for wire transmission.
      * @return An appropriate Record structure.
      */
-    public abstract Record toRequestRecord() ;
-    
+    public abstract Record toRequestRecord();
+
     /**
      * Reconstructs the transaction with the chroot prefix.
      * @return transaction with chroot.
@@ -241,7 +243,7 @@ public abstract class Op {
 
     /**
      * Performs client path validations.
-     * 
+     *
      * @throws IllegalArgumentException
      *             if an invalid path is specified
      * @throws KeeperException.BadArgumentsException
@@ -255,6 +257,7 @@ public abstract class Op {
     // these internal classes are public, but should not generally be referenced.
     //
     public static class Create extends Op {
+
         protected byte[] data;
         protected List<ACL> acl;
         protected int flags;
@@ -282,8 +285,12 @@ public abstract class Op {
 
         @Override
         public boolean equals(Object o) {
-            if (this == o) return true;
-            if (!(o instanceof Create)) return false;
+            if (this == o) {
+                return true;
+            }
+            if (!(o instanceof Create)) {
+                return false;
+            }
 
             Create op = (Create) o;
 
@@ -301,7 +308,11 @@ public abstract class Op {
                     break;
                 }
             }
-            return !i.hasNext() && getType() == op.getType() && Arrays.equals(data, op.data) && flags == op.flags && aclEquals;
+            return !i.hasNext()
+                   && getType() == op.getType()
+                   && Arrays.equals(data, op.data)
+                   && flags == op.flags
+                   && aclEquals;
         }
 
         @Override
@@ -325,9 +336,11 @@ public abstract class Op {
             PathUtils.validatePath(getPath(), createMode.isSequential());
             EphemeralType.validateTTL(createMode, -1);
         }
+
     }
 
     public static class CreateTTL extends Create {
+
         private final long ttl;
 
         private CreateTTL(String path, byte[] data, List<ACL> acl, int flags, long ttl) {
@@ -342,12 +355,12 @@ public abstract class Op {
 
         @Override
         public boolean equals(Object o) {
-            return super.equals(o) && (o instanceof CreateTTL) && (ttl == ((CreateTTL)o).ttl);
+            return super.equals(o) && (o instanceof CreateTTL) && (ttl == ((CreateTTL) o).ttl);
         }
 
         @Override
         public int hashCode() {
-            return super.hashCode() + (int)(ttl ^ (ttl >>> 32));
+            return super.hashCode() + (int) (ttl ^ (ttl >>> 32));
         }
 
         @Override
@@ -366,9 +379,11 @@ public abstract class Op {
             PathUtils.validatePath(getPath(), createMode.isSequential());
             EphemeralType.validateTTL(createMode, ttl);
         }
+
     }
 
     public static class Delete extends Op {
+
         private int version;
 
         private Delete(String path, int version) {
@@ -378,13 +393,16 @@ public abstract class Op {
 
         @Override
         public boolean equals(Object o) {
-            if (this == o) return true;
-            if (!(o instanceof Delete)) return false;
+            if (this == o) {
+                return true;
+            }
+            if (!(o instanceof Delete)) {
+                return false;
+            }
 
             Delete op = (Delete) o;
 
-            return getType() == op.getType() && version == op.version 
-                   && getPath().equals(op.getPath());
+            return getType() == op.getType() && version == op.version && getPath().equals(op.getPath());
         }
 
         @Override
@@ -401,9 +419,11 @@ public abstract class Op {
         Op withChroot(String path) {
             return new Delete(path, version);
         }
+
     }
 
     public static class SetData extends Op {
+
         private byte[] data;
         private int version;
 
@@ -415,13 +435,19 @@ public abstract class Op {
 
         @Override
         public boolean equals(Object o) {
-            if (this == o) return true;
-            if (!(o instanceof SetData)) return false;
+            if (this == o) {
+                return true;
+            }
+            if (!(o instanceof SetData)) {
+                return false;
+            }
 
             SetData op = (SetData) o;
 
-            return getType() == op.getType() && version == op.version 
-                   && getPath().equals(op.getPath()) && Arrays.equals(data, op.data);
+            return getType() == op.getType()
+                   && version == op.version
+                   && getPath().equals(op.getPath())
+                   && Arrays.equals(data, op.data);
         }
 
         @Override
@@ -438,9 +464,11 @@ public abstract class Op {
         Op withChroot(String path) {
             return new SetData(path, data, version);
         }
+
     }
 
     public static class Check extends Op {
+
         private int version;
 
         private Check(String path, int version) {
@@ -450,8 +478,12 @@ public abstract class Op {
 
         @Override
         public boolean equals(Object o) {
-            if (this == o) return true;
-            if (!(o instanceof Check)) return false;
+            if (this == o) {
+                return true;
+            }
+            if (!(o instanceof Check)) {
+                return false;
+            }
 
             Check op = (Check) o;
 
@@ -472,17 +504,23 @@ public abstract class Op {
         Op withChroot(String path) {
             return new Check(path, version);
         }
+
     }
 
     public static class GetChildren extends Op {
+
         GetChildren(String path) {
             super(ZooDefs.OpCode.getChildren, path, OpKind.READ);
         }
 
         @Override
         public boolean equals(Object o) {
-            if (this == o) return true;
-            if (!(o instanceof GetChildren)) return false;
+            if (this == o) {
+                return true;
+            }
+            if (!(o instanceof GetChildren)) {
+                return false;
+            }
 
             GetChildren op = (GetChildren) o;
 
@@ -503,17 +541,23 @@ public abstract class Op {
         Op withChroot(String path) {
             return new GetChildren(path);
         }
+
     }
 
     public static class GetData extends Op {
+
         GetData(String path) {
             super(ZooDefs.OpCode.getData, path, OpKind.READ);
         }
 
         @Override
         public boolean equals(Object o) {
-            if (this == o) return true;
-            if (!(o instanceof GetData)) return false;
+            if (this == o) {
+                return true;
+            }
+            if (!(o instanceof GetData)) {
+                return false;
+            }
 
             GetData op = (GetData) o;
 
@@ -534,5 +578,7 @@ public abstract class Op {
         Op withChroot(String path) {
             return new GetData(path);
         }
+
     }
+
 }

+ 68 - 29
zookeeper-server/src/main/java/org/apache/zookeeper/OpResult.java

@@ -17,16 +17,15 @@
 
 package org.apache.zookeeper;
 
-
-import org.apache.zookeeper.data.Stat;
-
 import java.util.Arrays;
 import java.util.List;
+import org.apache.zookeeper.data.Stat;
 
 /**
  * Encodes the result of a single part of a multiple operation commit.
  */
 public abstract class OpResult {
+
     private int type;
 
     private OpResult(int type) {
@@ -50,11 +49,12 @@ public abstract class OpResult {
      * create.
      */
     public static class CreateResult extends OpResult {
+
         private String path;
         private Stat stat;
 
         public CreateResult(String path) {
-        	this(ZooDefs.OpCode.create, path, null);
+            this(ZooDefs.OpCode.create, path, null);
         }
 
         public CreateResult(String path, Stat stat) {
@@ -62,7 +62,7 @@ public abstract class OpResult {
         }
 
         private CreateResult(int opcode, String path, Stat stat) {
-        	super(opcode);
+            super(opcode);
             this.path = path;
             this.stat = stat;
         }
@@ -77,37 +77,47 @@ public abstract class OpResult {
 
         @Override
         public boolean equals(Object o) {
-            if (this == o) return true;
-            if (!(o instanceof CreateResult)) return false;
+            if (this == o) {
+                return true;
+            }
+            if (!(o instanceof CreateResult)) {
+                return false;
+            }
 
             CreateResult other = (CreateResult) o;
 
-            boolean statsAreEqual = (stat == null && other.stat == null ||
-                        						(stat != null && other.stat != null &&
-                        					   stat.getMzxid() == other.stat.getMzxid()));
-            return getType() == other.getType() &&
-                   path.equals(other.getPath()) && statsAreEqual;
+            boolean statsAreEqual = stat == null
+                                    && other.stat == null
+                                    || (stat != null
+                                        && other.stat != null
+                                        && stat.getMzxid() == other.stat.getMzxid());
+            return getType() == other.getType() && path.equals(other.getPath()) && statsAreEqual;
         }
 
         @Override
         public int hashCode() {
-            return (int) (getType() * 35 + path.hashCode() +
-                    (stat == null ? 0 : stat.getMzxid()));
+            return (int) (getType() * 35 + path.hashCode() + (stat == null ? 0 : stat.getMzxid()));
         }
+
     }
 
     /**
      * A result from a delete operation.  No special values are available.
      */
     public static class DeleteResult extends OpResult {
+
         public DeleteResult() {
             super(ZooDefs.OpCode.delete);
         }
 
         @Override
         public boolean equals(Object o) {
-            if (this == o) return true;
-            if (!(o instanceof DeleteResult)) return false;
+            if (this == o) {
+                return true;
+            }
+            if (!(o instanceof DeleteResult)) {
+                return false;
+            }
 
             DeleteResult opResult = (DeleteResult) o;
             return getType() == opResult.getType();
@@ -117,6 +127,7 @@ public abstract class OpResult {
         public int hashCode() {
             return getType();
         }
+
     }
 
     /**
@@ -124,6 +135,7 @@ public abstract class OpResult {
      * to the Stat structure from the update.
      */
     public static class SetDataResult extends OpResult {
+
         private Stat stat;
 
         public SetDataResult(Stat stat) {
@@ -137,8 +149,12 @@ public abstract class OpResult {
 
         @Override
         public boolean equals(Object o) {
-            if (this == o) return true;
-            if (!(o instanceof SetDataResult)) return false;
+            if (this == o) {
+                return true;
+            }
+            if (!(o instanceof SetDataResult)) {
+                return false;
+            }
 
             SetDataResult other = (SetDataResult) o;
             return getType() == other.getType() && stat.getMzxid() == other.stat.getMzxid();
@@ -148,20 +164,26 @@ public abstract class OpResult {
         public int hashCode() {
             return (int) (getType() * 35 + stat.getMzxid());
         }
+
     }
 
     /**
      * A result from a version check operation.  No special values are available.
      */
     public static class CheckResult extends OpResult {
+
         public CheckResult() {
             super(ZooDefs.OpCode.check);
         }
 
         @Override
         public boolean equals(Object o) {
-            if (this == o) return true;
-            if (!(o instanceof CheckResult)) return false;
+            if (this == o) {
+                return true;
+            }
+            if (!(o instanceof CheckResult)) {
+                return false;
+            }
 
             CheckResult other = (CheckResult) o;
             return getType() == other.getType();
@@ -171,6 +193,7 @@ public abstract class OpResult {
         public int hashCode() {
             return getType();
         }
+
     }
 
     /**
@@ -178,6 +201,7 @@ public abstract class OpResult {
      * the names of the children of a given node.
      */
     public static class GetChildrenResult extends OpResult {
+
         private List<String> children;
 
         public GetChildrenResult(List<String> children) {
@@ -191,8 +215,12 @@ public abstract class OpResult {
 
         @Override
         public boolean equals(Object o) {
-            if (this == o) return true;
-            if (!(o instanceof GetChildrenResult)) return false;
+            if (this == o) {
+                return true;
+            }
+            if (!(o instanceof GetChildrenResult)) {
+                return false;
+            }
 
             GetChildrenResult other = (GetChildrenResult) o;
             return getType() == other.getType() && children.equals(other.children);
@@ -202,6 +230,7 @@ public abstract class OpResult {
         public int hashCode() {
             return getType() * 35 + children.hashCode();
         }
+
     }
 
     /**
@@ -227,19 +256,22 @@ public abstract class OpResult {
 
         @Override
         public boolean equals(Object o) {
-            if (this == o) return true;
-            if (!(o instanceof GetDataResult)) return false;
+            if (this == o) {
+                return true;
+            }
+            if (!(o instanceof GetDataResult)) {
+                return false;
+            }
 
             GetDataResult other = (GetDataResult) o;
-            return getType() == other.getType()
-                    && stat.equals(other.stat)
-                    && Arrays.equals(data, other.data);
+            return getType() == other.getType() && stat.equals(other.stat) && Arrays.equals(data, other.data);
         }
 
         @Override
         public int hashCode() {
             return (int) (getType() * 35 + stat.getMzxid() + Arrays.hashCode(data));
         }
+
     }
 
     /**
@@ -249,6 +281,7 @@ public abstract class OpResult {
      *
      */
     public static class ErrorResult extends OpResult {
+
         private int err;
 
         public ErrorResult(int err) {
@@ -262,8 +295,12 @@ public abstract class OpResult {
 
         @Override
         public boolean equals(Object o) {
-            if (this == o) return true;
-            if (!(o instanceof ErrorResult)) return false;
+            if (this == o) {
+                return true;
+            }
+            if (!(o instanceof ErrorResult)) {
+                return false;
+            }
 
             ErrorResult other = (ErrorResult) o;
             return getType() == other.getType() && err == other.getErr();
@@ -273,5 +310,7 @@ public abstract class OpResult {
         public int hashCode() {
             return getType() * 35 + err;
         }
+
     }
+
 }

+ 4 - 5
zookeeper-server/src/main/java/org/apache/zookeeper/Quotas.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -51,8 +51,7 @@ public class Quotas {
      * @return the limit quota path
      */
     public static String quotaPath(String path) {
-        return quotaZookeeper + path +
-        "/" + limitNode;
+        return quotaZookeeper + path + "/" + limitNode;
     }
 
     /**
@@ -62,7 +61,7 @@ public class Quotas {
      * @return the stat quota path
      */
     public static String statPath(String path) {
-        return quotaZookeeper + path + "/" +
-        statNode;
+        return quotaZookeeper + path + "/" + statNode;
     }
+
 }

+ 27 - 28
zookeeper-server/src/main/java/org/apache/zookeeper/SaslClientCallbackHandler.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,6 +15,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper;
 
 import javax.security.auth.callback.Callback;
@@ -24,7 +25,6 @@ import javax.security.auth.callback.PasswordCallback;
 import javax.security.auth.callback.UnsupportedCallbackException;
 import javax.security.sasl.AuthorizeCallback;
 import javax.security.sasl.RealmCallback;
-
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -37,6 +37,7 @@ import org.slf4j.LoggerFactory;
  * org.apache.zookeeper.server.auth.SaslServerCallbackHandler.
  */
 public class SaslClientCallbackHandler implements CallbackHandler {
+
     private String password = null;
     private static final Logger LOG = LoggerFactory.getLogger(SaslClientCallbackHandler.class);
     private final String entity;
@@ -50,36 +51,32 @@ public class SaslClientCallbackHandler implements CallbackHandler {
             if (callback instanceof NameCallback) {
                 NameCallback nc = (NameCallback) callback;
                 nc.setName(nc.getDefaultName());
-            }
-            else {
+            } else {
                 if (callback instanceof PasswordCallback) {
-                    PasswordCallback pc = (PasswordCallback)callback;
+                    PasswordCallback pc = (PasswordCallback) callback;
                     if (password != null) {
                         pc.setPassword(this.password.toCharArray());
                     } else {
-                        LOG.warn("Could not login: the {} is being asked for a password, but the ZooKeeper {}" +
-                          " code does not currently support obtaining a password from the user." +
-                          " Make sure that the {} is configured to use a ticket cache (using" +
-                          " the JAAS configuration setting 'useTicketCache=true)' and restart the {}. If" +
-                          " you still get this message after that, the TGT in the ticket cache has expired and must" +
-                          " be manually refreshed. To do so, first determine if you are using a password or a" +
-                          " keytab. If the former, run kinit in a Unix shell in the environment of the user who" +
-                          " is running this Zookeeper {} using the command" +
-                          " 'kinit <princ>' (where <princ> is the name of the {}'s Kerberos principal)." +
-                          " If the latter, do" +
-                          " 'kinit -k -t <keytab> <princ>' (where <princ> is the name of the Kerberos principal, and" +
-                          " <keytab> is the location of the keytab file). After manually refreshing your cache," +
-                          " restart this {}. If you continue to see this message after manually refreshing" +
-                          " your cache, ensure that your KDC host's clock is in sync with this host's clock.",
-                          new Object[]{entity, entity, entity, entity, entity, entity, entity});
+                        LOG.warn("Could not login: the {} is being asked for a password, but the ZooKeeper {}"
+                                 + " code does not currently support obtaining a password from the user."
+                                 + " Make sure that the {} is configured to use a ticket cache (using"
+                                 + " the JAAS configuration setting 'useTicketCache=true)' and restart the {}. If"
+                                 + " you still get this message after that, the TGT in the ticket cache has expired and must"
+                                 + " be manually refreshed. To do so, first determine if you are using a password or a"
+                                 + " keytab. If the former, run kinit in a Unix shell in the environment of the user who"
+                                 + " is running this Zookeeper {} using the command"
+                                 + " 'kinit <princ>' (where <princ> is the name of the {}'s Kerberos principal)."
+                                 + " If the latter, do"
+                                 + " 'kinit -k -t <keytab> <princ>' (where <princ> is the name of the Kerberos principal, and"
+                                 + " <keytab> is the location of the keytab file). After manually refreshing your cache,"
+                                 + " restart this {}. If you continue to see this message after manually refreshing"
+                                 + " your cache, ensure that your KDC host's clock is in sync with this host's clock.", entity, entity, entity, entity, entity, entity, entity);
                     }
-                }
-                else {
+                } else {
                     if (callback instanceof RealmCallback) {
                         RealmCallback rc = (RealmCallback) callback;
                         rc.setText(rc.getDefaultText());
-                    }
-                    else {
+                    } else {
                         if (callback instanceof AuthorizeCallback) {
                             AuthorizeCallback ac = (AuthorizeCallback) callback;
                             String authid = ac.getAuthenticationID();
@@ -92,13 +89,15 @@ public class SaslClientCallbackHandler implements CallbackHandler {
                             if (ac.isAuthorized()) {
                                 ac.setAuthorizedID(authzid);
                             }
-                        }
-                        else {
-                            throw new UnsupportedCallbackException(callback, "Unrecognized SASL " + entity + "Callback");
+                        } else {
+                            throw new UnsupportedCallbackException(
+                                callback,
+                                "Unrecognized SASL " + entity + "Callback");
                         }
                     }
                 }
             }
         }
     }
-}
+
+}

+ 16 - 5
zookeeper-server/src/main/java/org/apache/zookeeper/SaslServerPrincipal.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,6 +15,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper;
 
 import java.net.InetAddress;
@@ -27,6 +28,7 @@ import org.slf4j.LoggerFactory;
  * Computes the Server Principal for a SASL client.
  */
 public class SaslServerPrincipal {
+
     private static final Logger LOG = LoggerFactory.getLogger(SaslServerPrincipal.class);
 
     /**
@@ -46,18 +48,22 @@ public class SaslServerPrincipal {
      * @return the name of the principal.
      */
     static String getServerPrincipal(WrapperInetSocketAddress addr, ZKClientConfig clientConfig) {
-        String principalUserName = clientConfig.getProperty(ZKClientConfig.ZK_SASL_CLIENT_USERNAME,
+        String principalUserName = clientConfig.getProperty(
+            ZKClientConfig.ZK_SASL_CLIENT_USERNAME,
             ZKClientConfig.ZK_SASL_CLIENT_USERNAME_DEFAULT);
         String hostName = addr.getHostName();
 
         boolean canonicalize = true;
-        String canonicalizeText = clientConfig.getProperty(ZKClientConfig.ZK_SASL_CLIENT_CANONICALIZE_HOSTNAME,
+        String canonicalizeText = clientConfig.getProperty(
+            ZKClientConfig.ZK_SASL_CLIENT_CANONICALIZE_HOSTNAME,
             ZKClientConfig.ZK_SASL_CLIENT_CANONICALIZE_HOSTNAME_DEFAULT);
         try {
             canonicalize = Boolean.parseBoolean(canonicalizeText);
         } catch (IllegalArgumentException ea) {
-            LOG.warn("Could not parse config {} \"{}\" into a boolean using default {}", ZKClientConfig
-                .ZK_SASL_CLIENT_CANONICALIZE_HOSTNAME, canonicalizeText, canonicalize);
+            LOG.warn("Could not parse config {} \"{}\" into a boolean using default {}",
+                     ZKClientConfig.ZK_SASL_CLIENT_CANONICALIZE_HOSTNAME,
+                     canonicalizeText,
+                     canonicalize);
         }
 
         if (canonicalize) {
@@ -82,6 +88,7 @@ public class SaslServerPrincipal {
      * InetSocketAddress are marked as final.
      */
     static class WrapperInetSocketAddress {
+
         private final InetSocketAddress addr;
 
         WrapperInetSocketAddress(InetSocketAddress addr) {
@@ -101,6 +108,7 @@ public class SaslServerPrincipal {
         public String toString() {
             return addr.toString();
         }
+
     }
 
     /**
@@ -108,6 +116,7 @@ public class SaslServerPrincipal {
      * InetAddress are marked as final.
      */
     static class WrapperInetAddress {
+
         private final InetAddress ia;
 
         WrapperInetAddress(InetAddress ia) {
@@ -126,5 +135,7 @@ public class SaslServerPrincipal {
         public String toString() {
             return ia.toString();
         }
+
     }
+
 }

+ 9 - 10
zookeeper-server/src/main/java/org/apache/zookeeper/ServerAdminClient.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -24,13 +24,13 @@ import java.io.OutputStream;
 import java.net.InetSocketAddress;
 import java.net.Socket;
 import java.nio.ByteBuffer;
-
 import org.apache.yetus.audience.InterfaceAudience;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 @InterfaceAudience.Public
 public class ServerAdminClient {
+
     private static final Logger LOG = LoggerFactory.getLogger(ServerAdminClient.class);
 
     public static void ruok(String host, int port) {
@@ -192,9 +192,9 @@ public class ServerAdminClient {
             int rc = is.read(resBytes);
             ByteBuffer res = ByteBuffer.wrap(resBytes);
             long retv = res.getLong();
-            System.out.println("rc=" + rc + " retv=0"
-                    + Long.toOctalString(retv) + " masks=0"
-                    + Long.toOctalString(traceMask));
+            System.out.println("rc=" + rc
+                               + " retv=0" + Long.toOctalString(retv)
+                               + " masks=0" + Long.toOctalString(traceMask));
             assert (retv == traceMask);
         } catch (IOException e) {
             LOG.warn("Unexpected exception", e);
@@ -231,8 +231,7 @@ public class ServerAdminClient {
             int rc = is.read(resBytes);
             ByteBuffer res = ByteBuffer.wrap(resBytes);
             long retv = res.getLong();
-            System.out.println("rc=" + rc + " retv=0"
-                    + Long.toOctalString(retv));
+            System.out.println("rc=" + rc + " retv=0" + Long.toOctalString(retv));
         } catch (IOException e) {
             LOG.warn("Unexpected exception", e);
         } finally {
@@ -247,9 +246,8 @@ public class ServerAdminClient {
     }
 
     private static void usage() {
-        System.out
-                .println("usage: java [-cp CLASSPATH] org.apache.zookeeper.ServerAdminClient "
-                        + "host port op (ruok|stat|dump|kill|gettracemask|settracemask) [arguments]");
+        System.out.println("usage: java [-cp CLASSPATH] org.apache.zookeeper.ServerAdminClient "
+                           + "host port op (ruok|stat|dump|kill|gettracemask|settracemask) [arguments]");
 
     }
 
@@ -277,4 +275,5 @@ public class ServerAdminClient {
             System.out.println("Unrecognized op: " + op);
         }
     }
+
 }

+ 399 - 408
zookeeper-server/src/main/java/org/apache/zookeeper/Shell.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -17,16 +17,15 @@
  */
 
 /* This file copied from Hadoop's security branch,
-  * with the following changes:
-  * 1. package changed from org.apache.hadoop.util to
-  *    org.apache.zookeeper.
-  * 2. Usage of Hadoop's Configuration class removed since
-  *    it is not available in Zookeeper: instead, system properties
-  *    are used.
-  * 3. The deprecated getUlimitMemoryCommand() method removed since
-  *    it is not needed.
-  */
-
+ * with the following changes:
+ * 1. package changed from org.apache.hadoop.util to
+ *    org.apache.zookeeper.
+ * 2. Usage of Hadoop's Configuration class removed since
+ *    it is not available in Zookeeper: instead, system properties
+ *    are used.
+ * 3. The deprecated getUlimitMemoryCommand() method removed since
+ *    it is not needed.
+ */
 
 package org.apache.zookeeper;
 
@@ -38,7 +37,6 @@ import java.util.Map;
 import java.util.Timer;
 import java.util.TimerTask;
 import java.util.concurrent.atomic.AtomicBoolean;
-
 import org.apache.zookeeper.common.Time;
 import org.apache.zookeeper.server.ExitCode;
 import org.slf4j.Logger;
@@ -48,433 +46,426 @@ import org.slf4j.LoggerFactory;
  * A base class for running a Unix command.
  *
  * <code>Shell</code> can be used to run unix commands like <code>du</code> or
- * <code>df</code>. It also offers facilities to gate commands by 
+ * <code>df</code>. It also offers facilities to gate commands by
  * time-intervals.
  */
-abstract public class Shell {
-  
+public abstract class Shell {
+
     private static final Logger LOG = LoggerFactory.getLogger(Shell.class);
-  
-  /** a Unix command to get the current user's name */
-  public final static String USER_NAME_COMMAND = "whoami";
-  /** a Unix command to get the current user's groups list */
-  public static String[] getGroupsCommand() {
-    return new String[]{"bash", "-c", "groups"};
-  }
-  /** a Unix command to get a given user's groups list */
-  public static String[] getGroupsForUserCommand(final String user) {
-    //'groups username' command return is non-consistent across different unixes
-    return new String [] {"bash", "-c", "id -Gn " + user};
-  }
-  /** a Unix command to set permission */
-  public static final String SET_PERMISSION_COMMAND = "chmod";
-  /** a Unix command to set owner */
-  public static final String SET_OWNER_COMMAND = "chown";
-  public static final String SET_GROUP_COMMAND = "chgrp";
-  /** Return a Unix command to get permission information. */
-  public static String[] getGET_PERMISSION_COMMAND() {
-    //force /bin/ls, except on windows.
-    return new String[] {(WINDOWS ? "ls" : "/bin/ls"), "-ld"};
-  }
-
-  /**Time after which the executing script would be timedout*/
-  protected long timeOutInterval = 0L;
-  /** If or not script timed out*/
-  private AtomicBoolean timedOut;
-
-  /** a Unix command to get ulimit of a process. */
-  public static final String ULIMIT_COMMAND = "ulimit";
-  
-  /** 
-   * Get the Unix command for setting the maximum virtual memory available
-   * to a given child process. This is only relevant when we are forking a
-   * process from within the Mapper or the Reducer implementations.
-   * Also see Hadoop Pipes and Hadoop Streaming.
-   * 
-   * It also checks to ensure that we are running on a *nix platform else 
-   * (e.g. in Cygwin/Windows) it returns <code>null</code>.
-   * @param memoryLimit virtual memory limit
-   * @return a <code>String[]</code> with the ulimit command arguments or 
-   *         <code>null</code> if we are running on a non *nix platform or
-   *         if the limit is unspecified.
-   */
-  public static String[] getUlimitMemoryCommand(int memoryLimit) {
-    // ulimit isn't supported on Windows
-    if (WINDOWS) {
-      return null;
+
+    /** a Unix command to get the current user's name */
+    public static final String USER_NAME_COMMAND = "whoami";
+    /** a Unix command to get the current user's groups list */
+    public static String[] getGroupsCommand() {
+        return new String[]{"bash", "-c", "groups"};
+    }
+    /** a Unix command to get a given user's groups list */
+    public static String[] getGroupsForUserCommand(final String user) {
+        //'groups username' command return is non-consistent across different unixes
+        return new String[]{"bash", "-c", "id -Gn " + user};
+    }
+    /** a Unix command to set permission */
+    public static final String SET_PERMISSION_COMMAND = "chmod";
+    /** a Unix command to set owner */
+    public static final String SET_OWNER_COMMAND = "chown";
+    public static final String SET_GROUP_COMMAND = "chgrp";
+    /** Return a Unix command to get permission information. */
+    public static String[] getGET_PERMISSION_COMMAND() {
+        //force /bin/ls, except on windows.
+        return new String[]{(WINDOWS ? "ls" : "/bin/ls"), "-ld"};
+    }
+
+    /**Time after which the executing script would be timedout*/
+    protected long timeOutInterval = 0L;
+    /** If or not script timed out*/
+    private AtomicBoolean timedOut;
+
+    /** a Unix command to get ulimit of a process. */
+    public static final String ULIMIT_COMMAND = "ulimit";
+
+    /**
+     * Get the Unix command for setting the maximum virtual memory available
+     * to a given child process. This is only relevant when we are forking a
+     * process from within the Mapper or the Reducer implementations.
+     * Also see Hadoop Pipes and Hadoop Streaming.
+     *
+     * It also checks to ensure that we are running on a *nix platform else
+     * (e.g. in Cygwin/Windows) it returns <code>null</code>.
+     * @param memoryLimit virtual memory limit
+     * @return a <code>String[]</code> with the ulimit command arguments or
+     *         <code>null</code> if we are running on a non *nix platform or
+     *         if the limit is unspecified.
+     */
+    public static String[] getUlimitMemoryCommand(int memoryLimit) {
+        // ulimit isn't supported on Windows
+        if (WINDOWS) {
+            return null;
+        }
+
+        return new String[]{ULIMIT_COMMAND, "-v", String.valueOf(memoryLimit)};
+    }
+
+    /** Set to true on Windows platforms */
+    public static final boolean WINDOWS /* borrowed from Path.WINDOWS */ = System.getProperty("os.name").startsWith("Windows");
+
+    private long interval;   // refresh interval in msec
+    private long lastTime;   // last time the command was performed
+    private Map<String, String> environment; // env for the command execution
+    private File dir;
+    private Process process; // sub process used to execute the command
+    private int exitCode;
+
+    /**If or not script finished executing*/
+    private volatile AtomicBoolean completed;
+
+    public Shell() {
+        this(0L);
+    }
+
+    /**
+     * @param interval the minimum duration to wait before re-executing the
+     *        command.
+     */
+    public Shell(long interval) {
+        this.interval = interval;
+        this.lastTime = (interval < 0) ? 0 : -interval;
     }
-    
-    return new String[] {ULIMIT_COMMAND, "-v", String.valueOf(memoryLimit)};
-  }
-
-  /** Set to true on Windows platforms */
-  public static final boolean WINDOWS /* borrowed from Path.WINDOWS */
-                = System.getProperty("os.name").startsWith("Windows");
-  
-  private long    interval;   // refresh interval in msec
-  private long    lastTime;   // last time the command was performed
-  private Map<String, String> environment; // env for the command execution
-  private File dir;
-  private Process process; // sub process used to execute the command
-  private int exitCode;
-
-  /**If or not script finished executing*/
-  private volatile AtomicBoolean completed;
-  
-  public Shell() {
-    this(0L);
-  }
-  
-  /**
-   * @param interval the minimum duration to wait before re-executing the 
-   *        command.
-   */
-  public Shell( long interval ) {
-    this.interval = interval;
-    this.lastTime = (interval<0) ? 0 : -interval;
-  }
-  
-  /** set the environment for the command 
-   * @param env Mapping of environment variables
-   */
-  protected void setEnvironment(Map<String, String> env) {
-    this.environment = env;
-  }
-
-  /** set the working directory 
-   * @param dir The directory where the command would be executed
-   */
-  protected void setWorkingDirectory(File dir) {
-    this.dir = dir;
-  }
-
-  /** check to see if a command needs to be executed and execute if needed */
-  protected void run() throws IOException {
-    if (lastTime + interval > Time.currentElapsedTime())
-      return;
-    exitCode = ExitCode.EXECUTION_FINISHED.getValue(); // reset for next run
-    runCommand();
-  }
-
-  /** Run a command */
-  private void runCommand() throws IOException { 
-    ProcessBuilder builder = new ProcessBuilder(getExecString());
-    Timer timeOutTimer = null;
-    ShellTimeoutTimerTask timeoutTimerTask = null;
-    timedOut = new AtomicBoolean(false);
-    completed = new AtomicBoolean(false);
-    
-    if (environment != null) {
-      builder.environment().putAll(this.environment);
+
+    /** set the environment for the command
+     * @param env Mapping of environment variables
+     */
+    protected void setEnvironment(Map<String, String> env) {
+        this.environment = env;
     }
-    if (dir != null) {
-      builder.directory(this.dir);
+
+    /** set the working directory
+     * @param dir The directory where the command would be executed
+     */
+    protected void setWorkingDirectory(File dir) {
+        this.dir = dir;
     }
-    
-    process = builder.start();
-    if (timeOutInterval > 0) {
-      timeOutTimer = new Timer();
-      timeoutTimerTask = new ShellTimeoutTimerTask(
-          this);
-      //One time scheduling.
-      timeOutTimer.schedule(timeoutTimerTask, timeOutInterval);
+
+    /** check to see if a command needs to be executed and execute if needed */
+    protected void run() throws IOException {
+        if (lastTime + interval > Time.currentElapsedTime()) {
+            return;
+        }
+        exitCode = ExitCode.EXECUTION_FINISHED.getValue(); // reset for next run
+        runCommand();
     }
-    final BufferedReader errReader = 
-            new BufferedReader(new InputStreamReader(process
-                                                     .getErrorStream()));
-    BufferedReader inReader = 
-            new BufferedReader(new InputStreamReader(process
-                                                     .getInputStream()));
-    final StringBuffer errMsg = new StringBuffer();
-    
-    // read error and input streams as this would free up the buffers
-    // free the error stream buffer
-    Thread errThread = new Thread() {
-      @Override
-      public void run() {
+
+    /** Run a command */
+    private void runCommand() throws IOException {
+        ProcessBuilder builder = new ProcessBuilder(getExecString());
+        Timer timeOutTimer = null;
+        ShellTimeoutTimerTask timeoutTimerTask = null;
+        timedOut = new AtomicBoolean(false);
+        completed = new AtomicBoolean(false);
+
+        if (environment != null) {
+            builder.environment().putAll(this.environment);
+        }
+        if (dir != null) {
+            builder.directory(this.dir);
+        }
+
+        process = builder.start();
+        if (timeOutInterval > 0) {
+            timeOutTimer = new Timer();
+            timeoutTimerTask = new ShellTimeoutTimerTask(this);
+            //One time scheduling.
+            timeOutTimer.schedule(timeoutTimerTask, timeOutInterval);
+        }
+        final BufferedReader errReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
+        BufferedReader inReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
+        final StringBuffer errMsg = new StringBuffer();
+
+        // read error and input streams as this would free up the buffers
+        // free the error stream buffer
+        Thread errThread = new Thread() {
+            @Override
+            public void run() {
+                try {
+                    String line = errReader.readLine();
+                    while ((line != null) && !isInterrupted()) {
+                        errMsg.append(line);
+                        errMsg.append(System.getProperty("line.separator"));
+                        line = errReader.readLine();
+                    }
+                } catch (IOException ioe) {
+                    LOG.warn("Error reading the error stream", ioe);
+                }
+            }
+        };
+        try {
+            errThread.start();
+        } catch (IllegalStateException ise) {
+        }
         try {
-          String line = errReader.readLine();
-          while((line != null) && !isInterrupted()) {
-            errMsg.append(line);
-            errMsg.append(System.getProperty("line.separator"));
-            line = errReader.readLine();
-          }
-        } catch(IOException ioe) {
-          LOG.warn("Error reading the error stream", ioe);
+            parseExecResult(inReader); // parse the output
+            // clear the input stream buffer
+            String line = inReader.readLine();
+            while (line != null) {
+                line = inReader.readLine();
+            }
+            // wait for the process to finish and check the exit code
+            exitCode = process.waitFor();
+            try {
+                // make sure that the error thread exits
+                errThread.join();
+            } catch (InterruptedException ie) {
+                LOG.warn("Interrupted while reading the error stream", ie);
+            }
+            completed.set(true);
+            //the timeout thread handling
+            //taken care in finally block
+            if (exitCode != ExitCode.EXECUTION_FINISHED.getValue()) {
+                throw new ExitCodeException(exitCode, errMsg.toString());
+            }
+        } catch (InterruptedException ie) {
+            throw new IOException(ie.toString());
+        } finally {
+            if ((timeOutTimer != null) && !timedOut.get()) {
+                timeOutTimer.cancel();
+            }
+            // close the input stream
+            try {
+                inReader.close();
+            } catch (IOException ioe) {
+                LOG.warn("Error while closing the input stream", ioe);
+            }
+            if (!completed.get()) {
+                errThread.interrupt();
+            }
+            try {
+                errReader.close();
+            } catch (IOException ioe) {
+                LOG.warn("Error while closing the error stream", ioe);
+            }
+            process.destroy();
+            lastTime = Time.currentElapsedTime();
         }
-      }
-    };
-    try {
-      errThread.start();
-    } catch (IllegalStateException ise) { }
-    try {
-      parseExecResult(inReader); // parse the output
-      // clear the input stream buffer
-      String line = inReader.readLine();
-      while(line != null) { 
-        line = inReader.readLine();
-      }
-      // wait for the process to finish and check the exit code
-      exitCode  = process.waitFor();
-      try {
-        // make sure that the error thread exits
-        errThread.join();
-      } catch (InterruptedException ie) {
-        LOG.warn("Interrupted while reading the error stream", ie);
-      }
-      completed.set(true);
-      //the timeout thread handling
-      //taken care in finally block
-      if (exitCode != ExitCode.EXECUTION_FINISHED.getValue()) {
-        throw new ExitCodeException(exitCode, errMsg.toString());
-      }
-    } catch (InterruptedException ie) {
-      throw new IOException(ie.toString());
-    } finally {
-      if ((timeOutTimer!=null) && !timedOut.get()) {
-        timeOutTimer.cancel();
-      }
-      // close the input stream
-      try {
-        inReader.close();
-      } catch (IOException ioe) {
-        LOG.warn("Error while closing the input stream", ioe);
-      }
-      if (!completed.get()) {
-        errThread.interrupt();
-      }
-      try {
-        errReader.close();
-      } catch (IOException ioe) {
-        LOG.warn("Error while closing the error stream", ioe);
-      }
-      process.destroy();
-      lastTime = Time.currentElapsedTime();
     }
-  }
-
-  /** return an array containing the command name and its parameters */ 
-  protected abstract String[] getExecString();
-  
-  /** Parse the execution result */
-  protected abstract void parseExecResult(BufferedReader lines)
-  throws IOException;
-
-  /** get the current sub-process executing the given command 
-   * @return process executing the command
-   */
-  public Process getProcess() {
-    return process;
-  }
-
-  /** get the exit code 
-   * @return the exit code of the process
-   */
-  public int getExitCode() {
-    return exitCode;
-  }
-
-  /**
-   * This is an IOException with exit code added.
-   */
-  @SuppressWarnings("serial")
-  public static class ExitCodeException extends IOException {
-    int exitCode;
-    
-    public ExitCodeException(int exitCode, String message) {
-      super(message);
-      this.exitCode = exitCode;
+
+    /** return an array containing the command name and its parameters */
+    protected abstract String[] getExecString();
+
+    /** Parse the execution result */
+    protected abstract void parseExecResult(BufferedReader lines) throws IOException;
+
+    /** get the current sub-process executing the given command
+     * @return process executing the command
+     */
+    public Process getProcess() {
+        return process;
     }
-    
+
+    /** get the exit code
+     * @return the exit code of the process
+     */
     public int getExitCode() {
-      return exitCode;
+        return exitCode;
     }
-  }
-  
-  /**
-   * A simple shell command executor.
-   * 
-   * <code>ShellCommandExecutor</code>should be used in cases where the output 
-   * of the command needs no explicit parsing and where the command, working 
-   * directory and the environment remains unchanged. The output of the command 
-   * is stored as-is and is expected to be small.
-   */
-  public static class ShellCommandExecutor extends Shell {
-    
-    private String[] command;
-    private StringBuffer output;
-    
-    
-    public ShellCommandExecutor(String[] execString) {
-      this(execString, null);
-    }
-    
-    public ShellCommandExecutor(String[] execString, File dir) {
-      this(execString, dir, null);
+
+    /**
+     * This is an IOException with exit code added.
+     */
+    @SuppressWarnings("serial")
+    public static class ExitCodeException extends IOException {
+
+        int exitCode;
+
+        public ExitCodeException(int exitCode, String message) {
+            super(message);
+            this.exitCode = exitCode;
+        }
+
+        public int getExitCode() {
+            return exitCode;
+        }
+
     }
-   
-    public ShellCommandExecutor(String[] execString, File dir, 
-                                 Map<String, String> env) {
-      this(execString, dir, env , 0L);
+
+    /**
+     * A simple shell command executor.
+     *
+     * <code>ShellCommandExecutor</code>should be used in cases where the output
+     * of the command needs no explicit parsing and where the command, working
+     * directory and the environment remains unchanged. The output of the command
+     * is stored as-is and is expected to be small.
+     */
+    public static class ShellCommandExecutor extends Shell {
+
+        private String[] command;
+        private StringBuffer output;
+
+        public ShellCommandExecutor(String[] execString) {
+            this(execString, null);
+        }
+
+        public ShellCommandExecutor(String[] execString, File dir) {
+            this(execString, dir, null);
+        }
+
+        public ShellCommandExecutor(String[] execString, File dir, Map<String, String> env) {
+            this(execString, dir, env, 0L);
+        }
+
+        /**
+         * Create a new instance of the ShellCommandExecutor to execute a command.
+         *
+         * @param execString The command to execute with arguments
+         * @param dir If not-null, specifies the directory which should be set
+         *            as the current working directory for the command.
+         *            If null, the current working directory is not modified.
+         * @param env If not-null, environment of the command will include the
+         *            key-value pairs specified in the map. If null, the current
+         *            environment is not modified.
+         * @param timeout Specifies the time in milliseconds, after which the
+         *                command will be killed and the status marked as timedout.
+         *                If 0, the command will not be timed out.
+         */
+        public ShellCommandExecutor(String[] execString, File dir, Map<String, String> env, long timeout) {
+            command = execString.clone();
+            if (dir != null) {
+                setWorkingDirectory(dir);
+            }
+            if (env != null) {
+                setEnvironment(env);
+            }
+            timeOutInterval = timeout;
+        }
+
+        /** Execute the shell command. */
+        public void execute() throws IOException {
+            this.run();
+        }
+
+        protected String[] getExecString() {
+            return command;
+        }
+
+        protected void parseExecResult(BufferedReader lines) throws IOException {
+            output = new StringBuffer();
+            char[] buf = new char[512];
+            int nRead;
+            while ((nRead = lines.read(buf, 0, buf.length)) > 0) {
+                output.append(buf, 0, nRead);
+            }
+        }
+
+        /** Get the output of the shell command.*/
+        public String getOutput() {
+            return (output == null) ? "" : output.toString();
+        }
+
+        /**
+         * Returns the commands of this instance.
+         * Arguments with spaces in are presented with quotes round; other
+         * arguments are presented raw
+         *
+         * @return a string representation of the object.
+         */
+        public String toString() {
+            StringBuilder builder = new StringBuilder();
+            String[] args = getExecString();
+            for (String s : args) {
+                if (s.indexOf(' ') >= 0) {
+                    builder.append('"').append(s).append('"');
+                } else {
+                    builder.append(s);
+                }
+                builder.append(' ');
+            }
+            return builder.toString();
+        }
+
     }
 
     /**
-     * Create a new instance of the ShellCommandExecutor to execute a command.
-     * 
-     * @param execString The command to execute with arguments
-     * @param dir If not-null, specifies the directory which should be set
-     *            as the current working directory for the command.
-     *            If null, the current working directory is not modified.
-     * @param env If not-null, environment of the command will include the
-     *            key-value pairs specified in the map. If null, the current
-     *            environment is not modified.
-     * @param timeout Specifies the time in milliseconds, after which the
-     *                command will be killed and the status marked as timedout.
-     *                If 0, the command will not be timed out. 
+     * To check if the passed script to shell command executor timed out or
+     * not.
+     *
+     * @return if the script timed out.
      */
-    public ShellCommandExecutor(String[] execString, File dir, 
-        Map<String, String> env, long timeout) {
-      command = execString.clone();
-      if (dir != null) {
-        setWorkingDirectory(dir);
-      }
-      if (env != null) {
-        setEnvironment(env);
-      }
-      timeOutInterval = timeout;
+    public boolean isTimedOut() {
+        return timedOut.get();
     }
-        
 
-    /** Execute the shell command. */
-    public void execute() throws IOException {
-      this.run();    
+    /**
+     * Set if the command has timed out.
+     *
+     */
+    private void setTimedOut() {
+        this.timedOut.set(true);
     }
 
-    protected String[] getExecString() {
-      return command;
+    /**
+     * Static method to execute a shell command.
+     * Covers most of the simple cases without requiring the user to implement
+     * the <code>Shell</code> interface.
+     * @param cmd shell command to execute.
+     * @return the output of the executed command.
+     */
+    public static String execCommand(String... cmd) throws IOException {
+        return execCommand(null, cmd, 0L);
     }
 
-    protected void parseExecResult(BufferedReader lines) throws IOException {
-      output = new StringBuffer();
-      char[] buf = new char[512];
-      int nRead;
-      while ( (nRead = lines.read(buf, 0, buf.length)) > 0 ) {
-        output.append(buf, 0, nRead);
-      }
+    /**
+     * Static method to execute a shell command.
+     * Covers most of the simple cases without requiring the user to implement
+     * the <code>Shell</code> interface.
+     * @param env the map of environment key=value
+     * @param cmd shell command to execute.
+     * @param timeout time in milliseconds after which script should be marked timeout
+     * @return the output of the executed command.o
+     */
+
+    public static String execCommand(Map<String, String> env, String[] cmd, long timeout) throws IOException {
+        ShellCommandExecutor exec = new ShellCommandExecutor(cmd, null, env, timeout);
+        exec.execute();
+        return exec.getOutput();
     }
-    
-    /** Get the output of the shell command.*/
-    public String getOutput() {
-      return (output == null) ? "" : output.toString();
+
+    /**
+     * Static method to execute a shell command.
+     * Covers most of the simple cases without requiring the user to implement
+     * the <code>Shell</code> interface.
+     * @param env the map of environment key=value
+     * @param cmd shell command to execute.
+     * @return the output of the executed command.
+     */
+    public static String execCommand(Map<String, String> env, String... cmd) throws IOException {
+        return execCommand(env, cmd, 0L);
     }
 
     /**
-     * Returns the commands of this instance.
-     * Arguments with spaces in are presented with quotes round; other
-     * arguments are presented raw
-     *
-     * @return a string representation of the object.
+     * Timer which is used to timeout scripts spawned off by shell.
      */
-    public String toString() {
-      StringBuilder builder = new StringBuilder();
-      String[] args = getExecString();
-      for (String s : args) {
-        if (s.indexOf(' ') >= 0) {
-          builder.append('"').append(s).append('"');
-        } else {
-          builder.append(s);
+    private static class ShellTimeoutTimerTask extends TimerTask {
+
+        private Shell shell;
+
+        public ShellTimeoutTimerTask(Shell shell) {
+            this.shell = shell;
         }
-        builder.append(' ');
-      }
-      return builder.toString();
-    }
-  }
-  
-  /**
-   * To check if the passed script to shell command executor timed out or
-   * not.
-   * 
-   * @return if the script timed out.
-   */
-  public boolean isTimedOut() {
-    return timedOut.get();
-  }
-  
-  /**
-   * Set if the command has timed out.
-   * 
-   */
-  private void setTimedOut() {
-    this.timedOut.set(true);
-  }
-  
-  /** 
-   * Static method to execute a shell command. 
-   * Covers most of the simple cases without requiring the user to implement  
-   * the <code>Shell</code> interface.
-   * @param cmd shell command to execute.
-   * @return the output of the executed command.
-   */
-  public static String execCommand(String ... cmd) throws IOException {
-    return execCommand(null, cmd, 0L);
-  }
-  
-  /** 
-   * Static method to execute a shell command. 
-   * Covers most of the simple cases without requiring the user to implement  
-   * the <code>Shell</code> interface.
-   * @param env the map of environment key=value
-   * @param cmd shell command to execute.
-   * @param timeout time in milliseconds after which script should be marked timeout
-   * @return the output of the executed command.o
-   */
-  
-  public static String execCommand(Map<String, String> env, String[] cmd,
-      long timeout) throws IOException {
-    ShellCommandExecutor exec = new ShellCommandExecutor(cmd, null, env, 
-                                                          timeout);
-    exec.execute();
-    return exec.getOutput();
-  }
-
-  /** 
-   * Static method to execute a shell command. 
-   * Covers most of the simple cases without requiring the user to implement  
-   * the <code>Shell</code> interface.
-   * @param env the map of environment key=value
-   * @param cmd shell command to execute.
-   * @return the output of the executed command.
-   */
-  public static String execCommand(Map<String,String> env, String ... cmd) 
-  throws IOException {
-    return execCommand(env, cmd, 0L);
-  }
-  
-  /**
-   * Timer which is used to timeout scripts spawned off by shell.
-   */
-  private static class ShellTimeoutTimerTask extends TimerTask {
-
-    private Shell shell;
-
-    public ShellTimeoutTimerTask(Shell shell) {
-      this.shell = shell;
-    }
 
-    @Override
-    public void run() {
-      Process p = shell.getProcess();
-      try {
-        p.exitValue();
-      } catch (Exception e) {
-        //Process has not terminated.
-        //So check if it has completed 
-        //if not just destroy it.
-        if (p != null && !shell.completed.get()) {
-          shell.setTimedOut();
-          p.destroy();
+        @Override
+        public void run() {
+            Process p = shell.getProcess();
+            try {
+                p.exitValue();
+            } catch (Exception e) {
+                //Process has not terminated.
+                //So check if it has completed
+                //if not just destroy it.
+                if (p != null && !shell.completed.get()) {
+                    shell.setTimedOut();
+                    p.destroy();
+                }
+            }
         }
-      }
+
     }
-  }
+
 }

+ 4 - 4
zookeeper-server/src/main/java/org/apache/zookeeper/StatsTrack.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -22,6 +22,7 @@ package org.apache.zookeeper;
  * a class that represents the stats associated with quotas
  */
 public class StatsTrack {
+
     private int count;
     private long bytes;
     private String countStr = "count";
@@ -52,7 +53,6 @@ public class StatsTrack {
         bytes = Long.parseLong(split[1].split("=")[1]);
     }
 
-
     /**
      * get the count of nodes allowed as part of quota
      *
@@ -94,8 +94,8 @@ public class StatsTrack {
     @Override
     /*
      * returns the string that maps to this stat tracking.
-     */
-    public String toString() {
+     */ public String toString() {
         return countStr + "=" + count + "," + byteStr + "=" + bytes;
     }
+
 }

+ 3 - 1
zookeeper-server/src/main/java/org/apache/zookeeper/Testable.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -22,6 +22,7 @@ package org.apache.zookeeper;
  * Abstraction that exposes various methods useful for testing ZooKeeper
  */
 public interface Testable {
+
     /**
      * Cause the ZooKeeper instance to behave as if the session expired
      */
@@ -33,4 +34,5 @@ public interface Testable {
      * @param event event to insert
      */
     void queueEvent(WatchedEvent event);
+
 }

+ 6 - 5
zookeeper-server/src/main/java/org/apache/zookeeper/Transaction.java

@@ -17,11 +17,11 @@
 
 package org.apache.zookeeper;
 
+import java.util.ArrayList;
+import java.util.List;
 import org.apache.yetus.audience.InterfaceAudience;
 import org.apache.zookeeper.AsyncCallback.MultiCallback;
 import org.apache.zookeeper.data.ACL;
-import java.util.ArrayList;
-import java.util.List;
 
 /**
  * Provides a builder style interface for doing multiple updates.  This is
@@ -32,6 +32,7 @@ import java.util.List;
  */
 @InterfaceAudience.Public
 public class Transaction {
+
     private ZooKeeper zk;
     private List<Op> ops = new ArrayList<Op>();
 
@@ -39,8 +40,7 @@ public class Transaction {
         this.zk = zk;
     }
 
-    public Transaction create(final String path, byte data[], List<ACL> acl,
-                              CreateMode createMode) {
+    public Transaction create(final String path, byte[] data, List<ACL> acl, CreateMode createMode) {
         ops.add(Op.create(path, data, acl, createMode.toFlag()));
         return this;
     }
@@ -55,7 +55,7 @@ public class Transaction {
         return this;
     }
 
-    public Transaction setData(final String path, byte data[], int version) {
+    public Transaction setData(final String path, byte[] data, int version) {
         ops.add(Op.setData(path, data, version));
         return this;
     }
@@ -67,4 +67,5 @@ public class Transaction {
     public void commit(MultiCallback cb, Object ctx) {
         zk.multi(ops, cb, ctx);
     }
+
 }

+ 12 - 13
zookeeper-server/src/main/java/org/apache/zookeeper/Version.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -31,11 +31,9 @@ public class Version implements org.apache.zookeeper.version.Info {
         return BUILD_DATE;
     }
 
-    @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE",
-            justification = "Missing QUALIFIER causes redundant null-check")
+    @SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_OF_NULL_VALUE", justification = "Missing QUALIFIER causes redundant null-check")
     public static String getVersion() {
-        return MAJOR + "." + MINOR + "." + MICRO
-            + (QUALIFIER == null ? "" : "-" + QUALIFIER);
+        return MAJOR + "." + MINOR + "." + MICRO + (QUALIFIER == null ? "" : "-" + QUALIFIER);
     }
 
     public static String getVersionRevision() {
@@ -47,16 +45,15 @@ public class Version implements org.apache.zookeeper.version.Info {
     }
 
     public static void printUsage() {
-        System.out
-                .print("Usage:\tjava -cp ... org.apache.zookeeper.Version "
-                        + "[--full | --short | --revision],\n\tPrints --full version "
-                        + "info if no arg specified.");
+        System.out.print("Usage:\tjava -cp ... org.apache.zookeeper.Version "
+                         + "[--full | --short | --revision],\n\tPrints --full version "
+                         + "info if no arg specified.");
         System.exit(ExitCode.UNEXPECTED_ERROR.getValue());
     }
 
     /**
      * Prints the current version, revision and build date to the standard out.
-     * 
+     *
      * @param args
      *            <ul>
      *            <li> --short - prints a short version string "1.2.3"
@@ -73,12 +70,14 @@ public class Version implements org.apache.zookeeper.version.Info {
             System.out.println(getFullVersion());
             System.exit(ExitCode.EXECUTION_FINISHED.getValue());
         }
-        if (args[0].equals("--short"))
+        if (args[0].equals("--short")) {
             System.out.println(getVersion());
-        else if (args[0].equals("--revision"))
+        } else if (args[0].equals("--revision")) {
             System.out.println(getVersionRevision());
-        else
+        } else {
             printUsage();
+        }
         System.exit(ExitCode.EXECUTION_FINISHED.getValue());
     }
+
 }

+ 13 - 11
zookeeper-server/src/main/java/org/apache/zookeeper/WatchDeregistration.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -20,9 +20,8 @@ package org.apache.zookeeper;
 
 import java.util.Map;
 import java.util.Set;
-
-import org.apache.zookeeper.Watcher.WatcherType;
 import org.apache.zookeeper.Watcher.Event.EventType;
+import org.apache.zookeeper.Watcher.WatcherType;
 import org.apache.zookeeper.ZooKeeper.ZKWatchManager;
 
 /**
@@ -37,8 +36,12 @@ public class WatchDeregistration {
     private final boolean local;
     private final ZKWatchManager zkManager;
 
-    public WatchDeregistration(String clientPath, Watcher watcher,
-            WatcherType watcherType, boolean local, ZKWatchManager zkManager) {
+    public WatchDeregistration(
+        String clientPath,
+        Watcher watcher,
+        WatcherType watcherType,
+        boolean local,
+        ZKWatchManager zkManager) {
         this.clientPath = clientPath;
         this.watcher = watcher;
         this.watcherType = watcherType;
@@ -48,23 +51,22 @@ public class WatchDeregistration {
 
     /**
      * Unregistering watcher that was added on path.
-     * 
+     *
      * @param rc
      *            the result code of the operation that attempted to remove
      *            watch on the path.
      */
-    public Map<EventType, Set<Watcher>> unregister(int rc)
-            throws KeeperException {
-        return zkManager.removeWatcher(clientPath, watcher, watcherType, local,
-                rc);
+    public Map<EventType, Set<Watcher>> unregister(int rc) throws KeeperException {
+        return zkManager.removeWatcher(clientPath, watcher, watcherType, local, rc);
     }
 
     /**
      * Returns client path which has specified for unregistering its watcher
-     * 
+     *
      * @return client path
      */
     public String getClientPath() {
         return clientPath;
     }
+
 }

+ 14 - 14
zookeeper-server/src/main/java/org/apache/zookeeper/WatchedEvent.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,12 +15,13 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper;
 
 import org.apache.yetus.audience.InterfaceAudience;
-import org.apache.zookeeper.proto.WatcherEvent;
 import org.apache.zookeeper.Watcher.Event.EventType;
 import org.apache.zookeeper.Watcher.Event.KeeperState;
+import org.apache.zookeeper.proto.WatcherEvent;
 
 /**
  *  A WatchedEvent represents a change on the ZooKeeper that a Watcher
@@ -30,10 +31,11 @@ import org.apache.zookeeper.Watcher.Event.KeeperState;
  */
 @InterfaceAudience.Public
 public class WatchedEvent {
-    final private KeeperState keeperState;
-    final private EventType eventType;
+
+    private final KeeperState keeperState;
+    private final EventType eventType;
     private String path;
-    
+
     /**
      * Create a WatchedEvent with specified type, state and path
      */
@@ -42,7 +44,7 @@ public class WatchedEvent {
         this.eventType = eventType;
         this.path = path;
     }
-    
+
     /**
      * Convert a WatcherEvent sent over the wire into a full-fledged WatcherEvent
      */
@@ -51,31 +53,29 @@ public class WatchedEvent {
         eventType = EventType.fromInt(eventMessage.getType());
         path = eventMessage.getPath();
     }
-    
+
     public KeeperState getState() {
         return keeperState;
     }
-    
+
     public EventType getType() {
         return eventType;
     }
-    
+
     public String getPath() {
         return path;
     }
 
     @Override
     public String toString() {
-        return "WatchedEvent state:" + keeperState
-            + " type:" + eventType + " path:" + path;
+        return "WatchedEvent state:" + keeperState + " type:" + eventType + " path:" + path;
     }
 
     /**
      *  Convert WatchedEvent to type that can be sent over network
      */
     public WatcherEvent getWrapper() {
-        return new WatcherEvent(eventType.getIntValue(), 
-                                keeperState.getIntValue(), 
-                                path);
+        return new WatcherEvent(eventType.getIntValue(), keeperState.getIntValue(), path);
     }
+
 }

+ 78 - 58
zookeeper-server/src/main/java/org/apache/zookeeper/Watcher.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -26,7 +26,7 @@ import org.apache.yetus.audience.InterfaceAudience;
  * server it connects to. An application using such a client handles these
  * events by registering a callback object with the client. The callback object
  * is expected to be an instance of a class that implements Watcher interface.
- * 
+ *
  */
 @InterfaceAudience.Public
 public interface Watcher {
@@ -35,34 +35,35 @@ public interface Watcher {
      * This interface defines the possible states an Event may represent
      */
     @InterfaceAudience.Public
-    public interface Event {
+    interface Event {
+
         /**
          * Enumeration of states the ZooKeeper may be at the event
          */
         @InterfaceAudience.Public
-        public enum KeeperState {
+        enum KeeperState {
             /** Unused, this state is never generated by the server */
             @Deprecated
-            Unknown (-1),
+            Unknown(-1),
 
             /** The client is in the disconnected state - it is not connected
              * to any server in the ensemble. */
-            Disconnected (0),
+            Disconnected(0),
 
             /** Unused, this state is never generated by the server */
             @Deprecated
-            NoSyncConnected (1),
+            NoSyncConnected(1),
 
             /** The client is in the connected state - it is connected
              * to a server in the ensemble (one of the servers specified
              * in the host connection parameter during ZooKeeper client
              * creation). */
-            SyncConnected (3),
+            SyncConnected(3),
 
             /**
              * Auth failed state
              */
-            AuthFailed (4),
+            AuthFailed(4),
 
             /**
              * The client is connected to a read-only server, that is the
@@ -72,29 +73,29 @@ public interface Watcher {
              * This state is generated for read-only clients only since
              * read/write clients aren't allowed to connect to r/o servers.
              */
-            ConnectedReadOnly (5),
+            ConnectedReadOnly(5),
 
             /**
-              * SaslAuthenticated: used to notify clients that they are SASL-authenticated,
-              * so that they can perform Zookeeper actions with their SASL-authorized permissions.
-              */
+             * SaslAuthenticated: used to notify clients that they are SASL-authenticated,
+             * so that they can perform Zookeeper actions with their SASL-authorized permissions.
+             */
             SaslAuthenticated(6),
 
             /** The serving cluster has expired this session. The ZooKeeper
              * client connection (the session) is no longer valid. You must
              * create a new client connection (instantiate a new ZooKeeper
              * instance) if you with to access the ensemble. */
-            Expired (-112),
-            
-            /** 
+            Expired(-112),
+
+            /**
              * The client has been closed. This state is never generated by
              * the server, but is generated locally when a client calls
              * {@link ZooKeeper#close()} or {@link ZooKeeper#close(int)}
              */
-            Closed (7);
+            Closed(7);
 
             private final int intValue;     // Integer representation of value
-                                            // for sending over wire
+            // for sending over wire
 
             KeeperState(int intValue) {
                 this.intValue = intValue;
@@ -105,19 +106,28 @@ public interface Watcher {
             }
 
             public static KeeperState fromInt(int intValue) {
-                switch(intValue) {
-                    case   -1: return KeeperState.Unknown;
-                    case    0: return KeeperState.Disconnected;
-                    case    1: return KeeperState.NoSyncConnected;
-                    case    3: return KeeperState.SyncConnected;
-                    case    4: return KeeperState.AuthFailed;
-                    case    5: return KeeperState.ConnectedReadOnly;
-                    case    6: return KeeperState.SaslAuthenticated;
-                    case -112: return KeeperState.Expired;
-                    case   7: return KeeperState.Closed;
-
-                    default:
-                        throw new RuntimeException("Invalid integer value for conversion to KeeperState");
+                switch (intValue) {
+                case -1:
+                    return KeeperState.Unknown;
+                case 0:
+                    return KeeperState.Disconnected;
+                case 1:
+                    return KeeperState.NoSyncConnected;
+                case 3:
+                    return KeeperState.SyncConnected;
+                case 4:
+                    return KeeperState.AuthFailed;
+                case 5:
+                    return KeeperState.ConnectedReadOnly;
+                case 6:
+                    return KeeperState.SaslAuthenticated;
+                case -112:
+                    return KeeperState.Expired;
+                case 7:
+                    return KeeperState.Closed;
+
+                default:
+                    throw new RuntimeException("Invalid integer value for conversion to KeeperState");
                 }
             }
         }
@@ -126,17 +136,17 @@ public interface Watcher {
          * Enumeration of types of events that may occur on the ZooKeeper
          */
         @InterfaceAudience.Public
-        public enum EventType {
-            None (-1),
-            NodeCreated (1),
-            NodeDeleted (2),
-            NodeDataChanged (3),
-            NodeChildrenChanged (4),
-            DataWatchRemoved (5),
-            ChildWatchRemoved (6);
+        enum EventType {
+            None(-1),
+            NodeCreated(1),
+            NodeDeleted(2),
+            NodeDataChanged(3),
+            NodeChildrenChanged(4),
+            DataWatchRemoved(5),
+            ChildWatchRemoved(6);
 
             private final int intValue;     // Integer representation of value
-                                            // for sending over wire
+            // for sending over wire
 
             EventType(int intValue) {
                 this.intValue = intValue;
@@ -147,33 +157,43 @@ public interface Watcher {
             }
 
             public static EventType fromInt(int intValue) {
-                switch(intValue) {
-                    case -1: return EventType.None;
-                    case  1: return EventType.NodeCreated;
-                    case  2: return EventType.NodeDeleted;
-                    case  3: return EventType.NodeDataChanged;
-                    case  4: return EventType.NodeChildrenChanged;
-                    case  5: return EventType.DataWatchRemoved;
-                    case  6: return EventType.ChildWatchRemoved;
-
-                    default:
-                        throw new RuntimeException("Invalid integer value for conversion to EventType");
+                switch (intValue) {
+                case -1:
+                    return EventType.None;
+                case 1:
+                    return EventType.NodeCreated;
+                case 2:
+                    return EventType.NodeDeleted;
+                case 3:
+                    return EventType.NodeDataChanged;
+                case 4:
+                    return EventType.NodeChildrenChanged;
+                case 5:
+                    return EventType.DataWatchRemoved;
+                case 6:
+                    return EventType.ChildWatchRemoved;
+
+                default:
+                    throw new RuntimeException("Invalid integer value for conversion to EventType");
                 }
-            }           
+            }
         }
+
     }
 
     /**
      * Enumeration of types of watchers
      */
     @InterfaceAudience.Public
-    public enum WatcherType {
-        Children(1), Data(2), Any(3);
+    enum WatcherType {
+        Children(1),
+        Data(2),
+        Any(3);
 
         // Integer representation of value
         private final int intValue;
 
-        private WatcherType(int intValue) {
+        WatcherType(int intValue) {
             this.intValue = intValue;
         }
 
@@ -191,11 +211,11 @@ public interface Watcher {
                 return WatcherType.Any;
 
             default:
-                throw new RuntimeException(
-                        "Invalid integer value for conversion to WatcherType");
+                throw new RuntimeException("Invalid integer value for conversion to WatcherType");
             }
         }
     }
 
-    abstract public void process(WatchedEvent event);
+    void process(WatchedEvent event);
+
 }

+ 36 - 27
zookeeper-server/src/main/java/org/apache/zookeeper/ZKUtil.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,6 +15,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper;
 
 import java.io.File;
@@ -23,9 +24,8 @@ import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 import java.util.Queue;
-
-import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.Semaphore;
+import java.util.concurrent.atomic.AtomicBoolean;
 import org.apache.zookeeper.AsyncCallback.MultiCallback;
 import org.apache.zookeeper.AsyncCallback.StringCallback;
 import org.apache.zookeeper.AsyncCallback.VoidCallback;
@@ -35,6 +35,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 public class ZKUtil {
+
     private static final Logger LOG = LoggerFactory.getLogger(ZKUtil.class);
     /**
      * Recursively delete the node with the given path.
@@ -47,9 +48,10 @@ public class ZKUtil {
      *
      * @throws IllegalArgumentException if an invalid path is specified
      */
-    public static boolean deleteRecursive(ZooKeeper zk, final String pathRoot, final int batchSize)
-        throws InterruptedException, KeeperException
-    {
+    public static boolean deleteRecursive(
+        ZooKeeper zk,
+        final String pathRoot,
+        final int batchSize) throws InterruptedException, KeeperException {
         PathUtils.validatePath(pathRoot);
 
         List<String> tree = listSubTreeBFS(zk, pathRoot);
@@ -59,6 +61,7 @@ public class ZKUtil {
     }
 
     private static class BatchedDeleteCbContext {
+
         public Semaphore sem;
         public AtomicBoolean success;
 
@@ -66,23 +69,22 @@ public class ZKUtil {
             sem = new Semaphore(rateLimit);
             success = new AtomicBoolean(true);
         }
+
     }
 
-    private static boolean deleteInBatch(ZooKeeper zk, List<String> tree, int batchSize)
-        throws InterruptedException
-    {
+    private static boolean deleteInBatch(ZooKeeper zk, List<String> tree, int batchSize) throws InterruptedException {
         int rateLimit = 10;
         List<Op> ops = new ArrayList<>();
         BatchedDeleteCbContext context = new BatchedDeleteCbContext(rateLimit);
         MultiCallback cb = (rc, path, ctx, opResults) -> {
-            ((BatchedDeleteCbContext)ctx).sem.release();
+            ((BatchedDeleteCbContext) ctx).sem.release();
             if (rc != Code.OK.intValue()) {
-                ((BatchedDeleteCbContext)ctx).success.set(false);
+                ((BatchedDeleteCbContext) ctx).success.set(false);
             }
         };
 
         // Delete the leaves first and eventually get rid of the root
-        for (int i = tree.size() - 1; i >= 0 ; --i) {
+        for (int i = tree.size() - 1; i >= 0; --i) {
             // Create Op to delete all versions of the node with -1.
             ops.add(Op.delete(tree.get(i), -1));
 
@@ -117,20 +119,21 @@ public class ZKUtil {
      * @param ctx the context the callback method is called with
      * @throws IllegalArgumentException if an invalid path is specified
      */
-    public static void deleteRecursive(ZooKeeper zk, final String pathRoot, VoidCallback cb,
-        Object ctx)
-        throws InterruptedException, KeeperException
-    {
+    public static void deleteRecursive(
+        ZooKeeper zk,
+        final String pathRoot,
+        VoidCallback cb,
+        Object ctx) throws InterruptedException, KeeperException {
         PathUtils.validatePath(pathRoot);
 
         List<String> tree = listSubTreeBFS(zk, pathRoot);
         LOG.debug("Deleting tree: {}", tree);
-        for (int i = tree.size() - 1; i >= 0 ; --i) {
+        for (int i = tree.size() - 1; i >= 0; --i) {
             //Delete the leaves first and eventually get rid of the root
             zk.delete(tree.get(i), -1, cb, ctx); //Delete all versions of the node with -1.
         }
     }
-    
+
     /**
      * @param filePath the file path to be validated
      * @return Returns null if valid otherwise error message
@@ -163,8 +166,9 @@ public class ZKUtil {
      * @throws InterruptedException
      * @throws KeeperException
      */
-    public static List<String> listSubTreeBFS(ZooKeeper zk, final String pathRoot) throws
-        KeeperException, InterruptedException {
+    public static List<String> listSubTreeBFS(
+        ZooKeeper zk,
+        final String pathRoot) throws KeeperException, InterruptedException {
         Queue<String> queue = new ArrayDeque<>();
         List<String> tree = new ArrayList<String>();
         queue.add(pathRoot);
@@ -190,7 +194,10 @@ public class ZKUtil {
      * For practical purposes, it is suggested to bring the clients to the ensemble
      * down (i.e. prevent writes to pathRoot) to 'simulate' a snapshot behavior.
      */
-    public static void visitSubTreeDFS(ZooKeeper zk, final String path, boolean watch,
+    public static void visitSubTreeDFS(
+        ZooKeeper zk,
+        final String path,
+        boolean watch,
         StringCallback cb) throws KeeperException, InterruptedException {
         PathUtils.validatePath(path);
 
@@ -200,9 +207,11 @@ public class ZKUtil {
     }
 
     @SuppressWarnings("unchecked")
-    private static void visitSubTreeDFSHelper(ZooKeeper zk, final String path,
-        boolean watch, StringCallback cb)
-            throws KeeperException, InterruptedException {
+    private static void visitSubTreeDFSHelper(
+        ZooKeeper zk,
+        final String path,
+        boolean watch,
+        StringCallback cb) throws KeeperException, InterruptedException {
         // we've already validated, therefore if the path is of length 1 it's the root
         final boolean isRoot = path.length() == 1;
         try {
@@ -218,11 +227,11 @@ public class ZKUtil {
                 String childPath = (isRoot ? path : path + "/") + child;
                 visitSubTreeDFSHelper(zk, childPath, watch, cb);
             }
-        }
-        catch (KeeperException.NoNodeException e) {
+        } catch (KeeperException.NoNodeException e) {
             // Handle race condition where a node is listed
             // but gets deleted before it can be queried
             return; // ignore
         }
     }
-}
+
+}

+ 49 - 49
zookeeper-server/src/main/java/org/apache/zookeeper/ZooDefs.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -21,83 +21,85 @@ package org.apache.zookeeper;
 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
 import java.util.ArrayList;
 import java.util.Collections;
-
 import org.apache.yetus.audience.InterfaceAudience;
 import org.apache.zookeeper.data.ACL;
 import org.apache.zookeeper.data.Id;
 
 @InterfaceAudience.Public
 public class ZooDefs {
-   
-   final public static String CONFIG_NODE = "/zookeeper/config";
 
-   final public static String ZOOKEEPER_NODE_SUBTREE = "/zookeeper/";
+    public static final String CONFIG_NODE = "/zookeeper/config";
+
+    public static final String ZOOKEEPER_NODE_SUBTREE = "/zookeeper/";
 
-   @InterfaceAudience.Public
+    @InterfaceAudience.Public
     public interface OpCode {
-        public final int notification = 0;
 
-        public final int create = 1;
+        int notification = 0;
+
+        int create = 1;
+
+        int delete = 2;
+
+        int exists = 3;
 
-        public final int delete = 2;
+        int getData = 4;
 
-        public final int exists = 3;
+        int setData = 5;
 
-        public final int getData = 4;
+        int getACL = 6;
 
-        public final int setData = 5;
+        int setACL = 7;
 
-        public final int getACL = 6;
+        int getChildren = 8;
 
-        public final int setACL = 7;
+        int sync = 9;
 
-        public final int getChildren = 8;
+        int ping = 11;
 
-        public final int sync = 9;
+        int getChildren2 = 12;
 
-        public final int ping = 11;
+        int check = 13;
 
-        public final int getChildren2 = 12;
+        int multi = 14;
 
-        public final int check = 13;
+        int create2 = 15;
 
-        public final int multi = 14;
-        
-        public final int create2 = 15;
+        int reconfig = 16;
 
-        public final int reconfig = 16;
+        int checkWatches = 17;
 
-        public final int checkWatches = 17;
+        int removeWatches = 18;
 
-        public final int removeWatches = 18;
+        int createContainer = 19;
 
-        public final int createContainer = 19;
+        int deleteContainer = 20;
 
-        public final int deleteContainer = 20;
+        int createTTL = 21;
 
-        public final int createTTL = 21;
+        int multiRead = 22;
 
-        public final int multiRead = 22;
+        int auth = 100;
 
-        public final int auth = 100;
+        int setWatches = 101;
 
-        public final int setWatches = 101;
+        int sasl = 102;
 
-        public final int sasl = 102;
+        int getEphemerals = 103;
 
-        public final int getEphemerals = 103;
+        int getAllChildrenNumber = 104;
 
-        public final int getAllChildrenNumber = 104;
+        int createSession = -10;
 
-        public final int createSession = -10;
+        int closeSession = -11;
 
-        public final int closeSession = -11;
+        int error = -1;
 
-        public final int error = -1;
     }
 
     @InterfaceAudience.Public
     public interface Perms {
+
         int READ = 1 << 0;
 
         int WRITE = 1 << 1;
@@ -109,45 +111,43 @@ public class ZooDefs {
         int ADMIN = 1 << 4;
 
         int ALL = READ | WRITE | CREATE | DELETE | ADMIN;
+
     }
 
     @InterfaceAudience.Public
     public interface Ids {
+
         /**
          * This Id represents anyone.
          */
-        public final Id ANYONE_ID_UNSAFE = new Id("world", "anyone");
+        Id ANYONE_ID_UNSAFE = new Id("world", "anyone");
 
         /**
          * This Id is only usable to set ACLs. It will get substituted with the
          * Id's the client authenticated with.
          */
-        public final Id AUTH_IDS = new Id("auth", "");
+        Id AUTH_IDS = new Id("auth", "");
 
         /**
          * This is a completely open ACL .
          */
         @SuppressFBWarnings(value = "MS_MUTABLE_COLLECTION", justification = "Cannot break API")
-        public final ArrayList<ACL> OPEN_ACL_UNSAFE = new ArrayList<ACL>(
-                Collections.singletonList(new ACL(Perms.ALL, ANYONE_ID_UNSAFE)));
+        ArrayList<ACL> OPEN_ACL_UNSAFE = new ArrayList<ACL>(Collections.singletonList(new ACL(Perms.ALL, ANYONE_ID_UNSAFE)));
 
         /**
          * This ACL gives the creators authentication id's all permissions.
          */
         @SuppressFBWarnings(value = "MS_MUTABLE_COLLECTION", justification = "Cannot break API")
-        public final ArrayList<ACL> CREATOR_ALL_ACL = new ArrayList<ACL>(
-                Collections.singletonList(new ACL(Perms.ALL, AUTH_IDS)));
+        ArrayList<ACL> CREATOR_ALL_ACL = new ArrayList<ACL>(Collections.singletonList(new ACL(Perms.ALL, AUTH_IDS)));
 
         /**
          * This ACL gives the world the ability to read.
          */
         @SuppressFBWarnings(value = "MS_MUTABLE_COLLECTION", justification = "Cannot break API")
-        public final ArrayList<ACL> READ_ACL_UNSAFE = new ArrayList<ACL>(
-                Collections
-                        .singletonList(new ACL(Perms.READ, ANYONE_ID_UNSAFE)));
+        ArrayList<ACL> READ_ACL_UNSAFE = new ArrayList<ACL>(Collections.singletonList(new ACL(Perms.READ, ANYONE_ID_UNSAFE)));
+
     }
 
-    final public static String[] opNames = { "notification", "create",
-            "delete", "exists", "getData", "setData", "getACL", "setACL",
-            "getChildren", "getChildren2", "getMaxChildren", "setMaxChildren", "ping", "reconfig", "getConfig" };
+    public static final String[] opNames = {"notification", "create", "delete", "exists", "getData", "setData", "getACL", "setACL", "getChildren", "getChildren2", "getMaxChildren", "setMaxChildren", "ping", "reconfig", "getConfig"};
+
 }

Diff do ficheiro suprimidas por serem muito extensas
+ 282 - 202
zookeeper-server/src/main/java/org/apache/zookeeper/ZooKeeper.java


+ 65 - 72
zookeeper-server/src/main/java/org/apache/zookeeper/ZooKeeperMain.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -33,43 +33,40 @@ import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
 import java.util.NoSuchElementException;
-
-import org.apache.yetus.audience.InterfaceAudience;
-import org.apache.zookeeper.cli.CliException;
-import org.apache.zookeeper.cli.CommandNotFoundException;
-import org.apache.zookeeper.cli.GetAllChildrenNumberCommand;
-import org.apache.zookeeper.cli.GetEphemeralsCommand;
-import org.apache.zookeeper.cli.MalformedCommandException;
-import org.apache.zookeeper.cli.VersionCommand;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
-
+import org.apache.yetus.audience.InterfaceAudience;
+import org.apache.zookeeper.admin.ZooKeeperAdmin;
 import org.apache.zookeeper.cli.AddAuthCommand;
 import org.apache.zookeeper.cli.CliCommand;
+import org.apache.zookeeper.cli.CliException;
 import org.apache.zookeeper.cli.CloseCommand;
+import org.apache.zookeeper.cli.CommandNotFoundException;
 import org.apache.zookeeper.cli.CreateCommand;
 import org.apache.zookeeper.cli.DelQuotaCommand;
 import org.apache.zookeeper.cli.DeleteAllCommand;
 import org.apache.zookeeper.cli.DeleteCommand;
-import org.apache.zookeeper.cli.RemoveWatchesCommand;
 import org.apache.zookeeper.cli.GetAclCommand;
+import org.apache.zookeeper.cli.GetAllChildrenNumberCommand;
 import org.apache.zookeeper.cli.GetCommand;
 import org.apache.zookeeper.cli.GetConfigCommand;
+import org.apache.zookeeper.cli.GetEphemeralsCommand;
 import org.apache.zookeeper.cli.ListQuotaCommand;
 import org.apache.zookeeper.cli.Ls2Command;
 import org.apache.zookeeper.cli.LsCommand;
+import org.apache.zookeeper.cli.MalformedCommandException;
 import org.apache.zookeeper.cli.ReconfigCommand;
+import org.apache.zookeeper.cli.RemoveWatchesCommand;
 import org.apache.zookeeper.cli.SetAclCommand;
 import org.apache.zookeeper.cli.SetCommand;
 import org.apache.zookeeper.cli.SetQuotaCommand;
 import org.apache.zookeeper.cli.StatCommand;
 import org.apache.zookeeper.cli.SyncCommand;
+import org.apache.zookeeper.cli.VersionCommand;
 import org.apache.zookeeper.client.ZKClientConfig;
-import org.apache.zookeeper.admin.ZooKeeperAdmin;
 import org.apache.zookeeper.server.ExitCode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * The command line client to ZooKeeper.
@@ -77,13 +74,13 @@ import org.apache.zookeeper.server.ExitCode;
  */
 @InterfaceAudience.Public
 public class ZooKeeperMain {
+
     private static final Logger LOG = LoggerFactory.getLogger(ZooKeeperMain.class);
-    static final Map<String,String> commandMap = new HashMap<String,String>( );
-    static final Map<String,CliCommand> commandMapCli =
-            new HashMap<String,CliCommand>( );
+    static final Map<String, String> commandMap = new HashMap<String, String>();
+    static final Map<String, CliCommand> commandMapCli = new HashMap<String, CliCommand>();
 
     protected MyCommandOptions cl = new MyCommandOptions();
-    protected HashMap<Integer,String> history = new HashMap<Integer,String>( );
+    protected HashMap<Integer, String> history = new HashMap<Integer, String>();
     protected int commandCount = 0;
     protected boolean printWatches = true;
     protected int exitCode = ExitCode.EXECUTION_FINISHED.getValue();
@@ -91,14 +88,14 @@ public class ZooKeeperMain {
     protected ZooKeeper zk;
     protected String host = "";
 
-    public boolean getPrintWatches( ) {
+    public boolean getPrintWatches() {
         return printWatches;
     }
 
     static {
         commandMap.put("connect", "host:port");
-        commandMap.put("history","");
-        commandMap.put("redo","cmdno");
+        commandMap.put("history", "");
+        commandMap.put("redo", "cmdno");
         commandMap.put("printwatches", "on|off");
         commandMap.put("quit", "");
 
@@ -130,7 +127,7 @@ public class ZooKeeperMain {
         // add all to commandMap
         for (Entry<String, CliCommand> entry : commandMapCli.entrySet()) {
             commandMap.put(entry.getKey(), entry.getValue().getOptionStr());
-    }
+        }
     }
 
     static void usage() {
@@ -138,17 +135,19 @@ public class ZooKeeperMain {
         List<String> cmdList = new ArrayList<String>(commandMap.keySet());
         Collections.sort(cmdList);
         for (String cmd : cmdList) {
-            System.err.println("\t"+cmd+ " " + commandMap.get(cmd));
+            System.err.println("\t" + cmd + " " + commandMap.get(cmd));
         }
     }
 
     private class MyWatcher implements Watcher {
+
         public void process(WatchedEvent event) {
             if (getPrintWatches()) {
                 ZooKeeperMain.printMessage("WATCHER::");
                 ZooKeeperMain.printMessage(event.toString());
             }
         }
+
     }
 
     /**
@@ -157,30 +156,30 @@ public class ZooKeeperMain {
      */
     static class MyCommandOptions {
 
-        private Map<String,String> options = new HashMap<String,String>();
+        private Map<String, String> options = new HashMap<String, String>();
         private List<String> cmdArgs = null;
         private String command = null;
         public static final Pattern ARGS_PATTERN = Pattern.compile("\\s*([^\"\']\\S*|\"[^\"]*\"|'[^']*')\\s*");
         public static final Pattern QUOTED_PATTERN = Pattern.compile("^([\'\"])(.*)(\\1)$");
 
         public MyCommandOptions() {
-          options.put("server", "localhost:2181");
-          options.put("timeout", "30000");
+            options.put("server", "localhost:2181");
+            options.put("timeout", "30000");
         }
 
         public String getOption(String opt) {
             return options.get(opt);
         }
 
-        public String getCommand( ) {
+        public String getCommand() {
             return command;
         }
 
-        public String getCmdArgument( int index ) {
+        public String getCmdArgument(int index) {
             return cmdArgs.get(index);
         }
 
-        public int getNumArguments( ) {
+        public int getNumArguments() {
             return cmdArgs.size();
         }
 
@@ -208,16 +207,15 @@ public class ZooKeeperMain {
                     } else if (opt.equals("-r")) {
                         options.put("readonly", "true");
                     }
-                } catch (NoSuchElementException e){
-                    System.err.println("Error: no argument found for option "
-                            + opt);
+                } catch (NoSuchElementException e) {
+                    System.err.println("Error: no argument found for option " + opt);
                     return false;
                 }
 
                 if (!opt.startsWith("-")) {
                     command = opt;
-                    cmdArgs = new ArrayList<String>( );
-                    cmdArgs.add( command );
+                    cmdArgs = new ArrayList<String>();
+                    cmdArgs.add(command);
                     while (it.hasNext()) {
                         cmdArgs.add(it.next());
                     }
@@ -232,7 +230,7 @@ public class ZooKeeperMain {
          * @param cmdstring string of form "cmd arg1 arg2..etc"
          * @return true if parsing succeeded.
          */
-        public boolean parseCommand( String cmdstring ) {
+        public boolean parseCommand(String cmdstring) {
             Matcher matcher = ARGS_PATTERN.matcher(cmdstring);
 
             List<String> args = new LinkedList<String>();
@@ -244,15 +242,15 @@ public class ZooKeeperMain {
                 }
                 args.add(value);
             }
-            if (args.isEmpty()){
+            if (args.isEmpty()) {
                 return false;
             }
             command = args.get(0);
             cmdArgs = args;
             return true;
         }
-    }
 
+    }
 
     /**
      * Makes a list of possible completions, either for commands
@@ -260,8 +258,7 @@ public class ZooKeeperMain {
      *
      */
 
-
-    protected void addToHistory(int i,String cmd) {
+    protected void addToHistory(int i, String cmd) {
         history.put(i, cmd);
     }
 
@@ -271,12 +268,12 @@ public class ZooKeeperMain {
         return cmdList;
     }
 
-    protected String getPrompt() {       
-        return "[zk: " + host + "("+zk.getState()+")" + " " + commandCount + "] ";
+    protected String getPrompt() {
+        return "[zk: " + host + "(" + zk.getState() + ")" + " " + commandCount + "] ";
     }
 
     public static void printMessage(String msg) {
-        System.out.println("\n"+msg);
+        System.out.println("\n" + msg);
     }
 
     protected void connectToZK(String newHost) throws InterruptedException, IOException {
@@ -292,21 +289,20 @@ public class ZooKeeperMain {
         }
         zk = new ZooKeeperAdmin(host, Integer.parseInt(cl.getOption("timeout")), new MyWatcher(), readOnly);
     }
-    
-    public static void main(String args[]) throws CliException, IOException, InterruptedException
-    {
+
+    public static void main(String[] args) throws CliException, IOException, InterruptedException {
         ZooKeeperMain main = new ZooKeeperMain(args);
         main.run();
     }
 
-    public ZooKeeperMain(String args[]) throws IOException, InterruptedException {
+    public ZooKeeperMain(String[] args) throws IOException, InterruptedException {
         cl.parseOptions(args);
         System.out.println("Connecting to " + cl.getOption("server"));
         connectToZK(cl.getOption("server"));
     }
 
     public ZooKeeperMain(ZooKeeper zk) {
-      this.zk = zk;
+        this.zk = zk;
     }
 
     void run() throws CliException, IOException, InterruptedException {
@@ -317,23 +313,19 @@ public class ZooKeeperMain {
             // only use jline if it's in the classpath
             try {
                 Class<?> consoleC = Class.forName("jline.console.ConsoleReader");
-                Class<?> completorC =
-                    Class.forName("org.apache.zookeeper.JLineZNodeCompleter");
+                Class<?> completorC = Class.forName("org.apache.zookeeper.JLineZNodeCompleter");
 
                 System.out.println("JLine support is enabled");
 
-                Object console =
-                    consoleC.getConstructor().newInstance();
+                Object console = consoleC.getConstructor().newInstance();
 
-                Object completor =
-                    completorC.getConstructor(ZooKeeper.class).newInstance(zk);
-                Method addCompletor = consoleC.getMethod("addCompleter",
-                        Class.forName("jline.console.completer.Completer"));
+                Object completor = completorC.getConstructor(ZooKeeper.class).newInstance(zk);
+                Method addCompletor = consoleC.getMethod("addCompleter", Class.forName("jline.console.completer.Completer"));
                 addCompletor.invoke(console, completor);
 
                 String line;
                 Method readLine = consoleC.getMethod("readLine", String.class);
-                while ((line = (String)readLine.invoke(console, getPrompt())) != null) {
+                while ((line = (String) readLine.invoke(console, getPrompt())) != null) {
                     executeLine(line);
                 }
             } catch (ClassNotFoundException e) {
@@ -355,8 +347,7 @@ public class ZooKeeperMain {
 
             if (jlinemissing) {
                 System.out.println("JLine support is disabled");
-                BufferedReader br =
-                    new BufferedReader(new InputStreamReader(System.in));
+                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 
                 String line;
                 while ((line = br.readLine()) != null) {
@@ -371,12 +362,12 @@ public class ZooKeeperMain {
     }
 
     public void executeLine(String line) throws CliException, InterruptedException, IOException {
-      if (!line.equals("")) {
-        cl.parseCommand(line);
-        addToHistory(commandCount,line);
-        processCmd(cl);
-        commandCount++;
-      }
+        if (!line.equals("")) {
+            cl.parseCommand(line);
+            addToHistory(commandCount, line);
+            processCmd(cl);
+            commandCount++;
+        }
     }
 
     protected boolean processCmd(MyCommandOptions co) throws CliException, IOException, InterruptedException {
@@ -403,11 +394,10 @@ public class ZooKeeperMain {
             usage();
             throw new CommandNotFoundException("Command not found " + cmd);
         }
-        
+
         boolean watch = false;
         LOG.debug("Processing {}", cmd);
 
-
         if (cmd.equals("quit")) {
             zk.close();
             System.exit(exitCode);
@@ -424,7 +414,9 @@ public class ZooKeeperMain {
             processCmd(cl);
         } else if (cmd.equals("history")) {
             for (int i = commandCount - 10; i <= commandCount; ++i) {
-                if (i < 0) continue;
+                if (i < 0) {
+                    continue;
+                }
                 System.out.println(i + " - " + history.get(i));
             }
         } else if (cmd.equals("printwatches")) {
@@ -440,21 +432,22 @@ public class ZooKeeperMain {
                 connectToZK(host);
             }
         }
-        
+
         // Below commands all need a live connection
         if (zk == null || !zk.getState().isAlive()) {
             System.out.println("Not connected");
             return false;
         }
-        
+
         // execute from commandMap
         CliCommand cliCmd = commandMapCli.get(cmd);
-        if(cliCmd != null) {
+        if (cliCmd != null) {
             cliCmd.setZk(zk);
             watch = cliCmd.parse(args).exec();
         } else if (!commandMap.containsKey(cmd)) {
-             usage();
+            usage();
         }
         return watch;
     }
+
 }

+ 5 - 6
zookeeper-server/src/main/java/org/apache/zookeeper/ZooKeeperTestable.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -22,8 +22,8 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 class ZooKeeperTestable implements Testable {
-    private static final Logger LOG = LoggerFactory
-            .getLogger(ZooKeeperTestable.class);
+
+    private static final Logger LOG = LoggerFactory.getLogger(ZooKeeperTestable.class);
 
     private final ClientCnxn clientCnxn;
 
@@ -35,9 +35,7 @@ class ZooKeeperTestable implements Testable {
     public void injectSessionExpiration() {
         LOG.info("injectSessionExpiration() called");
 
-        clientCnxn.eventThread.queueEvent(new WatchedEvent(
-                Watcher.Event.EventType.None,
-                Watcher.Event.KeeperState.Expired, null));
+        clientCnxn.eventThread.queueEvent(new WatchedEvent(Watcher.Event.EventType.None, Watcher.Event.KeeperState.Expired, null));
         clientCnxn.eventThread.queueEventOfDeath();
         clientCnxn.state = ZooKeeper.States.CLOSED;
         clientCnxn.sendThread.getClientCnxnSocket().onClosing();
@@ -48,4 +46,5 @@ class ZooKeeperTestable implements Testable {
         LOG.info("queueEvent() called: {}", event);
         clientCnxn.eventThread.queueEvent(event);
     }
+
 }

+ 12 - 12
zookeeper-server/src/main/java/org/apache/zookeeper/ZookeeperBanner.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -26,21 +26,21 @@ import org.slf4j.Logger;
  */
 public class ZookeeperBanner {
 
-    private static final String[] BANNER = {"",
-            "  ______                  _                                          ",
-            " |___  /                 | |                                         ",
-            "    / /    ___     ___   | | __   ___    ___   _ __     ___   _ __   ",
-            "   / /    / _ \\   / _ \\  | |/ /  / _ \\  / _ \\ | '_ \\   / _ \\ | '__|",
-            "  / /__  | (_) | | (_) | |   <  |  __/ |  __/ | |_) | |  __/ | |    " ,
-            " /_____|  \\___/   \\___/  |_|\\_\\  \\___|  \\___| | .__/   \\___| |_|",
-            "                                              | |                     " ,
-            "                                              |_|                     ",
-            ""
-    };
+    private static final String[] BANNER = {
+        "",
+        "  ______                  _                                          ",
+        " |___  /                 | |                                         ",
+        "    / /    ___     ___   | | __   ___    ___   _ __     ___   _ __   ",
+        "   / /    / _ \\   / _ \\  | |/ /  / _ \\  / _ \\ | '_ \\   / _ \\ | '__|",
+        "  / /__  | (_) | | (_) | |   <  |  __/ |  __/ | |_) | |  __/ | |    ",
+        " /_____|  \\___/   \\___/  |_|\\_\\  \\___|  \\___| | .__/   \\___| |_|",
+        "                                              | |                     ",
+        "                                              |_|                     ", ""};
 
     public static void printBanner(Logger log) {
         for (String line : BANNER) {
             log.info(line);
         }
     }
+
 }

+ 70 - 33
zookeeper-server/src/main/java/org/apache/zookeeper/admin/ZooKeeperAdmin.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -20,13 +20,12 @@ package org.apache.zookeeper.admin;
 
 import java.io.IOException;
 import java.util.List;
-
 import org.apache.yetus.audience.InterfaceAudience;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.ZooDefs;
-import org.apache.zookeeper.Watcher;
-import org.apache.zookeeper.KeeperException;
 import org.apache.zookeeper.AsyncCallback.DataCallback;
+import org.apache.zookeeper.KeeperException;
+import org.apache.zookeeper.Watcher;
+import org.apache.zookeeper.ZooDefs;
+import org.apache.zookeeper.ZooKeeper;
 import org.apache.zookeeper.client.ZKClientConfig;
 import org.apache.zookeeper.common.StringUtils;
 import org.apache.zookeeper.data.Stat;
@@ -35,7 +34,6 @@ import org.apache.zookeeper.proto.ReconfigRequest;
 import org.apache.zookeeper.proto.ReplyHeader;
 import org.apache.zookeeper.proto.RequestHeader;
 import org.apache.zookeeper.server.DataTree;
-
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -52,6 +50,7 @@ import org.slf4j.LoggerFactory;
 @SuppressWarnings("try")
 @InterfaceAudience.Public
 public class ZooKeeperAdmin extends ZooKeeper {
+
     private static final Logger LOG = LoggerFactory.getLogger(ZooKeeperAdmin.class);
 
     /**
@@ -81,8 +80,10 @@ public class ZooKeeperAdmin extends ZooKeeper {
      * @see ZooKeeper#ZooKeeper(String, int, Watcher)
      *
      */
-    public ZooKeeperAdmin(String connectString, int sessionTimeout, Watcher watcher)
-        throws IOException {
+    public ZooKeeperAdmin(
+        String connectString,
+        int sessionTimeout,
+        Watcher watcher) throws IOException {
         super(connectString, sessionTimeout, watcher);
     }
 
@@ -115,8 +116,11 @@ public class ZooKeeperAdmin extends ZooKeeper {
      *
      * @see ZooKeeper#ZooKeeper(String, int, Watcher, ZKClientConfig)
      */
-    public ZooKeeperAdmin(String connectString, int sessionTimeout, Watcher watcher,
-            ZKClientConfig conf) throws IOException {
+    public ZooKeeperAdmin(
+        String connectString,
+        int sessionTimeout,
+        Watcher watcher,
+        ZKClientConfig conf) throws IOException {
         super(connectString, sessionTimeout, watcher, conf);
     }
 
@@ -154,8 +158,11 @@ public class ZooKeeperAdmin extends ZooKeeper {
      *
      * @see ZooKeeper#ZooKeeper(String, int, Watcher, boolean)
      */
-    public ZooKeeperAdmin(String connectString, int sessionTimeout, Watcher watcher,
-                     boolean canBeReadOnly) throws IOException {
+    public ZooKeeperAdmin(
+        String connectString,
+        int sessionTimeout,
+        Watcher watcher,
+        boolean canBeReadOnly) throws IOException {
         super(connectString, sessionTimeout, watcher, canBeReadOnly);
     }
 
@@ -176,8 +183,12 @@ public class ZooKeeperAdmin extends ZooKeeper {
      * @throws InterruptedException If the server transaction is interrupted.
      * @throws KeeperException If the server signals an error with a non-zero error code.
      */
-    public byte[] reconfigure(String joiningServers, String leavingServers,
-                              String newMembers, long fromConfig, Stat stat) throws KeeperException, InterruptedException {
+    public byte[] reconfigure(
+        String joiningServers,
+        String leavingServers,
+        String newMembers,
+        long fromConfig,
+        Stat stat) throws KeeperException, InterruptedException {
         RequestHeader h = new RequestHeader();
         h.setType(ZooDefs.OpCode.reconfig);
         ReconfigRequest request = new ReconfigRequest(joiningServers, leavingServers, newMembers, fromConfig);
@@ -198,13 +209,18 @@ public class ZooKeeperAdmin extends ZooKeeper {
      * @see #reconfigure
      *
      */
-    public byte[] reconfigure(List<String> joiningServers, List<String> leavingServers,
-                              List<String> newMembers, long fromConfig,
-                              Stat stat) throws KeeperException, InterruptedException {
-        return reconfigure(StringUtils.joinStrings(joiningServers, ","),
-                        StringUtils.joinStrings(leavingServers, ","),
-                        StringUtils.joinStrings(newMembers, ","),
-                        fromConfig, stat);
+    public byte[] reconfigure(
+        List<String> joiningServers,
+        List<String> leavingServers,
+        List<String> newMembers,
+        long fromConfig,
+        Stat stat) throws KeeperException, InterruptedException {
+        return reconfigure(
+            StringUtils.joinStrings(joiningServers, ","),
+            StringUtils.joinStrings(leavingServers, ","),
+            StringUtils.joinStrings(newMembers, ","),
+            fromConfig,
+            stat);
     }
 
     /**
@@ -213,14 +229,27 @@ public class ZooKeeperAdmin extends ZooKeeper {
      * @see #reconfigure
      *
      **/
-    public void reconfigure(String joiningServers, String leavingServers,
-                            String newMembers, long fromConfig, DataCallback cb, Object ctx) {
+    public void reconfigure(
+        String joiningServers,
+        String leavingServers,
+        String newMembers,
+        long fromConfig,
+        DataCallback cb,
+        Object ctx) {
         RequestHeader h = new RequestHeader();
         h.setType(ZooDefs.OpCode.reconfig);
         ReconfigRequest request = new ReconfigRequest(joiningServers, leavingServers, newMembers, fromConfig);
         GetDataResponse response = new GetDataResponse();
-        cnxn.queuePacket(h, new ReplyHeader(), request, response, cb,
-               ZooDefs.CONFIG_NODE, ZooDefs.CONFIG_NODE, ctx, null);
+        cnxn.queuePacket(
+            h,
+            new ReplyHeader(),
+            request,
+            response,
+            cb,
+            ZooDefs.CONFIG_NODE,
+            ZooDefs.CONFIG_NODE,
+            ctx,
+            null);
     }
 
     /**
@@ -229,13 +258,20 @@ public class ZooKeeperAdmin extends ZooKeeper {
      * @see #reconfigure
      *
      */
-    public void reconfigure(List<String> joiningServers,
-                            List<String> leavingServers, List<String> newMembers, long fromConfig,
-                            DataCallback cb, Object ctx) {
-        reconfigure(StringUtils.joinStrings(joiningServers, ","),
-                 StringUtils.joinStrings(leavingServers, ","),
-                 StringUtils.joinStrings(newMembers, ","),
-                 fromConfig, cb, ctx);
+    public void reconfigure(
+        List<String> joiningServers,
+        List<String> leavingServers,
+        List<String> newMembers,
+        long fromConfig,
+        DataCallback cb,
+        Object ctx) {
+        reconfigure(
+            StringUtils.joinStrings(joiningServers, ","),
+            StringUtils.joinStrings(leavingServers, ","),
+            StringUtils.joinStrings(newMembers, ","),
+            fromConfig,
+            cb,
+            ctx);
     }
 
     /**
@@ -251,4 +287,5 @@ public class ZooKeeperAdmin extends ZooKeeper {
     public String toString() {
         return super.toString();
     }
+
 }

+ 24 - 23
zookeeper-server/src/main/java/org/apache/zookeeper/cli/AclParser.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,6 +15,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.cli;
 
 import java.util.ArrayList;
@@ -31,11 +32,11 @@ public class AclParser {
     /**
      * parse string into list of ACL
      * @param aclString
-     * @return 
+     * @return
      */
     public static List<ACL> parse(String aclString) {
         List<ACL> acl;
-        String acls[] = aclString.split(",");
+        String[] acls = aclString.split(",");
         acl = new ArrayList<ACL>();
         for (String a : acls) {
             int firstColon = a.indexOf(':');
@@ -45,37 +46,37 @@ public class AclParser {
                 continue;
             }
             ACL newAcl = new ACL();
-            newAcl.setId(new Id(a.substring(0, firstColon), a.substring(
-                    firstColon + 1, lastColon)));
+            newAcl.setId(new Id(a.substring(0, firstColon), a.substring(firstColon + 1, lastColon)));
             newAcl.setPerms(getPermFromString(a.substring(lastColon + 1)));
             acl.add(newAcl);
         }
         return acl;
     }
 
-    static private int getPermFromString(String permString) {
+    private static int getPermFromString(String permString) {
         int perm = 0;
         for (int i = 0; i < permString.length(); i++) {
             switch (permString.charAt(i)) {
-                case 'r':
-                    perm |= ZooDefs.Perms.READ;
-                    break;
-                case 'w':
-                    perm |= ZooDefs.Perms.WRITE;
-                    break;
-                case 'c':
-                    perm |= ZooDefs.Perms.CREATE;
-                    break;
-                case 'd':
-                    perm |= ZooDefs.Perms.DELETE;
-                    break;
-                case 'a':
-                    perm |= ZooDefs.Perms.ADMIN;
-                    break;
-                default:
-                    System.err.println("Unknown perm type: " + permString.charAt(i));
+            case 'r':
+                perm |= ZooDefs.Perms.READ;
+                break;
+            case 'w':
+                perm |= ZooDefs.Perms.WRITE;
+                break;
+            case 'c':
+                perm |= ZooDefs.Perms.CREATE;
+                break;
+            case 'd':
+                perm |= ZooDefs.Perms.DELETE;
+                break;
+            case 'a':
+                perm |= ZooDefs.Perms.ADMIN;
+                break;
+            default:
+                System.err.println("Unknown perm type: " + permString.charAt(i));
             }
         }
         return perm;
     }
+
 }

+ 3 - 1
zookeeper-server/src/main/java/org/apache/zookeeper/cli/AddAuthCommand.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,6 +15,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.cli;
 
 import org.apache.commons.cli.CommandLine;
@@ -64,4 +65,5 @@ public class AddAuthCommand extends CliCommand {
 
         return false;
     }
+
 }

+ 17 - 14
zookeeper-server/src/main/java/org/apache/zookeeper/cli/CliCommand.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,6 +15,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.cli;
 
 import java.io.PrintStream;
@@ -24,7 +25,8 @@ import org.apache.zookeeper.ZooKeeper;
 /**
  * base class for all CLI commands
  */
-abstract public class CliCommand {
+public abstract class CliCommand {
+
     protected ZooKeeper zk;
     protected PrintStream out;
     protected PrintStream err;
@@ -35,7 +37,7 @@ abstract public class CliCommand {
      * a CLI command with command string and options.
      * Using System.out and System.err for printing
      * @param cmdStr the string used to call this command
-     * @param optionStr the string used to call this command 
+     * @param optionStr the string used to call this command
      */
     public CliCommand(String cmdStr, String optionStr) {
         this.out = System.out;
@@ -46,7 +48,7 @@ abstract public class CliCommand {
 
     /**
      * Set out printStream (usable for testing)
-     * @param out 
+     * @param out
      */
     public void setOut(PrintStream out) {
         this.out = out;
@@ -54,7 +56,7 @@ abstract public class CliCommand {
 
     /**
      * Set err printStream (usable for testing)
-     * @param err 
+     * @param err
      */
     public void setErr(PrintStream err) {
         this.err = err;
@@ -70,7 +72,7 @@ abstract public class CliCommand {
 
     /**
      * get the string used to call this command
-     * @return 
+     * @return
      */
     public String getCmdStr() {
         return cmdStr;
@@ -78,7 +80,7 @@ abstract public class CliCommand {
 
     /**
      * get the option string
-     * @return 
+     * @return
      */
     public String getOptionStr() {
         return optionStr;
@@ -86,7 +88,7 @@ abstract public class CliCommand {
 
     /**
      * get a usage string, contains the command and the options
-     * @return 
+     * @return
      */
     public String getUsageStr() {
         return cmdStr + " " + optionStr;
@@ -94,24 +96,25 @@ abstract public class CliCommand {
 
     /**
      * add this command to a map. Use the command string as key.
-     * @param cmdMap 
+     * @param cmdMap
      */
     public void addToMap(Map<String, CliCommand> cmdMap) {
         cmdMap.put(cmdStr, this);
     }
-    
+
     /**
      * parse the command arguments
      * @param cmdArgs
      * @return this CliCommand
      * @throws CliParseException
      */
-    abstract public CliCommand parse(String cmdArgs[]) throws CliParseException;
-    
+    public abstract CliCommand parse(String[] cmdArgs) throws CliParseException;
+
     /**
-     * 
+     *
      * @return
      * @throws CliException
      */
-    abstract public boolean exec() throws CliException;
+    public abstract boolean exec() throws CliException;
+
 }

+ 3 - 1
zookeeper-server/src/main/java/org/apache/zookeeper/cli/CliException.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,6 +15,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.cli;
 
 @SuppressWarnings("serial")
@@ -54,4 +55,5 @@ public class CliException extends Exception {
     public int getExitCode() {
         return exitCode;
     }
+
 }

+ 4 - 1
zookeeper-server/src/main/java/org/apache/zookeeper/cli/CliParseException.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,12 +15,14 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.cli;
 
 import org.apache.commons.cli.ParseException;
 
 @SuppressWarnings("serial")
 public class CliParseException extends CliException {
+
     public CliParseException(ParseException parseException) {
         super(parseException);
     }
@@ -28,4 +30,5 @@ public class CliParseException extends CliException {
     public CliParseException(String message) {
         super(message);
     }
+
 }

+ 10 - 8
zookeeper-server/src/main/java/org/apache/zookeeper/cli/CliWrapperException.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,18 +15,20 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.cli;
 
 import org.apache.zookeeper.KeeperException;
 
 @SuppressWarnings("serial")
 public class CliWrapperException extends CliException {
+
     public CliWrapperException(Throwable cause) {
         super(getMessage(cause), cause);
     }
-    
+
     private static String getMessage(Throwable cause) {
-        if (cause instanceof  KeeperException) {
+        if (cause instanceof KeeperException) {
             KeeperException keeperException = (KeeperException) cause;
             if (keeperException instanceof KeeperException.NoNodeException) {
                 return "Node does not exist: " + keeperException.getPath();
@@ -47,14 +49,14 @@ public class CliWrapperException extends CliException {
             } else if (keeperException instanceof KeeperException.BadVersionException) {
                 return "version No is not valid : " + keeperException.getPath();
             } else if (keeperException instanceof KeeperException.ReconfigInProgress) {
-                return "Another reconfiguration is in progress -- concurrent " +
-                        "reconfigs not supported (yet)";
+                return "Another reconfiguration is in progress -- concurrent " + "reconfigs not supported (yet)";
             } else if (keeperException instanceof KeeperException.NewConfigNoQuorum) {
-                return "No quorum of new config is connected and " +
-                        "up-to-date with the leader of last commmitted config - try invoking reconfiguration after " +
-                        "new servers are connected and synced";
+                return "No quorum of new config is connected and "
+                       + "up-to-date with the leader of last commmitted config - try invoking reconfiguration after "
+                       + "new servers are connected and synced";
             }
         }
         return cause.getMessage();
     }
+
 }

+ 5 - 5
zookeeper-server/src/main/java/org/apache/zookeeper/cli/CloseCommand.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,6 +15,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.cli;
 
 /**
@@ -25,8 +26,7 @@ public class CloseCommand extends CliCommand {
     public CloseCommand() {
         super("close", "");
     }
-    
-    
+
     @Override
     public CliCommand parse(String[] cmdArgs) throws CliParseException {
         return this;
@@ -39,8 +39,8 @@ public class CloseCommand extends CliCommand {
         } catch (Exception ex) {
             throw new CliWrapperException(ex);
         }
-        
+
         return false;
     }
-    
+
 }

+ 3 - 1
zookeeper-server/src/main/java/org/apache/zookeeper/cli/CommandNotFoundException.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,6 +15,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.cli;
 
 @SuppressWarnings("serial")
@@ -23,4 +24,5 @@ public class CommandNotFoundException extends CliException {
     public CommandNotFoundException(String command) {
         super("Command not found: " + command, 127);
     }
+
 }

+ 17 - 10
zookeeper-server/src/main/java/org/apache/zookeeper/cli/CreateCommand.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,10 +15,16 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.cli;
 
 import java.util.List;
-import org.apache.commons.cli.*;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.commons.cli.Parser;
+import org.apache.commons.cli.PosixParser;
 import org.apache.zookeeper.CreateMode;
 import org.apache.zookeeper.KeeperException;
 import org.apache.zookeeper.ZooDefs;
@@ -46,7 +52,6 @@ public class CreateCommand extends CliCommand {
         super("create", "[-s] [-e] [-c] [-t ttl] path [data] [acl]");
     }
 
-
     @Override
     public CliCommand parse(String[] cmdArgs) throws CliParseException {
         Parser parser = new PosixParser();
@@ -56,13 +61,12 @@ public class CreateCommand extends CliCommand {
             throw new CliParseException(ex);
         }
         args = cl.getArgs();
-        if(args.length < 2) {
+        if (args.length < 2) {
             throw new CliParseException(getUsageStr());
         }
         return this;
     }
 
-
     @Override
     public boolean exec() throws CliException {
         boolean hasE = cl.hasOption("e");
@@ -87,7 +91,7 @@ public class CreateCommand extends CliCommand {
         }
 
         CreateMode flags;
-        if(hasE && hasS) {
+        if (hasE && hasS) {
             flags = CreateMode.EPHEMERAL_SEQUENTIAL;
         } else if (hasE) {
             flags = CreateMode.EPHEMERAL;
@@ -116,19 +120,22 @@ public class CreateCommand extends CliCommand {
             acl = AclParser.parse(args[3]);
         }
         try {
-            String newPath = hasT ? zk.create(path, data, acl, flags, new Stat(), ttl) : zk.create(path, data, acl, flags);
+            String newPath = hasT
+                ? zk.create(path, data, acl, flags, new Stat(), ttl)
+                : zk.create(path, data, acl, flags);
             err.println("Created " + newPath);
-        } catch(IllegalArgumentException ex) {
+        } catch (IllegalArgumentException ex) {
             throw new MalformedPathException(ex.getMessage());
-        } catch(KeeperException.EphemeralOnLocalSessionException e) {
+        } catch (KeeperException.EphemeralOnLocalSessionException e) {
             err.println("Unable to create ephemeral node on a local session");
             throw new CliWrapperException(e);
         } catch (KeeperException.InvalidACLException ex) {
             err.println(ex.getMessage());
             throw new CliWrapperException(ex);
-        } catch (KeeperException|InterruptedException ex) {
+        } catch (KeeperException | InterruptedException ex) {
             throw new CliWrapperException(ex);
         }
         return true;
     }
+
 }

+ 20 - 10
zookeeper-server/src/main/java/org/apache/zookeeper/cli/DelQuotaCommand.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,11 +15,18 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.cli;
 
 import java.io.IOException;
 import java.util.List;
-import org.apache.commons.cli.*;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.OptionGroup;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.commons.cli.Parser;
+import org.apache.commons.cli.PosixParser;
 import org.apache.zookeeper.KeeperException;
 import org.apache.zookeeper.Quotas;
 import org.apache.zookeeper.StatsTrack;
@@ -75,7 +82,7 @@ public class DelQuotaCommand extends CliCommand {
                 // just delete whole quota node
                 delQuota(zk, path, true, true);
             }
-        } catch (KeeperException|InterruptedException|IOException ex) {
+        } catch (KeeperException | InterruptedException | IOException ex) {
             throw new CliWrapperException(ex);
         }
         return false;
@@ -93,12 +100,13 @@ public class DelQuotaCommand extends CliCommand {
      * @throws IOException
      * @throws InterruptedException
      */
-    public static boolean delQuota(ZooKeeper zk, String path,
-            boolean bytes, boolean numNodes)
-            throws KeeperException, IOException, InterruptedException, MalformedPathException {
+    public static boolean delQuota(
+        ZooKeeper zk,
+        String path,
+        boolean bytes,
+        boolean numNodes) throws KeeperException, IOException, InterruptedException, MalformedPathException {
         String parentPath = Quotas.quotaZookeeper + path;
-        String quotaPath = Quotas.quotaZookeeper + path + "/" + 
-                Quotas.limitNode;
+        String quotaPath = Quotas.quotaZookeeper + path + "/" + Quotas.limitNode;
         if (zk.exists(quotaPath, false) == null) {
             System.out.println("Quota does not exist for " + path);
             return true;
@@ -144,8 +152,9 @@ public class DelQuotaCommand extends CliCommand {
      * @throws IOException
      * @throws InterruptedException
      */
-    private static boolean trimProcQuotas(ZooKeeper zk, String path)
-            throws KeeperException, IOException, InterruptedException {
+    private static boolean trimProcQuotas(
+        ZooKeeper zk,
+        String path) throws KeeperException, IOException, InterruptedException {
         if (Quotas.quotaZookeeper.equals(path)) {
             return true;
         }
@@ -158,4 +167,5 @@ public class DelQuotaCommand extends CliCommand {
             return true;
         }
     }
+
 }

+ 8 - 7
zookeeper-server/src/main/java/org/apache/zookeeper/cli/DeleteAllCommand.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,6 +15,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.cli;
 
 import org.apache.commons.cli.CommandLine;
@@ -46,7 +47,7 @@ public class DeleteAllCommand extends CliCommand {
     public DeleteAllCommand(String cmdStr) {
         super(cmdStr, "path [-b batch size]");
     }
-    
+
     @Override
     public CliCommand parse(String[] cmdArgs) throws CliParseException {
         Parser parser = new PosixParser();
@@ -81,16 +82,16 @@ public class DeleteAllCommand extends CliCommand {
             }
         } catch (IllegalArgumentException ex) {
             throw new MalformedPathException(ex.getMessage());
-        } catch (KeeperException|InterruptedException ex) {
+        } catch (KeeperException | InterruptedException ex) {
             throw new CliWrapperException(ex);
         }
         return false;
     }
-    
+
     private void printDeprecatedWarning() {
-        if("rmr".equals(args[0])) {
-            err.println("The command 'rmr' has been deprecated. " +
-                  "Please use 'deleteall' instead.");
+        if ("rmr".equals(args[0])) {
+            err.println("The command 'rmr' has been deprecated. " + "Please use 'deleteall' instead.");
         }
     }
+
 }

+ 12 - 6
zookeeper-server/src/main/java/org/apache/zookeeper/cli/DeleteCommand.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,9 +15,14 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.cli;
 
-import org.apache.commons.cli.*;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.commons.cli.Parser;
+import org.apache.commons.cli.PosixParser;
 import org.apache.zookeeper.KeeperException;
 
 /**
@@ -49,7 +54,7 @@ public class DeleteCommand extends CliCommand {
         if (args.length < 2) {
             throw new CliParseException(getUsageStr());
         }
-        
+
         retainCompatibility(cmdArgs);
 
         return this;
@@ -58,7 +63,7 @@ public class DeleteCommand extends CliCommand {
     private void retainCompatibility(String[] cmdArgs) throws CliParseException {
         if (args.length > 2) {
             err.println("'delete path [version]' has been deprecated. "
-                    + "Please use 'delete [-v version] path' instead.");
+                        + "Please use 'delete [-v version] path' instead.");
             Parser parser = new PosixParser();
             try {
                 cl = parser.parse(options, cmdArgs);
@@ -78,14 +83,15 @@ public class DeleteCommand extends CliCommand {
         } else {
             version = -1;
         }
-        
+
         try {
             zk.delete(path, version);
         } catch (IllegalArgumentException ex) {
             throw new MalformedPathException(ex.getMessage());
-        } catch(KeeperException|InterruptedException ex) {
+        } catch (KeeperException | InterruptedException ex) {
             throw new CliWrapperException(ex);
         }
         return false;
     }
+
 }

+ 7 - 6
zookeeper-server/src/main/java/org/apache/zookeeper/cli/GetAclCommand.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one or more
  * contributor license agreements. See the NOTICE file distributed with this
  * work for additional information regarding copyright ownership. The ASF
@@ -14,6 +14,7 @@
  * License for the specific language governing permissions and limitations under
  * the License.
  */
+
 package org.apache.zookeeper.cli;
 
 import java.util.List;
@@ -33,7 +34,7 @@ import org.apache.zookeeper.data.Stat;
 public class GetAclCommand extends CliCommand {
 
     private static Options options = new Options();
-    private String args[];
+    private String[] args;
     private CommandLine cl;
 
     static {
@@ -66,16 +67,15 @@ public class GetAclCommand extends CliCommand {
         Stat stat = new Stat();
         List<ACL> acl;
         try {
-           acl = zk.getACL(path, stat);
+            acl = zk.getACL(path, stat);
         } catch (IllegalArgumentException ex) {
             throw new MalformedPathException(ex.getMessage());
-        } catch (KeeperException|InterruptedException ex) {
+        } catch (KeeperException | InterruptedException ex) {
             throw new CliWrapperException(ex);
         }
 
         for (ACL a : acl) {
-            out.println(a.getId() + ": "
-                        + getPermString(a.getPerms()));
+            out.println(a.getId() + ": " + getPermString(a.getPerms()));
         }
 
         if (cl.hasOption("s")) {
@@ -103,4 +103,5 @@ public class GetAclCommand extends CliCommand {
         }
         return p.toString();
     }
+
 }

+ 4 - 1
zookeeper-server/src/main/java/org/apache/zookeeper/cli/GetAllChildrenNumberCommand.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one or more
  * contributor license agreements. See the NOTICE file distributed with this
  * work for additional information regarding copyright ownership. The ASF
@@ -14,6 +14,7 @@
  * License for the specific language governing permissions and limitations under
  * the License.
  */
+
 package org.apache.zookeeper.cli;
 
 import org.apache.commons.cli.CommandLine;
@@ -27,6 +28,7 @@ import org.apache.zookeeper.KeeperException;
  * getAllChildrenNumber command for CLI
  */
 public class GetAllChildrenNumberCommand extends CliCommand {
+
     private static Options options = new Options();
     private String[] args;
 
@@ -67,4 +69,5 @@ public class GetAllChildrenNumberCommand extends CliCommand {
 
         return false;
     }
+
 }

+ 12 - 7
zookeeper-server/src/main/java/org/apache/zookeeper/cli/GetCommand.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,9 +15,14 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.cli;
 
-import org.apache.commons.cli.*;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.commons.cli.Parser;
+import org.apache.commons.cli.PosixParser;
 import org.apache.zookeeper.KeeperException;
 import org.apache.zookeeper.data.Stat;
 
@@ -27,7 +32,7 @@ import org.apache.zookeeper.data.Stat;
 public class GetCommand extends CliCommand {
 
     private static Options options = new Options();
-    private String args[];
+    private String[] args;
     private CommandLine cl;
 
     static {
@@ -63,8 +68,7 @@ public class GetCommand extends CliCommand {
         if (args.length > 2) {
             // rewrite to option
             cmdArgs[2] = "-w";
-            err.println("'get path [watch]' has been deprecated. "
-                    + "Please use 'get [-s] [-w] path' instead.");
+            err.println("'get path [watch]' has been deprecated. " + "Please use 'get [-s] [-w] path' instead.");
             Parser parser = new PosixParser();
             try {
                 cl = parser.parse(options, cmdArgs);
@@ -80,12 +84,12 @@ public class GetCommand extends CliCommand {
         boolean watch = cl.hasOption("w");
         String path = args[1];
         Stat stat = new Stat();
-        byte data[];
+        byte[] data;
         try {
             data = zk.getData(path, watch, stat);
         } catch (IllegalArgumentException ex) {
             throw new MalformedPathException(ex.getMessage());
-        } catch (KeeperException|InterruptedException ex) {
+        } catch (KeeperException | InterruptedException ex) {
             throw new CliException(ex);
         }
         data = (data == null) ? "null".getBytes() : data;
@@ -95,4 +99,5 @@ public class GetCommand extends CliCommand {
         }
         return watch;
     }
+
 }

+ 15 - 9
zookeeper-server/src/main/java/org/apache/zookeeper/cli/GetConfigCommand.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,9 +15,14 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.cli;
 
-import org.apache.commons.cli.*;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.commons.cli.Parser;
+import org.apache.commons.cli.PosixParser;
 import org.apache.zookeeper.KeeperException;
 import org.apache.zookeeper.data.Stat;
 import org.apache.zookeeper.server.util.ConfigUtils;
@@ -28,7 +33,7 @@ import org.apache.zookeeper.server.util.ConfigUtils;
 public class GetConfigCommand extends CliCommand {
 
     private static Options options = new Options();
-    private String args[];
+    private String[] args;
     private CommandLine cl;
 
     static {
@@ -60,12 +65,12 @@ public class GetConfigCommand extends CliCommand {
 
     @Override
     public boolean exec() throws CliException {
-        boolean watch = cl.hasOption("w");        
+        boolean watch = cl.hasOption("w");
         Stat stat = new Stat();
-        byte data[];
+        byte[] data;
         try {
             data = zk.getConfig(watch, stat);
-        } catch (KeeperException|InterruptedException ex) {
+        } catch (KeeperException | InterruptedException ex) {
             throw new CliWrapperException(ex);
         }
         data = (data == null) ? "null".getBytes() : data;
@@ -74,11 +79,12 @@ public class GetConfigCommand extends CliCommand {
         } else {
             out.println(new String(data));
         }
-        
+
         if (cl.hasOption("s")) {
             new StatPrinter(out).print(stat);
-        }                
-        
+        }
+
         return watch;
     }
+
 }

+ 5 - 3
zookeeper-server/src/main/java/org/apache/zookeeper/cli/GetEphemeralsCommand.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one or more
  * contributor license agreements. See the NOTICE file distributed with this
  * work for additional information regarding copyright ownership. The ASF
@@ -14,10 +14,10 @@
  * License for the specific language governing permissions and limitations under
  * the License.
  */
+
 package org.apache.zookeeper.cli;
 
 import java.util.List;
-
 import org.apache.commons.cli.CommandLine;
 import org.apache.commons.cli.Options;
 import org.apache.commons.cli.ParseException;
@@ -29,6 +29,7 @@ import org.apache.zookeeper.KeeperException;
  * getEphemerals command for CLI
  */
 public class GetEphemeralsCommand extends CliCommand {
+
     private static Options options = new Options();
     private String[] args;
 
@@ -64,10 +65,11 @@ public class GetEphemeralsCommand extends CliCommand {
             }
         } catch (IllegalArgumentException ex) {
             throw new MalformedPathException(ex.getMessage());
-        } catch (KeeperException|InterruptedException ex) {
+        } catch (KeeperException | InterruptedException ex) {
             throw new CliWrapperException(ex);
         }
         out.println(ephemerals);
         return false;
     }
+
 }

+ 18 - 16
zookeeper-server/src/main/java/org/apache/zookeeper/cli/ListQuotaCommand.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,9 +15,14 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.cli;
 
-import org.apache.commons.cli.*;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.commons.cli.Parser;
+import org.apache.commons.cli.PosixParser;
 import org.apache.zookeeper.KeeperException;
 import org.apache.zookeeper.Quotas;
 import org.apache.zookeeper.StatsTrack;
@@ -30,7 +35,7 @@ public class ListQuotaCommand extends CliCommand {
 
     private static Options options = new Options();
     private String[] args;
-    
+
     public ListQuotaCommand() {
         super("listquota", "path");
     }
@@ -45,38 +50,35 @@ public class ListQuotaCommand extends CliCommand {
             throw new CliParseException(ex);
         }
         args = cl.getArgs();
-        if(args.length < 2) {
+        if (args.length < 2) {
             throw new CliParseException(getUsageStr());
         }
-        
+
         return this;
     }
-    
+
     @Override
     public boolean exec() throws CliException {
         String path = args[1];
-        String absolutePath = Quotas.quotaZookeeper + path + "/"
-                + Quotas.limitNode;
+        String absolutePath = Quotas.quotaZookeeper + path + "/" + Quotas.limitNode;
         try {
             err.println("absolute path is " + absolutePath);
             Stat stat = new Stat();
             byte[] data = zk.getData(absolutePath, false, stat);
             StatsTrack st = new StatsTrack(new String(data));
-            out.println("Output quota for " + path + " "
-                    + st.toString());
+            out.println("Output quota for " + path + " " + st.toString());
 
-            data = zk.getData(Quotas.quotaZookeeper + path + "/"
-                    + Quotas.statNode, false, stat);
-            out.println("Output stat for " + path + " "
-                    + new StatsTrack(new String(data)).toString());
+            data = zk.getData(Quotas.quotaZookeeper + path + "/" + Quotas.statNode, false, stat);
+            out.println("Output stat for " + path + " " + new StatsTrack(new String(data)).toString());
         } catch (IllegalArgumentException ex) {
             throw new MalformedPathException(ex.getMessage());
         } catch (KeeperException.NoNodeException ne) {
             err.println("quota for " + path + " does not exist.");
-        } catch (KeeperException|InterruptedException ex) {
+        } catch (KeeperException | InterruptedException ex) {
             throw new CliWrapperException(ex);
         }
-        
+
         return false;
     }
+
 }

+ 14 - 9
zookeeper-server/src/main/java/org/apache/zookeeper/cli/Ls2Command.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one or more
  * contributor license agreements. See the NOTICE file distributed with this
  * work for additional information regarding copyright ownership. The ASF
@@ -14,10 +14,15 @@
  * License for the specific language governing permissions and limitations under
  * the License.
  */
+
 package org.apache.zookeeper.cli;
 
 import java.util.List;
-import org.apache.commons.cli.*;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.commons.cli.Parser;
+import org.apache.commons.cli.PosixParser;
 import org.apache.zookeeper.KeeperException;
 import org.apache.zookeeper.data.Stat;
 
@@ -27,12 +32,12 @@ import org.apache.zookeeper.data.Stat;
 public class Ls2Command extends CliCommand {
 
     private static Options options = new Options();
-    private String args[];
-    
+    private String[] args;
+
     public Ls2Command() {
         super("ls2", "path [watch]");
     }
-    
+
     @Override
     public CliCommand parse(String[] cmdArgs) throws CliParseException {
         Parser parser = new PosixParser();
@@ -46,14 +51,13 @@ public class Ls2Command extends CliCommand {
         if (args.length < 2) {
             throw new CliParseException(getUsageStr());
         }
-        
+
         return this;
     }
 
     @Override
     public boolean exec() throws CliException {
-        err.println("'ls2' has been deprecated. "
-                  + "Please use 'ls [-s] path' instead.");
+        err.println("'ls2' has been deprecated. " + "Please use 'ls [-s] path' instead.");
         String path = args[1];
         boolean watch = args.length > 2;
         Stat stat = new Stat();
@@ -62,11 +66,12 @@ public class Ls2Command extends CliCommand {
             children = zk.getChildren(path, watch, stat);
         } catch (IllegalArgumentException ex) {
             throw new MalformedPathException(ex.getMessage());
-        } catch (KeeperException|InterruptedException ex) {
+        } catch (KeeperException | InterruptedException ex) {
             throw new CliWrapperException(ex);
         }
         out.println(children);
         new StatPrinter(out).print(stat);
         return watch;
     }
+
 }

+ 12 - 6
zookeeper-server/src/main/java/org/apache/zookeeper/cli/LsCommand.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one or more
  * contributor license agreements. See the NOTICE file distributed with this
  * work for additional information regarding copyright ownership. The ASF
@@ -14,11 +14,17 @@
  * License for the specific language governing permissions and limitations under
  * the License.
  */
+
 package org.apache.zookeeper.cli;
 
 import java.util.Collections;
 import java.util.List;
-import org.apache.commons.cli.*;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.HelpFormatter;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.commons.cli.Parser;
+import org.apache.commons.cli.PosixParser;
 import org.apache.zookeeper.AsyncCallback.StringCallback;
 import org.apache.zookeeper.KeeperException;
 import org.apache.zookeeper.ZKUtil;
@@ -30,7 +36,7 @@ import org.apache.zookeeper.data.Stat;
 public class LsCommand extends CliCommand {
 
     private static Options options = new Options();
-    private String args[];
+    private String[] args;
     private CommandLine cl;
 
     static {
@@ -73,8 +79,7 @@ public class LsCommand extends CliCommand {
         if (args.length > 2) {
             // rewrite to option
             cmdArgs[2] = "-w";
-            err.println("'ls path [watch]' has been deprecated. "
-                    + "Please use 'ls [-w] path' instead.");
+            err.println("'ls path [watch]' has been deprecated. " + "Please use 'ls [-w] path' instead.");
             Parser parser = new PosixParser();
             try {
                 cl = parser.parse(options, cmdArgs);
@@ -110,7 +115,7 @@ public class LsCommand extends CliCommand {
             }
         } catch (IllegalArgumentException ex) {
             throw new MalformedPathException(ex.getMessage());
-        } catch (KeeperException|InterruptedException ex) {
+        } catch (KeeperException | InterruptedException ex) {
             throw new CliWrapperException(ex);
         }
         return watch;
@@ -134,4 +139,5 @@ public class LsCommand extends CliCommand {
         }
         out.append("\n");
     }
+
 }

+ 4 - 1
zookeeper-server/src/main/java/org/apache/zookeeper/cli/MalformedCommandException.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,11 +15,14 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.cli;
 
 @SuppressWarnings("serial")
 public class MalformedCommandException extends CliException {
+
     public MalformedCommandException(String message) {
         super(message);
     }
+
 }

+ 4 - 1
zookeeper-server/src/main/java/org/apache/zookeeper/cli/MalformedPathException.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,11 +15,14 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.cli;
 
 @SuppressWarnings("serial")
 public class MalformedPathException extends CliException {
+
     public MalformedPathException(String message) {
         super(message);
     }
+
 }

+ 30 - 29
zookeeper-server/src/main/java/org/apache/zookeeper/cli/ReconfigCommand.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,12 +15,16 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.cli;
 
 import java.io.FileInputStream;
 import java.util.Properties;
-
-import org.apache.commons.cli.*;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.commons.cli.Parser;
+import org.apache.commons.cli.PosixParser;
 import org.apache.zookeeper.KeeperException;
 import org.apache.zookeeper.admin.ZooKeeperAdmin;
 import org.apache.zookeeper.data.Stat;
@@ -34,7 +38,7 @@ public class ReconfigCommand extends CliCommand {
     private static Options options = new Options();
 
     /* joining - comma separated list of server config strings for servers to be added to the ensemble.
-     * Each entry is identical in syntax as it would appear in a configuration file. Only used for 
+     * Each entry is identical in syntax as it would appear in a configuration file. Only used for
      * incremental reconfigurations.
      */
     private String joining;
@@ -53,28 +57,25 @@ public class ReconfigCommand extends CliCommand {
 
     /* version - version of config from which we want to reconfigure - if current config is different
      * reconfiguration will fail. Should be committed from the CLI to disable this option.
-     */
-    long version = -1;
+     */ long version = -1;
     private CommandLine cl;
 
     static {
         options.addOption("s", false, "stats");
         options.addOption("v", true, "required current config version");
         options.addOption("file", true, "path of config file to parse for membership");
-        options.addOption("members", true, "comma-separated list of config strings for " +
-        		"non-incremental reconfig");
-        options.addOption("add", true, "comma-separated list of config strings for " +
-        		"new servers");
+        options.addOption("members", true, "comma-separated list of config strings for " + "non-incremental reconfig");
+        options.addOption("add", true, "comma-separated list of config strings for " + "new servers");
         options.addOption("remove", true, "comma-separated list of server IDs to remove");
     }
 
     public ReconfigCommand() {
-        super("reconfig", "[-s] " +
-        		"[-v version] " +
-        		"[[-file path] | " +
-        		"[-members serverID=host:port1:port2;port3[,...]*]] | " +
-        		"[-add serverId=host:port1:port2;port3[,...]]* " +
-        		"[-remove serverId[,...]*]");
+        super("reconfig", "[-s] "
+                          + "[-v version] "
+                          + "[[-file path] | "
+                          + "[-members serverID=host:port1:port2;port3[,...]*]] | "
+                          + "[-add serverId=host:port1:port2;port3[,...]]* "
+                          + "[-remove serverId[,...]*]");
     }
 
     @Override
@@ -92,9 +93,9 @@ public class ReconfigCommand extends CliCommand {
             throw new CliParseException(getUsageStr());
         }
         if (cl.hasOption("v")) {
-            try{ 
+            try {
                 version = Long.parseLong(cl.getOptionValue("v"), 16);
-            } catch (NumberFormatException e){
+            } catch (NumberFormatException e) {
                 throw new CliParseException("-v must be followed by a long (configuration version)");
             }
         } else {
@@ -103,8 +104,8 @@ public class ReconfigCommand extends CliCommand {
 
         // Simple error checking for conflicting modes
         if ((cl.hasOption("file") || cl.hasOption("members")) && (cl.hasOption("add") || cl.hasOption("remove"))) {
-            throw new CliParseException("Can't use -file or -members together with -add or -remove (mixing incremental" +
-            		" and non-incremental modes is not allowed)");
+            throw new CliParseException("Can't use -file or -members together with -add or -remove (mixing incremental"
+                                        + " and non-incremental modes is not allowed)");
         }
         if (cl.hasOption("file") && cl.hasOption("members")) {
             throw new CliParseException("Can't use -file and -members together (conflicting non-incremental modes)");
@@ -112,13 +113,13 @@ public class ReconfigCommand extends CliCommand {
 
         // Set the joining/leaving/members values based on the mode we're in
         if (cl.hasOption("add")) {
-           joining = cl.getOptionValue("add").toLowerCase();
+            joining = cl.getOptionValue("add").toLowerCase();
         }
         if (cl.hasOption("remove")) {
-           leaving = cl.getOptionValue("remove").toLowerCase();
+            leaving = cl.getOptionValue("remove").toLowerCase();
         }
         if (cl.hasOption("members")) {
-           members = cl.getOptionValue("members").toLowerCase();
+            members = cl.getOptionValue("members").toLowerCase();
         }
         if (cl.hasOption("file")) {
             try {
@@ -127,12 +128,12 @@ public class ReconfigCommand extends CliCommand {
                     dynamicCfg.load(inConfig);
                 }
                 //check that membership makes sense; leader will make these checks again
-                //don't check for leader election ports since 
+                //don't check for leader election ports since
                 //client doesn't know what leader election alg is used
                 members = QuorumPeerConfig.parseDynamicConfig(dynamicCfg, 0, true, false).toString();
             } catch (Exception e) {
                 throw new CliParseException("Error processing " + cl.getOptionValue("file") + e.getMessage());
-            } 
+            }
         }
         return this;
     }
@@ -150,16 +151,16 @@ public class ReconfigCommand extends CliCommand {
                 return false;
             }
 
-            byte[] curConfig = ((ZooKeeperAdmin)zk).reconfigure(joining,
-                    leaving, members, version, stat);
+            byte[] curConfig = ((ZooKeeperAdmin) zk).reconfigure(joining, leaving, members, version, stat);
             out.println("Committed new configuration:\n" + new String(curConfig));
-            
+
             if (cl.hasOption("s")) {
                 new StatPrinter(out).print(stat);
             }
-        } catch (KeeperException|InterruptedException ex) {
+        } catch (KeeperException | InterruptedException ex) {
             throw new CliWrapperException(ex);
         }
         return false;
     }
+
 }

+ 5 - 4
zookeeper-server/src/main/java/org/apache/zookeeper/cli/RemoveWatchesCommand.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,6 +15,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.cli;
 
 import org.apache.commons.cli.CommandLine;
@@ -38,8 +39,7 @@ public class RemoveWatchesCommand extends CliCommand {
         options.addOption("c", false, "child watcher type");
         options.addOption("d", false, "data watcher type");
         options.addOption("a", false, "any watcher type");
-        options.addOption("l", false,
-                "remove locally when there is no server connection");
+        options.addOption("l", false, "remove locally when there is no server connection");
     }
 
     public RemoveWatchesCommand() {
@@ -81,9 +81,10 @@ public class RemoveWatchesCommand extends CliCommand {
             zk.removeAllWatches(path, wtype, local);
         } catch (IllegalArgumentException ex) {
             throw new MalformedPathException(ex.getMessage());
-        } catch (KeeperException|InterruptedException ex) {
+        } catch (KeeperException | InterruptedException ex) {
             throw new CliWrapperException(ex);
         }
         return true;
     }
+
 }

+ 9 - 3
zookeeper-server/src/main/java/org/apache/zookeeper/cli/SetAclCommand.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,10 +15,15 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.cli;
 
 import java.util.List;
-import org.apache.commons.cli.*;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.commons.cli.Parser;
+import org.apache.commons.cli.PosixParser;
 import org.apache.zookeeper.AsyncCallback.StringCallback;
 import org.apache.zookeeper.KeeperException;
 import org.apache.zookeeper.ZKUtil;
@@ -94,11 +99,12 @@ public class SetAclCommand extends CliCommand {
             }
         } catch (IllegalArgumentException ex) {
             throw new MalformedPathException(ex.getMessage());
-        } catch (KeeperException|InterruptedException ex) {
+        } catch (KeeperException | InterruptedException ex) {
             throw new CliWrapperException(ex);
         }
 
         return false;
 
     }
+
 }

+ 9 - 3
zookeeper-server/src/main/java/org/apache/zookeeper/cli/SetCommand.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,9 +15,14 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.cli;
 
-import org.apache.commons.cli.*;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.commons.cli.Parser;
+import org.apache.commons.cli.PosixParser;
 import org.apache.zookeeper.KeeperException;
 import org.apache.zookeeper.data.Stat;
 
@@ -73,9 +78,10 @@ public class SetCommand extends CliCommand {
             }
         } catch (IllegalArgumentException ex) {
             throw new MalformedPathException(ex.getMessage());
-        } catch (KeeperException|InterruptedException ex) {
+        } catch (KeeperException | InterruptedException ex) {
             throw new CliWrapperException(ex);
         }
         return false;
     }
+
 }

+ 35 - 26
zookeeper-server/src/main/java/org/apache/zookeeper/cli/SetQuotaCommand.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,12 +15,26 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.cli;
 
 import java.util.ArrayList;
 import java.util.List;
-import org.apache.commons.cli.*;
-import org.apache.zookeeper.*;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.OptionGroup;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.commons.cli.Parser;
+import org.apache.commons.cli.PosixParser;
+import org.apache.zookeeper.AsyncCallback;
+import org.apache.zookeeper.CreateMode;
+import org.apache.zookeeper.KeeperException;
+import org.apache.zookeeper.Quotas;
+import org.apache.zookeeper.StatsTrack;
+import org.apache.zookeeper.ZKUtil;
+import org.apache.zookeeper.ZooDefs;
+import org.apache.zookeeper.ZooKeeper;
 import org.apache.zookeeper.data.Stat;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -37,13 +51,13 @@ public class SetQuotaCommand extends CliCommand {
 
     public SetQuotaCommand() {
         super("setquota", "-n|-b val path");
-        
+
         OptionGroup og1 = new OptionGroup();
         og1.addOption(new Option("b", true, "bytes quota"));
         og1.addOption(new Option("n", true, "num quota"));
         og1.setRequired(true);
         options.addOptionGroup(og1);
-   }
+    }
 
     @Override
     public CliCommand parse(String[] cmdArgs) throws CliParseException {
@@ -75,7 +89,7 @@ public class SetQuotaCommand extends CliCommand {
             long bytes = Long.parseLong(cl.getOptionValue("b"));
             try {
                 createQuota(zk, path, bytes, -1);
-            } catch (KeeperException|InterruptedException|IllegalArgumentException ex) {
+            } catch (KeeperException | InterruptedException | IllegalArgumentException ex) {
                 throw new CliWrapperException(ex);
             }
         } else if (cl.hasOption("n")) {
@@ -83,7 +97,7 @@ public class SetQuotaCommand extends CliCommand {
             int numNodes = Integer.parseInt(cl.getOptionValue("n"));
             try {
                 createQuota(zk, path, -1L, numNodes);
-            } catch (KeeperException|InterruptedException|IllegalArgumentException ex) {
+            } catch (KeeperException | InterruptedException | IllegalArgumentException ex) {
                 throw new CliWrapperException(ex);
             }
         } else {
@@ -93,9 +107,11 @@ public class SetQuotaCommand extends CliCommand {
         return false;
     }
 
-    public static boolean createQuota(ZooKeeper zk, String path,
-            long bytes, int numNodes)
-            throws KeeperException, InterruptedException, IllegalArgumentException, MalformedPathException {
+    public static boolean createQuota(
+        ZooKeeper zk,
+        String path,
+        long bytes,
+        int numNodes) throws KeeperException, InterruptedException, IllegalArgumentException, MalformedPathException {
         // check if the path exists. We cannot create
         // quota for a path that already exists in zookeeper
         // for now.
@@ -128,10 +144,8 @@ public class SetQuotaCommand extends CliCommand {
         // start creating all the parents
         if (zk.exists(quotaPath, false) == null) {
             try {
-                zk.create(Quotas.procZookeeper, null, ZooDefs.Ids.OPEN_ACL_UNSAFE,
-                        CreateMode.PERSISTENT);
-                zk.create(Quotas.quotaZookeeper, null, ZooDefs.Ids.OPEN_ACL_UNSAFE,
-                        CreateMode.PERSISTENT);
+                zk.create(Quotas.procZookeeper, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+                zk.create(Quotas.quotaZookeeper, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
             } catch (KeeperException.NodeExistsException ne) {
                 // do nothing
             }
@@ -146,8 +160,7 @@ public class SetQuotaCommand extends CliCommand {
             sb.append("/").append(splits[i]);
             quotaPath = sb.toString();
             try {
-                zk.create(quotaPath, null, ZooDefs.Ids.OPEN_ACL_UNSAFE,
-                        CreateMode.PERSISTENT);
+                zk.create(quotaPath, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
             } catch (KeeperException.NodeExistsException ne) {
                 //do nothing
             }
@@ -158,13 +171,11 @@ public class SetQuotaCommand extends CliCommand {
         strack.setBytes(bytes);
         strack.setCount(numNodes);
         try {
-            zk.create(quotaPath, strack.toString().getBytes(),
-                    ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+            zk.create(quotaPath, strack.toString().getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
             StatsTrack stats = new StatsTrack(null);
             stats.setBytes(0L);
             stats.setCount(0);
-            zk.create(statPath, stats.toString().getBytes(),
-                    ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
+            zk.create(statPath, stats.toString().getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
         } catch (KeeperException.NodeExistsException ne) {
             byte[] data = zk.getData(quotaPath, false, new Stat());
             StatsTrack strackC = new StatsTrack(new String(data));
@@ -202,8 +213,7 @@ public class SetQuotaCommand extends CliCommand {
                     }
                     for (String child : children) {
                         if (!quotaPath.equals(Quotas.quotaZookeeper + path) && Quotas.limitNode.equals(child)) {
-                            throw new IllegalArgumentException(path + " has a child "
-                                    + quotaPath.substring(Quotas.quotaZookeeper.length()) + " which has a quota");
+                            throw new IllegalArgumentException(path + " has a child " + quotaPath.substring(Quotas.quotaZookeeper.length()) + " which has a quota");
                         }
                     }
                 }
@@ -213,8 +223,7 @@ public class SetQuotaCommand extends CliCommand {
         }
     }
 
-    private static void checkIfParentQuota(ZooKeeper zk, String path)
-            throws InterruptedException, KeeperException {
+    private static void checkIfParentQuota(ZooKeeper zk, String path) throws InterruptedException, KeeperException {
         final String[] splits = path.split("/");
         String quotaPath = Quotas.quotaZookeeper;
         for (String str : splits) {
@@ -236,10 +245,10 @@ public class SetQuotaCommand extends CliCommand {
             }
             for (String child : children) {
                 if (!quotaPath.equals(Quotas.quotaZookeeper + path) && Quotas.limitNode.equals(child)) {
-                    throw new IllegalArgumentException(path + " has a parent "
-                            + quotaPath.substring(Quotas.quotaZookeeper.length()) + " which has a quota");
+                    throw new IllegalArgumentException(path + " has a parent " + quotaPath.substring(Quotas.quotaZookeeper.length()) + " which has a quota");
                 }
             }
         }
     }
+
 }

+ 15 - 11
zookeeper-server/src/main/java/org/apache/zookeeper/cli/StatCommand.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,9 +15,14 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.cli;
 
-import org.apache.commons.cli.*;
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.commons.cli.Parser;
+import org.apache.commons.cli.PosixParser;
 import org.apache.zookeeper.KeeperException;
 import org.apache.zookeeper.data.Stat;
 
@@ -33,12 +38,11 @@ public class StatCommand extends CliCommand {
     static {
         options.addOption("w", false, "watch");
     }
-    
+
     public StatCommand() {
         super("stat", "[-w] path");
     }
 
-    
     @Override
     public CliCommand parse(String[] cmdArgs) throws CliParseException {
         Parser parser = new PosixParser();
@@ -48,10 +52,10 @@ public class StatCommand extends CliCommand {
             throw new CliParseException(ex);
         }
         args = cl.getArgs();
-        if(args.length < 2) {
+        if (args.length < 2) {
             throw new CliParseException(getUsageStr());
-        }    
-        
+        }
+
         retainCompatibility(cmdArgs);
 
         return this;
@@ -62,8 +66,7 @@ public class StatCommand extends CliCommand {
         if (args.length > 2) {
             // rewrite to option
             cmdArgs[2] = "-w";
-            err.println("'stat path [watch]' has been deprecated. "
-                    + "Please use 'stat [-w] path' instead.");
+            err.println("'stat path [watch]' has been deprecated. " + "Please use 'stat [-w] path' instead.");
             Parser parser = new PosixParser();
             try {
                 cl = parser.parse(options, cmdArgs);
@@ -73,7 +76,7 @@ public class StatCommand extends CliCommand {
             args = cl.getArgs();
         }
     }
-    
+
     @Override
     public boolean exec() throws CliException {
         String path = args[1];
@@ -83,7 +86,7 @@ public class StatCommand extends CliCommand {
             stat = zk.exists(path, watch);
         } catch (IllegalArgumentException ex) {
             throw new MalformedPathException(ex.getMessage());
-        } catch (KeeperException|InterruptedException ex) {
+        } catch (KeeperException | InterruptedException ex) {
             throw new CliWrapperException(ex);
         }
         if (stat == null) {
@@ -92,4 +95,5 @@ public class StatCommand extends CliCommand {
         new StatPrinter(out).print(stat);
         return watch;
     }
+
 }

+ 4 - 3
zookeeper-server/src/main/java/org/apache/zookeeper/cli/StatPrinter.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,6 +15,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.cli;
 
 import java.io.PrintStream;
@@ -41,9 +42,9 @@ public class StatPrinter {
         out.println("cversion = " + stat.getCversion());
         out.println("dataVersion = " + stat.getVersion());
         out.println("aclVersion = " + stat.getAversion());
-        out.println("ephemeralOwner = 0x"
-                + Long.toHexString(stat.getEphemeralOwner()));
+        out.println("ephemeralOwner = 0x" + Long.toHexString(stat.getEphemeralOwner()));
         out.println("dataLength = " + stat.getDataLength());
         out.println("numChildren = " + stat.getNumChildren());
     }
+
 }

+ 4 - 3
zookeeper-server/src/main/java/org/apache/zookeeper/cli/SyncCommand.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one or more
  * contributor license agreements. See the NOTICE file distributed with this
  * work for additional information regarding copyright ownership. The ASF
@@ -14,13 +14,13 @@
  * License for the specific language governing permissions and limitations under
  * the License.
  */
+
 package org.apache.zookeeper.cli;
 
 import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
-
 import org.apache.commons.cli.CommandLine;
 import org.apache.commons.cli.Options;
 import org.apache.commons.cli.ParseException;
@@ -71,7 +71,7 @@ public class SyncCommand extends CliCommand {
             }, null);
 
             int resultCode = cf.get(SYNC_TIMEOUT, TimeUnit.MILLISECONDS);
-            if(resultCode == 0) {
+            if (resultCode == 0) {
                 out.println("Sync is OK");
             } else {
                 out.println("Sync has failed. rc=" + resultCode);
@@ -87,4 +87,5 @@ public class SyncCommand extends CliCommand {
 
         return false;
     }
+
 }

+ 3 - 1
zookeeper-server/src/main/java/org/apache/zookeeper/cli/VersionCommand.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one or more
  * contributor license agreements. See the NOTICE file distributed with this
  * work for additional information regarding copyright ownership. The ASF
@@ -14,6 +14,7 @@
  * License for the specific language governing permissions and limitations under
  * the License.
  */
+
 package org.apache.zookeeper.cli;
 
 import org.apache.commons.cli.CommandLine;
@@ -58,4 +59,5 @@ public class VersionCommand extends CliCommand {
 
         return false;
     }
+
 }

+ 12 - 12
zookeeper-server/src/main/java/org/apache/zookeeper/client/ConnectStringParser.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -18,27 +18,26 @@
 
 package org.apache.zookeeper.client;
 
-import org.apache.zookeeper.common.PathUtils;
-import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
-import org.apache.zookeeper.server.util.ConfigUtils;
-
+import static org.apache.zookeeper.common.StringUtils.split;
 import java.net.InetSocketAddress;
 import java.util.ArrayList;
 import java.util.List;
-
-import static org.apache.zookeeper.common.StringUtils.split;
+import org.apache.zookeeper.common.PathUtils;
+import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
+import org.apache.zookeeper.server.util.ConfigUtils;
 
 /**
  * A parser for ZooKeeper Client connect strings.
- * 
+ *
  * This class is not meant to be seen or used outside of ZooKeeper itself.
- * 
+ *
  * The chrootPath member should be replaced by a Path object in issue
  * ZOOKEEPER-849.
- * 
+ *
  * @see org.apache.zookeeper.ZooKeeper
  */
 public final class ConnectStringParser {
+
     private static final int DEFAULT_PORT = 2181;
 
     private final String chrootPath;
@@ -68,7 +67,7 @@ public final class ConnectStringParser {
             this.chrootPath = null;
         }
 
-        List<String> hostsList = split(connectString,",");
+        List<String> hostsList = split(connectString, ",");
         for (String host : hostsList) {
             int port = DEFAULT_PORT;
             try {
@@ -80,7 +79,7 @@ public final class ConnectStringParser {
             } catch (ConfigException e) {
                 e.printStackTrace();
             }
-		    
+
             serverAddresses.add(InetSocketAddress.createUnresolved(host, port));
         }
     }
@@ -92,4 +91,5 @@ public final class ConnectStringParser {
     public ArrayList<InetSocketAddress> getServerAddresses() {
         return serverAddresses;
     }
+
 }

+ 23 - 20
zookeeper-server/src/main/java/org/apache/zookeeper/client/FourLetterWordMain.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -26,13 +26,11 @@ import java.net.InetAddress;
 import java.net.InetSocketAddress;
 import java.net.Socket;
 import java.net.SocketTimeoutException;
-
 import javax.net.ssl.SSLContext;
 import javax.net.ssl.SSLSocket;
 import javax.net.ssl.SSLSocketFactory;
-
-import org.apache.zookeeper.common.ClientX509Util;
 import org.apache.yetus.audience.InterfaceAudience;
+import org.apache.zookeeper.common.ClientX509Util;
 import org.apache.zookeeper.common.X509Exception.SSLContextException;
 import org.apache.zookeeper.common.X509Util;
 import org.slf4j.Logger;
@@ -40,6 +38,7 @@ import org.slf4j.LoggerFactory;
 
 @InterfaceAudience.Public
 public class FourLetterWordMain {
+
     //in milliseconds, socket should connect/read within this period otherwise SocketTimeoutException
     private static final int DEFAULT_SOCKET_TIMEOUT = 5000;
     protected static final Logger LOG = LoggerFactory.getLogger(FourLetterWordMain.class);
@@ -52,8 +51,7 @@ public class FourLetterWordMain {
      * @throws java.io.IOException
      * @throws SSLContextException
      */
-    public static String send4LetterWord(String host, int port, String cmd)
-            throws IOException, SSLContextException {
+    public static String send4LetterWord(String host, int port, String cmd) throws IOException, SSLContextException {
         return send4LetterWord(host, port, cmd, false, DEFAULT_SOCKET_TIMEOUT);
     }
 
@@ -67,8 +65,11 @@ public class FourLetterWordMain {
      * @throws java.io.IOException
      * @throws SSLContextException
      */
-    public static String send4LetterWord(String host, int port, String cmd, boolean secure)
-            throws IOException, SSLContextException {
+    public static String send4LetterWord(
+        String host,
+        int port,
+        String cmd,
+        boolean secure) throws IOException, SSLContextException {
         return send4LetterWord(host, port, cmd, secure, DEFAULT_SOCKET_TIMEOUT);
     }
 
@@ -83,12 +84,17 @@ public class FourLetterWordMain {
      * @throws java.io.IOException
      * @throws SSLContextException
      */
-    public static String send4LetterWord(String host, int port, String cmd, boolean secure, int timeout)
-            throws IOException, SSLContextException {
+    public static String send4LetterWord(
+        String host,
+        int port,
+        String cmd,
+        boolean secure,
+        int timeout) throws IOException, SSLContextException {
         LOG.info("connecting to {} {}", host, port);
         Socket sock;
-        InetSocketAddress hostaddress= host != null ? new InetSocketAddress(host, port) :
-            new InetSocketAddress(InetAddress.getByName(null), port);
+        InetSocketAddress hostaddress = host != null
+            ? new InetSocketAddress(host, port)
+            : new InetSocketAddress(InetAddress.getByName(null), port);
         if (secure) {
             LOG.info("using secure socket");
             try (X509Util x509Util = new ClientX509Util()) {
@@ -116,12 +122,10 @@ public class FourLetterWordMain {
                 sock.shutdownOutput();
             }
 
-            reader =
-                    new BufferedReader(
-                            new InputStreamReader(sock.getInputStream()));
+            reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
             StringBuilder sb = new StringBuilder();
             String line;
-            while((line = reader.readLine()) != null) {
+            while ((line = reader.readLine()) != null) {
                 sb.append(line).append("\n");
             }
             return sb.toString();
@@ -134,10 +138,8 @@ public class FourLetterWordMain {
             }
         }
     }
-    
-    public static void main(String[] args)
-            throws IOException, SSLContextException
-    {
+
+    public static void main(String[] args) throws IOException, SSLContextException {
         if (args.length == 3) {
             System.out.println(send4LetterWord(args[0], Integer.parseInt(args[1]), args[2]));
         } else if (args.length == 4) {
@@ -146,4 +148,5 @@ public class FourLetterWordMain {
             System.out.println("Usage: FourLetterWordMain <host> <port> <cmd> <secure(optional)>");
         }
     }
+
 }

+ 20 - 20
zookeeper-server/src/main/java/org/apache/zookeeper/client/HostProvider.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -18,58 +18,58 @@
 
 package org.apache.zookeeper.client;
 
-import org.apache.yetus.audience.InterfaceAudience;
-
 import java.net.InetSocketAddress;
 import java.util.Collection;
+import org.apache.yetus.audience.InterfaceAudience;
 
 /**
  * A set of hosts a ZooKeeper client should connect to.
- * 
+ *
  * Classes implementing this interface must guarantee the following:
- * 
+ *
  * * Every call to next() returns an InetSocketAddress. So the iterator never
  * ends.
- * 
+ *
  * * The size() of a HostProvider may never be zero.
- * 
+ *
  * A HostProvider must return resolved InetSocketAddress instances on next() if the next address is resolvable.
  * In that case, it's up to the HostProvider, whether it returns the next resolvable address in the list or return
  * the next one as UnResolved.
- * 
+ *
  * Different HostProvider could be imagined:
- * 
- * * A HostProvider that loads the list of Hosts from an URL or from DNS 
- * * A HostProvider that re-resolves the InetSocketAddress after a timeout. 
+ *
+ * * A HostProvider that loads the list of Hosts from an URL or from DNS
+ * * A HostProvider that re-resolves the InetSocketAddress after a timeout.
  * * A HostProvider that prefers nearby hosts.
  */
 @InterfaceAudience.Public
 public interface HostProvider {
-    public int size();
+
+    int size();
 
     /**
      * The next host to try to connect to.
-     * 
+     *
      * For a spinDelay of 0 there should be no wait.
-     * 
+     *
      * @param spinDelay
      *            Milliseconds to wait if all hosts have been tried once.
      */
-    public InetSocketAddress next(long spinDelay);
+    InetSocketAddress next(long spinDelay);
 
     /**
      * Notify the HostProvider of a successful connection.
-     * 
+     *
      * The HostProvider may use this notification to reset it's inner state.
      */
-    public void onConnected();
+    void onConnected();
 
     /**
      * Update the list of servers. This returns true if changing connections is necessary for load-balancing, false otherwise.
      * @param serverAddresses new host list
      * @param currentHost the host to which this client is currently connected
-     * @return true if changing connections is necessary for load-balancing, false otherwise  
+     * @return true if changing connections is necessary for load-balancing, false otherwise
      */
-    boolean updateServerList(Collection<InetSocketAddress> serverAddresses,
-        InetSocketAddress currentHost);
+    boolean updateServerList(Collection<InetSocketAddress> serverAddresses, InetSocketAddress currentHost);
+
 }

+ 43 - 50
zookeeper-server/src/main/java/org/apache/zookeeper/client/StaticHostProvider.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -27,7 +27,6 @@ import java.util.Collection;
 import java.util.Collections;
 import java.util.List;
 import java.util.Random;
-
 import org.apache.yetus.audience.InterfaceAudience;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -42,15 +41,16 @@ import org.slf4j.LoggerFactory;
  */
 @InterfaceAudience.Public
 public final class StaticHostProvider implements HostProvider {
+
     public interface Resolver {
+
         InetAddress[] getAllByName(String name) throws UnknownHostException;
+
     }
 
-    private static final Logger LOG = LoggerFactory
-            .getLogger(StaticHostProvider.class);
+    private static final Logger LOG = LoggerFactory.getLogger(StaticHostProvider.class);
 
-    private List<InetSocketAddress> serverAddresses = new ArrayList<InetSocketAddress>(
-            5);
+    private List<InetSocketAddress> serverAddresses = new ArrayList<InetSocketAddress>(5);
 
     private Random sourceOfRandomness;
     private int lastIndex = -1;
@@ -62,11 +62,9 @@ public final class StaticHostProvider implements HostProvider {
      */
     private boolean reconfigMode = false;
 
-    private final List<InetSocketAddress> oldServers = new ArrayList<InetSocketAddress>(
-            5);
+    private final List<InetSocketAddress> oldServers = new ArrayList<InetSocketAddress>(5);
 
-    private final List<InetSocketAddress> newServers = new ArrayList<InetSocketAddress>(
-            5);
+    private final List<InetSocketAddress> newServers = new ArrayList<InetSocketAddress>(5);
 
     private int currentIndexOld = -1;
     private int currentIndexNew = -1;
@@ -77,16 +75,14 @@ public final class StaticHostProvider implements HostProvider {
 
     /**
      * Constructs a SimpleHostSet.
-     * 
+     *
      * @param serverAddresses
      *            possibly unresolved ZooKeeper server addresses
      * @throws IllegalArgumentException
      *             if serverAddresses is empty or resolves to an empty list
      */
     public StaticHostProvider(Collection<InetSocketAddress> serverAddresses) {
-        init(serverAddresses,
-                System.currentTimeMillis() ^ this.hashCode(),
-                new Resolver() {
+        init(serverAddresses, System.currentTimeMillis() ^ this.hashCode(), new Resolver() {
             @Override
             public InetAddress[] getAllByName(String name) throws UnknownHostException {
                 return InetAddress.getAllByName(name);
@@ -112,15 +108,14 @@ public final class StaticHostProvider implements HostProvider {
     /**
      * Constructs a SimpleHostSet. This constructor is used from StaticHostProviderTest to produce deterministic test results
      * by initializing sourceOfRandomness with the same seed
-     * 
+     *
      * @param serverAddresses
      *            possibly unresolved ZooKeeper server addresses
      * @param randomnessSeed a seed used to initialize sourceOfRandomnes
      * @throws IllegalArgumentException
      *             if serverAddresses is empty or resolves to an empty list
      */
-    public StaticHostProvider(Collection<InetSocketAddress> serverAddresses,
-        long randomnessSeed) {
+    public StaticHostProvider(Collection<InetSocketAddress> serverAddresses, long randomnessSeed) {
         init(serverAddresses, randomnessSeed, new Resolver() {
             @Override
             public InetAddress[] getAllByName(String name) throws UnknownHostException {
@@ -133,8 +128,7 @@ public final class StaticHostProvider implements HostProvider {
         this.sourceOfRandomness = new Random(randomnessSeed);
         this.resolver = resolver;
         if (serverAddresses.isEmpty()) {
-            throw new IllegalArgumentException(
-                    "A HostProvider may not be empty!");
+            throw new IllegalArgumentException("A HostProvider may not be empty!");
         }
         this.serverAddresses = shuffle(serverAddresses);
         currentIndex = -1;
@@ -165,14 +159,14 @@ public final class StaticHostProvider implements HostProvider {
 
     /**
      * Update the list of servers. This returns true if changing connections is necessary for load-balancing, false
-	 * otherwise. Changing connections is necessary if one of the following holds: 
+     * otherwise. Changing connections is necessary if one of the following holds:
      * a) the host to which this client is currently connected is not in serverAddresses.
-     *    Otherwise (if currentHost is in the new list serverAddresses):   
+     *    Otherwise (if currentHost is in the new list serverAddresses):
      * b) the number of servers in the cluster is increasing - in this case the load on currentHost should decrease,
      *    which means that SOME of the clients connected to it will migrate to the new servers. The decision whether
-     *    this client migrates or not (i.e., whether true or false is returned) is probabilistic so that the expected 
+     *    this client migrates or not (i.e., whether true or false is returned) is probabilistic so that the expected
      *    number of clients connected to each server is the same.
-     *    
+     *
      * If true is returned, the function sets pOld and pNew that correspond to the probability to migrate to ones of the
      * new servers in serverAddresses or one of the old servers (migrating to one of the old servers is done only
      * if our client's currentHost is not in serverAddresses). See nextHostInReconfigMode for the selection logic.
@@ -183,16 +177,15 @@ public final class StaticHostProvider implements HostProvider {
      *
      * @param serverAddresses new host list
      * @param currentHost the host to which this client is currently connected
-     * @return true if changing connections is necessary for load-balancing, false otherwise  
+     * @return true if changing connections is necessary for load-balancing, false otherwise
      */
     @Override
     public synchronized boolean updateServerList(
-            Collection<InetSocketAddress> serverAddresses,
-            InetSocketAddress currentHost) {
+        Collection<InetSocketAddress> serverAddresses,
+        InetSocketAddress currentHost) {
         List<InetSocketAddress> shuffledList = shuffle(serverAddresses);
         if (shuffledList.isEmpty()) {
-            throw new IllegalArgumentException(
-                    "A HostProvider may not be empty!");
+            throw new IllegalArgumentException("A HostProvider may not be empty!");
         }
         // Check if client's current server is in the new list of servers
         boolean myServerInNewConfig = false;
@@ -218,10 +211,10 @@ public final class StaticHostProvider implements HostProvider {
 
         for (InetSocketAddress addr : shuffledList) {
             if (addr.getPort() == myServer.getPort()
-                    && ((addr.getAddress() != null
-                            && myServer.getAddress() != null && addr
-                            .getAddress().equals(myServer.getAddress())) || addr
-                            .getHostString().equals(myServer.getHostString()))) {
+                && ((addr.getAddress() != null
+                     && myServer.getAddress() != null
+                     && addr.getAddress().equals(myServer.getAddress()))
+                    || addr.getHostString().equals(myServer.getHostString()))) {
                 myServerInNewConfig = true;
                 break;
             }
@@ -250,8 +243,7 @@ public final class StaticHostProvider implements HostProvider {
                 // my server is in new config, but load should be decreased.
                 // Need to decide if this client
                 // is moving to one of the new servers
-                if (sourceOfRandomness.nextFloat() <= (1 - ((float) this.serverAddresses
-                        .size()) / (numOld + numNew))) {
+                if (sourceOfRandomness.nextFloat() <= (1 - ((float) this.serverAddresses.size()) / (numOld + numNew))) {
                     pNew = 1;
                     pOld = 0;
                 } else {
@@ -272,7 +264,7 @@ public final class StaticHostProvider implements HostProvider {
                 reconfigMode = false;
             } else {
                 pOld = ((float) (numOld * (this.serverAddresses.size() - (numOld + numNew))))
-                        / ((numOld + numNew) * (this.serverAddresses.size() - numOld));
+                       / ((numOld + numNew) * (this.serverAddresses.size() - numOld));
                 pNew = 1 - pOld;
             }
         }
@@ -290,12 +282,14 @@ public final class StaticHostProvider implements HostProvider {
     }
 
     public synchronized InetSocketAddress getServerAtIndex(int i) {
-    	if (i < 0 || i >= serverAddresses.size()) return null;
-    	return serverAddresses.get(i);
+        if (i < 0 || i >= serverAddresses.size()) {
+            return null;
+        }
+        return serverAddresses.get(i);
     }
-    
+
     public synchronized InetSocketAddress getServerAtCurrentIndex() {
-    	return getServerAtIndex(currentIndex);
+        return getServerAtIndex(currentIndex);
     }
 
     public synchronized int size() {
@@ -303,11 +297,11 @@ public final class StaticHostProvider implements HostProvider {
     }
 
     /**
-     * Get the next server to connect to, when in "reconfigMode", which means that 
-     * you've just updated the server list, and now trying to find some server to connect to. 
+     * Get the next server to connect to, when in "reconfigMode", which means that
+     * you've just updated the server list, and now trying to find some server to connect to.
      * Once onConnected() is called, reconfigMode is set to false. Similarly, if we tried to connect
      * to all servers in new config and failed, reconfigMode is set to false.
-     * 
+     *
      * While in reconfigMode, we should connect to a server in newServers with probability pNew and to servers in
      * oldServers with probability pOld (which is just 1-pNew). If we tried out all servers in either oldServers
      * or newServers we continue to try servers from the other set, regardless of pNew or pOld. If we tried all servers
@@ -323,8 +317,7 @@ public final class StaticHostProvider implements HostProvider {
         // and either the probability tells us to connect to one of the new
         // servers or if we already
         // tried all the old servers
-        if (((currentIndexNew + 1) < newServers.size())
-                && (takeNew || (currentIndexOld + 1) >= oldServers.size())) {
+        if (((currentIndexNew + 1) < newServers.size()) && (takeNew || (currentIndexOld + 1) >= oldServers.size())) {
             ++currentIndexNew;
             return newServers.get(currentIndexNew);
         }
@@ -342,24 +335,24 @@ public final class StaticHostProvider implements HostProvider {
         boolean needToSleep = false;
         InetSocketAddress addr;
 
-        synchronized(this) {
+        synchronized (this) {
             if (reconfigMode) {
                 addr = nextHostInReconfigMode();
                 if (addr != null) {
-                	currentIndex = serverAddresses.indexOf(addr);
-                	return resolve(addr);
+                    currentIndex = serverAddresses.indexOf(addr);
+                    return resolve(addr);
                 }
                 //tried all servers and couldn't connect
                 reconfigMode = false;
                 needToSleep = (spinDelay > 0);
-            }        
+            }
             ++currentIndex;
             if (currentIndex == serverAddresses.size()) {
                 currentIndex = 0;
-            }            
+            }
             addr = serverAddresses.get(currentIndex);
             needToSleep = needToSleep || (currentIndex == lastIndex && spinDelay > 0);
-            if (lastIndex == -1) { 
+            if (lastIndex == -1) {
                 // We don't want to sleep on the first ever connect attempt.
                 lastIndex = 0;
             }

+ 6 - 7
zookeeper-server/src/main/java/org/apache/zookeeper/client/ZKClientConfig.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -19,7 +19,6 @@
 package org.apache.zookeeper.client;
 
 import java.io.File;
-
 import org.apache.yetus.audience.InterfaceAudience;
 import org.apache.zookeeper.ZooKeeper;
 import org.apache.zookeeper.common.ZKConfig;
@@ -31,13 +30,13 @@ import org.apache.zookeeper.server.quorum.QuorumPeerConfig.ConfigException;
  */
 @InterfaceAudience.Public
 public class ZKClientConfig extends ZKConfig {
+
     public static final String ZK_SASL_CLIENT_USERNAME = "zookeeper.sasl.client.username";
     public static final String ZK_SASL_CLIENT_USERNAME_DEFAULT = "zookeeper";
-    public static final String ZK_SASL_CLIENT_CANONICALIZE_HOSTNAME =
-        "zookeeper.sasl.client.canonicalize.hostname";
+    public static final String ZK_SASL_CLIENT_CANONICALIZE_HOSTNAME = "zookeeper.sasl.client.canonicalize.hostname";
     public static final String ZK_SASL_CLIENT_CANONICALIZE_HOSTNAME_DEFAULT = "true";
     @SuppressWarnings("deprecation")
-    public static final String LOGIN_CONTEXT_NAME_KEY = ZooKeeperSaslClient.LOGIN_CONTEXT_NAME_KEY;;
+    public static final String LOGIN_CONTEXT_NAME_KEY = ZooKeeperSaslClient.LOGIN_CONTEXT_NAME_KEY;
     public static final String LOGIN_CONTEXT_NAME_KEY_DEFAULT = "Client";
     @SuppressWarnings("deprecation")
     public static final String ENABLE_CLIENT_SASL_KEY = ZooKeeperSaslClient.ENABLE_CLIENT_SASL_KEY;
@@ -83,8 +82,7 @@ public class ZKClientConfig extends ZKConfig {
      * java system property
      */
     private void initFromJavaSystemProperties() {
-        setProperty(ZOOKEEPER_REQUEST_TIMEOUT,
-                System.getProperty(ZOOKEEPER_REQUEST_TIMEOUT));
+        setProperty(ZOOKEEPER_REQUEST_TIMEOUT, System.getProperty(ZOOKEEPER_REQUEST_TIMEOUT));
     }
 
     @Override
@@ -140,4 +138,5 @@ public class ZKClientConfig extends ZKConfig {
         }
         return defaultValue;
     }
+
 }

+ 91 - 100
zookeeper-server/src/main/java/org/apache/zookeeper/client/ZooKeeperSaslClient.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -21,14 +21,12 @@ package org.apache.zookeeper.client;
 import java.io.IOException;
 import java.security.PrivilegedActionException;
 import java.security.PrivilegedExceptionAction;
-
 import javax.security.auth.Subject;
 import javax.security.auth.login.AppConfigurationEntry;
 import javax.security.auth.login.Configuration;
 import javax.security.auth.login.LoginException;
 import javax.security.sasl.SaslClient;
 import javax.security.sasl.SaslException;
-
 import org.apache.zookeeper.AsyncCallback;
 import org.apache.zookeeper.ClientCnxn;
 import org.apache.zookeeper.Login;
@@ -38,7 +36,6 @@ import org.apache.zookeeper.ZooDefs;
 import org.apache.zookeeper.data.Stat;
 import org.apache.zookeeper.proto.GetSASLRequest;
 import org.apache.zookeeper.proto.SetSASLResponse;
-
 import org.apache.zookeeper.util.SecurityUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -48,6 +45,7 @@ import org.slf4j.LoggerFactory;
  * allows ClientCnxn to authenticate using SASL with a ZooKeeper server.
  */
 public class ZooKeeperSaslClient {
+
     /**
      * @deprecated Use {@link ZKClientConfig#LOGIN_CONTEXT_NAME_KEY}
      *             instead.
@@ -66,7 +64,7 @@ public class ZooKeeperSaslClient {
      */
     @Deprecated
     public static final String ENABLE_CLIENT_SASL_DEFAULT = "true";
-    private volatile boolean initializedLogin = false; 
+    private volatile boolean initializedLogin = false;
 
     /**
      * Returns true if the SASL client is enabled. By default, the client
@@ -79,9 +77,7 @@ public class ZooKeeperSaslClient {
      */
     @Deprecated
     public static boolean isEnabled() {
-        return Boolean.valueOf(System.getProperty(
-                ZKClientConfig.ENABLE_CLIENT_SASL_KEY,
-                ZKClientConfig.ENABLE_CLIENT_SASL_DEFAULT));
+        return Boolean.parseBoolean(System.getProperty(ZKClientConfig.ENABLE_CLIENT_SASL_KEY, ZKClientConfig.ENABLE_CLIENT_SASL_DEFAULT));
     }
 
     private static final Logger LOG = LoggerFactory.getLogger(ZooKeeperSaslClient.class);
@@ -93,7 +89,10 @@ public class ZooKeeperSaslClient {
     private byte[] saslToken = new byte[0];
 
     public enum SaslState {
-        INITIAL,INTERMEDIATE,COMPLETE,FAILED
+        INITIAL,
+        INTERMEDIATE,
+        COMPLETE,
+        FAILED
     }
 
     private SaslState saslState = SaslState.INITIAL;
@@ -107,8 +106,9 @@ public class ZooKeeperSaslClient {
     }
 
     public String getLoginContext() {
-        if (login != null)
+        if (login != null) {
             return login.getLoginContextName();
+        }
         return null;
     }
 
@@ -118,22 +118,19 @@ public class ZooKeeperSaslClient {
          * configuration section that the zookeeper client should use.
          * Default to "Client".
          */
-        String clientSection = clientConfig.getProperty(
-                ZKClientConfig.LOGIN_CONTEXT_NAME_KEY,
-                ZKClientConfig.LOGIN_CONTEXT_NAME_KEY_DEFAULT);
+        String clientSection = clientConfig.getProperty(ZKClientConfig.LOGIN_CONTEXT_NAME_KEY, ZKClientConfig.LOGIN_CONTEXT_NAME_KEY_DEFAULT);
         this.clientConfig = clientConfig;
         // Note that 'Configuration' here refers to javax.security.auth.login.Configuration.
-        AppConfigurationEntry entries[] = null;
+        AppConfigurationEntry[] entries = null;
         RuntimeException runtimeException = null;
         try {
-            entries = Configuration.getConfiguration()
-                    .getAppConfigurationEntry(clientSection);
+            entries = Configuration.getConfiguration().getAppConfigurationEntry(clientSection);
         } catch (SecurityException e) {
             // handle below: might be harmless if the user doesn't intend to use JAAS authentication.
             runtimeException = e;
         } catch (IllegalArgumentException e) {
             // third party customized getAppConfigurationEntry could throw IllegalArgumentException when JAAS
-            // configuration isn't set. We can reevaluate whether to catch RuntimeException instead when more 
+            // configuration isn't set. We can reevaluate whether to catch RuntimeException instead when more
             // different types of RuntimeException found
             runtimeException = e;
         }
@@ -141,24 +138,26 @@ public class ZooKeeperSaslClient {
             this.configStatus = "Will attempt to SASL-authenticate using Login Context section '" + clientSection + "'";
             this.saslClient = createSaslClient(serverPrincipal, clientSection);
         } else {
-            // Handle situation of clientSection's being null: it might simply because the client does not intend to 
+            // Handle situation of clientSection's being null: it might simply because the client does not intend to
             // use SASL, so not necessarily an error.
             saslState = SaslState.FAILED;
-            String explicitClientSection = clientConfig
-                    .getProperty(ZKClientConfig.LOGIN_CONTEXT_NAME_KEY);
+            String explicitClientSection = clientConfig.getProperty(ZKClientConfig.LOGIN_CONTEXT_NAME_KEY);
             if (explicitClientSection != null) {
                 // If the user explicitly overrides the default Login Context, they probably expected SASL to
                 // succeed. But if we got here, SASL failed.
                 if (runtimeException != null) {
-                    throw new LoginException(
-                            "Zookeeper client cannot authenticate using the "
-                                    + explicitClientSection
-                                    + " section of the supplied JAAS configuration: '"
-                                    + clientConfig.getJaasConfKey() + "' because of a "
-                                    + "RuntimeException: " + runtimeException);
+                    throw new LoginException("Zookeeper client cannot authenticate using the "
+                                             + explicitClientSection
+                                             + " section of the supplied JAAS configuration: '"
+                                             + clientConfig.getJaasConfKey()
+                                             + "' because of a "
+                                             + "RuntimeException: "
+                                             + runtimeException);
                 } else {
-                    throw new LoginException("Client cannot SASL-authenticate because the specified JAAS configuration " +
-                            "section '" + explicitClientSection + "' could not be found.");
+                    throw new LoginException("Client cannot SASL-authenticate because the specified JAAS configuration "
+                                             + "section '"
+                                             + explicitClientSection
+                                             + "' could not be found.");
                 }
             } else {
                 // The user did not override the default context. It might be that they just don't intend to use SASL,
@@ -176,27 +175,24 @@ public class ZooKeeperSaslClient {
                 // Again, the user explicitly set something SASL-related, so
                 // they probably expected SASL to succeed.
                 if (runtimeException != null) {
-                    throw new LoginException(
-                            "Zookeeper client cannot authenticate using the '"
-                                    + clientConfig.getProperty(
-                                            ZKClientConfig.LOGIN_CONTEXT_NAME_KEY,
-                                            ZKClientConfig.LOGIN_CONTEXT_NAME_KEY_DEFAULT)
-                                    + "' section of the supplied JAAS configuration: '"
-                                    + clientConfig.getJaasConfKey() + "' because of a "
-                                    + "RuntimeException: " + runtimeException);
+                    throw new LoginException("Zookeeper client cannot authenticate using the '"
+                                             + clientConfig.getProperty(ZKClientConfig.LOGIN_CONTEXT_NAME_KEY, ZKClientConfig.LOGIN_CONTEXT_NAME_KEY_DEFAULT)
+                                             + "' section of the supplied JAAS configuration: '"
+                                             + clientConfig.getJaasConfKey()
+                                             + "' because of a "
+                                             + "RuntimeException: "
+                                             + runtimeException);
                 } else {
-                    throw new LoginException(
-                            "No JAAS configuration section named '"
-                                    + clientConfig.getProperty(
-                                            ZKClientConfig.LOGIN_CONTEXT_NAME_KEY,
-                                            ZKClientConfig.LOGIN_CONTEXT_NAME_KEY_DEFAULT)
-                                    + "' was found in specified JAAS configuration file: '"
-                                    + clientConfig.getJaasConfKey() + "'.");
+                    throw new LoginException("No JAAS configuration section named '"
+                                             + clientConfig.getProperty(ZKClientConfig.LOGIN_CONTEXT_NAME_KEY, ZKClientConfig.LOGIN_CONTEXT_NAME_KEY_DEFAULT)
+                                             + "' was found in specified JAAS configuration file: '"
+                                             + clientConfig.getJaasConfKey()
+                                             + "'.");
                 }
             }
         }
     }
-    
+
     /**
      * @return informational message indicating the current configuration status.
      */
@@ -213,34 +209,32 @@ public class ZooKeeperSaslClient {
     }
 
     public static class ServerSaslResponseCallback implements AsyncCallback.DataCallback {
-        public void processResult(int rc, String path, Object ctx, byte data[], Stat stat) {
+
+        public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
             // processResult() is used by ClientCnxn's sendThread to respond to
             // data[] contains the Zookeeper Server's SASL token.
             // ctx is the ZooKeeperSaslClient object. We use this object's respondToServer() method
             // to reply to the Zookeeper Server's SASL token
-            ZooKeeperSaslClient client = ((ClientCnxn)ctx).zooKeeperSaslClient;
+            ZooKeeperSaslClient client = ((ClientCnxn) ctx).zooKeeperSaslClient;
             if (client == null) {
                 LOG.warn("sasl client was unexpectedly null: cannot respond to Zookeeper server.");
                 return;
             }
             byte[] usedata = data;
             if (data != null) {
-                LOG.debug(
-                    "ServerSaslResponseCallback(): saslToken server response: (length={})",
-                    usedata.length);
-            }
-            else {
+                LOG.debug("ServerSaslResponseCallback(): saslToken server response: (length={})", usedata.length);
+            } else {
                 usedata = new byte[0];
-                LOG.debug(
-                    "ServerSaslResponseCallback(): using empty data[] as server response (length={})",
-                    usedata.length);
+                LOG.debug("ServerSaslResponseCallback(): using empty data[] as server response (length={})", usedata.length);
             }
-            client.respondToServer(usedata, (ClientCnxn)ctx);
+            client.respondToServer(usedata, (ClientCnxn) ctx);
         }
+
     }
 
-    private SaslClient createSaslClient(final String servicePrincipal, final String loginContext)
-            throws LoginException {
+    private SaslClient createSaslClient(
+        final String servicePrincipal,
+        final String loginContext) throws LoginException {
         try {
             if (!initializedLogin) {
                 synchronized (this) {
@@ -254,8 +248,7 @@ public class ZooKeeperSaslClient {
                     }
                 }
             }
-            return SecurityUtils.createSaslClient(login.getSubject(),
-                    servicePrincipal, "zookeeper", "zk-sasl-md5", LOG, "Client");
+            return SecurityUtils.createSaslClient(login.getSubject(), servicePrincipal, "zookeeper", "zk-sasl-md5", LOG, "Client");
         } catch (LoginException e) {
             // We throw LoginExceptions...
             throw e;
@@ -279,8 +272,9 @@ public class ZooKeeperSaslClient {
                     sendSaslPacket(saslToken, cnxn);
                 }
             } catch (SaslException e) {
-                LOG.error("SASL authentication failed using login context '" +
-                        this.getLoginContext() + "' with exception: {}", e);
+                LOG.error("SASL authentication failed using login context '"
+                          + this.getLoginContext()
+                          + "' with exception: {}", e);
                 saslState = SaslState.FAILED;
                 gotLastPacket = true;
             }
@@ -289,8 +283,9 @@ public class ZooKeeperSaslClient {
         if (saslClient.isComplete()) {
             // GSSAPI: server sends a final packet after authentication succeeds
             // or fails.
-            if ((serverToken == null) && (saslClient.getMechanismName().equals("GSSAPI")))
+            if ((serverToken == null) && (saslClient.getMechanismName().equals("GSSAPI"))) {
                 gotLastPacket = true;
+            }
             // non-GSSAPI: no final packet from server.
             if (!saslClient.getMechanismName().equals("GSSAPI")) {
                 gotLastPacket = true;
@@ -316,28 +311,25 @@ public class ZooKeeperSaslClient {
 
         Subject subject = login.getSubject();
         if (subject != null) {
-            synchronized(login) {
+            synchronized (login) {
                 try {
-                    final byte[] retval =
-                        Subject.doAs(subject, new PrivilegedExceptionAction<byte[]>() {
-                                public byte[] run() throws SaslException {
-                                    LOG.debug("saslClient.evaluateChallenge(len={})", saslToken.length);
-                                    return saslClient.evaluateChallenge(saslToken);
-                                }
-                            });
+                    final byte[] retval = Subject.doAs(subject, new PrivilegedExceptionAction<byte[]>() {
+                        public byte[] run() throws SaslException {
+                            LOG.debug("saslClient.evaluateChallenge(len={})", saslToken.length);
+                            return saslClient.evaluateChallenge(saslToken);
+                        }
+                    });
                     return retval;
-                }
-                catch (PrivilegedActionException e) {
-                    String error = "An error: (" + e + ") occurred when evaluating Zookeeper Quorum Member's " +
-                      " received SASL token.";
+                } catch (PrivilegedActionException e) {
+                    String error = "An error: (" + e + ") occurred when evaluating Zookeeper Quorum Member's "
+                                   + " received SASL token.";
                     // Try to provide hints to use about what went wrong so they can fix their configuration.
                     // TODO: introspect about e: look for GSS information.
-                    final String UNKNOWN_SERVER_ERROR_TEXT =
-                      "(Mechanism level: Server not found in Kerberos database (7) - UNKNOWN_SERVER)";
+                    final String UNKNOWN_SERVER_ERROR_TEXT = "(Mechanism level: Server not found in Kerberos database (7) - UNKNOWN_SERVER)";
                     if (e.toString().contains(UNKNOWN_SERVER_ERROR_TEXT)) {
-                        error += " This may be caused by Java's being unable to resolve the Zookeeper Quorum Member's" +
-                          " hostname correctly. You may want to try to adding" +
-                          " '-Dsun.net.spi.nameservice.provider.1=dns,sun' to your client's JVMFLAGS environment.";
+                        error += " This may be caused by Java's being unable to resolve the Zookeeper Quorum Member's"
+                                 + " hostname correctly. You may want to try to adding"
+                                 + " '-Dsun.net.spi.nameservice.provider.1=dns,sun' to your client's JVMFLAGS environment.";
                     }
                     error += " Zookeeper Client will go to AUTH_FAILED state.";
                     LOG.error(error);
@@ -345,15 +337,13 @@ public class ZooKeeperSaslClient {
                     throw new SaslException(error);
                 }
             }
-        }
-        else {
-            throw new SaslException("Cannot make SASL token without subject defined. " +
-              "For diagnosis, please look for WARNs and ERRORs in your log related to the Login class.");
+        } else {
+            throw new SaslException("Cannot make SASL token without subject defined. "
+                                    + "For diagnosis, please look for WARNs and ERRORs in your log related to the Login class.");
         }
     }
 
-    private void sendSaslPacket(byte[] saslToken, ClientCnxn cnxn)
-      throws SaslException{
+    private void sendSaslPacket(byte[] saslToken, ClientCnxn cnxn) throws SaslException {
         LOG.debug("ClientCnxn:sendSaslPacket:length={}", saslToken.length);
 
         GetSASLRequest request = new GetSASLRequest();
@@ -362,10 +352,9 @@ public class ZooKeeperSaslClient {
         ServerSaslResponseCallback cb = new ServerSaslResponseCallback();
 
         try {
-            cnxn.sendPacket(request,response,cb, ZooDefs.OpCode.sasl);
+            cnxn.sendPacket(request, response, cb, ZooDefs.OpCode.sasl);
         } catch (IOException e) {
-            throw new SaslException("Failed to send SASL packet to server.",
-                e);
+            throw new SaslException("Failed to send SASL packet to server.", e);
         }
     }
 
@@ -377,10 +366,9 @@ public class ZooKeeperSaslClient {
         SetSASLResponse response = new SetSASLResponse();
         ServerSaslResponseCallback cb = new ServerSaslResponseCallback();
         try {
-            cnxn.sendPacket(request,response,cb, ZooDefs.OpCode.sasl);
+            cnxn.sendPacket(request, response, cb, ZooDefs.OpCode.sasl);
         } catch (IOException e) {
-            throw new SaslException("Failed to send SASL packet to server due " +
-              "to IOException:", e);
+            throw new SaslException("Failed to send SASL packet to server due " + "to IOException:", e);
         }
     }
 
@@ -389,7 +377,7 @@ public class ZooKeeperSaslClient {
     public KeeperState getKeeperState() {
         if (saslClient != null) {
             if (saslState == SaslState.FAILED) {
-              return KeeperState.AuthFailed;
+                return KeeperState.AuthFailed;
             }
             if (saslClient.isComplete()) {
                 if (saslState == SaslState.INTERMEDIATE) {
@@ -412,8 +400,7 @@ public class ZooKeeperSaslClient {
         if (saslState == SaslState.INITIAL) {
             if (saslClient.hasInitialResponse()) {
                 sendSaslPacket(cnxn);
-            }
-            else {
+            } else {
                 byte[] emptyToken = new byte[0];
                 sendSaslPacket(emptyToken, cnxn);
             }
@@ -422,17 +409,19 @@ public class ZooKeeperSaslClient {
     }
 
     public boolean clientTunneledAuthenticationInProgress() {
-    	if (!isSASLConfigured) {
-    	    return false;
-        } 
+        if (!isSASLConfigured) {
+            return false;
+        }
         // TODO: Rather than checking a disjunction here, should be a single member
         // variable or method in this class to determine whether the client is
         // configured to use SASL. (see also ZOOKEEPER-1455).
         try {
             if ((clientConfig.getJaasConfKey() != null)
-                    || ((Configuration.getConfiguration() != null) && (Configuration.getConfiguration()
-                            .getAppConfigurationEntry(clientConfig.getProperty(ZKClientConfig.LOGIN_CONTEXT_NAME_KEY,
-                                    ZKClientConfig.LOGIN_CONTEXT_NAME_KEY_DEFAULT)) != null))) {
+                || ((Configuration.getConfiguration() != null)
+                    && (Configuration.getConfiguration().getAppConfigurationEntry(
+                clientConfig.getProperty(
+                    ZKClientConfig.LOGIN_CONTEXT_NAME_KEY,
+                    ZKClientConfig.LOGIN_CONTEXT_NAME_KEY_DEFAULT)) != null))) {
                 // Client is configured to use a valid login Configuration, so
                 // authentication is either in progress, successful, or failed.
 
@@ -442,6 +431,7 @@ public class ZooKeeperSaslClient {
                 }
 
                 // 2. SASL authentication has succeeded or failed..
+                //noinspection RedundantIfStatement
                 if (!gotLastPacket) {
                     // ..but still in progress, because there is a final SASL
                     // message from server which must be received.
@@ -469,4 +459,5 @@ public class ZooKeeperSaslClient {
             login.shutdown();
         }
     }
+
 }

+ 9 - 12
zookeeper-server/src/main/java/org/apache/zookeeper/common/AtomicFileOutputStream.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,6 +15,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.common;
 
 import java.io.File;
@@ -22,7 +23,6 @@ import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.FilterOutputStream;
 import java.io.IOException;
-
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -44,10 +44,10 @@ import org.slf4j.LoggerFactory;
  * place.
  */
 public class AtomicFileOutputStream extends FilterOutputStream {
+
     private static final String TMP_EXTENSION = ".tmp";
 
-    private final static Logger LOG = LoggerFactory
-            .getLogger(AtomicFileOutputStream.class);
+    private static final Logger LOG = LoggerFactory.getLogger(AtomicFileOutputStream.class);
 
     private final File origFile;
     private final File tmpFile;
@@ -56,11 +56,9 @@ public class AtomicFileOutputStream extends FilterOutputStream {
         // Code unfortunately must be duplicated below since we can't assign
         // anything
         // before calling super
-        super(new FileOutputStream(new File(f.getParentFile(), f.getName()
-                + TMP_EXTENSION)));
+        super(new FileOutputStream(new File(f.getParentFile(), f.getName() + TMP_EXTENSION)));
         origFile = f.getAbsoluteFile();
-        tmpFile = new File(f.getParentFile(), f.getName() + TMP_EXTENSION)
-                .getAbsoluteFile();
+        tmpFile = new File(f.getParentFile(), f.getName() + TMP_EXTENSION).getAbsoluteFile();
     }
 
     /**
@@ -70,7 +68,7 @@ public class AtomicFileOutputStream extends FilterOutputStream {
      * efficient.
      */
     @Override
-    public void write(byte b[], int off, int len) throws IOException {
+    public void write(byte[] b, int off, int len) throws IOException {
         out.write(b, off, len);
     }
 
@@ -90,9 +88,7 @@ public class AtomicFileOutputStream extends FilterOutputStream {
                 if (!renamed) {
                     // On windows, renameTo does not replace.
                     if (!origFile.delete() || !tmpFile.renameTo(origFile)) {
-                        throw new IOException(
-                                "Could not rename temporary file " + tmpFile
-                                        + " to " + origFile);
+                        throw new IOException("Could not rename temporary file " + tmpFile + " to " + origFile);
                     }
                 }
             } else {
@@ -123,4 +119,5 @@ public class AtomicFileOutputStream extends FilterOutputStream {
             LOG.warn("Unable to delete tmp file during abort " + tmpFile);
         }
     }
+
 }

+ 13 - 9
zookeeper-server/src/main/java/org/apache/zookeeper/common/AtomicFileWritingIdiom.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,6 +15,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.common;
 
 import java.io.BufferedWriter;
@@ -26,34 +27,37 @@ import java.io.Writer;
 
 /*
  *  Used to perform an atomic write into a file.
- *  If there is a failure in the middle of the writing operation, 
+ *  If there is a failure in the middle of the writing operation,
  *  the original file (if it exists) is left intact.
  *  Based on the org.apache.zookeeper.server.quorum.QuorumPeer.writeLongToFile(...) idiom
  *  using the HDFS AtomicFileOutputStream class.
  */
 public class AtomicFileWritingIdiom {
 
-    public static interface OutputStreamStatement {
+    public interface OutputStreamStatement {
 
-        public void write(OutputStream os) throws IOException;
+        void write(OutputStream os) throws IOException;
 
     }
 
-    public static interface WriterStatement {
+    public interface WriterStatement {
 
-        public void write(Writer os) throws IOException;
+        void write(Writer os) throws IOException;
 
     }
 
-    public AtomicFileWritingIdiom(File targetFile, OutputStreamStatement osStmt)  throws IOException {
+    public AtomicFileWritingIdiom(File targetFile, OutputStreamStatement osStmt) throws IOException {
         this(targetFile, osStmt, null);
     }
 
-    public AtomicFileWritingIdiom(File targetFile, WriterStatement wStmt)  throws IOException {
+    public AtomicFileWritingIdiom(File targetFile, WriterStatement wStmt) throws IOException {
         this(targetFile, null, wStmt);
     }
 
-    private AtomicFileWritingIdiom(File targetFile, OutputStreamStatement osStmt, WriterStatement wStmt)  throws IOException {
+    private AtomicFileWritingIdiom(
+        File targetFile,
+        OutputStreamStatement osStmt,
+        WriterStatement wStmt) throws IOException {
         AtomicFileOutputStream out = null;
         boolean error = true;
         try {

+ 2 - 1
zookeeper-server/src/main/java/org/apache/zookeeper/common/ClientX509Util.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -35,4 +35,5 @@ public class ClientX509Util extends X509Util {
     public String getSslAuthProviderProperty() {
         return sslAuthProviderProperty;
     }
+
 }

+ 13 - 22
zookeeper-server/src/main/java/org/apache/zookeeper/common/FileChangeWatcher.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -19,10 +19,6 @@
 package org.apache.zookeeper.common;
 
 import com.sun.nio.file.SensitivityWatchEventModifier;
-import org.apache.zookeeper.server.ZooKeeperThread;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
 import java.io.IOException;
 import java.nio.file.ClosedWatchServiceException;
 import java.nio.file.FileSystem;
@@ -32,6 +28,9 @@ import java.nio.file.WatchEvent;
 import java.nio.file.WatchKey;
 import java.nio.file.WatchService;
 import java.util.function.Consumer;
+import org.apache.zookeeper.server.ZooKeeperThread;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * Instances of this class can be used to watch a directory for file changes. When a file is added to, deleted from,
@@ -45,6 +44,7 @@ import java.util.function.Consumer;
  * </ul>
  */
 public final class FileChangeWatcher {
+
     private static final Logger LOG = LoggerFactory.getLogger(FileChangeWatcher.class);
 
     public enum State {
@@ -72,14 +72,7 @@ public final class FileChangeWatcher {
 
         LOG.debug("Registering with watch service: {}", dirPath);
 
-        dirPath.register(
-                watchService,
-                new WatchEvent.Kind<?>[]{
-                        StandardWatchEventKinds.ENTRY_CREATE,
-                        StandardWatchEventKinds.ENTRY_DELETE,
-                        StandardWatchEventKinds.ENTRY_MODIFY,
-                        StandardWatchEventKinds.OVERFLOW},
-                SensitivityWatchEventModifier.HIGH);
+        dirPath.register(watchService, new WatchEvent.Kind<?>[]{StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.OVERFLOW}, SensitivityWatchEventModifier.HIGH);
         state = State.NEW;
         this.watcherThread = new WatcherThread(watchService, callback);
         this.watcherThread.setDaemon(true);
@@ -165,9 +158,7 @@ public final class FileChangeWatcher {
      * Tells the background thread to stop. Does not wait for it to exit.
      */
     public void stop() {
-        if (compareAndSetState(
-                new State[]{State.RUNNING, State.STARTING},
-                State.STOPPING)) {
+        if (compareAndSetState(new State[]{State.RUNNING, State.STARTING}, State.STOPPING)) {
             watcherThread.interrupt();
         }
     }
@@ -176,6 +167,7 @@ public final class FileChangeWatcher {
      * Inner class that implements the watcher thread logic.
      */
     private class WatcherThread extends ZooKeeperThread {
+
         private static final String THREAD_NAME = "FileChangeWatcher";
 
         final WatchService watchService;
@@ -191,9 +183,7 @@ public final class FileChangeWatcher {
         public void run() {
             try {
                 LOG.info(getName() + " thread started");
-                if (!compareAndSetState(
-                        FileChangeWatcher.State.STARTING,
-                        FileChangeWatcher.State.RUNNING)) {
+                if (!compareAndSetState(FileChangeWatcher.State.STARTING, FileChangeWatcher.State.RUNNING)) {
                     // stop() called shortly after start(), before
                     // this thread started running.
                     FileChangeWatcher.State state = FileChangeWatcher.this.getState();
@@ -222,13 +212,12 @@ public final class FileChangeWatcher {
                 WatchKey key;
                 try {
                     key = watchService.take();
-                } catch (InterruptedException|ClosedWatchServiceException e) {
+                } catch (InterruptedException | ClosedWatchServiceException e) {
                     LOG.debug("{} was interrupted and is shutting down...", getName());
                     break;
                 }
                 for (WatchEvent<?> event : key.pollEvents()) {
-                    LOG.debug("Got file changed event: {} with context: {}", event.kind(),
-                        event.context());
+                    LOG.debug("Got file changed event: {} with context: {}", event.kind(), event.context());
                     try {
                         callback.accept(event);
                     } catch (Throwable e) {
@@ -246,5 +235,7 @@ public final class FileChangeWatcher {
                 }
             }
         }
+
     }
+
 }

+ 9 - 7
zookeeper-server/src/main/java/org/apache/zookeeper/common/FileKeyStoreLoader.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -25,15 +25,13 @@ import java.util.Objects;
  * stores from files on a filesystem.
  */
 abstract class FileKeyStoreLoader implements KeyStoreLoader {
+
     final String keyStorePath;
     final String trustStorePath;
     final String keyStorePassword;
     final String trustStorePassword;
 
-    FileKeyStoreLoader(String keyStorePath,
-                       String trustStorePath,
-                       String keyStorePassword,
-                       String trustStorePassword) {
+    FileKeyStoreLoader(String keyStorePath, String trustStorePath, String keyStorePassword, String trustStorePassword) {
         this.keyStorePath = keyStorePath;
         this.trustStorePath = trustStorePath;
         this.keyStorePassword = keyStorePassword;
@@ -44,13 +42,15 @@ abstract class FileKeyStoreLoader implements KeyStoreLoader {
      * Base class for builder pattern used by subclasses.
      * @param <T> the subtype of FileKeyStoreLoader created by the Builder.
      */
-    static abstract class Builder<T extends FileKeyStoreLoader> {
+    abstract static class Builder<T extends FileKeyStoreLoader> {
+
         String keyStorePath;
         String trustStorePath;
         String keyStorePassword;
         String trustStorePassword;
 
-        Builder() {}
+        Builder() {
+        }
 
         Builder<T> setKeyStorePath(String keyStorePath) {
             this.keyStorePath = Objects.requireNonNull(keyStorePath);
@@ -73,5 +73,7 @@ abstract class FileKeyStoreLoader implements KeyStoreLoader {
         }
 
         abstract T build();
+
     }
+
 }

+ 11 - 12
zookeeper-server/src/main/java/org/apache/zookeeper/common/FileKeyStoreLoaderBuilderProvider.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -21,6 +21,7 @@ package org.apache.zookeeper.common;
 import java.util.Objects;
 
 public class FileKeyStoreLoaderBuilderProvider {
+
     /**
      * Returns a {@link FileKeyStoreLoader.Builder} that can build a loader
      * which loads keys and certs from files of the given
@@ -29,18 +30,16 @@ public class FileKeyStoreLoaderBuilderProvider {
      * @param type the file type to load keys/certs from.
      * @return a new Builder.
      */
-    static FileKeyStoreLoader.Builder<? extends FileKeyStoreLoader>
-    getBuilderForKeyStoreFileType(KeyStoreFileType type) {
+    static FileKeyStoreLoader.Builder<? extends FileKeyStoreLoader> getBuilderForKeyStoreFileType(KeyStoreFileType type) {
         switch (Objects.requireNonNull(type)) {
-            case JKS:
-                return new JKSFileLoader.Builder();
-            case PEM:
-                return new PEMFileLoader.Builder();
-            case PKCS12:
-                return new PKCS12FileLoader.Builder();
-            default:
-                throw new AssertionError(
-                        "Unexpected StoreFileType: " + type.name());
+        case JKS:
+            return new JKSFileLoader.Builder();
+        case PEM:
+            return new PEMFileLoader.Builder();
+        case PKCS12:
+            return new PKCS12FileLoader.Builder();
+        default:
+            throw new AssertionError("Unexpected StoreFileType: " + type.name());
         }
     }
 

+ 10 - 11
zookeeper-server/src/main/java/org/apache/zookeeper/common/IOUtils.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,6 +15,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.common;
 
 import java.io.Closeable;
@@ -22,7 +23,6 @@ import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.io.PrintStream;
-
 import org.slf4j.Logger;
 
 /*
@@ -31,10 +31,11 @@ import org.slf4j.Logger;
  */
 
 public class IOUtils {
+
     /**
      * Closes the stream ignoring {@link IOException}. Must only be called in
      * cleaning up from exception handlers.
-     * 
+     *
      * @param stream
      *            the Stream to close
      */
@@ -45,7 +46,7 @@ public class IOUtils {
     /**
      * Close the Closeable objects and <b>ignore</b> any {@link IOException} or
      * null pointers. Must only be used for cleanup in exception handlers.
-     * 
+     *
      * @param log
      *            the log to record problems to at debug level. Can be null.
      * @param closeables
@@ -67,7 +68,7 @@ public class IOUtils {
 
     /**
      * Copies from one stream to another.
-     * 
+     *
      * @param in
      *            InputStrem to read from
      * @param out
@@ -78,8 +79,7 @@ public class IOUtils {
      *            whether or not close the InputStream and OutputStream at the
      *            end. The streams are closed in the finally clause.
      */
-    public static void copyBytes(InputStream in, OutputStream out,
-            int buffSize, boolean close) throws IOException {
+    public static void copyBytes(InputStream in, OutputStream out, int buffSize, boolean close) throws IOException {
         try {
             copyBytes(in, out, buffSize);
             if (close) {
@@ -98,7 +98,7 @@ public class IOUtils {
 
     /**
      * Copies from one stream to another.
-     * 
+     *
      * @param in
      *            InputStrem to read from
      * @param out
@@ -106,10 +106,9 @@ public class IOUtils {
      * @param buffSize
      *            the size of the buffer
      */
-    public static void copyBytes(InputStream in, OutputStream out, int buffSize)
-            throws IOException {
+    public static void copyBytes(InputStream in, OutputStream out, int buffSize) throws IOException {
         PrintStream ps = out instanceof PrintStream ? (PrintStream) out : null;
-        byte buf[] = new byte[buffSize];
+        byte[] buf = new byte[buffSize];
         int bytesRead = in.read(buf);
         while (bytesRead >= 0) {
             out.write(buf, 0, bytesRead);

+ 10 - 5
zookeeper-server/src/main/java/org/apache/zookeeper/common/JKSFileLoader.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -25,10 +25,12 @@ import java.security.KeyStoreException;
  * Implementation of {@link FileKeyStoreLoader} that loads from JKS files.
  */
 class JKSFileLoader extends StandardTypeFileKeyStoreLoader {
-    private JKSFileLoader(String keyStorePath,
-                          String trustStorePath,
-                          String keyStorePassword,
-                          String trustStorePassword) {
+
+    private JKSFileLoader(
+        String keyStorePath,
+        String trustStorePath,
+        String keyStorePassword,
+        String trustStorePassword) {
         super(keyStorePath, trustStorePath, keyStorePassword, trustStorePassword);
     }
 
@@ -38,9 +40,12 @@ class JKSFileLoader extends StandardTypeFileKeyStoreLoader {
     }
 
     static class Builder extends FileKeyStoreLoader.Builder<JKSFileLoader> {
+
         @Override
         JKSFileLoader build() {
             return new JKSFileLoader(keyStorePath, trustStorePath, keyStorePassword, trustStorePassword);
         }
+
     }
+
 }

+ 6 - 6
zookeeper-server/src/main/java/org/apache/zookeeper/common/KeyStoreFileType.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -23,7 +23,9 @@ package org.apache.zookeeper.common;
  * Currently, JKS (Java keystore), PEM, and PKCS12 types are supported.
  */
 public enum KeyStoreFileType {
-    JKS(".jks"), PEM(".pem"), PKCS12(".p12");
+    JKS(".jks"),
+    PEM(".pem"),
+    PKCS12(".p12");
 
     private final String defaultFileExtension;
 
@@ -83,8 +85,7 @@ public enum KeyStoreFileType {
                 }
             }
         }
-        throw new IllegalArgumentException(
-                "Unable to auto-detect store file type from file name: " + filename);
+        throw new IllegalArgumentException("Unable to auto-detect store file type from file name: " + filename);
     }
 
     /**
@@ -103,8 +104,7 @@ public enum KeyStoreFileType {
      * @throws IllegalArgumentException if <code>propertyValue</code>is empty
      *         or null and the type could not be determined from the file name.
      */
-    public static KeyStoreFileType fromPropertyValueOrFileName(String propertyValue,
-                                                               String filename) {
+    public static KeyStoreFileType fromPropertyValueOrFileName(String propertyValue, String filename) {
         KeyStoreFileType result = KeyStoreFileType.fromPropertyValue(propertyValue);
         if (result == null) {
             result = KeyStoreFileType.fromFilename(filename);

+ 3 - 1
zookeeper-server/src/main/java/org/apache/zookeeper/common/KeyStoreLoader.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -26,6 +26,7 @@ import java.security.KeyStore;
  * An interface for an object that can load key stores or trust stores.
  */
 interface KeyStoreLoader {
+
     /**
      * Loads a KeyStore which contains at least one private key and the
      * associated X509 cert chain.
@@ -49,4 +50,5 @@ interface KeyStoreLoader {
      *         a security error, such as "unsupported crypto algorithm".
      */
     KeyStore loadTrustStore() throws IOException, GeneralSecurityException;
+
 }

+ 2 - 1
zookeeper-server/src/main/java/org/apache/zookeeper/common/NetUtils.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -40,4 +40,5 @@ public class NetUtils {
             return String.format("%s:%s", ia.getHostAddress(), addr.getPort());
         }
     }
+
 }

+ 11 - 12
zookeeper-server/src/main/java/org/apache/zookeeper/common/NettyUtils.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -18,15 +18,6 @@
 
 package org.apache.zookeeper.common;
 
-import java.net.InetAddress;
-import java.net.NetworkInterface;
-import java.net.SocketException;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.HashSet;
-import java.util.Set;
-
 import io.netty.channel.EventLoopGroup;
 import io.netty.channel.epoll.Epoll;
 import io.netty.channel.epoll.EpollEventLoopGroup;
@@ -37,6 +28,13 @@ import io.netty.channel.socket.ServerSocketChannel;
 import io.netty.channel.socket.SocketChannel;
 import io.netty.channel.socket.nio.NioServerSocketChannel;
 import io.netty.channel.socket.nio.NioSocketChannel;
+import java.net.InetAddress;
+import java.net.NetworkInterface;
+import java.net.SocketException;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.Set;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -44,6 +42,7 @@ import org.slf4j.LoggerFactory;
  * Helper methods for netty code.
  */
 public class NettyUtils {
+
     private static final Logger LOG = LoggerFactory.getLogger(NettyUtils.class);
 
     private static final int DEFAULT_INET_ADDRESS_COUNT = 1;
@@ -151,12 +150,12 @@ public class NettyUtils {
                     validInetAddresses.add(inetAddress);
                 }
             }
-            LOG.debug("Detected {} local network addresses: {}",
-                validInetAddresses.size(), validInetAddresses);
+            LOG.debug("Detected {} local network addresses: {}", validInetAddresses.size(), validInetAddresses);
             return validInetAddresses.size() > 0 ? validInetAddresses.size() : DEFAULT_INET_ADDRESS_COUNT;
         } catch (SocketException ex) {
             LOG.warn("Failed to list all network interfaces, assuming 1", ex);
             return DEFAULT_INET_ADDRESS_COUNT;
         }
     }
+
 }

+ 10 - 7
zookeeper-server/src/main/java/org/apache/zookeeper/common/PEMFileLoader.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -23,17 +23,18 @@ import java.io.IOException;
 import java.security.GeneralSecurityException;
 import java.security.KeyStore;
 import java.util.Optional;
-
 import org.apache.zookeeper.util.PemReader;
 
 /**
  * Implementation of {@link FileKeyStoreLoader} that loads from PEM files.
  */
 class PEMFileLoader extends FileKeyStoreLoader {
-    private PEMFileLoader(String keyStorePath,
-                          String trustStorePath,
-                          String keyStorePassword,
-                          String trustStorePassword) {
+
+    private PEMFileLoader(
+        String keyStorePath,
+        String trustStorePath,
+        String keyStorePassword,
+        String trustStorePassword) {
         super(keyStorePath, trustStorePath, keyStorePassword, trustStorePassword);
     }
 
@@ -54,11 +55,13 @@ class PEMFileLoader extends FileKeyStoreLoader {
         return PemReader.loadTrustStore(new File(trustStorePath));
     }
 
-
     static class Builder extends FileKeyStoreLoader.Builder<PEMFileLoader> {
+
         @Override
         PEMFileLoader build() {
             return new PEMFileLoader(keyStorePath, trustStorePath, keyStorePassword, trustStorePassword);
         }
+
     }
+
 }

+ 10 - 5
zookeeper-server/src/main/java/org/apache/zookeeper/common/PKCS12FileLoader.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -25,10 +25,12 @@ import java.security.KeyStoreException;
  * Implementation of {@link FileKeyStoreLoader} that loads from PKCS12 files.
  */
 class PKCS12FileLoader extends StandardTypeFileKeyStoreLoader {
-    private PKCS12FileLoader(String keyStorePath,
-                             String trustStorePath,
-                             String keyStorePassword,
-                             String trustStorePassword) {
+
+    private PKCS12FileLoader(
+        String keyStorePath,
+        String trustStorePath,
+        String keyStorePassword,
+        String trustStorePassword) {
         super(keyStorePath, trustStorePath, keyStorePassword, trustStorePassword);
     }
 
@@ -38,9 +40,12 @@ class PKCS12FileLoader extends StandardTypeFileKeyStoreLoader {
     }
 
     static class Builder extends FileKeyStoreLoader.Builder<PKCS12FileLoader> {
+
         @Override
         PKCS12FileLoader build() {
             return new PKCS12FileLoader(keyStorePath, trustStorePath, keyStorePassword, trustStorePassword);
         }
+
     }
+
 }

+ 346 - 345
zookeeper-server/src/main/java/org/apache/zookeeper/common/PathTrie.java

@@ -1,346 +1,347 @@
+ /*
+  * Licensed to the Apache Software Foundation (ASF) under one
+  * or more contributor license agreements.  See the NOTICE file
+  * distributed with this work for additional information
+  * regarding copyright ownership.  The ASF licenses this file
+  * to you under the Apache License, Version 2.0 (the
+  * "License"); you may not use this file except in compliance
+  * with the License.  You may obtain a copy of the License at
+  *
+  *     http://www.apache.org/licenses/LICENSE-2.0
+  *
+  * Unless required by applicable law or agreed to in writing, software
+  * distributed under the License is distributed on an "AS IS" BASIS,
+  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  * See the License for the specific language governing permissions and
+  * limitations under the License.
+  */
+
+ package org.apache.zookeeper.common;
+
+ import java.util.ArrayDeque;
+ import java.util.Collection;
+ import java.util.Deque;
+ import java.util.HashMap;
+ import java.util.Map;
+ import java.util.Objects;
+ import java.util.concurrent.locks.Lock;
+ import java.util.concurrent.locks.ReadWriteLock;
+ import java.util.concurrent.locks.ReentrantReadWriteLock;
+ import org.apache.commons.lang.StringUtils;
+ import org.slf4j.Logger;
+ import org.slf4j.LoggerFactory;
+
  /**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.zookeeper.common;
-
-import java.util.ArrayDeque;
-import java.util.Collection;
-import java.util.Deque;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Objects;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReadWriteLock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-
-import org.apache.commons.lang.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * a class that implements prefix matching for 
- * components of a filesystem path. the trie
- * looks like a tree with edges mapping to 
- * the component of a path.
- * example /ab/bc/cf would map to a trie
- *           /
- *        ab/
- *        (ab)
- *      bc/
- *       / 
- *      (bc)
- *   cf/
- *   (cf)
- */
-public class PathTrie {
-
-    /** Logger for this class */
-    private static final Logger LOG = LoggerFactory.getLogger(PathTrie.class);
-
-    /** Root node of PathTrie */
-    private final TrieNode rootNode;
-
-    private final ReadWriteLock lock = new ReentrantReadWriteLock(true);
-
-    private final Lock readLock = lock.readLock();
-
-    private final Lock writeLock = lock.writeLock();
-
-    static class TrieNode {
-        final String value;
-        final Map<String, TrieNode> children;
-        boolean property;
-        TrieNode parent;
-
-        /**
-         * Create a trie node with parent as parameter.
-         *
-         * @param parent the parent of this node
-         * @param value the value stored in this node
-         */
-        private TrieNode(TrieNode parent, String value) {
-            this.value = value;
-            this.parent = parent;
-            this.property = false;
-            this.children = new HashMap<>(4);
-        }
-
-        /**
-         * Get the parent of this node.
-         *
-         * @return the parent node
-         */
-        TrieNode getParent() {
-            return this.parent;
-        }
-
-        /**
-         * set the parent of this node.
-         *
-         * @param parent the parent to set to
-         */
-        void setParent(TrieNode parent) {
-            this.parent = parent;
-        }
-
-        /**
-         * A property that is set for a node - making it special.
-         */
-        void setProperty(boolean prop) {
-            this.property = prop;
-        }
-
-        /**
-         * The property of this node.
-         *
-         * @return the property for this node
-         */
-        boolean hasProperty() {
-            return this.property;
-        }
-
-        /**
-         * The value stored in this node.
-         *
-         * @return the value stored in this node
-         */
-        public String getValue() {
-          return this.value;
-        }
-
-        /**
-         * Add a child to the existing node.
-         *
-         * @param childName the string name of the child
-         * @param node the node that is the child
-         */
-        void addChild(String childName, TrieNode node) {
-            this.children.putIfAbsent(childName, node);
-        }
-
-        /**
-         * Delete child from this node.
-         *
-         * @param childName the name of the child to be deleted
-         */
-        void deleteChild(String childName) {
-            this.children.computeIfPresent(childName, (key, childNode) -> {
-                // Node no longer has an external property associated
-                childNode.setProperty(false);
-
-                // Delete it if it has no children (is a leaf node)
-                if (childNode.isLeafNode()) {
-                    childNode.setParent(null);
-                    return null;
-                }
-
-                return childNode;
-            });
-        }
-
-        /**
-         * Return the child of a node mapping to the input child name.
-         *
-         * @param childName the name of the child
-         * @return the child of a node
-         */
-        TrieNode getChild(String childName) {
-            return this.children.get(childName);
-        }
-
-        /**
-         * Get the list of children of this trienode.
-         *
-         * @return A collection containing the node's children
-         */
-        Collection<String> getChildren() {
-            return children.keySet();
-        }
-
-        /**
-         * Determine if this node is a leaf (has no children).
-         *
-         * @return true if this node is a lead node; otherwise false
-         */
-        boolean isLeafNode() {
-            return children.isEmpty();
-        }
-
-        @Override
-        public String toString() {
-          return "TrieNode [name=" + value + ", property=" + property
-              + ", children=" + children.keySet() + "]";
-        }
-    }
-
-    /**
-     * Construct a new PathTrie with a root node.
-     */
-    public PathTrie() {
-        this.rootNode = new TrieNode(null, "/");
-    }
-  
-    /**
-     * Add a path to the path trie. All paths are relative to the root node.
-     *
-     * @param path the path to add to the trie
-     */
-    public void addPath(final String path) {
-        Objects.requireNonNull(path, "Path cannot be null");
-
-        final String[] pathComponents = StringUtils.split(path, '/');
-        if (pathComponents.length == 0) {
-            throw new IllegalArgumentException("Invalid path: " + path);
-        }
-
-        writeLock.lock();
-        try {
-            TrieNode parent = rootNode;
-            for (final String part : pathComponents) {
-                TrieNode child = parent.getChild(part);
-                if (child == null) {
-                    child = new TrieNode(parent, part);
-                    parent.addChild(part, child);
-                }
-                parent = child;
-            }
-            parent.setProperty(true);
-        } finally {
-            writeLock.unlock();
-        }
-    }
-
-    /**
-     * Delete a path from the trie. All paths are relative to the root node.
-     *
-     * @param path the path to be deleted
-     */
-    public void deletePath(final String path) {
-        Objects.requireNonNull(path, "Path cannot be null");
-
-        final String[] pathComponents = StringUtils.split(path, '/');
-        if (pathComponents.length == 0) {
-            throw new IllegalArgumentException("Invalid path: " + path);
-        }
-
-        writeLock.lock();
-        try {
-            TrieNode parent = rootNode;
-            for (final String part : pathComponents) {
-                if (parent.getChild(part) == null) {
-                    // the path does not exist
-                    return;
-                }
-                parent = parent.getChild(part);
-                LOG.debug("{}", parent);
-            }
-
-            final TrieNode realParent = parent.getParent();
-            realParent.deleteChild(parent.getValue());
-        } finally {
-            writeLock.unlock();
-        }
-    }
-
-    /**
-     * Return true if the given path exists in the trie, otherwise return false;
-     * All paths are relative to the root node.
-     *
-     * @param path the input path
-     * @return the largest prefix for the
-     */ 
-    public boolean existsNode(final String path) {
-      Objects.requireNonNull(path, "Path cannot be null");
-
-      final String[] pathComponents = StringUtils.split(path, '/');
-      if (pathComponents.length == 0) {
-          throw new IllegalArgumentException("Invalid path: " + path);
-      }
-
-      readLock.lock();
-      try {
-          TrieNode parent = rootNode;
-          for (final String part : pathComponents) {
-              if (parent.getChild(part) == null) {
-                  // the path does not exist
-                  return false;
-              }
-              parent = parent.getChild(part);
-              LOG.debug("{}", parent);
-          }
-      } finally {
-          readLock.unlock();
-      }
-      return true;
-    }
-
-    /**
-     * Return the largest prefix for the input path. All paths are relative to the
-     * root node.
-     *
-     * @param path the input path
-     * @return the largest prefix for the input path
-     */
-    public String findMaxPrefix(final String path) {
-        Objects.requireNonNull(path, "Path cannot be null");
-
-        final String[] pathComponents = StringUtils.split(path, '/');
-
-        readLock.lock();
-        try {
-            TrieNode parent = rootNode;
-            TrieNode deepestPropertyNode = null;
-            for (final String element : pathComponents) {
-                parent = parent.getChild(element);
-                if (parent == null) {
-                    LOG.debug("{}", element);
-                    break;
-                }
-                if (parent.hasProperty()) {
-                  deepestPropertyNode = parent;
-                }
-            }
-
-            if (deepestPropertyNode == null) {
-              return "/";
-            }
-
-            final Deque<String> treePath = new ArrayDeque<>();
-            TrieNode node = deepestPropertyNode;
-            while (node != this.rootNode) {
-              treePath.offerFirst(node.getValue());
-              node = node.parent;
-            }
-            return "/" + String.join("/", treePath);
-        } finally {
-            readLock.unlock();
-        }
-    }
-
-    /**
-     * Clear all nodes in the trie.
-     */
-    public void clear() {
-      writeLock.lock();
-      try {
-          rootNode.getChildren().clear();
-      } finally {
-          writeLock.unlock();
-      }
-    }
-}
+  * a class that implements prefix matching for
+  * components of a filesystem path. the trie
+  * looks like a tree with edges mapping to
+  * the component of a path.
+  * example /ab/bc/cf would map to a trie
+  *           /
+  *        ab/
+  *        (ab)
+  *      bc/
+  *       /
+  *      (bc)
+  *   cf/
+  *   (cf)
+  */
+ public class PathTrie {
+
+     /** Logger for this class */
+     private static final Logger LOG = LoggerFactory.getLogger(PathTrie.class);
+
+     /** Root node of PathTrie */
+     private final TrieNode rootNode;
+
+     private final ReadWriteLock lock = new ReentrantReadWriteLock(true);
+
+     private final Lock readLock = lock.readLock();
+
+     private final Lock writeLock = lock.writeLock();
+
+     static class TrieNode {
+
+         final String value;
+         final Map<String, TrieNode> children;
+         boolean property;
+         TrieNode parent;
+
+         /**
+          * Create a trie node with parent as parameter.
+          *
+          * @param parent the parent of this node
+          * @param value the value stored in this node
+          */
+         private TrieNode(TrieNode parent, String value) {
+             this.value = value;
+             this.parent = parent;
+             this.property = false;
+             this.children = new HashMap<>(4);
+         }
+
+         /**
+          * Get the parent of this node.
+          *
+          * @return the parent node
+          */
+         TrieNode getParent() {
+             return this.parent;
+         }
+
+         /**
+          * set the parent of this node.
+          *
+          * @param parent the parent to set to
+          */
+         void setParent(TrieNode parent) {
+             this.parent = parent;
+         }
+
+         /**
+          * A property that is set for a node - making it special.
+          */
+         void setProperty(boolean prop) {
+             this.property = prop;
+         }
+
+         /**
+          * The property of this node.
+          *
+          * @return the property for this node
+          */
+         boolean hasProperty() {
+             return this.property;
+         }
+
+         /**
+          * The value stored in this node.
+          *
+          * @return the value stored in this node
+          */
+         public String getValue() {
+             return this.value;
+         }
+
+         /**
+          * Add a child to the existing node.
+          *
+          * @param childName the string name of the child
+          * @param node the node that is the child
+          */
+         void addChild(String childName, TrieNode node) {
+             this.children.putIfAbsent(childName, node);
+         }
+
+         /**
+          * Delete child from this node.
+          *
+          * @param childName the name of the child to be deleted
+          */
+         void deleteChild(String childName) {
+             this.children.computeIfPresent(childName, (key, childNode) -> {
+                 // Node no longer has an external property associated
+                 childNode.setProperty(false);
+
+                 // Delete it if it has no children (is a leaf node)
+                 if (childNode.isLeafNode()) {
+                     childNode.setParent(null);
+                     return null;
+                 }
+
+                 return childNode;
+             });
+         }
+
+         /**
+          * Return the child of a node mapping to the input child name.
+          *
+          * @param childName the name of the child
+          * @return the child of a node
+          */
+         TrieNode getChild(String childName) {
+             return this.children.get(childName);
+         }
+
+         /**
+          * Get the list of children of this trienode.
+          *
+          * @return A collection containing the node's children
+          */
+         Collection<String> getChildren() {
+             return children.keySet();
+         }
+
+         /**
+          * Determine if this node is a leaf (has no children).
+          *
+          * @return true if this node is a lead node; otherwise false
+          */
+         boolean isLeafNode() {
+             return children.isEmpty();
+         }
+
+         @Override
+         public String toString() {
+             return "TrieNode [name=" + value + ", property=" + property + ", children=" + children.keySet() + "]";
+         }
+
+     }
+
+     /**
+      * Construct a new PathTrie with a root node.
+      */
+     public PathTrie() {
+         this.rootNode = new TrieNode(null, "/");
+     }
+
+     /**
+      * Add a path to the path trie. All paths are relative to the root node.
+      *
+      * @param path the path to add to the trie
+      */
+     public void addPath(final String path) {
+         Objects.requireNonNull(path, "Path cannot be null");
+
+         final String[] pathComponents = StringUtils.split(path, '/');
+         if (pathComponents.length == 0) {
+             throw new IllegalArgumentException("Invalid path: " + path);
+         }
+
+         writeLock.lock();
+         try {
+             TrieNode parent = rootNode;
+             for (final String part : pathComponents) {
+                 TrieNode child = parent.getChild(part);
+                 if (child == null) {
+                     child = new TrieNode(parent, part);
+                     parent.addChild(part, child);
+                 }
+                 parent = child;
+             }
+             parent.setProperty(true);
+         } finally {
+             writeLock.unlock();
+         }
+     }
+
+     /**
+      * Delete a path from the trie. All paths are relative to the root node.
+      *
+      * @param path the path to be deleted
+      */
+     public void deletePath(final String path) {
+         Objects.requireNonNull(path, "Path cannot be null");
+
+         final String[] pathComponents = StringUtils.split(path, '/');
+         if (pathComponents.length == 0) {
+             throw new IllegalArgumentException("Invalid path: " + path);
+         }
+
+         writeLock.lock();
+         try {
+             TrieNode parent = rootNode;
+             for (final String part : pathComponents) {
+                 if (parent.getChild(part) == null) {
+                     // the path does not exist
+                     return;
+                 }
+                 parent = parent.getChild(part);
+                 LOG.debug("{}", parent);
+             }
+
+             final TrieNode realParent = parent.getParent();
+             realParent.deleteChild(parent.getValue());
+         } finally {
+             writeLock.unlock();
+         }
+     }
+
+     /**
+      * Return true if the given path exists in the trie, otherwise return false;
+      * All paths are relative to the root node.
+      *
+      * @param path the input path
+      * @return the largest prefix for the
+      */
+     public boolean existsNode(final String path) {
+         Objects.requireNonNull(path, "Path cannot be null");
+
+         final String[] pathComponents = StringUtils.split(path, '/');
+         if (pathComponents.length == 0) {
+             throw new IllegalArgumentException("Invalid path: " + path);
+         }
+
+         readLock.lock();
+         try {
+             TrieNode parent = rootNode;
+             for (final String part : pathComponents) {
+                 if (parent.getChild(part) == null) {
+                     // the path does not exist
+                     return false;
+                 }
+                 parent = parent.getChild(part);
+                 LOG.debug("{}", parent);
+             }
+         } finally {
+             readLock.unlock();
+         }
+         return true;
+     }
+
+     /**
+      * Return the largest prefix for the input path. All paths are relative to the
+      * root node.
+      *
+      * @param path the input path
+      * @return the largest prefix for the input path
+      */
+     public String findMaxPrefix(final String path) {
+         Objects.requireNonNull(path, "Path cannot be null");
+
+         final String[] pathComponents = StringUtils.split(path, '/');
+
+         readLock.lock();
+         try {
+             TrieNode parent = rootNode;
+             TrieNode deepestPropertyNode = null;
+             for (final String element : pathComponents) {
+                 parent = parent.getChild(element);
+                 if (parent == null) {
+                     LOG.debug("{}", element);
+                     break;
+                 }
+                 if (parent.hasProperty()) {
+                     deepestPropertyNode = parent;
+                 }
+             }
+
+             if (deepestPropertyNode == null) {
+                 return "/";
+             }
+
+             final Deque<String> treePath = new ArrayDeque<>();
+             TrieNode node = deepestPropertyNode;
+             while (node != this.rootNode) {
+                 treePath.offerFirst(node.getValue());
+                 node = node.parent;
+             }
+             return "/" + String.join("/", treePath);
+         } finally {
+             readLock.unlock();
+         }
+     }
+
+     /**
+      * Clear all nodes in the trie.
+      */
+     public void clear() {
+         writeLock.lock();
+         try {
+             rootNode.getChildren().clear();
+         } finally {
+             writeLock.unlock();
+         }
+     }
+
+ }

+ 104 - 112
zookeeper-server/src/main/java/org/apache/zookeeper/common/PathUtils.java

@@ -1,120 +1,112 @@
+ /*
+  * Licensed to the Apache Software Foundation (ASF) under one
+  * or more contributor license agreements.  See the NOTICE file
+  * distributed with this work for additional information
+  * regarding copyright ownership.  The ASF licenses this file
+  * to you under the Apache License, Version 2.0 (the
+  * "License"); you may not use this file except in compliance
+  * with the License.  You may obtain a copy of the License at
+  *
+  *     http://www.apache.org/licenses/LICENSE-2.0
+  *
+  * Unless required by applicable law or agreed to in writing, software
+  * distributed under the License is distributed on an "AS IS" BASIS,
+  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+  * See the License for the specific language governing permissions and
+  * limitations under the License.
+  */
+
+ package org.apache.zookeeper.common;
+
  /**
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements.  See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership.  The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License.  You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
+  * Path related utilities
+  */
+ public class PathUtils {
 
-package org.apache.zookeeper.common;
+     /** validate the provided znode path string
+      * @param path znode path string
+      * @param isSequential if the path is being created
+      * with a sequential flag
+      * @throws IllegalArgumentException if the path is invalid
+      */
+     public static void validatePath(String path, boolean isSequential) throws IllegalArgumentException {
+         validatePath(isSequential ? path + "1" : path);
+     }
 
+     /**
+      * Validate the provided znode path string
+      * @param path znode path string
+      * @throws IllegalArgumentException if the path is invalid
+      */
+     public static void validatePath(String path) throws IllegalArgumentException {
+         if (path == null) {
+             throw new IllegalArgumentException("Path cannot be null");
+         }
+         if (path.length() == 0) {
+             throw new IllegalArgumentException("Path length must be > 0");
+         }
+         if (path.charAt(0) != '/') {
+             throw new IllegalArgumentException("Path must start with / character");
+         }
+         if (path.length() == 1) { // done checking - it's the root
+             return;
+         }
+         if (path.charAt(path.length() - 1) == '/') {
+             throw new IllegalArgumentException("Path must not end with / character");
+         }
 
-/**
- * Path related utilities
- */    
-public class PathUtils {
-	
-	/** validate the provided znode path string
-	 * @param path znode path string
-	 * @param isSequential if the path is being created
-	 * with a sequential flag
-	 * @throws IllegalArgumentException if the path is invalid
-	 */
-	public static void validatePath(String path, boolean isSequential) 
-		throws IllegalArgumentException {
-		validatePath(isSequential? path + "1": path);
-	}
-	
-    /**
-     * Validate the provided znode path string
-     * @param path znode path string
-     * @throws IllegalArgumentException if the path is invalid
-     */
-    public static void validatePath(String path) throws IllegalArgumentException {
-        if (path == null) {
-            throw new IllegalArgumentException("Path cannot be null");
-        }
-        if (path.length() == 0) {
-            throw new IllegalArgumentException("Path length must be > 0");
-        }
-        if (path.charAt(0) != '/') {
-            throw new IllegalArgumentException(
-                         "Path must start with / character");
-        }
-        if (path.length() == 1) { // done checking - it's the root
-            return;
-        }
-        if (path.charAt(path.length() - 1) == '/') {
-            throw new IllegalArgumentException(
-                         "Path must not end with / character");
-        }
+         String reason = null;
+         char lastc = '/';
+         char[] chars = path.toCharArray();
+         char c;
+         for (int i = 1; i < chars.length; lastc = chars[i], i++) {
+             c = chars[i];
 
-        String reason = null;
-        char lastc = '/';
-        char chars[] = path.toCharArray();
-        char c;
-        for (int i = 1; i < chars.length; lastc = chars[i], i++) {
-            c = chars[i];
+             if (c == 0) {
+                 reason = "null character not allowed @" + i;
+                 break;
+             } else if (c == '/' && lastc == '/') {
+                 reason = "empty node name specified @" + i;
+                 break;
+             } else if (c == '.' && lastc == '.') {
+                 if (chars[i - 2] == '/' && ((i + 1 == chars.length) || chars[i + 1] == '/')) {
+                     reason = "relative paths not allowed @" + i;
+                     break;
+                 }
+             } else if (c == '.') {
+                 if (chars[i - 1] == '/' && ((i + 1 == chars.length) || chars[i + 1] == '/')) {
+                     reason = "relative paths not allowed @" + i;
+                     break;
+                 }
+             } else if (c > '\u0000' && c <= '\u001f'
+                        || c >= '\u007f' && c <= '\u009F'
+                        || c >= '\ud800' && c <= '\uf8ff'
+                        || c >= '\ufff0' && c <= '\uffff') {
+                 reason = "invalid character @" + i;
+                 break;
+             }
+         }
 
-            if (c == 0) {
-                reason = "null character not allowed @" + i;
-                break;
-            } else if (c == '/' && lastc == '/') {
-                reason = "empty node name specified @" + i;
-                break;
-            } else if (c == '.' && lastc == '.') {
-                if (chars[i-2] == '/' &&
-                        ((i + 1 == chars.length)
-                                || chars[i+1] == '/')) {
-                    reason = "relative paths not allowed @" + i;
-                    break;
-                }
-            } else if (c == '.') {
-                if (chars[i-1] == '/' &&
-                        ((i + 1 == chars.length)
-                                || chars[i+1] == '/')) {
-                    reason = "relative paths not allowed @" + i;
-                    break;
-                }
-            } else if (c > '\u0000' && c <= '\u001f'
-                    || c >= '\u007f' && c <= '\u009F'
-                    || c >= '\ud800' && c <= '\uf8ff'
-                    || c >= '\ufff0' && c <= '\uffff') {
-                reason = "invalid character @" + i;
-                break;
-            }
-        }
+         if (reason != null) {
+             throw new IllegalArgumentException("Invalid path string \"" + path + "\" caused by " + reason);
+         }
+     }
 
-        if (reason != null) {
-            throw new IllegalArgumentException(
-                    "Invalid path string \"" + path + "\" caused by " + reason);
-        }
-    }
+     /**
+      * Convert Windows path to Unix
+      *
+      * @param path
+      *            file path
+      * @return converted file path
+      */
+     public static String normalizeFileSystemPath(String path) {
+         if (path != null) {
+             String osname = java.lang.System.getProperty("os.name");
+             if (osname.toLowerCase().contains("windows")) {
+                 return path.replace('\\', '/');
+             }
+         }
+         return path;
+     }
 
-    /**
-     * Convert Windows path to Unix
-     *
-     * @param path
-     *            file path
-     * @return converted file path
-     */
-    public static String normalizeFileSystemPath(String path) {
-        if (path != null) {
-            String osname = java.lang.System.getProperty("os.name");
-            if (osname.toLowerCase().contains("windows")) {
-                return path.replace('\\', '/');
-            }
-        }
-        return path;
-    }
-}
+ }

+ 2 - 1
zookeeper-server/src/main/java/org/apache/zookeeper/common/QuorumX509Util.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -29,4 +29,5 @@ public class QuorumX509Util extends X509Util {
     protected boolean shouldVerifyClientHostname() {
         return true;
     }
+
 }

+ 36 - 39
zookeeper-server/src/main/java/org/apache/zookeeper/common/SSLContextAndOptions.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -15,29 +15,26 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+
 package org.apache.zookeeper.common;
 
+import static java.util.Objects.requireNonNull;
+import io.netty.handler.ssl.IdentityCipherSuiteFilter;
+import io.netty.handler.ssl.JdkSslContext;
+import io.netty.handler.ssl.SslContext;
 import java.io.ByteArrayInputStream;
 import java.io.IOException;
 import java.net.Socket;
 import java.util.Arrays;
-
-import javax.net.ssl.SSLContext;
 import java.util.Collections;
 import java.util.List;
-
+import javax.net.ssl.SSLContext;
 import javax.net.ssl.SSLParameters;
 import javax.net.ssl.SSLServerSocket;
 import javax.net.ssl.SSLSocket;
-
-import io.netty.handler.ssl.IdentityCipherSuiteFilter;
-import io.netty.handler.ssl.JdkSslContext;
-import io.netty.handler.ssl.SslContext;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import static java.util.Objects.requireNonNull;
-
 /**
  * Wrapper class for an SSLContext + some config options that can't be set on the context when it is created but
  * must be set on a secure socket created by the context after the socket creation. By wrapping the options in this
@@ -46,6 +43,7 @@ import static java.util.Objects.requireNonNull;
  * unit test interactions between them.
  */
 public class SSLContextAndOptions {
+
     private static final Logger LOG = LoggerFactory.getLogger(SSLContextAndOptions.class);
 
     private final X509Util x509Util;
@@ -85,24 +83,21 @@ public class SSLContextAndOptions {
     public SSLSocket createSSLSocket(Socket socket, byte[] pushbackBytes) throws IOException {
         SSLSocket sslSocket;
         if (pushbackBytes != null && pushbackBytes.length > 0) {
-            sslSocket = (SSLSocket) sslContext.getSocketFactory().createSocket(
-                    socket, new ByteArrayInputStream(pushbackBytes), true);
+            sslSocket = (SSLSocket) sslContext.getSocketFactory()
+                                              .createSocket(socket, new ByteArrayInputStream(pushbackBytes), true);
         } else {
-            sslSocket = (SSLSocket) sslContext.getSocketFactory().createSocket(
-                    socket, null, socket.getPort(), true);
+            sslSocket = (SSLSocket) sslContext.getSocketFactory().createSocket(socket, null, socket.getPort(), true);
         }
         return configureSSLSocket(sslSocket, false);
     }
 
     public SSLServerSocket createSSLServerSocket() throws IOException {
-        SSLServerSocket sslServerSocket =
-                (SSLServerSocket) sslContext.getServerSocketFactory().createServerSocket();
+        SSLServerSocket sslServerSocket = (SSLServerSocket) sslContext.getServerSocketFactory().createServerSocket();
         return configureSSLServerSocket(sslServerSocket);
     }
 
     public SSLServerSocket createSSLServerSocket(int port) throws IOException {
-        SSLServerSocket sslServerSocket =
-                (SSLServerSocket) sslContext.getServerSocketFactory().createServerSocket(port);
+        SSLServerSocket sslServerSocket = (SSLServerSocket) sslContext.getServerSocketFactory().createServerSocket(port);
         return configureSSLServerSocket(sslServerSocket);
     }
 
@@ -113,7 +108,9 @@ public class SSLContextAndOptions {
                 cipherSuitesAsList,
                 IdentityCipherSuiteFilter.INSTANCE,
                 null,
-                isClientSocket ? X509Util.ClientAuth.NONE.toNettyClientAuth() : clientAuth.toNettyClientAuth(),
+                isClientSocket
+                        ? X509Util.ClientAuth.NONE.toNettyClientAuth()
+                        : clientAuth.toNettyClientAuth(),
                 enabledProtocols,
                 false);
     }
@@ -141,31 +138,33 @@ public class SSLContextAndOptions {
     private void configureSslParameters(SSLParameters sslParameters, boolean isClientSocket) {
         if (cipherSuites != null) {
             if (LOG.isDebugEnabled()) {
-                LOG.debug("Setup cipher suites for {} socket: {}",
-                        isClientSocket ? "client" : "server",
-                        Arrays.toString(cipherSuites));
+                LOG.debug(
+                    "Setup cipher suites for {} socket: {}",
+                    isClientSocket ? "client" : "server",
+                    Arrays.toString(cipherSuites));
             }
             sslParameters.setCipherSuites(cipherSuites);
         }
         if (enabledProtocols != null) {
             if (LOG.isDebugEnabled()) {
-                LOG.debug("Setup enabled protocols for {} socket: {}",
-                        isClientSocket ? "client" : "server",
-                        Arrays.toString(enabledProtocols));
+                LOG.debug(
+                    "Setup enabled protocols for {} socket: {}",
+                    isClientSocket ? "client" : "server",
+                    Arrays.toString(enabledProtocols));
             }
             sslParameters.setProtocols(enabledProtocols);
         }
         if (!isClientSocket) {
             switch (clientAuth) {
-                case NEED:
-                    sslParameters.setNeedClientAuth(true);
-                    break;
-                case WANT:
-                    sslParameters.setWantClientAuth(true);
-                    break;
-                default:
-                    sslParameters.setNeedClientAuth(false); // also clears the wantClientAuth flag according to docs
-                    break;
+            case NEED:
+                sslParameters.setNeedClientAuth(true);
+                break;
+            case WANT:
+                sslParameters.setWantClientAuth(true);
+                break;
+            default:
+                sslParameters.setNeedClientAuth(false); // also clears the wantClientAuth flag according to docs
+                break;
             }
         }
     }
@@ -173,7 +172,7 @@ public class SSLContextAndOptions {
     private String[] getEnabledProtocols(final ZKConfig config, final SSLContext sslContext) {
         String enabledProtocolsInput = config.getProperty(x509Util.getSslEnabledProtocolsProperty());
         if (enabledProtocolsInput == null) {
-            return new String[] { sslContext.getProtocol() };
+            return new String[]{sslContext.getProtocol()};
         }
         return enabledProtocolsInput.split(",");
     }
@@ -201,13 +200,11 @@ public class SSLContextAndOptions {
             if (result < 1) {
                 // Timeout of 0 is not allowed, since an infinite timeout can permanently lock up an
                 // accept() thread.
-                LOG.warn("Invalid value for {}: {}, using the default value of {}",
-                        x509Util.getSslHandshakeDetectionTimeoutMillisProperty(),
-                        result,
-                        X509Util.DEFAULT_HANDSHAKE_DETECTION_TIMEOUT_MILLIS);
+                LOG.warn("Invalid value for {}: {}, using the default value of {}", x509Util.getSslHandshakeDetectionTimeoutMillisProperty(), result, X509Util.DEFAULT_HANDSHAKE_DETECTION_TIMEOUT_MILLIS);
                 result = X509Util.DEFAULT_HANDSHAKE_DETECTION_TIMEOUT_MILLIS;
             }
         }
         return result;
     }
+
 }

+ 8 - 5
zookeeper-server/src/main/java/org/apache/zookeeper/common/StandardTypeFileKeyStoreLoader.java

@@ -1,4 +1,4 @@
-/**
+/*
  * Licensed to the Apache Software Foundation (ASF) under one
  * or more contributor license agreements.  See the NOTICE file
  * distributed with this work for additional information
@@ -32,12 +32,14 @@ import java.security.KeyStoreException;
  * JKS or PKCS12.
  */
 abstract class StandardTypeFileKeyStoreLoader extends FileKeyStoreLoader {
+
     private static final char[] EMPTY_CHAR_ARRAY = new char[0];
 
-    StandardTypeFileKeyStoreLoader(String keyStorePath,
-                                   String trustStorePath,
-                                   String keyStorePassword,
-                                   String trustStorePassword) {
+    StandardTypeFileKeyStoreLoader(
+        String keyStorePath,
+        String trustStorePath,
+        String keyStorePassword,
+        String trustStorePassword) {
         super(keyStorePath, trustStorePath, keyStorePassword, trustStorePassword);
     }
 
@@ -64,4 +66,5 @@ abstract class StandardTypeFileKeyStoreLoader extends FileKeyStoreLoader {
     private static char[] passwordStringToCharArray(String password) {
         return password == null ? EMPTY_CHAR_ARRAY : password.toCharArray();
     }
+
 }

+ 11 - 9
zookeeper-server/src/main/java/org/apache/zookeeper/common/StringUtils.java

@@ -16,9 +16,10 @@
  */
 
 package org.apache.zookeeper.common;
+
 import java.util.ArrayList;
-import java.util.List;
 import java.util.Collections;
+import java.util.List;
 
 public class StringUtils {
 
@@ -36,28 +37,29 @@ public class StringUtils {
         for (int i = 0; i < splits.length; i++) {
             splits[i] = splits[i].trim();
             if (splits[i].length() > 0) {
-               results.add(splits[i]);
+                results.add(splits[i]);
             }
         }
         return Collections.unmodifiableList(results);
     }
-    
+
     /**
      * This method takes a List&lt;String&gt; and a delimiter and joins the strings
-     * into a single string, where the original strings are separated using 
+     * into a single string, where the original strings are separated using
      * the given delimiter.
      *
-     */ 
-    public static String joinStrings(List<String> list, String delim)
-    {
-        if (list == null)
+     */
+    public static String joinStrings(List<String> list, String delim) {
+        if (list == null) {
             return null;
+        }
 
-       StringBuilder builder = new StringBuilder(list.get(0));
+        StringBuilder builder = new StringBuilder(list.get(0));
         for (String s : list.subList(1, list.size())) {
             builder.append(delim).append(s);
         }
 
         return builder.toString();
     }
+
 }

Alguns ficheiros não foram mostrados porque muitos ficheiros mudaram neste diff