This is an automated email from the ASF dual-hosted git repository.

adoroszlai pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/ozone.git


The following commit(s) were added to refs/heads/master by this push:
     new 5894ac20198 HDDS-17760. Avoid using CommandLine.getOut/getErr (#12005)
5894ac20198 is described below

commit 5894ac20198eb28636b6af5bb58a4ca936d91bd3
Author: Doroszlai, Attila <[email protected]>
AuthorDate: Thu Nov 12 07:38:55 2026 +0100

    HDDS-17760. Avoid using CommandLine.getOut/getErr (#12005)
---
 .../apache/hadoop/hdds/cli/AbstractSubcommand.java |  14 ++-
 .../hadoop/hdds/cli/DeprecatedCliOption.java       |   6 +-
 .../org/apache/hadoop/hdds/cli/GenericCli.java     |  24 +++--
 .../org/apache/ozone/test/GenericTestUtils.java    |   7 +-
 .../hdds/scm/cli/ContainerBalancerCliHelper.java   |   4 +-
 .../ozone/admin/upgrade/StatusSubCommand.java      |   6 +-
 .../hdds/cli/TestOzoneAdminDeprecatedOptions.java  |  16 +++-
 .../apache/hadoop/ozone/debug/ldb/DBScanner.java   |  28 +++---
 .../ozone/debug/om/ContainerToKeyMapping.java      |  15 ++-
 .../container/analyze/TestAnalyzeSubcommand.java   |  22 +++--
 .../ozone/debug/om/TestContainerToKeyMapping.java  |  15 ++-
 .../org/apache/hadoop/ozone/local/OzoneLocal.java  |  30 +++---
 .../apache/hadoop/ozone/local/TestOzoneLocal.java  | 102 ++++++++++-----------
 .../apache/hadoop/ozone/shell/acl/AclOption.java   |   8 +-
 .../ozone/shell/snapshot/SnapshotDiffHandler.java  |  31 +++----
 .../org/apache/hadoop/ozone/debug/TestLDBCli.java  |  31 +++----
 .../hadoop/ozone/shell/TestOzoneDebugShell.java    |  56 ++++++-----
 .../ozone/admin/om/lease/TestLeaseRecoverer.java   |  64 ++++++-------
 .../hadoop/ozone/shell/TestOzoneTenantShell.java   |  46 ++++++----
 19 files changed, 265 insertions(+), 260 deletions(-)

diff --git 
a/hadoop-hdds/cli-common/src/main/java/org/apache/hadoop/hdds/cli/AbstractSubcommand.java
 
b/hadoop-hdds/cli-common/src/main/java/org/apache/hadoop/hdds/cli/AbstractSubcommand.java
index 08d271d7f12..ffd67c206de 100644
--- 
a/hadoop-hdds/cli-common/src/main/java/org/apache/hadoop/hdds/cli/AbstractSubcommand.java
+++ 
b/hadoop-hdds/cli-common/src/main/java/org/apache/hadoop/hdds/cli/AbstractSubcommand.java
@@ -18,7 +18,7 @@
 package org.apache.hadoop.hdds.cli;
 
 import java.io.IOException;
-import java.io.PrintWriter;
+import java.io.PrintStream;
 import java.util.function.Supplier;
 import org.apache.hadoop.hdds.conf.OzoneConfiguration;
 import org.apache.hadoop.security.UserGroupInformation;
@@ -94,11 +94,15 @@ public void printError(Throwable t) {
     }
   }
 
-  protected PrintWriter out() {
-    return spec().commandLine().getOut();
+  protected PrintStream out() {
+    return System.out;
+    // until https://github.com/remkop/picocli/issues/2546 is fixed
+    // return spec().commandLine().getOut();
   }
 
-  protected PrintWriter err() {
-    return spec().commandLine().getErr();
+  protected PrintStream err() {
+    return System.err;
+    // until https://github.com/remkop/picocli/issues/2546 is fixed
+    // return spec().commandLine().getErr();
   }
 }
diff --git 
a/hadoop-hdds/cli-common/src/main/java/org/apache/hadoop/hdds/cli/DeprecatedCliOption.java
 
b/hadoop-hdds/cli-common/src/main/java/org/apache/hadoop/hdds/cli/DeprecatedCliOption.java
index 2f324778ffe..3c972ff09c1 100644
--- 
a/hadoop-hdds/cli-common/src/main/java/org/apache/hadoop/hdds/cli/DeprecatedCliOption.java
+++ 
b/hadoop-hdds/cli-common/src/main/java/org/apache/hadoop/hdds/cli/DeprecatedCliOption.java
@@ -17,7 +17,7 @@
 
 package org.apache.hadoop.hdds.cli;
 
-import java.io.PrintWriter;
+import java.io.PrintStream;
 import java.util.LinkedHashMap;
 import java.util.Map;
 import java.util.Objects;
@@ -84,7 +84,7 @@ private static Map<String, String> buildDeprecatedOptions() {
    * If {@code arg} is a deprecated option (with or without {@code =value} 
part),
    * print a warning to stderr and return with the recommended replacement 
option.
    */
-  public static String toNonDeprecated(String arg, PrintWriter err) {
+  public static String toNonDeprecated(String arg, PrintStream err) {
     if (arg == null || arg.isEmpty()) {
       return arg;
     }
@@ -104,7 +104,7 @@ public static String toNonDeprecated(String arg, 
PrintWriter err) {
     return result;
   }
 
-  private static void warn(PrintWriter err, String deprecated, String 
replacement) {
+  private static void warn(PrintStream err, String deprecated, String 
replacement) {
     err.printf("WARNING: Option '%s' is deprecated. Use '%s' instead.%n",
         deprecated, replacement);
   }
diff --git 
a/hadoop-hdds/cli-common/src/main/java/org/apache/hadoop/hdds/cli/GenericCli.java
 
b/hadoop-hdds/cli-common/src/main/java/org/apache/hadoop/hdds/cli/GenericCli.java
index b90bf49ce2d..e86cb57c013 100644
--- 
a/hadoop-hdds/cli-common/src/main/java/org/apache/hadoop/hdds/cli/GenericCli.java
+++ 
b/hadoop-hdds/cli-common/src/main/java/org/apache/hadoop/hdds/cli/GenericCli.java
@@ -18,7 +18,7 @@
 package org.apache.hadoop.hdds.cli;
 
 import java.io.IOException;
-import java.io.PrintWriter;
+import java.io.PrintStream;
 import java.nio.file.AccessDeniedException;
 import java.nio.file.FileAlreadyExistsException;
 import java.nio.file.FileSystemException;
@@ -70,7 +70,7 @@ public GenericCli(CommandLine.IFactory factory) {
     cmd = new CommandLine(this, factory);
     ExtensibleParentCommand.addSubcommands(cmd);
     cmd.getCommandSpec().preprocessor((args, commandSpec, argSpec, info) -> {
-      args.replaceAll(arg -> DeprecatedCliOption.toNonDeprecated(arg, 
cmd.getErr()));
+      args.replaceAll(arg -> DeprecatedCliOption.toNonDeprecated(arg, err()));
       return false;
     });
 
@@ -98,20 +98,20 @@ public void printError(Throwable error) {
     //print out the stack trace.
     final String rawMessage = error.getMessage();
     if (verbose || rawMessage == null || rawMessage.isEmpty()) {
-      error.printStackTrace(cmd.getErr());
+      error.printStackTrace(err());
       return;
     }
     String aclLine = HddsUtils.formatAccessControlExceptionLine(error);
     if (aclLine != null) {
-      cmd.getErr().println(aclLine);
+      err().println(aclLine);
       ExitUtils.terminate(EXECUTION_ERROR_EXIT_CODE, aclLine, null);
     }
     if (error instanceof FileSystemException) {
       String errorMessage = handleFileSystemException((FileSystemException) 
error);
-      cmd.getErr().println(errorMessage);
+      err().println(errorMessage);
       return;
     }
-    cmd.getErr().println(rawMessage.split("\n")[0]);
+    err().println(rawMessage.split("\n")[0]);
   }
 
   @Override
@@ -136,12 +136,16 @@ public boolean isVerbose() {
     return verbose;
   }
 
-  protected PrintWriter out() {
-    return cmd.getOut();
+  protected PrintStream out() {
+    return System.out;
+    // until https://github.com/remkop/picocli/issues/2546 is fixed
+    // return cmd.getOut();
   }
 
-  protected PrintWriter err() {
-    return cmd.getErr();
+  protected PrintStream err() {
+    return System.err;
+    // until https://github.com/remkop/picocli/issues/2546 is fixed
+    // return cmd.getErr();
   }
 
   private static String handleFileSystemException(FileSystemException e) {
diff --git 
a/hadoop-hdds/test-utils/src/main/java/org/apache/ozone/test/GenericTestUtils.java
 
b/hadoop-hdds/test-utils/src/main/java/org/apache/ozone/test/GenericTestUtils.java
index a65175287ff..2d4209c5a25 100644
--- 
a/hadoop-hdds/test-utils/src/main/java/org/apache/ozone/test/GenericTestUtils.java
+++ 
b/hadoop-hdds/test-utils/src/main/java/org/apache/ozone/test/GenericTestUtils.java
@@ -313,6 +313,11 @@ public String get() {
       return getOutput();
     }
 
+    @Override
+    public String toString() {
+      return getOutput();
+    }
+
     public String getOutput() {
       try {
         return bytes.toString(UTF_8.name());
@@ -326,7 +331,7 @@ public void reset() {
     }
 
     @Override
-    public void close() throws Exception {
+    public void close() {
       IOUtils.closeQuietly(bytesPrintStream);
       restore.accept(old);
     }
diff --git 
a/hadoop-ozone/cli-admin/src/main/java/org/apache/hadoop/hdds/scm/cli/ContainerBalancerCliHelper.java
 
b/hadoop-ozone/cli-admin/src/main/java/org/apache/hadoop/hdds/scm/cli/ContainerBalancerCliHelper.java
index 75d47168c72..4b732c5e71b 100644
--- 
a/hadoop-ozone/cli-admin/src/main/java/org/apache/hadoop/hdds/scm/cli/ContainerBalancerCliHelper.java
+++ 
b/hadoop-ozone/cli-admin/src/main/java/org/apache/hadoop/hdds/scm/cli/ContainerBalancerCliHelper.java
@@ -20,7 +20,7 @@
 import static org.apache.hadoop.util.StringUtils.byteDesc;
 
 import java.io.IOException;
-import java.io.PrintWriter;
+import java.io.PrintStream;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.Optional;
@@ -59,7 +59,7 @@ public static Set<String> parseNodeSet(String nodes) {
         .collect(Collectors.toSet());
   }
 
-  public static void printEstimation(PrintWriter out, 
ContainerBalancerEstimation estimation) {
+  public static void printEstimation(PrintStream out, 
ContainerBalancerEstimation estimation) {
     long estimatedIterations = estimation.getEstimatedIterations();
     long planningIterations = (long) Math.ceil(estimatedIterations * 
PLANNING_ITERATION_BUFFER);
     long cycleTimeMillis = estimation.getMoveTimeoutMillis() + 
estimation.getBalancingIntervalMillis();
diff --git 
a/hadoop-ozone/cli-admin/src/main/java/org/apache/hadoop/ozone/admin/upgrade/StatusSubCommand.java
 
b/hadoop-ozone/cli-admin/src/main/java/org/apache/hadoop/ozone/admin/upgrade/StatusSubCommand.java
index d8627320749..be009515312 100644
--- 
a/hadoop-ozone/cli-admin/src/main/java/org/apache/hadoop/ozone/admin/upgrade/StatusSubCommand.java
+++ 
b/hadoop-ozone/cli-admin/src/main/java/org/apache/hadoop/ozone/admin/upgrade/StatusSubCommand.java
@@ -17,7 +17,7 @@
 
 package org.apache.hadoop.ozone.admin.upgrade;
 
-import java.io.PrintWriter;
+import java.io.PrintStream;
 import java.util.concurrent.Callable;
 import org.apache.hadoop.hdds.HDDSVersion;
 import org.apache.hadoop.hdds.cli.AbstractSubcommand;
@@ -74,7 +74,7 @@ public Integer call() throws Exception {
   }
 
   /** Basic, non-verbose human-readable status. */
-  static void printBasic(QueryUpgradeStatusResponse status, PrintWriter out) {
+  static void printBasic(QueryUpgradeStatusResponse status, PrintStream out) {
     out.println("Upgrade finalization status:");
     out.println("    Cluster: " + 
status.getClusterFinalizationStatus().name());
     out.println("    OM: " + status.getOmFinalizationStatus().name());
@@ -87,7 +87,7 @@ static void printBasic(QueryUpgradeStatusResponse status, 
PrintWriter out) {
    * Verbose human-readable status that includes the apparent versions 
reported by OM and SCM, and the
    * range of apparent versions across healthy datanodes.
    */
-  static void printVerbose(QueryUpgradeStatusResponse status, PrintWriter out) 
{
+  static void printVerbose(QueryUpgradeStatusResponse status, PrintStream out) 
{
     HddsProtos.UpgradeStatus hdds = status.getHddsStatus();
     out.println("Upgrade finalization status:");
     out.println("    Cluster:                 " + 
status.getClusterFinalizationStatus().name());
diff --git 
a/hadoop-ozone/cli-admin/src/test/java/org/apache/hadoop/hdds/cli/TestOzoneAdminDeprecatedOptions.java
 
b/hadoop-ozone/cli-admin/src/test/java/org/apache/hadoop/hdds/cli/TestOzoneAdminDeprecatedOptions.java
index c70cc921eb5..1f3a6d4b80d 100644
--- 
a/hadoop-ozone/cli-admin/src/test/java/org/apache/hadoop/hdds/cli/TestOzoneAdminDeprecatedOptions.java
+++ 
b/hadoop-ozone/cli-admin/src/test/java/org/apache/hadoop/hdds/cli/TestOzoneAdminDeprecatedOptions.java
@@ -19,9 +19,11 @@
 
 import static org.assertj.core.api.Assertions.assertThat;
 
-import java.io.PrintWriter;
-import java.io.StringWriter;
+import org.apache.hadoop.hdds.utils.IOUtils;
 import org.apache.hadoop.ozone.admin.OzoneAdmin;
+import org.apache.ozone.test.GenericTestUtils.PrintStreamCapturer;
+import org.apache.ozone.test.GenericTestUtils.SystemErrCapturer;
+import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.params.ParameterizedTest;
@@ -34,18 +36,22 @@
 class TestOzoneAdminDeprecatedOptions {
 
   private CommandLine cli;
-  private StringWriter err;
+  private PrintStreamCapturer err;
 
   @BeforeEach
   public void setup() {
-    err = new StringWriter();
+    err = new SystemErrCapturer();
     cli = createCommandLine();
   }
 
+  @AfterEach
+  void close() {
+    IOUtils.closeQuietly(err);
+  }
+
   private CommandLine createCommandLine() {
     OzoneAdmin command = new OzoneAdmin();
     CommandLine cmd = command.getCmd();
-    cmd.setErr(new PrintWriter(err, true));
     cmd.setExecutionStrategy(parseResult -> CommandLine.ExitCode.OK);
     return cmd;
   }
diff --git 
a/hadoop-ozone/cli-debug/src/main/java/org/apache/hadoop/ozone/debug/ldb/DBScanner.java
 
b/hadoop-ozone/cli-debug/src/main/java/org/apache/hadoop/ozone/debug/ldb/DBScanner.java
index d0e0510716d..f18d95c6e0c 100644
--- 
a/hadoop-ozone/cli-debug/src/main/java/org/apache/hadoop/ozone/debug/ldb/DBScanner.java
+++ 
b/hadoop-ozone/cli-debug/src/main/java/org/apache/hadoop/ozone/debug/ldb/DBScanner.java
@@ -30,11 +30,13 @@
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.util.concurrent.ThreadFactoryBuilder;
 import com.google.protobuf.ByteString;
-import java.io.BufferedWriter;
+import java.io.BufferedOutputStream;
 import java.io.File;
 import java.io.IOException;
-import java.io.PrintWriter;
+import java.io.PrintStream;
 import java.lang.reflect.Field;
+import java.nio.file.Files;
+import java.nio.file.Path;
 import java.nio.file.Paths;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -265,8 +267,8 @@ private boolean displayTable(ManagedRocksIterator iterator,
     while (iterator.get().isValid() && withinLimit(globalCount)) {
       String fileNameTarget = recordsPerFile > 0 ? fileName + "." + 
fileSuffix++ :
           fileName;
-      try (PrintWriter out = new PrintWriter(new BufferedWriter(
-          new PrintWriter(fileNameTarget, UTF_8.name())))) {
+      Path path = Paths.get(fileNameTarget);
+      try (PrintStream out = new PrintStream(new 
BufferedOutputStream(Files.newOutputStream(path)), false, UTF_8)) {
         if (!displayTable(iterator, dbColumnFamilyDef, out, schemaV3)) {
           return false;
         }
@@ -277,7 +279,7 @@ private boolean displayTable(ManagedRocksIterator iterator,
 
   private boolean displayTable(ManagedRocksIterator iterator,
                                DBColumnFamilyDefinition dbColumnFamilyDef,
-                               PrintWriter printWriter, boolean schemaV3) {
+                               PrintStream out, boolean schemaV3) {
     exception = false;
     ThreadFactory factory = new ThreadFactoryBuilder()
         .setNameFormat("DBScanner-%d")
@@ -286,10 +288,10 @@ private boolean displayTable(ManagedRocksIterator 
iterator,
         threadCount, threadCount, 60, TimeUnit.SECONDS,
         new LinkedBlockingQueue<>(1024), factory,
         new ThreadPoolExecutor.CallerRunsPolicy());
-    LogWriter logWriter = new LogWriter(printWriter);
+    LogWriter logWriter = new LogWriter(out);
     try {
       // Start JSON object (map) or array
-      printWriter.print(withKey ? "{ " : "[ ");
+      out.print(withKey ? "{ " : "[ ");
       logWriter.start();
       processRecords(iterator, dbColumnFamilyDef, logWriter,
           threadPool, schemaV3);
@@ -301,7 +303,7 @@ private boolean displayTable(ManagedRocksIterator iterator,
       logWriter.stop();
       logWriter.join();
       // End JSON object (map) or array
-      printWriter.println(withKey ? " }" : " ]");
+      out.println(withKey ? " }" : " ]");
     }
     return !exception;
   }
@@ -913,16 +915,16 @@ public String toString() {
 
   private static class LogWriter {
     private final Map<Long, ArrayList<String>> logs;
-    private final PrintWriter printWriter;
+    private final PrintStream out;
     private final Thread writerThread;
     private volatile boolean stop = false;
     private long expectedSequenceId = FIRST_SEQUENCE_ID;
     private final Object lock = new Object();
     private final AtomicLong inflightLogCount = new AtomicLong();
 
-    LogWriter(PrintWriter printWriter) {
+    LogWriter(PrintStream out) {
       this.logs = new HashMap<>();
-      this.printWriter = printWriter;
+      this.out = out;
       this.writerThread = new Thread(new WriterTask());
     }
 
@@ -956,7 +958,7 @@ public void run() {
               ArrayList<String> results = logs.get(expectedSequenceId);
               if (results != null) {
                 for (String result : results) {
-                  printWriter.println(result);
+                  out.println(result);
                 }
                 inflightLogCount.decrementAndGet();
                 logs.remove(expectedSequenceId);
@@ -985,7 +987,7 @@ private void drainRemainingMessages() {
       ArrayList<String> results;
       while ((results = logs.get(expectedSequenceId)) != null) {
         for (String result : results) {
-          printWriter.println(result);
+          out.println(result);
         }
         expectedSequenceId++;
       }
diff --git 
a/hadoop-ozone/cli-debug/src/main/java/org/apache/hadoop/ozone/debug/om/ContainerToKeyMapping.java
 
b/hadoop-ozone/cli-debug/src/main/java/org/apache/hadoop/ozone/debug/om/ContainerToKeyMapping.java
index 4e625f64b0b..9f781b46f8f 100644
--- 
a/hadoop-ozone/cli-debug/src/main/java/org/apache/hadoop/ozone/debug/om/ContainerToKeyMapping.java
+++ 
b/hadoop-ozone/cli-debug/src/main/java/org/apache/hadoop/ozone/debug/om/ContainerToKeyMapping.java
@@ -24,7 +24,6 @@
 import com.fasterxml.jackson.databind.node.ObjectNode;
 import java.io.File;
 import java.io.IOException;
-import java.io.PrintWriter;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.HashMap;
@@ -129,7 +128,7 @@ public Void call() throws Exception {
     conf = new OzoneConfiguration();
     File dbFile = new File(dbPath);
 
-    try (PrintWriter writer = out()) {
+    try {
       omDbStore = DBStoreBuilder.newBuilder(conf, OMDBDefinition.get(), 
dbFile.getName(),
           dbFile.getParentFile().toPath())
           .setOpenReadOnly(true)
@@ -145,7 +144,7 @@ public Void call() throws Exception {
       multipartInfoTable = 
OMDBDefinition.MULTIPART_INFO_TABLE_DEF.getTable(omDbStore, CacheType.NO_CACHE);
       multipartPartsTable = 
OMDBDefinition.MULTIPART_PARTS_TABLE_DEF.getTable(omDbStore, 
CacheType.NO_CACHE);
 
-      retrieve(dbPath, writer, containerIDs);
+      retrieve(dbPath, containerIDs);
     } catch (Exception e) {
       err().println("Failed to open RocksDB: " + e);
       throw e;
@@ -184,7 +183,7 @@ private void closeDirTreeDB(String dbPath) throws 
IOException {
     }
   }
 
-  private void retrieve(String dbPath, PrintWriter writer, Set<Long> 
containerIds) {
+  private void retrieve(String dbPath, Set<Long> containerIds) {
     Map<Long, Pair<Long, String>> bucketVolMap = new HashMap<>();
     // Build dir tree for FSO keys only if we need full paths
     if (!onlyFileNames) {
@@ -221,7 +220,7 @@ private void retrieve(String dbPath, PrintWriter writer, 
Set<Long> containerIds)
     processFSOKeys(containerIds, containerToKeysMap, unreferencedCountMap, 
bucketVolMap);
     // Process OBS keys (keyTable)
     processOBSKeys(containerIds, containerToKeysMap);
-    jsonOutput(writer, containerToKeysMap, containerToOpenKeysMap, 
unreferencedCountMap);
+    jsonOutput(containerToKeysMap, containerToOpenKeysMap, 
unreferencedCountMap);
   }
 
   private void processFSOKeys(Set<Long> containerIds, Map<Long, List<String>> 
containerToKeysMap,
@@ -504,7 +503,7 @@ private void addToDirTree(Long objectId, Long parentId, 
String name) throws IOEx
     }
   }
 
-  private void jsonOutput(PrintWriter writer, Map<Long, List<String>> 
containerToKeysMap,
+  private void jsonOutput(Map<Long, List<String>> containerToKeysMap,
       Map<Long, List<String>> containerToOpenKeysMap, Map<Long, Long> 
unreferencedCountMap) {
     try {
       ObjectMapper mapper = new ObjectMapper();
@@ -550,8 +549,8 @@ private void jsonOutput(PrintWriter writer, Map<Long, 
List<String>> containerToK
       }
 
       root.set("containers", containersNode);
-      
writer.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root));
-      writer.flush();
+      
out().println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root));
+      out().flush();
     } catch (Exception e) {
       err().println("Error writing JSON output: " + e.getMessage());
     }
diff --git 
a/hadoop-ozone/cli-debug/src/test/java/org/apache/hadoop/ozone/debug/datanode/container/analyze/TestAnalyzeSubcommand.java
 
b/hadoop-ozone/cli-debug/src/test/java/org/apache/hadoop/ozone/debug/datanode/container/analyze/TestAnalyzeSubcommand.java
index 54c780b897a..0b8eac0d1ca 100644
--- 
a/hadoop-ozone/cli-debug/src/test/java/org/apache/hadoop/ozone/debug/datanode/container/analyze/TestAnalyzeSubcommand.java
+++ 
b/hadoop-ozone/cli-debug/src/test/java/org/apache/hadoop/ozone/debug/datanode/container/analyze/TestAnalyzeSubcommand.java
@@ -21,8 +21,6 @@
 import static org.junit.jupiter.params.provider.Arguments.arguments;
 
 import java.io.File;
-import java.io.PrintWriter;
-import java.io.StringWriter;
 import java.nio.file.Path;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -34,7 +32,12 @@
 import org.apache.hadoop.hdds.conf.OzoneConfiguration;
 import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
 import org.apache.hadoop.hdds.scm.ScmConfigKeys;
+import org.apache.hadoop.hdds.utils.IOUtils;
 import org.apache.hadoop.ozone.debug.OzoneDebug;
+import org.apache.ozone.test.GenericTestUtils.PrintStreamCapturer;
+import org.apache.ozone.test.GenericTestUtils.SystemErrCapturer;
+import org.apache.ozone.test.GenericTestUtils.SystemOutCapturer;
+import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.io.TempDir;
@@ -53,8 +56,8 @@ public class TestAnalyzeSubcommand {
 
   private ContainerAnalyzeTestHelper testHelper;
   private CommandLine cmd;
-  private StringWriter outWriter;
-  private StringWriter errWriter;
+  private PrintStreamCapturer outWriter;
+  private PrintStreamCapturer errWriter;
 
   @BeforeEach
   public void setup() {
@@ -63,10 +66,13 @@ public void setup() {
         UUID.randomUUID().toString(), UUID.randomUUID().toString());
 
     cmd = new OzoneDebug().getCmd();
-    outWriter = new StringWriter();
-    errWriter = new StringWriter();
-    cmd.setOut(new PrintWriter(outWriter));
-    cmd.setErr(new PrintWriter(errWriter));
+    outWriter = new SystemOutCapturer();
+    errWriter = new SystemErrCapturer();
+  }
+
+  @AfterEach
+  void close() {
+    IOUtils.closeQuietly(outWriter, errWriter);
   }
 
   @Test
diff --git 
a/hadoop-ozone/cli-debug/src/test/java/org/apache/hadoop/ozone/debug/om/TestContainerToKeyMapping.java
 
b/hadoop-ozone/cli-debug/src/test/java/org/apache/hadoop/ozone/debug/om/TestContainerToKeyMapping.java
index 74a68a96b8c..da3a062d287 100644
--- 
a/hadoop-ozone/cli-debug/src/test/java/org/apache/hadoop/ozone/debug/om/TestContainerToKeyMapping.java
+++ 
b/hadoop-ozone/cli-debug/src/test/java/org/apache/hadoop/ozone/debug/om/TestContainerToKeyMapping.java
@@ -20,8 +20,6 @@
 import static org.assertj.core.api.Assertions.assertThat;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 
-import java.io.PrintWriter;
-import java.io.StringWriter;
 import java.nio.file.Path;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -31,6 +29,7 @@
 import org.apache.hadoop.hdds.client.StandaloneReplicationConfig;
 import org.apache.hadoop.hdds.conf.OzoneConfiguration;
 import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
+import org.apache.hadoop.hdds.utils.IOUtils;
 import org.apache.hadoop.ozone.ClientVersion;
 import org.apache.hadoop.ozone.OzoneConsts;
 import org.apache.hadoop.ozone.debug.OzoneDebug;
@@ -48,6 +47,8 @@
 import org.apache.hadoop.ozone.om.helpers.OmVolumeArgs;
 import 
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.KeyInfo;
 import 
org.apache.hadoop.ozone.protocol.proto.OzoneManagerProtocolProtos.PartKeyInfo;
+import org.apache.ozone.test.GenericTestUtils.PrintStreamCapturer;
+import org.apache.ozone.test.GenericTestUtils.SystemOutCapturer;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
@@ -65,7 +66,7 @@ public class TestContainerToKeyMapping {
   private OMMetadataManager omMetadataManager;
   private String dbPath;
   private CommandLine cmd;
-  private StringWriter outWriter;
+  private PrintStreamCapturer outWriter;
 
   private static final String VOLUME_NAME = "vol1";
   private static final String FSO_BUCKET_NAME = "fso-bucket";
@@ -95,11 +96,8 @@ public void setup() throws Exception {
     dbPath = dbFile.toString();
     
     cmd = new OzoneDebug().getCmd();
-    outWriter = new StringWriter();
-    StringWriter errWriter = new StringWriter();
-    cmd.setOut(new PrintWriter(outWriter));
-    cmd.setErr(new PrintWriter(errWriter));
-    
+    outWriter = new SystemOutCapturer();
+
     OzoneConfiguration conf = new OzoneConfiguration();
     omMetadataManager = new OmMetadataManagerImpl(conf,
         tempDir.toFile(), "om.db", false);
@@ -111,6 +109,7 @@ public void setup() throws Exception {
 
   @AfterEach
   public void tearDown() throws Exception {
+    IOUtils.closeQuietly(outWriter);
     if (omMetadataManager != null && !omMetadataManager.getStore().isClosed()) 
{
       omMetadataManager.getStore().close();
     }
diff --git 
a/hadoop-ozone/cli-local/src/main/java/org/apache/hadoop/ozone/local/OzoneLocal.java
 
b/hadoop-ozone/cli-local/src/main/java/org/apache/hadoop/ozone/local/OzoneLocal.java
index 2a7292a9886..64233f7357e 100644
--- 
a/hadoop-ozone/cli-local/src/main/java/org/apache/hadoop/ozone/local/OzoneLocal.java
+++ 
b/hadoop-ozone/cli-local/src/main/java/org/apache/hadoop/ozone/local/OzoneLocal.java
@@ -17,7 +17,6 @@
 
 package org.apache.hadoop.ozone.local;
 
-import java.io.PrintWriter;
 import java.nio.file.Path;
 import java.nio.file.Paths;
 import java.time.Duration;
@@ -260,25 +259,24 @@ LocalOzoneRuntime createRuntime(LocalOzoneClusterConfig 
config, OzoneConfigurati
     }
 
     private void printSummary(LocalOzoneRuntime runtime, 
LocalOzoneClusterConfig config) {
-      PrintWriter writer = out();
-      writer.println("Local Ozone is running from " + config.getDataDir());
-      writer.println("SCM RPC: " + 
HddsUtils.getHostPortString(runtime.getDisplayHost(), runtime.getScmPort()));
-      writer.println("OM RPC: " + 
HddsUtils.getHostPortString(runtime.getDisplayHost(), runtime.getOmPort()));
+      out().println("Local Ozone is running from " + config.getDataDir());
+      out().println("SCM RPC: " + 
HddsUtils.getHostPortString(runtime.getDisplayHost(), runtime.getScmPort()));
+      out().println("OM RPC: " + 
HddsUtils.getHostPortString(runtime.getDisplayHost(), runtime.getOmPort()));
       if (config.isS3gEnabled()) {
-        writer.println("S3 endpoint: " + runtime.getS3Endpoint());
-        writer.println("Suggested local AWS settings:");
-        writer.println("AWS_ACCESS_KEY_ID=" + 
LocalOzoneClusterConfig.LOCAL_S3_ACCESS_KEY);
-        writer.println("AWS_SECRET_ACCESS_KEY=" + 
LocalOzoneClusterConfig.LOCAL_S3_SECRET_KEY);
-        writer.println("AWS_REGION=" + 
LocalOzoneClusterConfig.LOCAL_S3_REGION);
-        writer.println("AWS_ENDPOINT_URL_S3=" + runtime.getS3Endpoint());
-        writer.println("Use path-style addressing (AWS CLI: aws configure set 
default.s3.addressing_style path).");
-        writer.println("With security off (the default), the S3 Gateway 
accepts any credentials.");
+        out().println("S3 endpoint: " + runtime.getS3Endpoint());
+        out().println("Suggested local AWS settings:");
+        out().println("AWS_ACCESS_KEY_ID=" + 
LocalOzoneClusterConfig.LOCAL_S3_ACCESS_KEY);
+        out().println("AWS_SECRET_ACCESS_KEY=" + 
LocalOzoneClusterConfig.LOCAL_S3_SECRET_KEY);
+        out().println("AWS_REGION=" + LocalOzoneClusterConfig.LOCAL_S3_REGION);
+        out().println("AWS_ENDPOINT_URL_S3=" + runtime.getS3Endpoint());
+        out().println("Use path-style addressing (AWS CLI: aws configure set 
default.s3.addressing_style path).");
+        out().println("With security off (the default), the S3 Gateway accepts 
any credentials.");
       }
       if (config.isReconEnabled()) {
-        writer.println("Recon endpoint: " + runtime.getReconEndpoint());
+        out().println("Recon endpoint: " + runtime.getReconEndpoint());
       }
-      writer.println("Press Ctrl+C to stop.");
-      writer.flush();
+      out().println("Press Ctrl+C to stop.");
+      out().flush();
     }
 
     /**
diff --git 
a/hadoop-ozone/cli-local/src/test/java/org/apache/hadoop/ozone/local/TestOzoneLocal.java
 
b/hadoop-ozone/cli-local/src/test/java/org/apache/hadoop/ozone/local/TestOzoneLocal.java
index a47cd6cf069..cbd7ca43bfe 100644
--- 
a/hadoop-ozone/cli-local/src/test/java/org/apache/hadoop/ozone/local/TestOzoneLocal.java
+++ 
b/hadoop-ozone/cli-local/src/test/java/org/apache/hadoop/ozone/local/TestOzoneLocal.java
@@ -19,6 +19,7 @@
 
 import static java.nio.charset.StandardCharsets.UTF_8;
 import static org.apache.hadoop.ozone.OzoneConfigKeys.OZONE_REPLICATION;
+import static org.assertj.core.api.Assertions.assertThat;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
 import static org.junit.jupiter.api.Assertions.assertNotNull;
@@ -38,6 +39,9 @@
 import java.time.Duration;
 import org.apache.hadoop.hdds.cli.GenericCli;
 import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.ozone.test.GenericTestUtils.PrintStreamCapturer;
+import org.apache.ozone.test.GenericTestUtils.SystemErrCapturer;
+import org.apache.ozone.test.GenericTestUtils.SystemOutCapturer;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.io.TempDir;
 import picocli.CommandLine;
@@ -100,19 +104,14 @@ void rootHelpListsRunCommand() throws Exception {
 
   @Test
   void runCommandStartsRuntimeAndPrintsStartupSummary() throws Exception {
-    ByteArrayOutputStream out = new ByteArrayOutputStream();
     StubRuntime runtime = new StubRuntime("localhost", 9860, 9862, 
"http://localhost:9878";);
     TestableRunCommand command = new TestableRunCommand(runtime);
     CommandLine commandLine = new CommandLine(command);
-    commandLine.setOut(new PrintWriter(new OutputStreamWriter(out, UTF_8),
-        true));
-
-    int exitCode = commandLine.execute();
-
-    assertEquals(0, exitCode);
+    CommandResult result = execute(commandLine);
+    String text = result.out;
+    assertEquals(0, result.exitCode);
     assertTrue(runtime.started);
     assertTrue(runtime.closed);
-    String text = out.toString(UTF_8.name());
     assertTrue(text.contains("Local Ozone is running from"), text);
     assertTrue(text.contains("SCM RPC: localhost:9860"), text);
     assertTrue(text.contains("OM RPC: localhost:9862"), text);
@@ -129,63 +128,54 @@ void runCommandStartsRuntimeAndPrintsStartupSummary() 
throws Exception {
 
   @Test
   void runCommandBracketsIpv6HostInStartupSummary() throws Exception {
-    ByteArrayOutputStream out = new ByteArrayOutputStream();
     StubRuntime runtime = new StubRuntime("::1", 9860, 9862, 
"http://[::1]:9878";);
     CommandLine commandLine = new CommandLine(new TestableRunCommand(runtime));
-    commandLine.setOut(new PrintWriter(new OutputStreamWriter(out, UTF_8), 
true));
+    CommandResult result = execute(commandLine);
 
-    assertEquals(0, commandLine.execute());
-    String text = out.toString(UTF_8.name());
+    assertEquals(0, result.exitCode);
+    String text = result.out;
     assertTrue(text.contains("SCM RPC: [::1]:9860"), text);
     assertTrue(text.contains("OM RPC: [::1]:9862"), text);
   }
 
   @Test
   void runCommandPrintsReconEndpointWhenEnabled() throws Exception {
-    ByteArrayOutputStream out = new ByteArrayOutputStream();
     StubRuntime runtime = new StubRuntime("localhost", 9860, 9862,
         "http://localhost:9878";);
     runtime.reconEndpoint = "http://localhost:9888";;
     TestableRunCommand command = new TestableRunCommand(runtime);
     CommandLine commandLine = new CommandLine(command);
-    commandLine.setOut(new PrintWriter(new OutputStreamWriter(out, UTF_8),
-        true));
 
-    int exitCode = commandLine.execute("--recon");
+    CommandResult result = execute(commandLine, "--recon");
 
-    assertEquals(0, exitCode);
-    String text = out.toString(UTF_8.name());
+    assertEquals(0, result.exitCode);
+    String text = result.out;
     assertTrue(text.contains("Recon endpoint: http://localhost:9888";), text);
   }
 
   @Test
   void runCommandOmitsReconEndpointWhenDisabled() throws Exception {
-    ByteArrayOutputStream out = new ByteArrayOutputStream();
     StubRuntime runtime = new StubRuntime("localhost", 9860, 9862,
         "http://localhost:9878";);
     TestableRunCommand command = new TestableRunCommand(runtime);
     CommandLine commandLine = new CommandLine(command);
-    commandLine.setOut(new PrintWriter(new OutputStreamWriter(out, UTF_8),
-        true));
 
-    int exitCode = commandLine.execute();
+    CommandResult result = execute(commandLine);
 
-    assertEquals(0, exitCode);
-    assertFalse(out.toString(UTF_8.name()).contains("Recon endpoint:"));
+    assertEquals(0, result.exitCode);
+    assertFalse(result.out.contains("Recon endpoint:"));
   }
 
   @Test
   void runCommandOmitsS3SummaryWhenS3gDisabled() throws Exception {
-    ByteArrayOutputStream out = new ByteArrayOutputStream();
     StubRuntime runtime = new StubRuntime("localhost", 9860, 9862, "");
     TestableRunCommand command = new TestableRunCommand(runtime);
     CommandLine commandLine = new CommandLine(command);
-    commandLine.setOut(new PrintWriter(new OutputStreamWriter(out, UTF_8), 
true));
 
-    int exitCode = commandLine.execute("--no-s3g");
+    CommandResult result = execute(commandLine, "--no-s3g");
 
-    assertEquals(0, exitCode);
-    String text = out.toString(UTF_8.name());
+    assertEquals(0, result.exitCode);
+    String text = result.out;
     assertFalse(text.contains("S3 endpoint:"), text);
     assertFalse(text.contains("AWS_ACCESS_KEY_ID="), text);
     assertTrue(text.contains("Press Ctrl+C to stop."), text);
@@ -205,39 +195,39 @@ void runCommandClosesRuntimeWhenStartupFails() {
 
   @Test
   void runCommandPreservesStartupFailureAsTheCause() throws Exception {
-    ByteArrayOutputStream err = new ByteArrayOutputStream();
     StubRuntime runtime = new StubRuntime("localhost", 9860, 9862, "");
     runtime.failStart = true;
     TestableRunCommand command = new TestableRunCommand(runtime);
     CommandLine commandLine = new CommandLine(command);
-    commandLine.setErr(new PrintWriter(new OutputStreamWriter(err, UTF_8), 
true));
     commandLine.parseArgs();
 
-    Exception error = assertThrows(Exception.class, command::call);
+    try (PrintStreamCapturer err = new SystemErrCapturer()) {
+      Exception error = assertThrows(Exception.class, command::call);
 
-    assertTrue(error.getCause() instanceof IllegalStateException, 
error.toString());
-    assertEquals("startup failed", error.getCause().getMessage());
-    assertEquals("", err.toString(UTF_8.name()));
+      assertTrue(error.getCause() instanceof IllegalStateException, 
error.toString());
+      assertEquals("startup failed", error.getCause().getMessage());
+      assertEquals("", err.get());
+    }
     assertTrue(runtime.closed);
   }
 
   /** Preemptive timeout: execute() otherwise blocks in awaitShutdown() until 
a JVM shutdown hook fires. */
   @Test
   void conflictingConfigReachesStderrThroughGenericCli(@TempDir Path dataDir) 
throws Exception {
-    ByteArrayOutputStream err = new ByteArrayOutputStream();
     OzoneLocal ozoneLocal = new OzoneLocal();
-    ozoneLocal.getCmd().setErr(new PrintWriter(new OutputStreamWriter(err, 
UTF_8), true));
-
-    int exitCode = assertTimeoutPreemptively(Duration.ofSeconds(30),
-        () -> ozoneLocal.execute(new String[] {"-D", OZONE_REPLICATION + 
"=THREE",
-            "run", "--data-dir", dataDir.toString()}));
 
-    assertEquals(GenericCli.EXECUTION_ERROR_EXIT_CODE, exitCode);
-    String[] lines = err.toString(UTF_8.name()).trim().split("\n");
-    assertEquals(2, lines.length, err.toString(UTF_8.name()));
-    assertTrue(lines[0].contains(OZONE_REPLICATION), lines[0]);
-    assertTrue(lines[0].contains("THREE"), lines[0]);
-    assertTrue(lines[1].contains("--verbose"), lines[1]);
+    try (PrintStreamCapturer err = new SystemErrCapturer()) {
+      int exitCode = assertTimeoutPreemptively(Duration.ofSeconds(30),
+          () -> ozoneLocal.execute(new String[]{"-D", OZONE_REPLICATION + 
"=THREE",
+              "run", "--data-dir", dataDir.toString()}));
+
+      assertEquals(GenericCli.EXECUTION_ERROR_EXIT_CODE, exitCode);
+      String[] lines = err.toString().trim().split("\n");
+      assertEquals(2, lines.length, err.toString());
+      assertTrue(lines[0].contains(OZONE_REPLICATION), lines[0]);
+      assertTrue(lines[0].contains("THREE"), lines[0]);
+      assertTrue(lines[1].contains("--verbose"), lines[1]);
+    }
   }
 
   @Test
@@ -477,14 +467,11 @@ void legacyWithoutS3gOptionIsNotAccepted() {
   void genericCliErrorOutputIncludesOffendingConfigSource()
       throws Exception {
     OzoneLocal local = new OzoneLocal();
-    ByteArrayOutputStream err = new ByteArrayOutputStream();
-    local.getCmd().setErr(new PrintWriter(new OutputStreamWriter(err, UTF_8),
-        true));
 
-    int exitCode = local.execute(new String[] {"run", "--datanodes", "0"});
+    CommandResult result = execute(local.getCmd(), "run", "--datanodes", "0");
 
-    assertEquals(-1, exitCode);
-    assertTrue(err.toString(UTF_8.name()).contains("--datanodes"));
+    assertThat(result.exitCode).isNotZero();
+    assertThat(result.err).contains("--datanodes");
   }
 
   private static LocalOzoneClusterConfig resolve(String... args) {
@@ -664,4 +651,13 @@ public String defaultValue(ArgSpec argSpec) {
       return null;
     }
   }
+
+  private CommandResult execute(CommandLine cmd, String... args) {
+    try (PrintStreamCapturer out = new SystemOutCapturer();
+        PrintStreamCapturer err = new SystemErrCapturer()) {
+      return new CommandResult(cmd.execute(args), out.toString(), 
err.toString());
+    }
+  }
+
+  private record CommandResult(int exitCode, String out, String err) { }
 }
diff --git 
a/hadoop-ozone/cli-shell/src/main/java/org/apache/hadoop/ozone/shell/acl/AclOption.java
 
b/hadoop-ozone/cli-shell/src/main/java/org/apache/hadoop/ozone/shell/acl/AclOption.java
index 8acf81bdb05..8bd3b2ad873 100644
--- 
a/hadoop-ozone/cli-shell/src/main/java/org/apache/hadoop/ozone/shell/acl/AclOption.java
+++ 
b/hadoop-ozone/cli-shell/src/main/java/org/apache/hadoop/ozone/shell/acl/AclOption.java
@@ -19,7 +19,7 @@
 
 import com.google.common.collect.ImmutableList;
 import java.io.IOException;
-import java.io.PrintWriter;
+import java.io.PrintStream;
 import java.util.List;
 import org.apache.hadoop.ozone.OzoneAcl;
 import org.apache.hadoop.ozone.client.ObjectStore;
@@ -51,7 +51,7 @@ private List<OzoneAcl> getAclList() {
     return ImmutableList.copyOf(values);
   }
 
-  public void addTo(OzoneObj obj, ObjectStore objectStore, PrintWriter out)
+  public void addTo(OzoneObj obj, ObjectStore objectStore, PrintStream out)
       throws IOException {
     for (OzoneAcl acl : getAclList()) {
       boolean result = objectStore.addAcl(obj, acl);
@@ -64,7 +64,7 @@ public void addTo(OzoneObj obj, ObjectStore objectStore, 
PrintWriter out)
     }
   }
 
-  public void removeFrom(OzoneObj obj, ObjectStore objectStore, PrintWriter 
out)
+  public void removeFrom(OzoneObj obj, ObjectStore objectStore, PrintStream 
out)
       throws IOException {
     for (OzoneAcl acl : getAclList()) {
       boolean result = objectStore.removeAcl(obj, acl);
@@ -77,7 +77,7 @@ public void removeFrom(OzoneObj obj, ObjectStore objectStore, 
PrintWriter out)
     }
   }
 
-  public void setOn(OzoneObj obj, ObjectStore objectStore, PrintWriter out)
+  public void setOn(OzoneObj obj, ObjectStore objectStore, PrintStream out)
       throws IOException {
     objectStore.setAcl(obj, getAclList());
     out.println("ACLs set successfully.");
diff --git 
a/hadoop-ozone/cli-shell/src/main/java/org/apache/hadoop/ozone/shell/snapshot/SnapshotDiffHandler.java
 
b/hadoop-ozone/cli-shell/src/main/java/org/apache/hadoop/ozone/shell/snapshot/SnapshotDiffHandler.java
index ed493dd146a..71a25960933 100644
--- 
a/hadoop-ozone/cli-shell/src/main/java/org/apache/hadoop/ozone/shell/snapshot/SnapshotDiffHandler.java
+++ 
b/hadoop-ozone/cli-shell/src/main/java/org/apache/hadoop/ozone/shell/snapshot/SnapshotDiffHandler.java
@@ -22,7 +22,6 @@
 import com.fasterxml.jackson.databind.node.ArrayNode;
 import com.fasterxml.jackson.databind.node.ObjectNode;
 import java.io.IOException;
-import java.io.PrintWriter;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.hdds.server.JsonUtils;
@@ -140,19 +139,19 @@ private void submitSnapshotDiff(ObjectStore store, String 
volumeName,
       if (ex.getResult() == OMException.ResultCodes.NOT_SUPPORTED_OPERATION) {
         SnapshotDiffResponse diffResponse = store.snapshotDiff(volumeName, 
bucketName, fromSnapshot, toSnapshot,
             token, pageSize, forceFullDiff, diffDisableNativeLibs);
-        try (PrintWriter writer = out()) {
-          if (json) {
-            
writer.println(toJsonStringWithDefaultPrettyPrinter(getJsonObject(diffResponse)));
-          } else {
-            writer.println(diffResponse);
-          }
-        }
+        printResponse(diffResponse);
         return;
       }
       throw ex;
     }
-    try (PrintWriter writer = out()) {
-      writer.println(response);
+    out().println(response);
+  }
+
+  private void printResponse(SnapshotDiffResponse diffResponse) throws 
IOException {
+    if (json) {
+      
out().println(toJsonStringWithDefaultPrettyPrinter(getJsonObject(diffResponse)));
+    } else {
+      out().println(diffResponse);
     }
   }
 
@@ -160,20 +159,12 @@ private void getSnapshotDiff(ObjectStore store, String 
volumeName,
                                String bucketName) throws IOException {
     SnapshotDiffResponse diffResponse = store.snapshotDiff(volumeName, 
bucketName, fromSnapshot, toSnapshot,
         token, pageSize);
-    try (PrintWriter writer = out()) {
-      if (json) {
-        
writer.println(toJsonStringWithDefaultPrettyPrinter(getJsonObject(diffResponse)));
-      } else {
-        writer.println(diffResponse);
-      }
-    }
+    printResponse(diffResponse);
   }
 
   private void cancelSnapshotDiff(ObjectStore store, String volumeName,
                                   String bucketName) throws IOException {
-    try (PrintWriter writer = out()) {
-      writer.println(store.cancelSnapshotDiff(volumeName, bucketName, 
fromSnapshot, toSnapshot));
-    }
+    out().println(store.cancelSnapshotDiff(volumeName, bucketName, 
fromSnapshot, toSnapshot));
   }
 
   private ObjectNode getJsonObject(SnapshotDiffResponse diffResponse) {
diff --git 
a/hadoop-ozone/integration-test-tools/src/test/java/org/apache/hadoop/ozone/debug/TestLDBCli.java
 
b/hadoop-ozone/integration-test-tools/src/test/java/org/apache/hadoop/ozone/debug/TestLDBCli.java
index f6cfc6759d7..e7945d95adb 100644
--- 
a/hadoop-ozone/integration-test-tools/src/test/java/org/apache/hadoop/ozone/debug/TestLDBCli.java
+++ 
b/hadoop-ozone/integration-test-tools/src/test/java/org/apache/hadoop/ozone/debug/TestLDBCli.java
@@ -31,8 +31,6 @@
 import jakarta.annotation.Nonnull;
 import java.io.File;
 import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.StringWriter;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
@@ -49,6 +47,7 @@
 import org.apache.hadoop.hdds.client.ReplicationConfig;
 import org.apache.hadoop.hdds.conf.OzoneConfiguration;
 import org.apache.hadoop.hdds.protocol.proto.HddsProtos;
+import org.apache.hadoop.hdds.utils.IOUtils;
 import org.apache.hadoop.hdds.utils.db.DBStore;
 import org.apache.hadoop.hdds.utils.db.DBStoreBuilder;
 import org.apache.hadoop.hdds.utils.db.FixedLengthStringCodec;
@@ -63,6 +62,9 @@
 import org.apache.hadoop.ozone.debug.ldb.RDBParser;
 import org.apache.hadoop.ozone.om.helpers.OmKeyInfo;
 import org.apache.hadoop.ozone.om.request.OMRequestTestUtils;
+import org.apache.ozone.test.GenericTestUtils.PrintStreamCapturer;
+import org.apache.ozone.test.GenericTestUtils.SystemErrCapturer;
+import org.apache.ozone.test.GenericTestUtils.SystemOutCapturer;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Named;
@@ -85,8 +87,7 @@ public class TestLDBCli {
   private DBStore dbStore;
   @TempDir
   private File tempDir;
-  private StringWriter stdout, stderr;
-  private PrintWriter pstdout, pstderr;
+  private PrintStreamCapturer stdout, stderr;
   private CommandLine cmd;
   private NavigableMap<String, Map<String, ?>> dbMap;
   private String keySeparatorSchemaV3 =
@@ -94,29 +95,19 @@ public class TestLDBCli {
           .getContainerSchemaV3KeySeparator();
 
   @BeforeEach
-  public void setup() throws IOException {
+  public void setup() {
     conf = new OzoneConfiguration();
-    stdout = new StringWriter();
-    pstdout = new PrintWriter(stdout);
-    stderr = new StringWriter();
-    pstderr = new PrintWriter(stderr);
+    stdout = new SystemOutCapturer();
+    stderr = new SystemErrCapturer();
 
-    cmd = new CommandLine(new RDBParser())
-        .setOut(pstdout)
-        .setErr(pstderr);
+    cmd = new CommandLine(new RDBParser());
 
     dbMap = new TreeMap<>();
   }
 
   @AfterEach
-  public void shutdown() throws IOException {
-    if (dbStore != null) {
-      dbStore.close();
-    }
-    pstderr.close();
-    stderr.close();
-    pstdout.close();
-    stdout.close();
+  public void shutdown() {
+    IOUtils.closeQuietly(stdout, stderr, dbStore);
   }
 
   /**
diff --git 
a/hadoop-ozone/integration-test-tools/src/test/java/org/apache/hadoop/ozone/shell/TestOzoneDebugShell.java
 
b/hadoop-ozone/integration-test-tools/src/test/java/org/apache/hadoop/ozone/shell/TestOzoneDebugShell.java
index 23e652e1452..8f7071b7cf1 100644
--- 
a/hadoop-ozone/integration-test-tools/src/test/java/org/apache/hadoop/ozone/shell/TestOzoneDebugShell.java
+++ 
b/hadoop-ozone/integration-test-tools/src/test/java/org/apache/hadoop/ozone/shell/TestOzoneDebugShell.java
@@ -27,8 +27,6 @@
 import com.fasterxml.jackson.databind.ObjectMapper;
 import java.io.File;
 import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.StringWriter;
 import java.nio.charset.StandardCharsets;
 import java.util.HashSet;
 import java.util.Set;
@@ -59,6 +57,8 @@
 import org.apache.hadoop.ozone.om.helpers.OmKeyLocationInfo;
 import org.apache.ozone.test.ClusterForTests;
 import org.apache.ozone.test.GenericTestUtils;
+import org.apache.ozone.test.GenericTestUtils.PrintStreamCapturer;
+import org.apache.ozone.test.GenericTestUtils.SystemOutCapturer;
 import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.TestInstance;
@@ -145,33 +145,32 @@ public void 
testChunkInfoVerifyPathsAreDifferent(BucketLayout layout) throws Exc
   @ParameterizedTest
   @EnumSource
   public void testLdbCliForOzoneSnapshot(BucketLayout layout) throws Exception 
{
-    String columnFamily = omMetadataManager.getKeyTable(layout).getName();
-    StringWriter stdout = new StringWriter();
-    PrintWriter pstdout = new PrintWriter(stdout);
-    CommandLine cmd = new CommandLine(new RDBParser())
-        .setOut(pstdout);
-    final String volumeName = UUID.randomUUID().toString();
-    final String bucketName = UUID.randomUUID().toString();
-    final String keyName = UUID.randomUUID().toString();
+    try (PrintStreamCapturer stdout = new SystemOutCapturer()) {
+      String columnFamily = omMetadataManager.getKeyTable(layout).getName();
+      CommandLine cmd = new CommandLine(new RDBParser());
+      final String volumeName = UUID.randomUUID().toString();
+      final String bucketName = UUID.randomUUID().toString();
+      final String keyName = UUID.randomUUID().toString();
 
-    writeKey(volumeName, bucketName, keyName, false, layout);
+      writeKey(volumeName, bucketName, keyName, false, layout);
 
-    String snapshotName =
-        client.getObjectStore().createSnapshot(volumeName, bucketName, 
"snap1");
-    OzoneSnapshot snapshot =
-        client.getObjectStore().listSnapshot(volumeName, bucketName, null, 
null)
-            .next();
-    assertEquals(snapshotName, snapshot.getName());
-    String dbPath = getSnapshotDBPath(snapshot.getCheckpointDir());
-    String snapshotCurrent = dbPath + OM_KEY_PREFIX + "CURRENT";
-    GenericTestUtils
-        .waitFor(() -> new File(snapshotCurrent).exists(), 1000, 120000);
-    String[] args =
-        new String[] {"--db=" + dbPath, "scan", "--cf", columnFamily};
-    int exitCode = cmd.execute(args);
-    assertEquals(0, exitCode);
-    String cmdOut = stdout.toString();
-    assertThat(cmdOut).contains(keyName);
+      String snapshotName =
+          client.getObjectStore().createSnapshot(volumeName, bucketName, 
"snap1");
+      OzoneSnapshot snapshot =
+          client.getObjectStore().listSnapshot(volumeName, bucketName, null, 
null)
+              .next();
+      assertEquals(snapshotName, snapshot.getName());
+      String dbPath = getSnapshotDBPath(snapshot.getCheckpointDir());
+      String snapshotCurrent = dbPath + OM_KEY_PREFIX + "CURRENT";
+      GenericTestUtils
+          .waitFor(() -> new File(snapshotCurrent).exists(), 1000, 120000);
+      String[] args =
+          new String[]{"--db=" + dbPath, "scan", "--cf", columnFamily};
+      int exitCode = cmd.execute(args);
+      assertEquals(0, exitCode);
+      String cmdOut = stdout.toString();
+      assertThat(cmdOut).contains(keyName);
+    }
   }
 
   private String getSnapshotDBPath(String checkPointDir) {
@@ -224,8 +223,7 @@ private int runChunkInfoAndVerifyPaths(String volumeName, 
String bucketName,
     try {
       GenericTestUtils.waitFor(() -> {
         Set<String> blockFilePaths = new HashSet<>();
-        try (GenericTestUtils.SystemOutCapturer capture = new GenericTestUtils
-            .SystemOutCapturer()) {
+        try (SystemOutCapturer capture = new SystemOutCapturer()) {
           exitCode.set(runChunkInfoCommand(volumeName, bucketName, keyName));
           String output = capture.getOutput();
           // Parse the JSON array string into a JsonNode
diff --git 
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/admin/om/lease/TestLeaseRecoverer.java
 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/admin/om/lease/TestLeaseRecoverer.java
index 2209fdb491c..e768a23786a 100644
--- 
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/admin/om/lease/TestLeaseRecoverer.java
+++ 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/admin/om/lease/TestLeaseRecoverer.java
@@ -25,8 +25,6 @@
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
 import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.StringWriter;
 import java.net.URI;
 import java.util.concurrent.ThreadLocalRandom;
 import org.apache.hadoop.fs.FSDataOutputStream;
@@ -40,6 +38,8 @@
 import org.apache.hadoop.ozone.client.OzoneClient;
 import org.apache.hadoop.ozone.om.helpers.BucketLayout;
 import org.apache.ozone.test.ClusterForTests;
+import org.apache.ozone.test.GenericTestUtils.PrintStreamCapturer;
+import org.apache.ozone.test.GenericTestUtils.SystemErrCapturer;
 import org.junit.jupiter.api.AfterAll;
 import org.junit.jupiter.api.BeforeAll;
 import org.junit.jupiter.api.Test;
@@ -92,42 +92,38 @@ private void testWithFS(FileSystem fs, Path file) throws 
IOException {
     // call lease recovery cli
     String[] args = new String[] {
         "--path", file.toUri().toString()};
-    StringWriter stdout = new StringWriter();
-    PrintWriter pstdout = new PrintWriter(stdout);
-    StringWriter stderr = new StringWriter();
-    PrintWriter pstderr = new PrintWriter(stderr);
 
-    CommandLine cmd = new CommandLine(new LeaseRecoverer())
-        .setOut(pstdout)
-        .setErr(pstderr);
-    cmd.execute(args);
+    try (PrintStreamCapturer stderr = new SystemErrCapturer()) {
+      CommandLine cmd = new CommandLine(new LeaseRecoverer());
+      cmd.execute(args);
 
-    assertEquals("", stderr.toString());
+      assertEquals("", stderr.toString());
 
-    // make sure file is visible and closed
-    FileStatus fileStatus = fs.getFileStatus(file);
-    assertEquals(dataSize, fileStatus.getLen());
-    // write data
-    os.write(data);
-    // flush should fail since flush will call writeChunk and putBlock
-    assertThrows(IOException.class, os::flush);
+      // make sure file is visible and closed
+      FileStatus fileStatus = fs.getFileStatus(file);
+      assertEquals(dataSize, fileStatus.getLen());
+      // write data
+      os.write(data);
+      // flush should fail since flush will call writeChunk and putBlock
+      assertThrows(IOException.class, os::flush);
 
-    fileStatus = fs.getFileStatus(file);
-    assertEquals(dataSize, fileStatus.getLen());
-    // make sure hsync fails
-    assertThrows(IOException.class, os::hsync);
-    // make sure length remains the same
-    fileStatus = fs.getFileStatus(file);
-    assertEquals(dataSize, fileStatus.getLen());
-    // close succeeds since it's already closed in failure handling of flush
-    assertTrue(((LeaseRecoverable)fs).isFileClosed(file));
-    os.close();
-    // make sure length remains the same
-    fileStatus = fs.getFileStatus(file);
-    assertEquals(dataSize, fileStatus.getLen());
+      fileStatus = fs.getFileStatus(file);
+      assertEquals(dataSize, fileStatus.getLen());
+      // make sure hsync fails
+      assertThrows(IOException.class, os::hsync);
+      // make sure length remains the same
+      fileStatus = fs.getFileStatus(file);
+      assertEquals(dataSize, fileStatus.getLen());
+      // close succeeds since it's already closed in failure handling of flush
+      assertTrue(((LeaseRecoverable) fs).isFileClosed(file));
+      os.close();
+      // make sure length remains the same
+      fileStatus = fs.getFileStatus(file);
+      assertEquals(dataSize, fileStatus.getLen());
 
-    // recover the same file second time should succeed
-    cmd.execute(args);
-    assertEquals("", stderr.toString());
+      // recover the same file second time should succeed
+      cmd.execute(args);
+      assertEquals("", stderr.toString());
+    }
   }
 }
diff --git 
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/shell/TestOzoneTenantShell.java
 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/shell/TestOzoneTenantShell.java
index 0218be6ab34..de5e82a0f6b 100644
--- 
a/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/shell/TestOzoneTenantShell.java
+++ 
b/hadoop-ozone/integration-test/src/test/java/org/apache/hadoop/ozone/shell/TestOzoneTenantShell.java
@@ -29,18 +29,18 @@
 import com.fasterxml.jackson.databind.ObjectMapper;
 import java.io.File;
 import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.StringWriter;
 import java.io.UnsupportedEncodingException;
 import java.nio.file.Path;
 import java.security.PrivilegedExceptionAction;
 import java.util.Arrays;
 import java.util.List;
+import java.util.regex.Pattern;
 import java.util.stream.Collectors;
 import org.apache.commons.io.FileUtils;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.hadoop.hdds.cli.GenericCli;
 import org.apache.hadoop.hdds.conf.OzoneConfiguration;
+import org.apache.hadoop.hdds.utils.IOUtils;
 import org.apache.hadoop.io_.retry.RetryInvocationHandler;
 import org.apache.hadoop.ozone.MiniOzoneCluster;
 import org.apache.hadoop.ozone.MiniOzoneHAClusterImpl;
@@ -55,7 +55,11 @@
 import org.apache.hadoop.ozone.shell.tenant.TenantShell;
 import org.apache.hadoop.security.UserGroupInformation;
 import org.apache.ozone.test.GenericTestUtils;
+import org.apache.ozone.test.GenericTestUtils.PrintStreamCapturer;
+import org.apache.ozone.test.GenericTestUtils.SystemErrCapturer;
+import org.apache.ozone.test.GenericTestUtils.SystemOutCapturer;
 import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
 import org.junit.jupiter.api.BeforeAll;
 import org.junit.jupiter.api.BeforeEach;
 import org.junit.jupiter.api.Test;
@@ -93,8 +97,8 @@ public class TestOzoneTenantShell {
   private static OzoneShell ozoneSh = null;
   private static TenantShell tenantShell = null;
 
-  private final StringWriter out = new StringWriter();
-  private final StringWriter err = new StringWriter();
+  private PrintStreamCapturer out;
+  private PrintStreamCapturer err;
 
   private static String omServiceId;
   private static int numOfOMs;
@@ -151,10 +155,6 @@ public static void shutdown() {
 
   @BeforeEach
   public void setup() throws UnsupportedEncodingException {
-    tenantShell.getCmd().setOut(new PrintWriter(out));
-    tenantShell.getCmd().setErr(new PrintWriter(err));
-    ozoneSh.getCmd().setOut(new PrintWriter(out));
-    ozoneSh.getCmd().setErr(new PrintWriter(err));
     // Suppress OMNotLeaderException in the log
     GenericTestUtils.setLogLevel(RetryInvocationHandler.class, Level.WARN);
     // Enable debug logging for interested classes
@@ -164,6 +164,14 @@ public void setup() throws UnsupportedEncodingException {
     GenericTestUtils.setLogLevel(AuthorizerLockImpl.class, Level.DEBUG);
 
     GenericTestUtils.setLogLevel(OMRangerBGSyncService.class, Level.DEBUG);
+
+    out = new SystemOutCapturer();
+    err = new SystemErrCapturer();
+  }
+
+  @AfterEach
+  void close() {
+    IOUtils.closeQuietly(out, err);
   }
 
   /**
@@ -174,7 +182,7 @@ private int execute(GenericCli shell, String[] args) {
     CommandLine cmd = shell.getCmd();
     CommandLine.IExecutionExceptionHandler exceptionHandler =
         (ex, commandLine, parseResult) -> {
-          commandLine.getErr().println(ex.getMessage());
+          System.err.println(ex.getMessage());
           return commandLine.getCommandSpec().exitCodeOnExecutionException();
         };
 
@@ -183,6 +191,7 @@ private int execute(GenericCli shell, String[] args) {
     String[] argsWithHAConf = getHASetConfStrings(args);
 
     cmd.setExecutionExceptionHandler(exceptionHandler);
+    out.reset(); err.reset(); // drop previous content
     return cmd.execute(argsWithHAConf);
   }
 
@@ -257,17 +266,13 @@ private String[] getHASetConfStrings(String[] 
existingArgs) {
   /**
    * Helper function that checks command output AND clears it.
    */
-  private void checkOutput(StringWriter writer, String stringToMatch,
-                           boolean exactMatch) throws IOException {
-    writer.flush();
+  private void checkOutput(PrintStreamCapturer writer, String stringToMatch, 
boolean exactMatch) {
     final String str = writer.toString();
     checkOutput(str, stringToMatch, exactMatch);
-    writer.getBuffer().setLength(0);
   }
 
-  private void checkOutput(StringWriter writer, String stringToMatch,
+  private void checkOutput(PrintStreamCapturer writer, String stringToMatch,
       boolean exactMatch, boolean expectValidJSON) throws IOException {
-    writer.flush();
     final String str = writer.toString();
     if (expectValidJSON) {
       // Verify if the String can be parsed as a valid JSON
@@ -275,7 +280,6 @@ private void checkOutput(StringWriter writer, String 
stringToMatch,
       objectMapper.readTree(str);
     }
     checkOutput(str, stringToMatch, exactMatch);
-    writer.getBuffer().setLength(0);
   }
 
   private void checkOutput(String str, String stringToMatch,
@@ -360,8 +364,14 @@ public void testOzoneTenantBasicOperations() throws 
IOException {
     assertEquals(0, lines.size());
 
     executeHA(tenantShell, new String[] {"list"});
-    checkOutput(out, "", true);
-    checkOutput(err, "", true);
+    // ignore possible output from gRPC TcpMetrics static init:
+    // ... org.apache.ratis.thirdparty.io.grpc.netty.TcpMetrics loadEpollInfo
+    // INFO: Epoll available during static init of TcpMetrics:true
+    Pattern tcpMetrics = Pattern.compile(".*TcpMetrics.*\n");
+    String stdout = tcpMetrics.matcher(out.get()).replaceAll("");
+    String stderr = tcpMetrics.matcher(err.get()).replaceAll("");
+    checkOutput(stdout, "", true);
+    checkOutput(stderr, "", true);
 
     // Create tenants
     // Equivalent to `ozone tenant create finance`


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to