Quellcode durchsuchen

ZOOKEEPER-3342: Use StandardCharsets

> Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.  The behavior of this method when this string cannot be encoded in the default charset is unspecified.

https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#getBytes--

1.  Since this is a distributed system, it is always possible that different nodes have different default charsets defined.  I think it's most safe to specify it explicitly across all nodes for safety sake.  You could for example see a situation where an upgrade JVM uses a different default and during a rolling upgrade of the JVM, different nodes now have a different default.
2.  The default charset is usually "ISO-8859-1".  UTF-8 covers more of our international friends.
3. Explicitly specifying the CharSet yields slight performance gains
4. Explicitly specifying the CharSet removes the need for try/catch blocks of UnsupportedEncodingException

https://blog.codecentric.de/en/2014/04/faster-cleaner-code-since-java-7/

Author: David Mollitor <dmollitor@apache.org>
Author: Beluga Behr <dam6923@gmail.com>
Author: David Mollitor <dam6923@gmail.com>

Reviewers: Enrico Olivelli <eolivelli@apache.org>, Andor Molnar <anmolnar@apache.org>

Closes #882 from belugabehr/ZOOKEEPER-3342
David Mollitor vor 4 Jahren
Ursprung
Commit
8654e7ed37
32 geänderte Dateien mit 101 neuen und 82 gelöschten Zeilen
  1. 15 14
      zookeeper-recipes/zookeeper-recipes-queue/src/test/java/org/apache/zookeeper/recipes/queue/DistributedQueueTest.java
  2. 5 4
      zookeeper-server/src/main/java/org/apache/zookeeper/ServerAdminClient.java
  3. 2 1
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/AddAuthCommand.java
  4. 2 1
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/CreateCommand.java
  5. 4 3
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/DelQuotaCommand.java
  6. 2 1
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/GetCommand.java
  7. 4 3
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/GetConfigCommand.java
  8. 4 3
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/ListQuotaCommand.java
  9. 2 1
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/ReconfigCommand.java
  10. 2 1
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/SetCommand.java
  11. 5 4
      zookeeper-server/src/main/java/org/apache/zookeeper/cli/SetQuotaCommand.java
  12. 2 1
      zookeeper-server/src/main/java/org/apache/zookeeper/client/FourLetterWordMain.java
  13. 2 1
      zookeeper-server/src/main/java/org/apache/zookeeper/server/ContainerManager.java
  14. 5 4
      zookeeper-server/src/main/java/org/apache/zookeeper/server/DataTree.java
  15. 2 1
      zookeeper-server/src/main/java/org/apache/zookeeper/server/FinalRequestProcessor.java
  16. 2 1
      zookeeper-server/src/main/java/org/apache/zookeeper/server/NIOServerCnxn.java
  17. 2 1
      zookeeper-server/src/main/java/org/apache/zookeeper/server/NettyServerCnxn.java
  18. 2 1
      zookeeper-server/src/main/java/org/apache/zookeeper/server/PrepRequestProcessor.java
  19. 2 1
      zookeeper-server/src/main/java/org/apache/zookeeper/server/Request.java
  20. 2 1
      zookeeper-server/src/main/java/org/apache/zookeeper/server/ZKDatabase.java
  21. 2 1
      zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/DigestAuthenticationProvider.java
  22. 2 1
      zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/EnsembleAuthenticationProvider.java
  23. 5 16
      zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/KeyAuthenticationProvider.java
  24. 4 3
      zookeeper-server/src/main/java/org/apache/zookeeper/server/quorum/FastLeaderElection.java
  25. 3 2
      zookeeper-server/src/main/java/org/apache/zookeeper/server/quorum/Follower.java
  26. 2 1
      zookeeper-server/src/main/java/org/apache/zookeeper/server/quorum/Leader.java
  27. 5 4
      zookeeper-server/src/main/java/org/apache/zookeeper/server/quorum/Learner.java
  28. 2 1
      zookeeper-server/src/main/java/org/apache/zookeeper/server/quorum/Observer.java
  29. 2 1
      zookeeper-server/src/main/java/org/apache/zookeeper/server/quorum/ObserverMaster.java
  30. 2 1
      zookeeper-server/src/main/java/org/apache/zookeeper/server/quorum/QuorumCnxManager.java
  31. 1 1
      zookeeper-server/src/main/java/org/apache/zookeeper/server/quorum/QuorumZooKeeperServer.java
  32. 3 2
      zookeeper-server/src/test/java/org/apache/zookeeper/common/AtomicFileWritingIdiomTest.java

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

@@ -18,6 +18,7 @@
 
 package org.apache.zookeeper.recipes.queue;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.fail;
@@ -50,10 +51,10 @@ public class DistributedQueueTest extends ClientBase {
             queueHandles[i] = new DistributedQueue(clients[i], dir, null);
         }
 
-        queueHandles[0].offer(testString.getBytes());
+        queueHandles[0].offer(testString.getBytes(UTF_8));
 
         byte[] dequeuedBytes = queueHandles[0].remove();
-        assertEquals(new String(dequeuedBytes), testString);
+        assertEquals(new String(dequeuedBytes, UTF_8), testString);
     }
 
     @Test
@@ -68,10 +69,10 @@ public class DistributedQueueTest extends ClientBase {
             queueHandles[i] = new DistributedQueue(clients[i], dir, null);
         }
 
-        queueHandles[0].offer(testString.getBytes());
+        queueHandles[0].offer(testString.getBytes(UTF_8));
 
         byte[] dequeuedBytes = queueHandles[1].remove();
-        assertEquals(new String(dequeuedBytes), testString);
+        assertEquals(new String(dequeuedBytes, UTF_8), testString);
     }
 
     @Test
@@ -86,10 +87,10 @@ public class DistributedQueueTest extends ClientBase {
             queueHandles[i] = new DistributedQueue(clients[i], dir, null);
         }
 
-        queueHandles[0].offer(testString.getBytes());
+        queueHandles[0].offer(testString.getBytes(UTF_8));
 
         byte[] dequeuedBytes = queueHandles[0].take();
-        assertEquals(new String(dequeuedBytes), testString);
+        assertEquals(new String(dequeuedBytes, UTF_8), testString);
     }
 
     @Test
@@ -124,7 +125,7 @@ public class DistributedQueueTest extends ClientBase {
 
         for (int i = 0; i < n; i++) {
             String offerString = testString + i;
-            queueHandles[0].offer(offerString.getBytes());
+            queueHandles[0].offer(offerString.getBytes(UTF_8));
         }
 
         byte[] data = null;
@@ -133,7 +134,7 @@ public class DistributedQueueTest extends ClientBase {
         }
 
         assertNotNull(data);
-        assertEquals(new String(data), testString + (m - 1));
+        assertEquals(new String(data, UTF_8), testString + (m - 1));
     }
 
     @Test
@@ -157,13 +158,13 @@ public class DistributedQueueTest extends ClientBase {
 
         for (int i = 0; i < n; i++) {
             String offerString = testString + i;
-            queueHandles[0].offer(offerString.getBytes());
+            queueHandles[0].offer(offerString.getBytes(UTF_8));
         }
 
         for (int i = 0; i < m; i++) {
             queueHandles[1].remove();
         }
-        assertEquals(new String(queueHandles[1].element()), testString + m);
+        assertEquals(new String(queueHandles[1].element(), UTF_8), testString + m);
     }
 
     @Test
@@ -211,7 +212,7 @@ public class DistributedQueueTest extends ClientBase {
         Thread.sleep(1000);
         Thread offerThread = new Thread(() -> {
             try {
-                queueHandles[0].offer(testString.getBytes());
+                queueHandles[0].offer(testString.getBytes(UTF_8));
             } catch (KeeperException | InterruptedException ignore) {
                 // no op
             }
@@ -222,7 +223,7 @@ public class DistributedQueueTest extends ClientBase {
         takeThread.join();
 
         assertNotNull(takeResult[0]);
-        assertEquals(new String(takeResult[0]), testString);
+        assertEquals(new String(takeResult[0], UTF_8), testString);
     }
 
     @Test
@@ -252,7 +253,7 @@ public class DistributedQueueTest extends ClientBase {
             Thread.sleep(1000);
             Thread offerThread = new Thread(() -> {
                 try {
-                    queueHandles[0].offer(threadTestString.getBytes());
+                    queueHandles[0].offer(threadTestString.getBytes(UTF_8));
                 } catch (KeeperException | InterruptedException ignore) {
                     // no op
                 }
@@ -263,7 +264,7 @@ public class DistributedQueueTest extends ClientBase {
             takeThread.join();
 
             assertNotNull(takeResult[0]);
-            assertEquals(new String(takeResult[0]), threadTestString);
+            assertEquals(new String(takeResult[0], UTF_8), threadTestString);
         }
     }
 

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

@@ -18,6 +18,7 @@
 
 package org.apache.zookeeper;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
@@ -52,7 +53,7 @@ public class ServerAdminClient {
             byte[] resBytes = new byte[4];
 
             int rc = is.read(resBytes);
-            String retv = new String(resBytes);
+            String retv = new String(resBytes, UTF_8);
             System.out.println("rc=" + rc + " retv=" + retv);
         } catch (IOException e) {
             LOG.warn("Unexpected exception", e);
@@ -86,7 +87,7 @@ public class ServerAdminClient {
             byte[] resBytes = new byte[1024];
 
             int rc = is.read(resBytes);
-            String retv = new String(resBytes);
+            String retv = new String(resBytes, UTF_8);
             System.out.println("rc=" + rc + " retv=" + retv);
         } catch (IOException e) {
             LOG.warn("Unexpected exception", e);
@@ -120,7 +121,7 @@ public class ServerAdminClient {
             byte[] resBytes = new byte[1024];
 
             int rc = is.read(resBytes);
-            String retv = new String(resBytes);
+            String retv = new String(resBytes, UTF_8);
             System.out.println("rc=" + rc + " retv=" + retv);
         } catch (IOException e) {
             LOG.warn("Unexpected exception", e);
@@ -153,7 +154,7 @@ public class ServerAdminClient {
             byte[] resBytes = new byte[4];
 
             int rc = is.read(resBytes);
-            String retv = new String(resBytes);
+            String retv = new String(resBytes, UTF_8);
             System.out.println("rc=" + rc + " retv=" + retv);
         } catch (IOException e) {
             LOG.warn("Unexpected exception", e);

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

@@ -18,6 +18,7 @@
 
 package org.apache.zookeeper.cli;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
 import org.apache.commons.cli.CommandLine;
 import org.apache.commons.cli.DefaultParser;
 import org.apache.commons.cli.Options;
@@ -57,7 +58,7 @@ public class AddAuthCommand extends CliCommand {
     public boolean exec() throws CliException {
         byte[] b = null;
         if (args.length >= 3) {
-            b = args[2].getBytes();
+            b = args[2].getBytes(UTF_8);
         }
 
         zk.addAuthInfo(args[1], b);

+ 2 - 1
zookeeper-server/src/main/java/org/apache/zookeeper/cli/CreateCommand.java

@@ -18,6 +18,7 @@
 
 package org.apache.zookeeper.cli;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
 import java.util.List;
 import org.apache.commons.cli.CommandLine;
 import org.apache.commons.cli.DefaultParser;
@@ -112,7 +113,7 @@ public class CreateCommand extends CliCommand {
         String path = args[1];
         byte[] data = null;
         if (args.length > 2) {
-            data = args[2].getBytes();
+            data = args[2].getBytes(UTF_8);
         }
         List<ACL> acl = ZooDefs.Ids.OPEN_ACL_UNSAFE;
         if (args.length > 3) {

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

@@ -18,6 +18,7 @@
 
 package org.apache.zookeeper.cli;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
 import java.io.IOException;
 import java.util.List;
 import org.apache.commons.cli.CommandLine;
@@ -119,13 +120,13 @@ public class DelQuotaCommand extends CliCommand {
             System.err.println("quota does not exist for " + path);
             return true;
         }
-        StatsTrack strack = new StatsTrack(new String(data));
+        StatsTrack strack = new StatsTrack(new String(data, UTF_8));
         if (bytes && !numNodes) {
             strack.setBytes(-1L);
-            zk.setData(quotaPath, strack.toString().getBytes(), -1);
+            zk.setData(quotaPath, strack.toString().getBytes(UTF_8), -1);
         } else if (!bytes && numNodes) {
             strack.setCount(-1);
-            zk.setData(quotaPath, strack.toString().getBytes(), -1);
+            zk.setData(quotaPath, strack.toString().getBytes(UTF_8), -1);
         } else if (bytes && numNodes) {
             // delete till you can find a node with more than
             // one child

+ 2 - 1
zookeeper-server/src/main/java/org/apache/zookeeper/cli/GetCommand.java

@@ -18,6 +18,7 @@
 
 package org.apache.zookeeper.cli;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
 import org.apache.commons.cli.CommandLine;
 import org.apache.commons.cli.DefaultParser;
 import org.apache.commons.cli.Options;
@@ -92,7 +93,7 @@ public class GetCommand extends CliCommand {
             throw new CliException(ex);
         }
         data = (data == null) ? "null".getBytes() : data;
-        out.println(new String(data));
+        out.println(new String(data, UTF_8));
         if (cl.hasOption("s")) {
             new StatPrinter(out).print(stat);
         }

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

@@ -18,6 +18,7 @@
 
 package org.apache.zookeeper.cli;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
 import org.apache.commons.cli.CommandLine;
 import org.apache.commons.cli.DefaultParser;
 import org.apache.commons.cli.Options;
@@ -72,11 +73,11 @@ public class GetConfigCommand extends CliCommand {
         } catch (KeeperException | InterruptedException ex) {
             throw new CliWrapperException(ex);
         }
-        data = (data == null) ? "null".getBytes() : data;
+        data = (data == null) ? "null".getBytes(UTF_8) : data;
         if (cl.hasOption("c")) {
-            out.println(ConfigUtils.getClientConfigStr(new String(data)));
+            out.println(ConfigUtils.getClientConfigStr(new String(data, UTF_8)));
         } else {
-            out.println(new String(data));
+            out.println(new String(data, UTF_8));
         }
 
         if (cl.hasOption("s")) {

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

@@ -18,6 +18,7 @@
 
 package org.apache.zookeeper.cli;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
 import org.apache.commons.cli.CommandLine;
 import org.apache.commons.cli.DefaultParser;
 import org.apache.commons.cli.Options;
@@ -64,11 +65,11 @@ public class ListQuotaCommand extends CliCommand {
             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());
+            StatsTrack st = new StatsTrack(new String(data, UTF_8));
+            out.println("Output quota for " + path + " " + st);
 
             data = zk.getData(Quotas.quotaZookeeper + path + "/" + Quotas.statNode, false, stat);
-            out.println("Output stat for " + path + " " + new StatsTrack(new String(data)).toString());
+            out.println("Output stat for " + path + " " + new StatsTrack(new String(data, UTF_8)));
         } catch (IllegalArgumentException ex) {
             throw new MalformedPathException(ex.getMessage());
         } catch (KeeperException.NoNodeException ne) {

+ 2 - 1
zookeeper-server/src/main/java/org/apache/zookeeper/cli/ReconfigCommand.java

@@ -18,6 +18,7 @@
 
 package org.apache.zookeeper.cli;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
 import java.io.FileInputStream;
 import java.util.Properties;
 import org.apache.commons.cli.CommandLine;
@@ -151,7 +152,7 @@ public class ReconfigCommand extends CliCommand {
             }
 
             byte[] curConfig = ((ZooKeeperAdmin) zk).reconfigure(joining, leaving, members, version, stat);
-            out.println("Committed new configuration:\n" + new String(curConfig));
+            out.println("Committed new configuration:\n" + new String(curConfig, UTF_8));
 
             if (cl.hasOption("s")) {
                 new StatPrinter(out).print(stat);

+ 2 - 1
zookeeper-server/src/main/java/org/apache/zookeeper/cli/SetCommand.java

@@ -18,6 +18,7 @@
 
 package org.apache.zookeeper.cli;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
 import org.apache.commons.cli.CommandLine;
 import org.apache.commons.cli.DefaultParser;
 import org.apache.commons.cli.Options;
@@ -62,7 +63,7 @@ public class SetCommand extends CliCommand {
     @Override
     public boolean exec() throws CliException {
         String path = args[1];
-        byte[] data = args[2].getBytes();
+        byte[] data = args[2].getBytes(UTF_8);
         int version;
         if (cl.hasOption("v")) {
             version = Integer.parseInt(cl.getOptionValue("v"));

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

@@ -18,6 +18,7 @@
 
 package org.apache.zookeeper.cli;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
 import java.util.ArrayList;
 import java.util.List;
 import org.apache.commons.cli.CommandLine;
@@ -169,21 +170,21 @@ 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(UTF_8), 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(UTF_8), 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));
+            StatsTrack strackC = new StatsTrack(new String(data, UTF_8));
             if (bytes != -1L) {
                 strackC.setBytes(bytes);
             }
             if (numNodes != -1) {
                 strackC.setCount(numNodes);
             }
-            zk.setData(quotaPath, strackC.toString().getBytes(), -1);
+            zk.setData(quotaPath, strackC.toString().getBytes(UTF_8), -1);
         }
         return true;
     }

+ 2 - 1
zookeeper-server/src/main/java/org/apache/zookeeper/client/FourLetterWordMain.java

@@ -18,6 +18,7 @@
 
 package org.apache.zookeeper.client;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
 import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStreamReader;
@@ -113,7 +114,7 @@ public class FourLetterWordMain {
         BufferedReader reader = null;
         try {
             OutputStream outstream = sock.getOutputStream();
-            outstream.write(cmd.getBytes());
+            outstream.write(cmd.getBytes(UTF_8));
             outstream.flush();
 
             // this replicates NC - close the output stream before reading

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

@@ -18,6 +18,7 @@
 
 package org.apache.zookeeper.server;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
 import java.nio.ByteBuffer;
 import java.util.Collection;
 import java.util.HashSet;
@@ -128,7 +129,7 @@ public class ContainerManager {
         for (String containerPath : getCandidates()) {
             long startMs = Time.currentElapsedTime();
 
-            ByteBuffer path = ByteBuffer.wrap(containerPath.getBytes());
+            ByteBuffer path = ByteBuffer.wrap(containerPath.getBytes(UTF_8));
             Request request = new Request(null, 0, 0, ZooDefs.OpCode.deleteContainer, path, null);
             try {
                 LOG.info("Attempting to delete candidate container: {}", containerPath);

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

@@ -18,6 +18,7 @@
 
 package org.apache.zookeeper.server;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
 import java.io.EOFException;
 import java.io.IOException;
 import java.io.PrintWriter;
@@ -391,10 +392,10 @@ public class DataTree {
             return;
         }
         synchronized (node) {
-            updatedStat = new StatsTrack(new String(node.data));
+            updatedStat = new StatsTrack(new String(node.data, UTF_8));
             updatedStat.setCount(updatedStat.getCount() + countDiff);
             updatedStat.setBytes(updatedStat.getBytes() + bytesDiff);
-            node.data = updatedStat.toString().getBytes();
+            node.data = updatedStat.toString().getBytes(UTF_8);
         }
         // now check if the counts match the quota
         String quotaNode = Quotas.quotaPath(lastPrefix);
@@ -406,7 +407,7 @@ public class DataTree {
             return;
         }
         synchronized (node) {
-            thisStats = new StatsTrack(new String(node.data));
+            thisStats = new StatsTrack(new String(node.data, UTF_8));
         }
         if (thisStats.getCount() > -1 && (thisStats.getCount() < updatedStat.getCount())) {
             LOG.warn(
@@ -1260,7 +1261,7 @@ public class DataTree {
         }
         synchronized (node) {
             nodes.preChange(statPath, node);
-            node.data = strack.toString().getBytes();
+            node.data = strack.toString().getBytes(UTF_8);
             nodes.postChange(statPath, node);
         }
     }

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

@@ -18,6 +18,7 @@
 
 package org.apache.zookeeper.server;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
 import java.io.IOException;
 import java.nio.ByteBuffer;
 import java.util.ArrayList;
@@ -329,7 +330,7 @@ public class FinalRequestProcessor implements RequestProcessor {
             case OpCode.reconfig: {
                 lastOp = "RECO";
                 rsp = new GetDataResponse(
-                    ((QuorumZooKeeperServer) zks).self.getQuorumVerifier().toString().getBytes(),
+                    ((QuorumZooKeeperServer) zks).self.getQuorumVerifier().toString().getBytes(UTF_8),
                     rc.stat);
                 err = Code.get(rc.err);
                 break;

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

@@ -18,6 +18,7 @@
 
 package org.apache.zookeeper.server;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
 import java.io.BufferedWriter;
 import java.io.IOException;
 import java.io.PrintWriter;
@@ -442,7 +443,7 @@ public class NIOServerCnxn extends ServerCnxn {
          */
         private void checkFlush(boolean force) {
             if ((force && sb.length() > 0) || sb.length() > 2048) {
-                sendBufferSync(ByteBuffer.wrap(sb.toString().getBytes()));
+                sendBufferSync(ByteBuffer.wrap(sb.toString().getBytes(UTF_8)));
                 // clear our internal buffer
                 sb.setLength(0);
             }

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

@@ -18,6 +18,7 @@
 
 package org.apache.zookeeper.server;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
 import io.netty.buffer.ByteBuf;
 import io.netty.buffer.ByteBufUtil;
 import io.netty.buffer.CompositeByteBuf;
@@ -233,7 +234,7 @@ public class NettyServerCnxn extends ServerCnxn {
          */
         private void checkFlush(boolean force) {
             if ((force && sb.length() > 0) || sb.length() > 2048) {
-                sendBuffer(ByteBuffer.wrap(sb.toString().getBytes()));
+                sendBuffer(ByteBuffer.wrap(sb.toString().getBytes(UTF_8)));
                 // clear our internal buffer
                 sb.setLength(0);
             }

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

@@ -18,6 +18,7 @@
 
 package org.apache.zookeeper.server;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.io.StringReader;
@@ -331,7 +332,7 @@ public class PrepRequestProcessor extends ZooKeeperCriticalThread implements Req
             break;
         }
         case OpCode.deleteContainer: {
-            String path = new String(request.request.array());
+            String path = new String(request.request.array(), UTF_8);
             String parentPath = getParentPathAndValidate(path);
             ChangeRecord nodeRecord = getRecordForPath(path);
             if (nodeRecord.childCount > 0) {

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

@@ -18,6 +18,7 @@
 
 package org.apache.zookeeper.server;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
 import java.nio.ByteBuffer;
 import java.util.List;
 import org.apache.jute.Record;
@@ -408,7 +409,7 @@ public class Request {
                 if (pathLen >= 0 && pathLen < 4096 && rbuf.remaining() >= pathLen) {
                     byte[] b = new byte[pathLen];
                     rbuf.get(b);
-                    path = new String(b);
+                    path = new String(b, UTF_8);
                 }
             } catch (Exception e) {
                 // ignore - can't find the path, will output "n/a" instead

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

@@ -18,6 +18,7 @@
 
 package org.apache.zookeeper.server;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
 import java.io.File;
 import java.io.IOException;
 import java.io.PrintWriter;
@@ -677,7 +678,7 @@ public class ZKDatabase {
             }
             this.dataTree.setData(
                 ZooDefs.CONFIG_NODE,
-                qv.toString().getBytes(),
+                qv.toString().getBytes(UTF_8),
                 -1,
                 qv.getVersion(),
                 Time.currentWallTime());

+ 2 - 1
zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/DigestAuthenticationProvider.java

@@ -18,6 +18,7 @@
 
 package org.apache.zookeeper.server.auth;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
 import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
 import org.apache.zookeeper.KeeperException;
@@ -88,7 +89,7 @@ public class DigestAuthenticationProvider implements AuthenticationProvider {
 
     public static String generateDigest(String idPassword) throws NoSuchAlgorithmException {
         String[] parts = idPassword.split(":", 2);
-        byte[] digest = MessageDigest.getInstance("SHA1").digest(idPassword.getBytes());
+        byte[] digest = MessageDigest.getInstance("SHA1").digest(idPassword.getBytes(UTF_8));
         return parts[0] + ":" + base64Encode(digest);
     }
 

+ 2 - 1
zookeeper-server/src/main/java/org/apache/zookeeper/server/auth/EnsembleAuthenticationProvider.java

@@ -18,6 +18,7 @@
 
 package org.apache.zookeeper.server.auth;
 
+import java.nio.charset.StandardCharsets;
 import java.util.HashSet;
 import java.util.Set;
 import org.apache.zookeeper.KeeperException;
@@ -76,7 +77,7 @@ public class EnsembleAuthenticationProvider implements AuthenticationProvider {
             return KeeperException.Code.OK;
         }
 
-        String receivedEnsembleName = new String(authData);
+        String receivedEnsembleName = new String(authData, StandardCharsets.UTF_8);
 
         if (ensembleNames == null) {
             ServerMetrics.getMetrics().ENSEMBLE_AUTH_SKIP.add(1);

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

@@ -18,7 +18,7 @@
 
 package org.apache.zookeeper.server.auth;
 
-import java.nio.charset.StandardCharsets;
+import static java.nio.charset.StandardCharsets.UTF_8;
 import org.apache.zookeeper.KeeperException;
 import org.apache.zookeeper.KeeperException.NoNodeException;
 import org.apache.zookeeper.data.Id;
@@ -75,8 +75,8 @@ public class KeyAuthenticationProvider extends ServerAuthenticationProvider {
     private boolean validate(byte[] key, byte[] auth) {
         // perform arbitrary function (auth is a multiple of key)
         try {
-            String keyStr = new String(key, StandardCharsets.UTF_8);
-            String authStr = new String(auth, StandardCharsets.UTF_8);
+            String keyStr = new String(key, UTF_8);
+            String authStr = new String(auth, UTF_8);
             int keyVal = Integer.parseInt(keyStr);
             int authVal = Integer.parseInt(authStr);
             if (keyVal != 0 && ((authVal % keyVal) != 0)) {
@@ -92,22 +92,11 @@ public class KeyAuthenticationProvider extends ServerAuthenticationProvider {
     @Override
     public KeeperException.Code handleAuthentication(ServerObjs serverObjs, byte[] authData) {
         byte[] key = getKey(serverObjs.getZks());
-        String authStr = "";
+        String authStr = new String(authData, UTF_8);
         String keyStr = "";
-        try {
-            authStr = new String(authData, StandardCharsets.UTF_8);
-        } catch (Exception e) {
-            LOG.error("UTF-8", e);
-        }
         if (key != null) {
             if (!validate(key, authData)) {
-                try {
-                    keyStr = new String(key, StandardCharsets.UTF_8);
-                } catch (Exception e) {
-                    LOG.error("UTF-8", e);
-                    // empty key
-                    keyStr = authStr;
-                }
+                keyStr = new String(key, UTF_8);
                 LOG.debug("KeyAuthenticationProvider handleAuthentication ({}, {}) -> FAIL.\n", keyStr, authStr);
                 return KeeperException.Code.AUTHFAILED;
             }

+ 4 - 3
zookeeper-server/src/main/java/org/apache/zookeeper/server/quorum/FastLeaderElection.java

@@ -18,6 +18,7 @@
 
 package org.apache.zookeeper.server.quorum;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
 import java.io.IOException;
 import java.nio.BufferUnderflowException;
 import java.nio.ByteBuffer;
@@ -301,7 +302,7 @@ public class FastLeaderElection implements Election {
 
                                 synchronized (self) {
                                     try {
-                                        rqv = self.configFromString(new String(b));
+                                        rqv = self.configFromString(new String(b, UTF_8));
                                         QuorumVerifier curQV = self.getQuorumVerifier();
                                         if (rqv.getVersion() > curQV.getVersion()) {
                                             LOG.info("{} Received version: {} my version: {}",
@@ -349,7 +350,7 @@ public class FastLeaderElection implements Election {
                                 self.getPeerState(),
                                 response.sid,
                                 current.getPeerEpoch(),
-                                qv.toString().getBytes());
+                                qv.toString().getBytes(UTF_8));
 
                             sendqueue.offer(notmsg);
                         } else {
@@ -697,7 +698,7 @@ public class FastLeaderElection implements Election {
                 QuorumPeer.ServerState.LOOKING,
                 sid,
                 proposedEpoch,
-                qv.toString().getBytes());
+                qv.toString().getBytes(UTF_8));
 
             LOG.debug(
                 "Sending Notification: {} (n.leader), 0x{} (n.zxid), 0x{} (n.round), {} (recipient),"

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

@@ -18,6 +18,7 @@
 
 package org.apache.zookeeper.server.quorum;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
 import java.io.IOException;
 import java.nio.ByteBuffer;
 import java.util.Collections;
@@ -176,7 +177,7 @@ public class Follower extends Learner {
 
             if (hdr.getType() == OpCode.reconfig) {
                 SetDataTxn setDataTxn = (SetDataTxn) txn;
-                QuorumVerifier qv = self.configFromString(new String(setDataTxn.getData()));
+                QuorumVerifier qv = self.configFromString(new String(setDataTxn.getData(), UTF_8));
                 self.setLastSeenQuorumVerifier(qv, true);
             }
 
@@ -213,7 +214,7 @@ public class Follower extends Learner {
             // get the new configuration from the request
             Request request = fzk.pendingTxns.element();
             SetDataTxn setDataTxn = (SetDataTxn) request.getTxn();
-            QuorumVerifier qv = self.configFromString(new String(setDataTxn.getData()));
+            QuorumVerifier qv = self.configFromString(new String(setDataTxn.getData(), UTF_8));
 
             // get new designated leader from (current) leader's message
             ByteBuffer buffer = ByteBuffer.wrap(qp.getData());

+ 2 - 1
zookeeper-server/src/main/java/org/apache/zookeeper/server/quorum/Leader.java

@@ -18,6 +18,7 @@
 
 package org.apache.zookeeper.server.quorum;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
 import java.io.BufferedInputStream;
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
@@ -1693,7 +1694,7 @@ public class Leader extends LearnerMaster {
 
     @Override
     public byte[] getQuorumVerifierBytes() {
-        return self.getLastSeenQuorumVerifier().toString().getBytes();
+        return self.getLastSeenQuorumVerifier().toString().getBytes(UTF_8);
     }
 
     @Override

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

@@ -18,6 +18,7 @@
 
 package org.apache.zookeeper.server.quorum;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
 import java.io.BufferedInputStream;
 import java.io.BufferedOutputStream;
 import java.io.ByteArrayInputStream;
@@ -634,7 +635,7 @@ public class Learner {
 
                     if (pif.hdr.getType() == OpCode.reconfig) {
                         SetDataTxn setDataTxn = (SetDataTxn) pif.rec;
-                        QuorumVerifier qv = self.configFromString(new String(setDataTxn.getData()));
+                        QuorumVerifier qv = self.configFromString(new String(setDataTxn.getData(), UTF_8));
                         self.setLastSeenQuorumVerifier(qv, true);
                     }
 
@@ -644,7 +645,7 @@ public class Learner {
                 case Leader.COMMITANDACTIVATE:
                     pif = packetsNotCommitted.peekFirst();
                     if (pif.hdr.getZxid() == qp.getZxid() && qp.getType() == Leader.COMMITANDACTIVATE) {
-                        QuorumVerifier qv = self.configFromString(new String(((SetDataTxn) pif.rec).getData()));
+                        QuorumVerifier qv = self.configFromString(new String(((SetDataTxn) pif.rec).getData(), UTF_8));
                         boolean majorChange = self.processReconfig(
                             qv,
                             ByteBuffer.wrap(qp.getData()).getLong(), qp.getZxid(),
@@ -680,7 +681,7 @@ public class Learner {
                         packet.hdr = logEntry.getHeader();
                         packet.rec = logEntry.getTxn();
                         packet.digest = logEntry.getDigest();
-                        QuorumVerifier qv = self.configFromString(new String(((SetDataTxn) packet.rec).getData()));
+                        QuorumVerifier qv = self.configFromString(new String(((SetDataTxn) packet.rec).getData(), UTF_8));
                         boolean majorChange = self.processReconfig(qv, suggestedLeaderId, qp.getZxid(), true);
                         if (majorChange) {
                             throw new Exception("changes proposed in reconfig");
@@ -728,7 +729,7 @@ public class Learner {
                     LOG.info("Learner received NEWLEADER message");
                     if (qp.getData() != null && qp.getData().length > 1) {
                         try {
-                            QuorumVerifier qv = self.configFromString(new String(qp.getData()));
+                            QuorumVerifier qv = self.configFromString(new String(qp.getData(), UTF_8));
                             self.setLastSeenQuorumVerifier(qv, true);
                             newLeaderQV = qv;
                         } catch (Exception e) {

+ 2 - 1
zookeeper-server/src/main/java/org/apache/zookeeper/server/quorum/Observer.java

@@ -18,6 +18,7 @@
 
 package org.apache.zookeeper.server.quorum;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
 import java.nio.ByteBuffer;
 import java.util.concurrent.atomic.AtomicReference;
 import org.apache.jute.Record;
@@ -216,7 +217,7 @@ public class Observer extends Learner {
             hdr = logEntry.getHeader();
             txn = logEntry.getTxn();
             digest = logEntry.getDigest();
-            QuorumVerifier qv = self.configFromString(new String(((SetDataTxn) txn).getData()));
+            QuorumVerifier qv = self.configFromString(new String(((SetDataTxn) txn).getData(), UTF_8));
 
             request = new Request(hdr.getClientId(), hdr.getCxid(), hdr.getType(), hdr, txn, 0);
             request.setTxnDigest(digest);

+ 2 - 1
zookeeper-server/src/main/java/org/apache/zookeeper/server/quorum/ObserverMaster.java

@@ -18,6 +18,7 @@
 
 package org.apache.zookeeper.server.quorum;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
 import java.io.BufferedInputStream;
 import java.io.ByteArrayInputStream;
 import java.io.DataInputStream;
@@ -343,7 +344,7 @@ public class ObserverMaster extends LearnerMaster implements Runnable {
 
     @Override
     public byte[] getQuorumVerifierBytes() {
-        return self.getLastSeenQuorumVerifier().toString().getBytes();
+        return self.getLastSeenQuorumVerifier().toString().getBytes(UTF_8);
     }
 
     @Override

+ 2 - 1
zookeeper-server/src/main/java/org/apache/zookeeper/server/quorum/QuorumCnxManager.java

@@ -18,6 +18,7 @@
 
 package org.apache.zookeeper.server.quorum;
 
+import static java.nio.charset.StandardCharsets.UTF_8;
 import static org.apache.zookeeper.common.NetUtils.formatInetAddr;
 import java.io.BufferedInputStream;
 import java.io.BufferedOutputStream;
@@ -255,7 +256,7 @@ public class QuorumCnxManager {
 
             // in PROTOCOL_VERSION_V1 we expect to get a single address here represented as a 'host:port' string
             // in PROTOCOL_VERSION_V2 we expect to get multiple addresses like: 'host1:port1|host2:port2|...'
-            String[] addressStrings = new String(b).split("\\|");
+            String[] addressStrings = new String(b, UTF_8).split("\\|");
             List<InetSocketAddress> addresses = new ArrayList<>(addressStrings.length);
             for (String addr : addressStrings) {
 

+ 1 - 1
zookeeper-server/src/main/java/org/apache/zookeeper/server/quorum/QuorumZooKeeperServer.java

@@ -186,7 +186,7 @@ public abstract class QuorumZooKeeperServer extends ZooKeeperServer {
         pwriter.print("peerType=");
         pwriter.println(self.getLearnerType().ordinal());
         pwriter.println("membership: ");
-        pwriter.print(new String(self.getQuorumVerifier().toString().getBytes()));
+        pwriter.print(self.getQuorumVerifier().toString());
     }
 
     @Override

+ 3 - 2
zookeeper-server/src/test/java/org/apache/zookeeper/common/AtomicFileWritingIdiomTest.java

@@ -27,6 +27,7 @@ import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.OutputStream;
 import java.io.Writer;
+import java.nio.charset.Charset;
 import java.nio.charset.StandardCharsets;
 import org.apache.zookeeper.ZKTestCase;
 import org.apache.zookeeper.common.AtomicFileWritingIdiom.OutputStreamStatement;
@@ -335,7 +336,7 @@ public class AtomicFileWritingIdiomTest extends ZKTestCase {
         assertFalse(target.exists(), "file should not exist");
     }
 
-    private String getContent(File file, String encoding) throws IOException {
+    private String getContent(File file, Charset encoding) throws IOException {
         StringBuilder result = new StringBuilder();
         FileInputStream fis = new FileInputStream(file);
         byte[] b = new byte[20];
@@ -348,7 +349,7 @@ public class AtomicFileWritingIdiomTest extends ZKTestCase {
     }
 
     private String getContent(File file) throws IOException {
-        return getContent(file, "ASCII");
+        return getContent(file, StandardCharsets.US_ASCII);
     }
 
     private void createFile(File file, String content) throws IOException {