Apache Solr open-source search software
SOLR-17651: Make sure CLI unit tests don't call System.exit() (#3258)
Pierre Salagnaca122401a021b
diff --git a/gradle/validation/forbidden-apis/defaults.all.txt b/gradle/validation/forbidden-apis/defaults.all.txtindex 2faad099236..ba0d86c5eec 100644--- a/gradle/validation/forbidden-apis/defaults.all.txt+++ b/gradle/validation/forbidden-apis/defaults.all.txt@@ -57,6 +57,11 @@ java.util.Collections#shuffle(java.util.List) @ Use shuffle(List, Random) insteajava.util.Locale#forLanguageTag(java.lang.String) @ use new Locale.Builder().setLanguageTag(...).build() which has error handlingjava.util.Locale#toString() @ use Locale#toLanguageTag() for a standardized BCP47 locale name++@defaultMessage Direct calls to force the JVM to quit are forbidden in server code.+java.lang.System#exit(int)+java.lang.Runtime#exit(int)+@defaultMessage Constructors for wrapper classes of Java primitives should be avoided in favor of the public static methods available or autoboxingjava.lang.Integer#<init>(**)java.lang.Byte#<init>(**)diff --git a/solr/CHANGES.txt b/solr/CHANGES.txtindex 3e1849b031e..fe0ebea90d9 100644--- a/solr/CHANGES.txt+++ b/solr/CHANGES.txt@@ -265,6 +265,8 @@ Other Changes* SOLR-17716: Handle interrupted exception in SolrCores.waitAddPendingCoreOps. (Bruno Roustant)+* SOLR-17651: Add System.exit() in forbidden APIs, and make sure CLI unit tests never call it. (Pierre Salagnac)+================== 9.8.1 ==================Bug Fixes---------------------diff --git a/solr/core/src/java/org/apache/solr/cli/ApiTool.java b/solr/core/src/java/org/apache/solr/cli/ApiTool.javaindex c187360061f..548f29f2485 100644--- a/solr/core/src/java/org/apache/solr/cli/ApiTool.java+++ b/solr/core/src/java/org/apache/solr/cli/ApiTool.java@@ -17,7 +17,6 @@package org.apache.solr.cli;-import java.io.PrintStream;import java.net.URI;import org.apache.commons.cli.CommandLine;import org.apache.commons.cli.Option;@@ -46,12 +45,8 @@ public class ApiTool extends ToolBase {.desc("Send a GET request to a Solr API endpoint.").build();- public ApiTool() {- this(CLIO.getOutStream());- }-- public ApiTool(PrintStream stdout) {- super(stdout);+ public ApiTool(ToolRuntime runtime) {+ super(runtime);}@Overridediff --git a/solr/core/src/java/org/apache/solr/cli/AssertTool.java b/solr/core/src/java/org/apache/solr/cli/AssertTool.javaindex b111ef7b481..f4e92c0c008 100644--- a/solr/core/src/java/org/apache/solr/cli/AssertTool.java+++ b/solr/core/src/java/org/apache/solr/cli/AssertTool.java@@ -17,7 +17,6 @@package org.apache.solr.cli;import java.io.IOException;-import java.io.PrintStream;import java.lang.invoke.MethodHandles;import java.nio.file.Files;import java.nio.file.Path;@@ -144,12 +143,8 @@ public class AssertTool extends ToolBase {.longOpt("exitcode").build();- public AssertTool() {- this(CLIO.getOutStream());- }-- public AssertTool(PrintStream stdout) {- super(stdout);+ public AssertTool(ToolRuntime runtime) {+ super(runtime);}@Override@@ -262,8 +257,8 @@ public class AssertTool extends ToolBase {return ret;}- public static int assertSolrRunning(String url, String credentials) throws Exception {- StatusTool status = new StatusTool();+ public int assertSolrRunning(String url, String credentials) throws Exception {+ StatusTool status = new StatusTool(runtime);try {status.waitToSeeSolrUp(url, credentials, timeoutMs, TimeUnit.MILLISECONDS);} catch (Exception se) {@@ -280,8 +275,8 @@ public class AssertTool extends ToolBase {return 0;}- public static int assertSolrNotRunning(String url, String credentials) throws Exception {- StatusTool status = new StatusTool();+ public int assertSolrNotRunning(String url, String credentials) throws Exception {+ StatusTool status = new StatusTool(runtime);long timeout =System.nanoTime() + TimeUnit.NANOSECONDS.convert(timeoutMs, TimeUnit.MILLISECONDS);try (SolrClient solrClient = CLIUtils.getSolrClient(url, credentials)) {@@ -316,7 +311,7 @@ public class AssertTool extends ToolBase {+ " seconds");}- public static int assertSolrRunningInCloudMode(String url, String credentials) throws Exception {+ public int assertSolrRunningInCloudMode(String url, String credentials) throws Exception {if (!isSolrRunningOn(url, credentials)) {return exitOrException("Solr is not running on url "@@ -332,8 +327,7 @@ public class AssertTool extends ToolBase {return 0;}- public static int assertSolrNotRunningInCloudMode(String url, String credentials)- throws Exception {+ public int assertSolrNotRunningInCloudMode(String url, String credentials) throws Exception {if (!isSolrRunningOn(url, credentials)) {return exitOrException("Solr is not running on url "@@ -411,8 +405,8 @@ public class AssertTool extends ToolBase {}}- private static boolean isSolrRunningOn(String url, String credentials) throws Exception {- StatusTool status = new StatusTool();+ private boolean isSolrRunningOn(String url, String credentials) throws Exception {+ StatusTool status = new StatusTool(runtime);try {status.waitToSeeSolrUp(url, credentials, timeoutMs, TimeUnit.MILLISECONDS);return true;diff --git a/solr/core/src/java/org/apache/solr/cli/AuthTool.java b/solr/core/src/java/org/apache/solr/cli/AuthTool.javaindex c1fd6098e6c..597197b4ff8 100644--- a/solr/core/src/java/org/apache/solr/cli/AuthTool.java+++ b/solr/core/src/java/org/apache/solr/cli/AuthTool.java@@ -23,7 +23,6 @@ import com.fasterxml.jackson.databind.node.ArrayNode;import com.fasterxml.jackson.databind.node.ObjectNode;import java.io.Console;import java.io.IOException;-import java.io.PrintStream;import java.net.URL;import java.nio.charset.StandardCharsets;import java.nio.file.Files;@@ -101,12 +100,8 @@ public class AuthTool extends ToolBase {"This is where any authentication related configuration files, if any, would be placed. Defaults to $SOLR_HOME.").build();- public AuthTool() {- this(CLIO.getOutStream());- }-- public AuthTool(PrintStream stdout) {- super(stdout);+ public AuthTool(ToolRuntime runtime) {+ super(runtime);}@Override@@ -155,7 +150,7 @@ public class AuthTool extends ToolBase {+ "] must be either true or false, but was ["+ value+ "]");- SolrCLI.exit(1);+ runtime.exit(1);}}}@@ -169,12 +164,12 @@ public class AuthTool extends ToolBase {case "enable":if (!prompt && !cli.hasOption(CommonCLIOptions.CREDENTIALS_OPTION)) {CLIO.out("Option --credentials or --prompt is required with enable.");- SolrCLI.exit(1);+ runtime.exit(1);} else if (!prompt&& (cli.getOptionValue(CommonCLIOptions.CREDENTIALS_OPTION) == null|| !cli.getOptionValue(CommonCLIOptions.CREDENTIALS_OPTION).contains(":"))) {CLIO.out("Option --credentials is not in correct format.");- SolrCLI.exit(1);+ runtime.exit(1);}String zkHost = null;@@ -190,7 +185,7 @@ public class AuthTool extends ToolBase {CLIO.out("Couldn't get ZooKeeper host. Please make sure Solr is running in cloud mode, or a zk-host has been passed in.");}- SolrCLI.exit(1);+ runtime.exit(1);}if (zkHost == null) {if (cli.hasOption(CommonCLIOptions.ZK_HOST_OPTION)) {@@ -200,7 +195,7 @@ public class AuthTool extends ToolBase {CLIO.out("Couldn't get ZooKeeper host. Please make sure Solr is running in cloud mode, or a zk-host has been passed in.");}- SolrCLI.exit(1);+ runtime.exit(1);}// check if security is already enabled or not@@ -264,7 +259,7 @@ public class AuthTool extends ToolBase {CLIO.out("Solr include file " + solrIncludeFilename + " doesn't exist or is not writeable.");printAuthEnablingInstructions(username, password);- System.exit(0);+ runtime.exit(0);}String authConfDir = cli.getOptionValue(AUTH_CONF_DIR_OPTION);Path basicAuthConfFile = Path.of(authConfDir, "basicAuth.conf");@@ -272,7 +267,7 @@ public class AuthTool extends ToolBase {if (!Files.isWritable(basicAuthConfFile.getParent())) {CLIO.out("Cannot write to file: " + basicAuthConfFile.toAbsolutePath());printAuthEnablingInstructions(username, password);- System.exit(0);+ runtime.exit(0);}Files.writeString(@@ -297,7 +292,7 @@ public class AuthTool extends ToolBase {"Solr include file " + solrIncludeFilename + " doesn't exist or is not writeable.");CLIO.out("Security has been disabled. Please remove any SOLR_AUTH_TYPE or SOLR_AUTHENTICATION_OPTS configuration from solr.in.sh/solr.in.cmd.\n");- System.exit(0);+ runtime.exit(0);}// update the solr.in.sh file to comment out the necessary authentication lines@@ -305,11 +300,11 @@ public class AuthTool extends ToolBase {return;default:CLIO.out("Valid auth commands are: enable, disable.");- SolrCLI.exit(1);+ runtime.exit(1);}CLIO.out("Options not understood.");- SolrCLI.exit(1);+ runtime.exit(1);}private void checkSecurityJsonExists(SolrZkClient zkClient)@@ -320,7 +315,7 @@ public class AuthTool extends ToolBase {CLIO.out("Security is already enabled. You can disable it with 'bin/solr auth disable'. Existing security.json: \n"+ new String(oldSecurityBytes, StandardCharsets.UTF_8));- SolrCLI.exit(1);+ runtime.exit(1);}}}@@ -330,8 +325,8 @@ public class AuthTool extends ToolBase {if (!updateIncludeFileOnly) {zkHost = CLIUtils.getZkHost(cli);if (zkHost == null) {- stdout.print("ZK Host not found. Solr should be running in cloud mode.");- SolrCLI.exit(1);+ runtime.print("ZK Host not found. Solr should be running in cloud mode.");+ runtime.exit(1);}echoIfVerbose("Uploading following security.json: {}");diff --git a/solr/core/src/java/org/apache/solr/cli/CLIUtils.java b/solr/core/src/java/org/apache/solr/cli/CLIUtils.javaindex de41c34d6dd..22143e1dbfa 100644--- a/solr/core/src/java/org/apache/solr/cli/CLIUtils.java+++ b/solr/core/src/java/org/apache/solr/cli/CLIUtils.java@@ -234,8 +234,7 @@ public final class CLIUtils {new GenericSolrRequest(SolrRequest.METHOD.GET, CommonParams.SYSTEM_INFO_PATH));// convert raw JSON into user-friendly output- StatusTool statusTool = new StatusTool();- Map<String, Object> status = statusTool.reportStatus(systemInfo, solrClient);+ Map<String, Object> status = StatusTool.reportStatus(systemInfo, solrClient);@SuppressWarnings("unchecked")Map<String, Object> cloud = (Map<String, Object>) status.get("cloud");if (cloud != null) {diff --git a/solr/core/src/java/org/apache/solr/cli/ClusterTool.java b/solr/core/src/java/org/apache/solr/cli/ClusterTool.javaindex 714654829cc..7f0a5bbb586 100644--- a/solr/core/src/java/org/apache/solr/cli/ClusterTool.java+++ b/solr/core/src/java/org/apache/solr/cli/ClusterTool.java@@ -18,7 +18,6 @@package org.apache.solr.cli;import java.io.IOException;-import java.io.PrintStream;import java.util.concurrent.TimeUnit;import org.apache.commons.cli.CommandLine;import org.apache.commons.cli.Option;@@ -53,12 +52,8 @@ public class ClusterTool extends ToolBase {.desc("Set the property to this value.").build();- public ClusterTool() {- this(CLIO.getOutStream());- }-- public ClusterTool(PrintStream stdout) {- super(stdout);+ public ClusterTool(ToolRuntime runtime) {+ super(runtime);}@Overridediff --git a/solr/core/src/java/org/apache/solr/cli/ConfigSetDownloadTool.java b/solr/core/src/java/org/apache/solr/cli/ConfigSetDownloadTool.javaindex 264023640f7..bc4390c8d01 100644--- a/solr/core/src/java/org/apache/solr/cli/ConfigSetDownloadTool.java+++ b/solr/core/src/java/org/apache/solr/cli/ConfigSetDownloadTool.java@@ -16,7 +16,6 @@*/package org.apache.solr.cli;-import java.io.PrintStream;import java.lang.invoke.MethodHandles;import java.nio.file.Files;import java.nio.file.Path;@@ -50,12 +49,8 @@ public class ConfigSetDownloadTool extends ToolBase {.desc("Local directory with configs.").build();- public ConfigSetDownloadTool() {- this(CLIO.getOutStream());- }-- public ConfigSetDownloadTool(PrintStream stdout) {- super(stdout);+ public ConfigSetDownloadTool(ToolRuntime runtime) {+ super(runtime);}@Overridediff --git a/solr/core/src/java/org/apache/solr/cli/ConfigSetUploadTool.java b/solr/core/src/java/org/apache/solr/cli/ConfigSetUploadTool.javaindex a9fc0631e11..8b77fec8135 100644--- a/solr/core/src/java/org/apache/solr/cli/ConfigSetUploadTool.java+++ b/solr/core/src/java/org/apache/solr/cli/ConfigSetUploadTool.java@@ -16,7 +16,6 @@*/package org.apache.solr.cli;-import java.io.PrintStream;import java.lang.invoke.MethodHandles;import java.nio.file.Path;import java.nio.file.Paths;@@ -52,12 +51,8 @@ public class ConfigSetUploadTool extends ToolBase {.desc("Local directory with configs.").build();- public ConfigSetUploadTool() {- this(CLIO.getOutStream());- }-- public ConfigSetUploadTool(PrintStream stdout) {- super(stdout);+ public ConfigSetUploadTool(ToolRuntime runtime) {+ super(runtime);}@Overridediff --git a/solr/core/src/java/org/apache/solr/cli/ConfigTool.java b/solr/core/src/java/org/apache/solr/cli/ConfigTool.javaindex e5e7c96791c..b70f4c1b9a5 100644--- a/solr/core/src/java/org/apache/solr/cli/ConfigTool.java+++ b/solr/core/src/java/org/apache/solr/cli/ConfigTool.java@@ -17,7 +17,6 @@package org.apache.solr.cli;-import java.io.PrintStream;import java.util.HashMap;import java.util.Map;import org.apache.commons.cli.CommandLine;@@ -72,12 +71,8 @@ public class ConfigTool extends ToolBase {.desc("Set the property to this value; accepts JSON objects and strings.").build();- public ConfigTool() {- this(CLIO.getOutStream());- }-- public ConfigTool(PrintStream stdout) {- super(stdout);+ public ConfigTool(ToolRuntime runtime) {+ super(runtime);}@Overridediff --git a/solr/core/src/java/org/apache/solr/cli/CreateTool.java b/solr/core/src/java/org/apache/solr/cli/CreateTool.javaindex 8c46bc13c4f..b4d5f2ef846 100644--- a/solr/core/src/java/org/apache/solr/cli/CreateTool.java+++ b/solr/core/src/java/org/apache/solr/cli/CreateTool.java@@ -17,7 +17,6 @@package org.apache.solr.cli;import java.io.IOException;-import java.io.PrintStream;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;@@ -99,12 +98,8 @@ public class CreateTool extends ToolBase {.desc("Configuration name; default is the collection name.").build();- public CreateTool() {- this(CLIO.getOutStream());- }-- public CreateTool(PrintStream stdout) {- super(stdout);+ public CreateTool(ToolRuntime runtime) {+ super(runtime);}@Override@@ -346,7 +341,7 @@ public class CreateTool extends ToolBase {Path fullConfDir = getFullConfDir(solrInstallDir, confDirName);if (!Files.isDirectory(fullConfDir)) {echo("Specified configuration directory " + confDirName + " not found!");- System.exit(1);+ runtime.exit(1);}}}diff --git a/solr/core/src/java/org/apache/solr/cli/DefaultToolRuntime.java b/solr/core/src/java/org/apache/solr/cli/DefaultToolRuntime.javanew file mode 100644index 00000000000..e97a7829a6f--- /dev/null+++ b/solr/core/src/java/org/apache/solr/cli/DefaultToolRuntime.java@@ -0,0 +1,40 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package org.apache.solr.cli;++import org.apache.solr.common.util.SuppressForbidden;++/**+ * Standard implementation of tool runtime when running from command line.+ *+ * <p>This implementation may do a call to {@link System#exit(int)} and consequently should not be+ * used in tests.+ */+public class DefaultToolRuntime extends ToolRuntime {++ @Override+ @SuppressForbidden(reason = "For use in CLI only")+ public void print(String message) {+ System.out.print(message);+ }++ @Override+ @SuppressForbidden(reason = "For use in CLI only")+ public void println(String message) {+ System.out.println(message);+ }+}diff --git a/solr/core/src/java/org/apache/solr/cli/DeleteTool.java b/solr/core/src/java/org/apache/solr/cli/DeleteTool.javaindex c06e5ddf63c..c63ba852aed 100644--- a/solr/core/src/java/org/apache/solr/cli/DeleteTool.java+++ b/solr/core/src/java/org/apache/solr/cli/DeleteTool.java@@ -16,7 +16,6 @@*/package org.apache.solr.cli;-import java.io.PrintStream;import java.lang.invoke.MethodHandles;import java.util.Collection;import java.util.Locale;@@ -68,12 +67,8 @@ public class DeleteTool extends ToolBase {"Skip safety checks when deleting the configuration directory used by a collection.").build();- public DeleteTool() {- this(CLIO.getOutStream());- }-- public DeleteTool(PrintStream stdout) {- super(stdout);+ public DeleteTool(ToolRuntime runtime) {+ super(runtime);}@Overridediff --git a/solr/core/src/java/org/apache/solr/cli/ExportTool.java b/solr/core/src/java/org/apache/solr/cli/ExportTool.javaindex 7d0b386d733..30187d13ffc 100644--- a/solr/core/src/java/org/apache/solr/cli/ExportTool.java+++ b/solr/core/src/java/org/apache/solr/cli/ExportTool.java@@ -29,7 +29,6 @@ import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.io.OutputStreamWriter;-import java.io.PrintStream;import java.io.Writer;import java.nio.charset.StandardCharsets;import java.nio.file.Files;@@ -141,6 +140,10 @@ public class ExportTool extends ToolBase {.desc("Comma separated list of fields to export. By default all fields are fetched.").build();+ public ExportTool(ToolRuntime runtime) {+ super(runtime);+ }+@Overridepublic String getName() {return "export";@@ -161,6 +164,8 @@ public class ExportTool extends ToolBase {}public abstract static class Info {+ final ToolRuntime runtime;+String baseurl;String credentials;String format;@@ -172,12 +177,12 @@ public class ExportTool extends ToolBase {long limit = 100;AtomicLong docsWritten = new AtomicLong(0);int bufferSize = 1024 * 1024;- PrintStream output;String uniqueKey;CloudSolrClient solrClient;DocsSink sink;- public Info(String url, String credentials) {+ public Info(ToolRuntime runtime, String url, String credentials) {+ this.runtime = runtime;setUrl(url);setCredentials(credentials);setOutFormat(null, "jsonl", false);@@ -290,7 +295,7 @@ public class ExportTool extends ToolBase {throw new IllegalArgumentException("Must specify --solr-url.");}String credentials = cli.getOptionValue(CommonCLIOptions.CREDENTIALS_OPTION);- Info info = new MultiThreadedRunner(url, credentials);+ Info info = new MultiThreadedRunner(runtime, url, credentials);info.query = cli.getOptionValue(QUERY_OPTION, "*:*");info.setOutFormat(@@ -299,7 +304,6 @@ public class ExportTool extends ToolBase {cli.hasOption(COMPRESS_OPTION));info.fields = cli.getOptionValue(FIELDS_OPTION);info.setLimit(cli.getOptionValue(LIMIT_OPTION, "100"));- info.output = super.stdout;info.exportDocs();}@@ -548,8 +552,8 @@ public class ExportTool extends ToolBase {private final long startTime;@SuppressForbidden(reason = "Need to print out time")- public MultiThreadedRunner(String url, String credentials) {- super(url, credentials);+ public MultiThreadedRunner(ToolRuntime runtime, String url, String credentials) {+ super(runtime, url, credentials);startTime = System.currentTimeMillis();}@@ -572,9 +576,7 @@ public class ExportTool extends ToolBase {try {addConsumer(consumerlatch);addProducers(m);- if (output != null) {- output.println("Number of shards : " + corehandlers.size());- }+ runtime.println("Number of shards : " + corehandlers.size());CountDownLatch producerLatch = new CountDownLatch(corehandlers.size());corehandlers.forEach((s, coreHandler) ->@@ -583,7 +585,7 @@ public class ExportTool extends ToolBase {try {coreHandler.exportDocsFromCore();} catch (Exception e) {- if (output != null) output.println("Error exporting docs from : " + s);+ runtime.println("Error exporting docs from : " + s);}producerLatch.countDown();}));@@ -631,7 +633,7 @@ public class ExportTool extends ToolBase {try {doc = queue.poll(30, TimeUnit.SECONDS);} catch (InterruptedException e) {- if (output != null) output.println("Consumer interrupted");+ runtime.println("Consumer interrupted");failed = true;break;}@@ -642,7 +644,7 @@ public class ExportTool extends ToolBase {}sink.accept(doc);} catch (Exception e) {- if (output != null) output.println("Failed to write to file " + e.getMessage());+ runtime.println("Failed to write to file " + e.getMessage());failed = true;}}@@ -678,7 +680,7 @@ public class ExportTool extends ToolBase {receivedDocs.incrementAndGet();} catch (InterruptedException e) {failed = true;- if (output != null) output.println("Failed to write docs from" + e.getMessage());+ runtime.println("Failed to write docs from" + e.getMessage());}};StreamingBinaryResponseParser responseParser =@@ -693,32 +695,27 @@ public class ExportTool extends ToolBase {NamedList<Object> rsp = client.request(request, replica.getCoreName());String nextCursorMark = (String) rsp.get(CursorMarkParams.CURSOR_MARK_NEXT);if (nextCursorMark == null || Objects.equals(cursorMark, nextCursorMark)) {- if (output != null) {- output.println(- StrUtils.formatString(- "\nExport complete from shard {0}, core {1}, docs received: {2}",- replica.getShard(), replica.getCoreName(), receivedDocs.get()));- }+ runtime.println(+ StrUtils.formatString(+ "\nExport complete from shard {0}, core {1}, docs received: {2}",+ replica.getShard(), replica.getCoreName(), receivedDocs.get()));if (expectedDocs != receivedDocs.get()) {- if (output != null) {- output.println(- StrUtils.formatString(- "Could not download all docs from core {0}, docs expected: {1}, received: {2}",- replica.getCoreName(), expectedDocs, receivedDocs.get()));- return false;- }+ runtime.println(+ StrUtils.formatString(+ "Could not download all docs from core {0}, docs expected: {1}, received: {2}",+ replica.getCoreName(), expectedDocs, receivedDocs.get()));+ return false;}return true;}cursorMark = nextCursorMark;- if (output != null) output.print(".");+ runtime.print(".");} catch (SolrServerException e) {- if (output != null)- output.println(- "Error reading from server "- + replica.getBaseUrl()- + "/"- + replica.getCoreName());+ runtime.println(+ "Error reading from server "+ + replica.getBaseUrl()+ + "/"+ + replica.getCoreName());failed = true;return false;}diff --git a/solr/core/src/java/org/apache/solr/cli/HealthcheckTool.java b/solr/core/src/java/org/apache/solr/cli/HealthcheckTool.javaindex 950ac3430b9..4201392f933 100644--- a/solr/core/src/java/org/apache/solr/cli/HealthcheckTool.java+++ b/solr/core/src/java/org/apache/solr/cli/HealthcheckTool.java@@ -20,7 +20,6 @@ package org.apache.solr.cli;import static org.apache.solr.common.params.CommonParams.DISTRIB;import static org.apache.solr.common.params.CommonParams.NAME;-import java.io.PrintStream;import java.lang.invoke.MethodHandles;import java.util.ArrayList;import java.util.Collection;@@ -79,12 +78,8 @@ public class HealthcheckTool extends ToolBase {}/** Requests health information about a specific collection in SolrCloud. */- public HealthcheckTool() {- this(CLIO.getOutStream());- }-- public HealthcheckTool(PrintStream stdout) {- super(stdout);+ public HealthcheckTool(ToolRuntime runtime) {+ super(runtime);}@Override@@ -92,7 +87,7 @@ public class HealthcheckTool extends ToolBase {String zkHost = CLIUtils.getZkHost(cli);if (zkHost == null) {CLIO.err("Healthcheck tool only works in Solr Cloud mode.");- System.exit(1);+ runtime.exit(1);}try (CloudHttp2SolrClient cloudSolrClient = CLIUtils.getCloudHttp2SolrClient(zkHost)) {echoIfVerbose("\nConnecting to ZooKeeper at " + zkHost + " ...");diff --git a/solr/core/src/java/org/apache/solr/cli/LinkConfigTool.java b/solr/core/src/java/org/apache/solr/cli/LinkConfigTool.javaindex 619e1d82e5c..afc14edea83 100644--- a/solr/core/src/java/org/apache/solr/cli/LinkConfigTool.java+++ b/solr/core/src/java/org/apache/solr/cli/LinkConfigTool.java@@ -17,7 +17,6 @@package org.apache.solr.cli;-import java.io.PrintStream;import java.util.concurrent.TimeUnit;import org.apache.commons.cli.CommandLine;import org.apache.commons.cli.Option;@@ -47,12 +46,8 @@ public class LinkConfigTool extends ToolBase {.desc("Configset name in ZooKeeper.").build();- public LinkConfigTool() {- this(CLIO.getOutStream());- }-- public LinkConfigTool(PrintStream stdout) {- super(stdout);+ public LinkConfigTool(ToolRuntime runtime) {+ super(runtime);}@Overridediff --git a/solr/core/src/java/org/apache/solr/cli/PackageTool.java b/solr/core/src/java/org/apache/solr/cli/PackageTool.javaindex b71c86896cb..e60507bebe7 100644--- a/solr/core/src/java/org/apache/solr/cli/PackageTool.java+++ b/solr/core/src/java/org/apache/solr/cli/PackageTool.java@@ -94,7 +94,8 @@ public class PackageTool extends ToolBase {@SuppressForbidden(reason = "Need to turn off logging, and SLF4J doesn't seem to provide for a way.")- public PackageTool() {+ public PackageTool(ToolRuntime runtime) {+ super(runtime);// Need a logging free, clean output going through to the user.Configurator.setRootLevel(Level.OFF);}@@ -126,7 +127,7 @@ public class PackageTool extends ToolBase {String cmd = cli.getArgs()[0];try (SolrClient solrClient = CLIUtils.getSolrClient(cli, true)) {- packageManager = new PackageManager(solrClient, solrUrl, zkHost);+ packageManager = new PackageManager(runtime, solrClient, solrUrl, zkHost);try {repositoryManager = new RepositoryManager(solrClient, packageManager);diff --git a/solr/core/src/java/org/apache/solr/cli/PostLogsTool.java b/solr/core/src/java/org/apache/solr/cli/PostLogsTool.javaindex c14d9c216db..fd993291ed8 100644--- a/solr/core/src/java/org/apache/solr/cli/PostLogsTool.java+++ b/solr/core/src/java/org/apache/solr/cli/PostLogsTool.java@@ -20,7 +20,6 @@ package org.apache.solr.cli;import java.io.BufferedReader;import java.io.IOException;import java.io.LineNumberReader;-import java.io.PrintStream;import java.net.URLDecoder;import java.nio.charset.Charset;import java.nio.file.Files;@@ -67,12 +66,8 @@ public class PostLogsTool extends ToolBase {.desc("All files found at or below the root directory will be indexed.").build();- public PostLogsTool() {- this(CLIO.getOutStream());- }-- public PostLogsTool(PrintStream stdout) {- super(stdout);+ public PostLogsTool(ToolRuntime runtime) {+ super(runtime);}@Overridediff --git a/solr/core/src/java/org/apache/solr/cli/PostTool.java b/solr/core/src/java/org/apache/solr/cli/PostTool.javaindex 5ec8eb3eb7e..f4a6dc4085b 100644--- a/solr/core/src/java/org/apache/solr/cli/PostTool.java+++ b/solr/core/src/java/org/apache/solr/cli/PostTool.java@@ -26,7 +26,6 @@ import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;-import java.io.PrintStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.ProtocolException;@@ -245,12 +244,8 @@ public class PostTool extends ToolBase {mimeMap.put("log", "text/plain");}- public PostTool() {- this(CLIO.getOutStream());- }-- public PostTool(PrintStream stdout) {- super(stdout);+ public PostTool(ToolRuntime runtime) {+ super(runtime);}@Overridediff --git a/solr/core/src/java/org/apache/solr/cli/RunExampleTool.java b/solr/core/src/java/org/apache/solr/cli/RunExampleTool.javaindex 974039cb66f..3d3c93a9361 100644--- a/solr/core/src/java/org/apache/solr/cli/RunExampleTool.java+++ b/solr/core/src/java/org/apache/solr/cli/RunExampleTool.java@@ -19,7 +19,6 @@ package org.apache.solr.cli;import java.io.IOException;import java.io.InputStream;-import java.io.PrintStream;import java.net.Socket;import java.net.URI;import java.nio.charset.StandardCharsets;@@ -179,12 +178,12 @@ public class RunExampleTool extends ToolBase {protected String urlScheme;/** Default constructor used by the framework when running as a command-line application. */- public RunExampleTool() {- this(null, System.in, CLIO.getOutStream());+ public RunExampleTool(ToolRuntime runtime) {+ this(null, System.in, runtime);}- public RunExampleTool(Executor executor, InputStream userInput, PrintStream stdout) {- super(stdout);+ public RunExampleTool(Executor executor, InputStream userInput, ToolRuntime runtime) {+ super(runtime);this.executor = (executor != null) ? executor : new DefaultExecutor();this.userInput = userInput;}@@ -355,7 +354,7 @@ public class RunExampleTool extends ToolBase {"--conf-dir", configSet,"--solr-url", solrUrl};- CreateTool createTool = new CreateTool(stdout);+ CreateTool createTool = new CreateTool(runtime);int createCode = createTool.runTool(SolrCLI.processCommandLineArgs(createTool, createArgs));if (createCode != 0)throw new Exception(@@ -388,7 +387,7 @@ public class RunExampleTool extends ToolBase {"xml",exampledocsDir.toAbsolutePath().toString()};- PostTool postTool = new PostTool();+ PostTool postTool = new PostTool(runtime);CommandLine postToolCli = SolrCLI.parseCmdLine(postTool, args);postTool.runTool(postToolCli);@@ -497,7 +496,7 @@ public class RunExampleTool extends ToolBase {"application/json",filmsJsonFile.toAbsolutePath().toString()};- PostTool postTool = new PostTool();+ PostTool postTool = new PostTool(runtime);CommandLine postToolCli = SolrCLI.parseCmdLine(postTool, args);postTool.runTool(postToolCli);@@ -795,7 +794,7 @@ public class RunExampleTool extends ToolBase {Map<String, Object> nodeStatus = null;try {- nodeStatus = (new StatusTool()).getStatus(solrUrl, credentials);+ nodeStatus = (new StatusTool(runtime)).getStatus(solrUrl, credentials);} catch (Exception ignore) {/* just trying to determine if this example is already running. */}@@ -945,7 +944,7 @@ public class RunExampleTool extends ToolBase {"--solr-url", solrUrl};- CreateTool createTool = new CreateTool(stdout);+ CreateTool createTool = new CreateTool(runtime);int createCode = createTool.runTool(SolrCLI.processCommandLineArgs(createTool, createArgs));if (createCode != 0)@@ -966,7 +965,7 @@ public class RunExampleTool extends ToolBase {protected Map<String, Object> getNodeStatus(String solrUrl, String credentials, int maxWaitSecs)throws Exception {- StatusTool statusTool = new StatusTool();+ StatusTool statusTool = new StatusTool(runtime);echoIfVerbose("\nChecking status of Solr at " + solrUrl + " ...");URI solrURI = new URI(solrUrl);diff --git a/solr/core/src/java/org/apache/solr/cli/SnapshotCreateTool.java b/solr/core/src/java/org/apache/solr/cli/SnapshotCreateTool.javaindex 49cce02a15c..30e8b27c3d6 100644--- a/solr/core/src/java/org/apache/solr/cli/SnapshotCreateTool.java+++ b/solr/core/src/java/org/apache/solr/cli/SnapshotCreateTool.java@@ -16,7 +16,6 @@*/package org.apache.solr.cli;-import java.io.PrintStream;import org.apache.commons.cli.CommandLine;import org.apache.commons.cli.Option;import org.apache.commons.cli.Options;@@ -45,12 +44,8 @@ public class SnapshotCreateTool extends ToolBase {.desc("Name of the snapshot to produce").build();- public SnapshotCreateTool() {- this(CLIO.getOutStream());- }-- public SnapshotCreateTool(PrintStream stdout) {- super(stdout);+ public SnapshotCreateTool(ToolRuntime runtime) {+ super(runtime);}@Overridediff --git a/solr/core/src/java/org/apache/solr/cli/SnapshotDeleteTool.java b/solr/core/src/java/org/apache/solr/cli/SnapshotDeleteTool.javaindex c9dc90abab7..bd9e6aeeb05 100644--- a/solr/core/src/java/org/apache/solr/cli/SnapshotDeleteTool.java+++ b/solr/core/src/java/org/apache/solr/cli/SnapshotDeleteTool.java@@ -16,7 +16,6 @@*/package org.apache.solr.cli;-import java.io.PrintStream;import org.apache.commons.cli.CommandLine;import org.apache.commons.cli.Option;import org.apache.commons.cli.Options;@@ -45,12 +44,8 @@ public class SnapshotDeleteTool extends ToolBase {.desc("Name of the snapshot to delete").build();- public SnapshotDeleteTool() {- this(CLIO.getOutStream());- }-- public SnapshotDeleteTool(PrintStream stdout) {- super(stdout);+ public SnapshotDeleteTool(ToolRuntime runtime) {+ super(runtime);}@Overridediff --git a/solr/core/src/java/org/apache/solr/cli/SnapshotDescribeTool.java b/solr/core/src/java/org/apache/solr/cli/SnapshotDescribeTool.javaindex dcae8619f3e..6e6fef8f0e8 100644--- a/solr/core/src/java/org/apache/solr/cli/SnapshotDescribeTool.java+++ b/solr/core/src/java/org/apache/solr/cli/SnapshotDescribeTool.java@@ -17,7 +17,6 @@package org.apache.solr.cli;import java.io.IOException;-import java.io.PrintStream;import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.ArrayList;@@ -55,12 +54,8 @@ public class SnapshotDescribeTool extends ToolBase {.desc("Name of the snapshot to describe").build();- public SnapshotDescribeTool() {- this(CLIO.getOutStream());- }-- public SnapshotDescribeTool(PrintStream stdout) {- super(stdout);+ public SnapshotDescribeTool(ToolRuntime runtime) {+ super(runtime);}private static final DateFormat dateFormat =diff --git a/solr/core/src/java/org/apache/solr/cli/SnapshotExportTool.java b/solr/core/src/java/org/apache/solr/cli/SnapshotExportTool.javaindex 6b8cf3a45d0..ea47d1b2a31 100644--- a/solr/core/src/java/org/apache/solr/cli/SnapshotExportTool.java+++ b/solr/core/src/java/org/apache/solr/cli/SnapshotExportTool.java@@ -16,7 +16,6 @@*/package org.apache.solr.cli;-import java.io.PrintStream;import java.util.Optional;import org.apache.commons.cli.CommandLine;import org.apache.commons.cli.Option;@@ -73,12 +72,8 @@ public class SnapshotExportTool extends ToolBase {"Specifies the async request identifier to be used during snapshot export preparation.").build();- public SnapshotExportTool() {- this(CLIO.getOutStream());- }-- public SnapshotExportTool(PrintStream stdout) {- super(stdout);+ public SnapshotExportTool(ToolRuntime runtime) {+ super(runtime);}@Overridediff --git a/solr/core/src/java/org/apache/solr/cli/SnapshotListTool.java b/solr/core/src/java/org/apache/solr/cli/SnapshotListTool.javaindex 4b952199e1b..2bbad50688b 100644--- a/solr/core/src/java/org/apache/solr/cli/SnapshotListTool.java+++ b/solr/core/src/java/org/apache/solr/cli/SnapshotListTool.java@@ -16,7 +16,6 @@*/package org.apache.solr.cli;-import java.io.PrintStream;import org.apache.commons.cli.CommandLine;import org.apache.commons.cli.Option;import org.apache.commons.cli.Options;@@ -38,12 +37,8 @@ public class SnapshotListTool extends ToolBase {.desc("Name of collection to list snapshots for.").build();- public SnapshotListTool() {- this(CLIO.getOutStream());- }-- public SnapshotListTool(PrintStream stdout) {- super(stdout);+ public SnapshotListTool(ToolRuntime runtime) {+ super(runtime);}@Overridediff --git a/solr/core/src/java/org/apache/solr/cli/SolrCLI.java b/solr/core/src/java/org/apache/solr/cli/SolrCLI.javaindex 568bc211964..eda67918864 100755--- a/solr/core/src/java/org/apache/solr/cli/SolrCLI.java+++ b/solr/core/src/java/org/apache/solr/cli/SolrCLI.java@@ -51,24 +51,17 @@ public class SolrCLI implements CLIO {private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());- public static void exit(int exitStatus) {- try {- System.exit(exitStatus);- } catch (java.lang.SecurityException secExc) {- if (exitStatus != 0)- throw new RuntimeException("SolrCLI failed to exit with status " + exitStatus);- }- }-/** Runs a tool. */public static void main(String[] args) throws Exception {+ ToolRuntime runtime = new DefaultToolRuntime();+final boolean hasNoCommand =args == null || args.length == 0 || args[0] == null || args[0].trim().length() == 0;final boolean isHelpCommand = !hasNoCommand && Arrays.asList("-h", "--help").contains(args[0]);if (hasNoCommand || isHelpCommand) {printHelp();- exit(1);+ runtime.exit(1);}if (Arrays.asList("-v", "--version").contains(args[0])) {@@ -111,18 +104,18 @@ public class SolrCLI implements CLIO {Tool tool = null;try {- tool = findTool(args);+ tool = findTool(args, runtime);} catch (IllegalArgumentException iae) {CLIO.err(iae.getMessage());- System.exit(1);+ runtime.exit(1);}CommandLine cli = parseCmdLine(tool, args);- System.exit(tool.runTool(cli));+ runtime.exit(tool.runTool(cli));}- public static Tool findTool(String[] args) throws Exception {+ public static Tool findTool(String[] args, ToolRuntime runtime) throws Exception {String toolType = args[0].trim().toLowerCase(Locale.ROOT);- return newTool(toolType);+ return newTool(toolType, runtime);}public static CommandLine parseCmdLine(Tool tool, String[] args) {@@ -179,38 +172,38 @@ public class SolrCLI implements CLIO {}// Creates an instance of the requested tool, using classpath scanning if necessary- private static Tool newTool(String toolType) throws Exception {- if ("healthcheck".equals(toolType)) return new HealthcheckTool();- else if ("status".equals(toolType)) return new StatusTool();- else if ("api".equals(toolType)) return new ApiTool();- else if ("create".equals(toolType)) return new CreateTool();- else if ("delete".equals(toolType)) return new DeleteTool();- else if ("config".equals(toolType)) return new ConfigTool();- else if ("run_example".equals(toolType)) return new RunExampleTool();- else if ("upconfig".equals(toolType)) return new ConfigSetUploadTool();- else if ("downconfig".equals(toolType)) return new ConfigSetDownloadTool();- else if ("zk-tool-help".equals(toolType)) return new ZkToolHelp();- else if ("rm".equals(toolType)) return new ZkRmTool();- else if ("mv".equals(toolType)) return new ZkMvTool();- else if ("cp".equals(toolType)) return new ZkCpTool();- else if ("ls".equals(toolType)) return new ZkLsTool();- else if ("cluster".equals(toolType)) return new ClusterTool();- else if ("updateacls".equals(toolType)) return new UpdateACLTool();- else if ("linkconfig".equals(toolType)) return new LinkConfigTool();- else if ("mkroot".equals(toolType)) return new ZkMkrootTool();- else if ("assert".equals(toolType)) return new AssertTool();- else if ("auth".equals(toolType)) return new AuthTool();- else if ("export".equals(toolType)) return new ExportTool();- else if ("package".equals(toolType)) return new PackageTool();- else if ("post".equals(toolType)) return new PostTool();- else if ("postlogs".equals(toolType)) return new PostLogsTool();- else if ("version".equals(toolType)) return new VersionTool();- else if ("stream".equals(toolType)) return new StreamTool();- else if ("snapshot-create".equals(toolType)) return new SnapshotCreateTool();- else if ("snapshot-delete".equals(toolType)) return new SnapshotDeleteTool();- else if ("snapshot-list".equals(toolType)) return new SnapshotListTool();- else if ("snapshot-describe".equals(toolType)) return new SnapshotDescribeTool();- else if ("snapshot-export".equals(toolType)) return new SnapshotExportTool();+ private static Tool newTool(String toolType, ToolRuntime runtime) throws Exception {+ if ("healthcheck".equals(toolType)) return new HealthcheckTool(runtime);+ else if ("status".equals(toolType)) return new StatusTool(runtime);+ else if ("api".equals(toolType)) return new ApiTool(runtime);+ else if ("create".equals(toolType)) return new CreateTool(runtime);+ else if ("delete".equals(toolType)) return new DeleteTool(runtime);+ else if ("config".equals(toolType)) return new ConfigTool(runtime);+ else if ("run_example".equals(toolType)) return new RunExampleTool(runtime);+ else if ("upconfig".equals(toolType)) return new ConfigSetUploadTool(runtime);+ else if ("downconfig".equals(toolType)) return new ConfigSetDownloadTool(runtime);+ else if ("zk-tool-help".equals(toolType)) return new ZkToolHelp(runtime);+ else if ("rm".equals(toolType)) return new ZkRmTool(runtime);+ else if ("mv".equals(toolType)) return new ZkMvTool(runtime);+ else if ("cp".equals(toolType)) return new ZkCpTool(runtime);+ else if ("ls".equals(toolType)) return new ZkLsTool(runtime);+ else if ("cluster".equals(toolType)) return new ClusterTool(runtime);+ else if ("updateacls".equals(toolType)) return new UpdateACLTool(runtime);+ else if ("linkconfig".equals(toolType)) return new LinkConfigTool(runtime);+ else if ("mkroot".equals(toolType)) return new ZkMkrootTool(runtime);+ else if ("assert".equals(toolType)) return new AssertTool(runtime);+ else if ("auth".equals(toolType)) return new AuthTool(runtime);+ else if ("export".equals(toolType)) return new ExportTool(runtime);+ else if ("package".equals(toolType)) return new PackageTool(runtime);+ else if ("post".equals(toolType)) return new PostTool(runtime);+ else if ("postlogs".equals(toolType)) return new PostLogsTool(runtime);+ else if ("version".equals(toolType)) return new VersionTool(runtime);+ else if ("stream".equals(toolType)) return new StreamTool(runtime);+ else if ("snapshot-create".equals(toolType)) return new SnapshotCreateTool(runtime);+ else if ("snapshot-delete".equals(toolType)) return new SnapshotDeleteTool(runtime);+ else if ("snapshot-list".equals(toolType)) return new SnapshotListTool(runtime);+ else if ("snapshot-describe".equals(toolType)) return new SnapshotDescribeTool(runtime);+ else if ("snapshot-export".equals(toolType)) return new SnapshotExportTool(runtime);// If you add a built-in tool to this class, add it here to avoid// classpath scanning@@ -258,6 +251,7 @@ public class SolrCLI implements CLIO {/** Parses the command-line arguments passed by the user. */public static CommandLine processCommandLineArgs(Tool tool, String[] args) {Options options = tool.getOptions();+ ToolRuntime runtime = tool.getRuntime();CommandLine cli = null;try {@@ -280,16 +274,16 @@ public class SolrCLI implements CLIO {if (!hasHelpArg) {CLIO.err("Failed to parse command-line arguments due to: " + exp.getMessage() + "\n");printToolHelp(tool);- exit(1);+ runtime.exit(1);} else {printToolHelp(tool);- exit(0);+ runtime.exit(0);}}if (cli.hasOption(CommonCLIOptions.HELP_OPTION)) {printToolHelp(tool);- exit(0);+ runtime.exit(0);}return cli;diff --git a/solr/core/src/java/org/apache/solr/cli/StatusTool.java b/solr/core/src/java/org/apache/solr/cli/StatusTool.javaindex a935a7b364f..43af8ebb34d 100644--- a/solr/core/src/java/org/apache/solr/cli/StatusTool.java+++ b/solr/core/src/java/org/apache/solr/cli/StatusTool.java@@ -17,7 +17,6 @@package org.apache.solr.cli;-import java.io.PrintStream;import java.util.Collection;import java.util.LinkedHashMap;import java.util.List;@@ -76,12 +75,8 @@ public class StatusTool extends ToolBase {private final SolrProcessManager processMgr;- public StatusTool() {- this(CLIO.getOutStream());- }-- public StatusTool(PrintStream stdout) {- super(stdout);+ public StatusTool(ToolRuntime runtime) {+ super(runtime);processMgr = new SolrProcessManager();}@@ -112,7 +107,7 @@ public class StatusTool extends ToolBase {if (solrUrl != null) {if (!URLUtil.hasScheme(solrUrl)) {CLIO.err("Invalid URL provided: " + solrUrl);- System.exit(1);+ runtime.exit(1);}// URL provided, do not consult local processes, as the URL may be remote@@ -120,14 +115,14 @@ public class StatusTool extends ToolBase {// Used by Windows start script when starting Solrtry {waitForSolrUpAndPrintStatus(solrUrl, cli, maxWaitSecs);- System.exit(0);+ runtime.exit(0);} catch (Exception e) {CLIO.err(e.getMessage());- System.exit(1);+ runtime.exit(1);}} else {boolean running = printStatusFromRunningSolr(solrUrl, cli);- System.exit(running ? 0 : 1);+ runtime.exit(running ? 0 : 1);}}@@ -135,7 +130,7 @@ public class StatusTool extends ToolBase {Optional<SolrProcess> proc = processMgr.processForPort(port);if (proc.isEmpty()) {CLIO.err("Could not find a running Solr on port " + port);- System.exit(1);+ runtime.exit(1);} else {solrUrl = proc.get().getLocalUrl();if (shortFormat) {@@ -143,7 +138,7 @@ public class StatusTool extends ToolBase {} else {printProcessStatus(proc.get(), cli);}- System.exit(0);+ runtime.exit(0);}}@@ -193,7 +188,7 @@ public class StatusTool extends ToolBase {solrPort = CLIUtils.portFromUrl(solrUrl);} catch (Exception e) {CLIO.err("Invalid URL provided, does not contain port");- SolrCLI.exit(1);+ runtime.exit(1);}echo("Waiting up to " + maxWaitSecs + " seconds to see Solr running on port " + solrPort);boolean solrUp = waitForSolrUp(solrUrl, cli, maxWaitSecs);@@ -234,7 +229,7 @@ public class StatusTool extends ToolBase {/* ignore */}if (statusJson != null) {- CLIO.out(statusJson);+ runtime.println(statusJson);} else {CLIO.err("Solr at " + solrUrl + " not online.");}@@ -313,7 +308,7 @@ public class StatusTool extends ToolBase {return status;}- public Map<String, Object> reportStatus(NamedList<Object> info, SolrClient solrClient)+ public static Map<String, Object> reportStatus(NamedList<Object> info, SolrClient solrClient)throws Exception {Map<String, Object> status = new LinkedHashMap<>();@@ -341,7 +336,7 @@ public class StatusTool extends ToolBase {* cluster.*/@SuppressWarnings("unchecked")- protected Map<String, String> getCloudStatus(SolrClient solrClient, String zkHost)+ private static Map<String, String> getCloudStatus(SolrClient solrClient, String zkHost)throws Exception {Map<String, String> cloudStatus = new LinkedHashMap<>();cloudStatus.put("ZooKeeper", (zkHost != null) ? zkHost : "?");diff --git a/solr/core/src/java/org/apache/solr/cli/StreamTool.java b/solr/core/src/java/org/apache/solr/cli/StreamTool.javaindex 39684310f0e..62b80c6a40a 100644--- a/solr/core/src/java/org/apache/solr/cli/StreamTool.java+++ b/solr/core/src/java/org/apache/solr/cli/StreamTool.java@@ -22,7 +22,6 @@ import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.LineNumberReader;-import java.io.PrintStream;import java.io.Reader;import java.io.StringReader;import java.nio.charset.Charset;@@ -60,12 +59,8 @@ import org.apache.solr.handler.CatStream;/** Supports stream command in the bin/solr script. */public class StreamTool extends ToolBase {- public StreamTool() {- this(CLIO.getOutStream());- }-- public StreamTool(PrintStream stdout) {- super(stdout);+ public StreamTool(ToolRuntime runtime) {+ super(runtime);}private final SolrClientCache solrClientCache = new SolrClientCache();diff --git a/solr/core/src/java/org/apache/solr/cli/Tool.java b/solr/core/src/java/org/apache/solr/cli/Tool.javaindex a95af511642..1ad58bce50e 100644--- a/solr/core/src/java/org/apache/solr/cli/Tool.java+++ b/solr/core/src/java/org/apache/solr/cli/Tool.java@@ -49,6 +49,9 @@ public interface Tool {return "\nPlease see the Reference Guide for more tools documentation: https://solr.apache.org/guide/solr/latest/deployment-guide/solr-control-script-reference.html";}+ /** Return non-null runtime of the tool. */+ ToolRuntime getRuntime();+/*** Retrieve the {@link Options} supported by this tool.*diff --git a/solr/core/src/java/org/apache/solr/cli/ToolBase.java b/solr/core/src/java/org/apache/solr/cli/ToolBase.javaindex b0a0e1063a7..96ed3138ace 100644--- a/solr/core/src/java/org/apache/solr/cli/ToolBase.java+++ b/solr/core/src/java/org/apache/solr/cli/ToolBase.java@@ -17,7 +17,6 @@package org.apache.solr.cli;-import java.io.PrintStream;import org.apache.commons.cli.CommandLine;import org.apache.commons.cli.OptionGroup;import org.apache.commons.cli.Options;@@ -25,15 +24,12 @@ import org.apache.solr.util.StartupLoggingUtils;public abstract class ToolBase implements Tool {- private boolean verbose = false;- protected PrintStream stdout;+ protected final ToolRuntime runtime;- protected ToolBase() {- this(CLIO.getOutStream());- }+ private boolean verbose = false;- protected ToolBase(PrintStream stdout) {- this.stdout = stdout;+ protected ToolBase(ToolRuntime runtime) {+ this.runtime = runtime;}/** Is this tool being run in a verbose mode? */@@ -48,7 +44,7 @@ public abstract class ToolBase implements Tool {}protected void echo(final String msg) {- stdout.println(msg);+ runtime.println(msg);}@Override@@ -58,6 +54,11 @@ public abstract class ToolBase implements Tool {.addOption(CommonCLIOptions.VERBOSE_OPTION);}+ @Override+ public ToolRuntime getRuntime() {+ return runtime;+ }+/*** Provides the two ways of connecting to Solr for CLI Tools*diff --git a/solr/core/src/java/org/apache/solr/cli/ToolRuntime.java b/solr/core/src/java/org/apache/solr/cli/ToolRuntime.javanew file mode 100644index 00000000000..5b5e0b9306c--- /dev/null+++ b/solr/core/src/java/org/apache/solr/cli/ToolRuntime.java@@ -0,0 +1,42 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package org.apache.solr.cli;++import org.apache.solr.common.util.SuppressForbidden;++/**+ * An implementation of this class is specified when executing {@link ToolBase} to access+ * environment specific methods (mostly to differentiate test from non-test executions for now).+ *+ * @see ToolBase+ */+public abstract class ToolRuntime {++ public abstract void print(String message);++ public abstract void println(String message);++ /** Invokes {@link System#exit(int)} to force the JVM to immediately quit. */+ @SuppressForbidden(reason = "That's the only method in CLI code where we allow to exit the JVM")+ public void exit(int status) {+ try {+ System.exit(status);+ } catch (java.lang.SecurityException secExc) {+ if (status != 0) throw new RuntimeException("SolrCLI failed to exit with status " + status);+ }+ }+}diff --git a/solr/core/src/java/org/apache/solr/cli/UpdateACLTool.java b/solr/core/src/java/org/apache/solr/cli/UpdateACLTool.javaindex bf54152d2ac..021f05d7e82 100644--- a/solr/core/src/java/org/apache/solr/cli/UpdateACLTool.java+++ b/solr/core/src/java/org/apache/solr/cli/UpdateACLTool.java@@ -17,7 +17,6 @@package org.apache.solr.cli;-import java.io.PrintStream;import java.util.concurrent.TimeUnit;import org.apache.commons.cli.CommandLine;import org.apache.commons.cli.Options;@@ -33,12 +32,8 @@ import org.apache.solr.common.cloud.SolrZkClient;public class UpdateACLTool extends ToolBase {// It is a shame this tool doesn't more closely mimic how the ConfigTool works.- public UpdateACLTool() {- this(CLIO.getOutStream());- }-- public UpdateACLTool(PrintStream stdout) {- super(stdout);+ public UpdateACLTool(ToolRuntime runtime) {+ super(runtime);}@Overridediff --git a/solr/core/src/java/org/apache/solr/cli/VersionTool.java b/solr/core/src/java/org/apache/solr/cli/VersionTool.javaindex 148bdf36a40..b8ae826ebc6 100644--- a/solr/core/src/java/org/apache/solr/cli/VersionTool.java+++ b/solr/core/src/java/org/apache/solr/cli/VersionTool.java@@ -22,6 +22,10 @@ import org.apache.solr.client.api.util.SolrVersion;public class VersionTool extends ToolBase {+ public VersionTool(ToolRuntime runtime) {+ super(runtime);+ }+@Overridepublic String getName() {return "version";diff --git a/solr/core/src/java/org/apache/solr/cli/ZkCpTool.java b/solr/core/src/java/org/apache/solr/cli/ZkCpTool.javaindex 7f901e67cf2..0ae4c9f0055 100644--- a/solr/core/src/java/org/apache/solr/cli/ZkCpTool.java+++ b/solr/core/src/java/org/apache/solr/cli/ZkCpTool.java@@ -18,7 +18,6 @@ package org.apache.solr.cli;import static org.apache.solr.packagemanager.PackageUtils.format;-import java.io.PrintStream;import java.lang.invoke.MethodHandles;import java.lang.reflect.InvocationTargetException;import java.nio.file.Path;@@ -52,12 +51,8 @@ public class ZkCpTool extends ToolBase {.desc("Required to look up configuration for compressing state.json.").build();- public ZkCpTool() {- this(CLIO.getOutStream());- }-- public ZkCpTool(PrintStream stdout) {- super(stdout);+ public ZkCpTool(ToolRuntime runtime) {+ super(runtime);}@Overridediff --git a/solr/core/src/java/org/apache/solr/cli/ZkLsTool.java b/solr/core/src/java/org/apache/solr/cli/ZkLsTool.javaindex 57bb45d4e40..2ca4be286f2 100644--- a/solr/core/src/java/org/apache/solr/cli/ZkLsTool.java+++ b/solr/core/src/java/org/apache/solr/cli/ZkLsTool.java@@ -16,7 +16,6 @@*/package org.apache.solr.cli;-import java.io.PrintStream;import java.lang.invoke.MethodHandles;import org.apache.commons.cli.CommandLine;import org.apache.commons.cli.Options;@@ -28,12 +27,8 @@ import org.slf4j.LoggerFactory;public class ZkLsTool extends ToolBase {private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());- public ZkLsTool() {- this(CLIO.getOutStream());- }-- public ZkLsTool(PrintStream stdout) {- super(stdout);+ public ZkLsTool(ToolRuntime runtime) {+ super(runtime);}@Override@@ -71,7 +66,7 @@ public class ZkLsTool extends ToolBase {+ zkHost+ " recursive: "+ recursive);- stdout.print(zkClient.listZnode(znode, recursive));+ runtime.print(zkClient.listZnode(znode, recursive));} catch (Exception e) {log.error("Could not complete ls operation for reason: ", e);throw (e);diff --git a/solr/core/src/java/org/apache/solr/cli/ZkMkrootTool.java b/solr/core/src/java/org/apache/solr/cli/ZkMkrootTool.javaindex ace32ad5ce7..a3d4e513649 100644--- a/solr/core/src/java/org/apache/solr/cli/ZkMkrootTool.java+++ b/solr/core/src/java/org/apache/solr/cli/ZkMkrootTool.java@@ -18,7 +18,6 @@ package org.apache.solr.cli;import static org.apache.solr.packagemanager.PackageUtils.format;-import java.io.PrintStream;import java.lang.invoke.MethodHandles;import org.apache.commons.cli.CommandLine;import org.apache.commons.cli.Option;@@ -38,12 +37,8 @@ public class ZkMkrootTool extends ToolBase {.desc("Raise an error if the root exists. Defaults to false.").build();- public ZkMkrootTool() {- this(CLIO.getOutStream());- }-- public ZkMkrootTool(PrintStream stdout) {- super(stdout);+ public ZkMkrootTool(ToolRuntime runtime) {+ super(runtime);}@Overridediff --git a/solr/core/src/java/org/apache/solr/cli/ZkMvTool.java b/solr/core/src/java/org/apache/solr/cli/ZkMvTool.javaindex dba47d5b824..a11ac0884f8 100644--- a/solr/core/src/java/org/apache/solr/cli/ZkMvTool.java+++ b/solr/core/src/java/org/apache/solr/cli/ZkMvTool.java@@ -18,7 +18,6 @@ package org.apache.solr.cli;import static org.apache.solr.packagemanager.PackageUtils.format;-import java.io.PrintStream;import java.lang.invoke.MethodHandles;import java.util.Locale;import org.apache.commons.cli.CommandLine;@@ -32,12 +31,8 @@ import org.slf4j.LoggerFactory;public class ZkMvTool extends ToolBase {private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());- public ZkMvTool() {- this(CLIO.getOutStream());- }-- public ZkMvTool(PrintStream stdout) {- super(stdout);+ public ZkMvTool(ToolRuntime runtime) {+ super(runtime);}@Overridediff --git a/solr/core/src/java/org/apache/solr/cli/ZkRmTool.java b/solr/core/src/java/org/apache/solr/cli/ZkRmTool.javaindex 777ad6035a5..126286d9c2f 100644--- a/solr/core/src/java/org/apache/solr/cli/ZkRmTool.java+++ b/solr/core/src/java/org/apache/solr/cli/ZkRmTool.java@@ -16,7 +16,6 @@*/package org.apache.solr.cli;-import java.io.PrintStream;import java.lang.invoke.MethodHandles;import java.util.Locale;import org.apache.commons.cli.CommandLine;@@ -30,12 +29,8 @@ import org.slf4j.LoggerFactory;public class ZkRmTool extends ToolBase {private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());- public ZkRmTool() {- this(CLIO.getOutStream());- }-- public ZkRmTool(PrintStream stdout) {- super(stdout);+ public ZkRmTool(ToolRuntime runtime) {+ super(runtime);}@Overridediff --git a/solr/core/src/java/org/apache/solr/cli/ZkToolHelp.java b/solr/core/src/java/org/apache/solr/cli/ZkToolHelp.javaindex 525030dab11..93c1672de48 100644--- a/solr/core/src/java/org/apache/solr/cli/ZkToolHelp.java+++ b/solr/core/src/java/org/apache/solr/cli/ZkToolHelp.java@@ -18,7 +18,6 @@ package org.apache.solr.cli;import static org.apache.solr.cli.SolrCLI.print;-import java.io.PrintStream;import org.apache.commons.cli.CommandLine;import org.apache.commons.cli.Option;import org.apache.commons.cli.Options;@@ -38,12 +37,8 @@ public class ZkToolHelp extends ToolBase {.desc("Invokes the detailed help for zk commands.").build();- public ZkToolHelp() {- this(CLIO.getOutStream());- }-- public ZkToolHelp(PrintStream stdout) {- super(stdout);+ public ZkToolHelp(ToolRuntime runtime) {+ super(runtime);}@Override@@ -69,15 +64,15 @@ public class ZkToolHelp extends ToolBase {}if (cli.hasOption(PRINT_LONG_ZK_USAGE_OPTION)) {print("usage:");- print(new ZkLsTool().getUsage());- print(new ZkCpTool().getUsage());- print(new ZkMvTool().getUsage());+ print(new ZkLsTool(runtime).getUsage());+ print(new ZkCpTool(runtime).getUsage());+ print(new ZkMvTool(runtime).getUsage());- print(new ConfigSetUploadTool().getUsage());- print(new ConfigSetDownloadTool().getUsage());- print(new ZkMkrootTool().getUsage());- print(new LinkConfigTool().getUsage());- print(new UpdateACLTool().getUsage());+ print(new ConfigSetUploadTool(runtime).getUsage());+ print(new ConfigSetDownloadTool(runtime).getUsage());+ print(new ZkMkrootTool(runtime).getUsage());+ print(new LinkConfigTool(runtime).getUsage());+ print(new UpdateACLTool(runtime).getUsage());print("");print("Pass --help or -h after any COMMAND to see command-specific usage information such as: ./solr zk ls --help");diff --git a/solr/core/src/java/org/apache/solr/packagemanager/PackageManager.java b/solr/core/src/java/org/apache/solr/packagemanager/PackageManager.javaindex 07fb72965eb..49863a74700 100644--- a/solr/core/src/java/org/apache/solr/packagemanager/PackageManager.java+++ b/solr/core/src/java/org/apache/solr/packagemanager/PackageManager.java@@ -42,6 +42,7 @@ import java.util.concurrent.TimeUnit;import java.util.stream.Collectors;import org.apache.solr.cli.CLIUtils;import org.apache.solr.cli.SolrCLI;+import org.apache.solr.cli.ToolRuntime;import org.apache.solr.client.api.util.SolrVersion;import org.apache.solr.client.solrj.SolrClient;import org.apache.solr.client.solrj.SolrRequest;@@ -75,6 +76,7 @@ import org.slf4j.LoggerFactory;/** Handles most of the management of packages that are already installed in Solr. */public class PackageManager implements Closeable {+ final ToolRuntime runtime;final String solrUrl;final SolrClient solrClient;final SolrZkClient zkClient;@@ -83,7 +85,8 @@ public class PackageManager implements Closeable {private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());- public PackageManager(SolrClient solrClient, String solrUrl, String zkHost) {+ public PackageManager(ToolRuntime runtime, SolrClient solrClient, String solrUrl, String zkHost) {+ this.runtime = runtime;this.solrUrl = solrUrl;this.solrClient = solrClient;this.zkClient =@@ -111,7 +114,7 @@ public class PackageManager implements Closeable {+ ":"+ version+ " doesn't exist. Use the install command to install this package version first.");- System.exit(1);+ runtime.exit(1);}// Make sure that this package instance is not deployed on any collection@@ -124,7 +127,7 @@ public class PackageManager implements Closeable {+ " is currently deployed on collection: "+ collection+ ". Undeploy the package with undeploy <package-name> --collections <collection1>[,<collection2>,...] before attempting to uninstall the package.");- System.exit(1);+ runtime.exit(1);}}@@ -141,7 +144,7 @@ public class PackageManager implements Closeable {+ "is currently deployed as a cluster-level plugin ("+ clusterPackageInstance.getCustomData()+ "). Undeploy the package with undeploy <package-name> --collections <collection1>[,<collection2>,...] before uninstalling the package.");- System.exit(1);+ runtime.exit(1);}}@@ -932,7 +935,7 @@ public class PackageManager implements Closeable {+ ":"+ version+ ". Use install command to install this version first.");- System.exit(1);+ runtime.exit(1);}Manifest manifest = packageInstance.manifest;@@ -942,7 +945,7 @@ public class PackageManager implements Closeable {+ SolrVersion.LATEST+ ", package version constraint: "+ manifest.versionConstraint);- System.exit(1);+ runtime.exit(1);}boolean res =diff --git a/solr/core/src/test/org/apache/solr/cli/ApiToolTest.java b/solr/core/src/test/org/apache/solr/cli/ApiToolTest.javaindex bec194ea808..c1ebe13af0e 100644--- a/solr/core/src/test/org/apache/solr/cli/ApiToolTest.java+++ b/solr/core/src/test/org/apache/solr/cli/ApiToolTest.java@@ -79,7 +79,8 @@ public class ApiToolTest extends SolrCloudTestCase {}cluster.getSolrClient().request(ur, COLLECTION_NAME);- ApiTool tool = new ApiTool();+ ToolRuntime runtime = new CLITestHelper.TestingRuntime(false);+ ApiTool tool = new ApiTool(runtime);String response =tool.callGet(diff --git a/solr/core/src/test/org/apache/solr/cli/AssertToolTest.java b/solr/core/src/test/org/apache/solr/cli/AssertToolTest.javaindex f1aeb55d1c6..9f3aa0e77a5 100644--- a/solr/core/src/test/org/apache/solr/cli/AssertToolTest.java+++ b/solr/core/src/test/org/apache/solr/cli/AssertToolTest.java@@ -16,13 +16,9 @@*/package org.apache.solr.cli;-import static org.apache.solr.cli.SolrCLI.findTool;-import static org.apache.solr.cli.SolrCLI.parseCmdLine;-import java.nio.file.Files;import java.nio.file.Path;import java.util.Set;-import org.apache.commons.cli.CommandLine;import org.apache.solr.client.solrj.impl.CloudSolrClient;import org.apache.solr.cloud.SolrCloudTestCase;import org.apache.solr.common.cloud.ZkStateReader;@@ -46,7 +42,7 @@ public class AssertToolTest extends SolrCloudTestCase {System.getSecurityManager() != null);final String[] args = new String[] {"assert", "--exitcode", "--exists", "/tmp"};- final int numAssertionsFailed = runAssertToolWithArgs(args);+ final int numAssertionsFailed = CLITestHelper.runTool(args, AssertTool.class);assertEquals("Expected AssertTool to raise an error", 100, numAssertionsFailed);}@@ -56,7 +52,7 @@ public class AssertToolTest extends SolrCloudTestCase {Path tempDir = Files.createTempDirectory("myTempDir");final String[] args = new String[] {"assert", "--exitcode", "--exists", tempDir.toString()};- final int numAssertionsFailed = runAssertToolWithArgs(args);+ final int numAssertionsFailed = CLITestHelper.runTool(args, AssertTool.class);assertEquals("Expected AssertTool to pass assertion that directory exists", 0, numAssertionsFailed);@@ -70,7 +66,7 @@ public class AssertToolTest extends SolrCloudTestCase {final String[] args =new String[] {"assert", "--exitcode", "--exists", tempDir.toString() + "/foo/bar/baz"};- final int numAssertionsFailed = runAssertToolWithArgs(args);+ final int numAssertionsFailed = CLITestHelper.runTool(args, AssertTool.class);assertEquals("Expected AssertTool to fail assertion that directory exists", 1, numAssertionsFailed);@@ -81,7 +77,7 @@ public class AssertToolTest extends SolrCloudTestCase {Path tempDir = Files.createTempDirectory("myTempDir");final String[] args = new String[] {"assert", "--exitcode", "--not-exists", tempDir.toString()};- final int numAssertionsFailed = runAssertToolWithArgs(args);+ final int numAssertionsFailed = CLITestHelper.runTool(args, AssertTool.class);assertEquals("Expected AssertTool to fail assertion that directory doesnt exist",@@ -95,7 +91,7 @@ public class AssertToolTest extends SolrCloudTestCase {final String[] args =new String[] {"assert", "--exitcode", "--not-exists", tempDir.toString() + "/foo/bar/baz"};- final int numAssertionsFailed = runAssertToolWithArgs(args);+ final int numAssertionsFailed = CLITestHelper.runTool(args, AssertTool.class);assertEquals("Expected AssertTool to fail assertion that directory doesnt exist",@@ -108,7 +104,7 @@ public class AssertToolTest extends SolrCloudTestCase {final String baseUrl = getRealSolrBaseUrl();final String[] args = new String[] {"assert", "--exitcode", "--started", baseUrl};- final int numAssertionsFailed = runAssertToolWithArgs(args);+ final int numAssertionsFailed = CLITestHelper.runTool(args, AssertTool.class);assertEquals("Expected AssertTool to pass assertion when Solr is running on provided URL",@@ -121,7 +117,7 @@ public class AssertToolTest extends SolrCloudTestCase {final String[] args =new String[] {"assert", "--exitcode", "--started", "http://www.google.com"};- final int numAssertionsFailed = runAssertToolWithArgs(args);+ final int numAssertionsFailed = CLITestHelper.runTool(args, AssertTool.class);assertEquals("Expected AssertTool to fail assertion when Solr isn't running on provided URL",@@ -134,7 +130,7 @@ public class AssertToolTest extends SolrCloudTestCase {final String baseUrl = getRealSolrBaseUrl();final String[] args = new String[] {"assert", "--exitcode", "--not-started", baseUrl};- final int numAssertionsFailed = runAssertToolWithArgs(args);+ final int numAssertionsFailed = CLITestHelper.runTool(args, AssertTool.class);assertEquals("Expected AssertTool to fail assertion when Solr is running on provided URL",@@ -147,7 +143,7 @@ public class AssertToolTest extends SolrCloudTestCase {final String[] args =new String[] {"assert", "--exitcode", "--not-started", "http://www.google.com"};- final int numAssertionsFailed = runAssertToolWithArgs(args);+ final int numAssertionsFailed = CLITestHelper.runTool(args, AssertTool.class);assertEquals("Expected AssertTool to pass assertion when Solr isn't running on provided URL",@@ -155,13 +151,6 @@ public class AssertToolTest extends SolrCloudTestCase {numAssertionsFailed);}- private int runAssertToolWithArgs(String[] args) throws Exception {- Tool tool = findTool(args);- assertTrue(tool instanceof AssertTool);- final CommandLine cli = parseCmdLine(tool, args);- return tool.runTool(cli);- }-private String getRealSolrBaseUrl() {final CloudSolrClient cloudSolrClient = cluster.getSolrClient();final Set<String> liveNodes = cloudSolrClient.getClusterState().getLiveNodes();diff --git a/solr/core/src/test/org/apache/solr/cli/AuthToolTest.java b/solr/core/src/test/org/apache/solr/cli/AuthToolTest.javaindex 8c32db28026..28d62999ced 100644--- a/solr/core/src/test/org/apache/solr/cli/AuthToolTest.java+++ b/solr/core/src/test/org/apache/solr/cli/AuthToolTest.java@@ -17,12 +17,8 @@package org.apache.solr.cli;-import static org.apache.solr.cli.SolrCLI.findTool;-import static org.apache.solr.cli.SolrCLI.parseCmdLine;-import java.nio.file.Files;import java.nio.file.Path;-import org.apache.commons.cli.CommandLine;import org.apache.commons.io.file.PathUtils;import org.apache.solr.cloud.SolrCloudTestCase;import org.junit.After;@@ -75,13 +71,6 @@ public class AuthToolTest extends SolrCloudTestCase {"--block-unknown","true"};- assertEquals(0, runTool(args));- }-- private int runTool(String[] args) throws Exception {- Tool tool = findTool(args);- assertTrue(tool instanceof AuthTool);- CommandLine cli = parseCmdLine(tool, args);- return tool.runTool(cli);+ assertEquals(0, CLITestHelper.runTool(args, AuthTool.class));}}diff --git a/solr/core/src/test/org/apache/solr/cli/CLITestHelper.java b/solr/core/src/test/org/apache/solr/cli/CLITestHelper.javanew file mode 100644index 00000000000..f1701ef9c2a--- /dev/null+++ b/solr/core/src/test/org/apache/solr/cli/CLITestHelper.java@@ -0,0 +1,141 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package org.apache.solr.cli;++import static org.apache.solr.cli.SolrCLI.findTool;+import static org.apache.solr.cli.SolrCLI.parseCmdLine;+import static org.junit.Assert.assertEquals;+import static org.junit.Assert.fail;++import java.io.PrintWriter;+import java.io.Reader;+import java.io.StringReader;+import java.io.StringWriter;+import java.lang.invoke.MethodHandles;+import org.apache.commons.cli.CommandLine;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++public class CLITestHelper {++ /**+ * Run a tool with all parameters, as specified in the command line. First parameter must be the+ * tool name.+ *+ * @param args Complete command line.+ * @param clazz Expected class name of tool implementation.+ */+ public static int runTool(String[] args, Class<?> clazz) throws Exception {+ ToolRuntime runtime = new TestingRuntime(false);+ return runTool(args, runtime, clazz);+ }++ /**+ * Run a tool with all parameters, as specified in the command line. First parameter must be the+ * tool name.+ *+ * @param args Complete command line.+ * @param runtime The runtime implementation specified to the tool. In tests, an instance of+ * {@link TestingRuntime} should be typically used for additional checks.+ * @param clazz Expected class name of tool implementation.+ */+ public static int runTool(String[] args, ToolRuntime runtime, Class<?> clazz) throws Exception {+ Tool tool = findTool(args, runtime);++ // Check the tool actual class+ assertEquals(clazz, tool.getClass());++ CommandLine cli = parseCmdLine(tool, args);+ return tool.runTool(cli);+ }++ /**+ * Runtime for test with additional validations. Mostly, we ensure tests never call {@link+ * System#exit(int)}.+ */+ public static class TestingRuntime extends ToolRuntime {+ private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());++ private final StringWriter writer;+ private final PrintWriter printer;++ public TestingRuntime(boolean captureOutput) {+ if (captureOutput) {+ writer = new StringWriter();+ printer = new PrintWriter(writer);+ } else {+ writer = null;+ printer = null;+ }+ }++ @Override+ public void print(String message) {+ // This logs with a full line, while prod code prints to System.out with no new line char+ log.info(message);++ if (printer != null) {+ printer.print(message);+ }+ }++ @Override+ public void println(String message) {+ log.info(message);++ if (printer != null) {+ printer.println(message);+ }+ }++ public void clearOutput() {+ if (printer == null) {+ fail("TestingRuntime was created without capturing output");+ }++ printer.flush();+ writer.getBuffer().setLength(0);+ }++ public String getOutput() {+ if (printer == null) {+ fail("TestingRuntime was created without capturing output");+ }++ printer.flush();+ return writer.toString();+ }++ public Reader getReader() {+ if (printer == null) {+ fail("TestingRuntime was created without capturing output");+ }++ return new StringReader(writer.toString());+ }++ /**+ * Do not allow to exit the JMV in unit tests!+ *+ * @param status JVM return code.+ */+ @Override+ public void exit(int status) {+ throw new RuntimeException("exit() not allowed in tests");+ }+ }+}diff --git a/solr/core/src/test/org/apache/solr/cli/CreateToolTest.java b/solr/core/src/test/org/apache/solr/cli/CreateToolTest.javaindex 7b4da6f9901..74c9a641166 100644--- a/solr/core/src/test/org/apache/solr/cli/CreateToolTest.java+++ b/solr/core/src/test/org/apache/solr/cli/CreateToolTest.java@@ -17,10 +17,6 @@package org.apache.solr.cli;-import static org.apache.solr.cli.SolrCLI.findTool;-import static org.apache.solr.cli.SolrCLI.parseCmdLine;--import org.apache.commons.cli.CommandLine;import org.apache.solr.cloud.SolrCloudTestCase;import org.apache.solr.util.SecurityJson;import org.junit.BeforeClass;@@ -54,13 +50,6 @@ public class CreateToolTest extends SolrCloudTestCase {"--verbose"};- assertEquals(0, runTool(args));- }-- private int runTool(String[] args) throws Exception {- Tool tool = findTool(args);- assertTrue(tool instanceof CreateTool);- CommandLine cli = parseCmdLine(tool, args);- return tool.runTool(cli);+ assertEquals(0, CLITestHelper.runTool(args, CreateTool.class));}}diff --git a/solr/core/src/test/org/apache/solr/cli/DeleteToolTest.java b/solr/core/src/test/org/apache/solr/cli/DeleteToolTest.javaindex 45c48697663..c0444b82009 100644--- a/solr/core/src/test/org/apache/solr/cli/DeleteToolTest.java+++ b/solr/core/src/test/org/apache/solr/cli/DeleteToolTest.java@@ -17,10 +17,6 @@package org.apache.solr.cli;-import static org.apache.solr.cli.SolrCLI.findTool;-import static org.apache.solr.cli.SolrCLI.parseCmdLine;--import org.apache.commons.cli.CommandLine;import org.apache.solr.client.solrj.SolrRequest;import org.apache.solr.client.solrj.SolrResponse;import org.apache.solr.client.solrj.request.CollectionAdminRequest;@@ -66,7 +62,7 @@ public class DeleteToolTest extends SolrCloudTestCase {SecurityJson.USER_PASS,"--verbose"};- assertEquals(0, runTool(args));+ assertEquals(0, CLITestHelper.runTool(args, DeleteTool.class));}@Test@@ -89,13 +85,6 @@ public class DeleteToolTest extends SolrCloudTestCase {cluster.getZkClient().getZkServerAddress(),"--verbose"};- assertEquals(1, runTool(args));- }-- private int runTool(String[] args) throws Exception {- Tool tool = findTool(args);- assertTrue(tool instanceof DeleteTool);- CommandLine cli = parseCmdLine(tool, args);- return tool.runTool(cli);+ assertEquals(1, CLITestHelper.runTool(args, DeleteTool.class));}}diff --git a/solr/core/src/test/org/apache/solr/cli/HealthcheckToolTest.java b/solr/core/src/test/org/apache/solr/cli/HealthcheckToolTest.javaindex a0f3263207d..429777afaf4 100644--- a/solr/core/src/test/org/apache/solr/cli/HealthcheckToolTest.java+++ b/solr/core/src/test/org/apache/solr/cli/HealthcheckToolTest.java@@ -17,11 +17,7 @@package org.apache.solr.cli;-import static org.apache.solr.cli.SolrCLI.findTool;-import static org.apache.solr.cli.SolrCLI.parseCmdLine;-import java.util.Set;-import org.apache.commons.cli.CommandLine;import org.apache.solr.client.solrj.impl.CloudSolrClient;import org.apache.solr.client.solrj.request.CollectionAdminRequest;import org.apache.solr.cloud.SolrCloudTestCase;@@ -48,7 +44,7 @@ public class HealthcheckToolTest extends SolrCloudTestCase {String[] args =new String[] {"healthcheck", "-c", "bob", "-z", cluster.getZkClient().getZkServerAddress()};- assertEquals(0, runTool(args));+ assertEquals(0, CLITestHelper.runTool(args, HealthcheckTool.class));}@Test@@ -60,7 +56,7 @@ public class HealthcheckToolTest extends SolrCloudTestCase {ZkStateReader.from(cluster.getSolrClient()).getBaseUrlForNodeName(firstLiveNode);String[] args = new String[] {"healthcheck", "-c", "bob", "--solr-url", solrUrl};- assertEquals(0, runTool(args));+ assertEquals(0, CLITestHelper.runTool(args, HealthcheckTool.class));}@Test@@ -74,13 +70,6 @@ public class HealthcheckToolTest extends SolrCloudTestCase {solrUrl = solrUrl.substring(0, solrUrl.indexOf("/solr"));String[] args = new String[] {"healthcheck", "-c", "bob", "--solr-url", solrUrl};- assertEquals(0, runTool(args));- }-- private int runTool(String[] args) throws Exception {- Tool tool = findTool(args);- assertTrue(tool instanceof HealthcheckTool);- CommandLine cli = parseCmdLine(tool, args);- return tool.runTool(cli);+ assertEquals(0, CLITestHelper.runTool(args, HealthcheckTool.class));}}diff --git a/solr/core/src/test/org/apache/solr/cli/PackageToolTest.java b/solr/core/src/test/org/apache/solr/cli/PackageToolTest.javaindex fa75ba3206e..e7a59053a81 100644--- a/solr/core/src/test/org/apache/solr/cli/PackageToolTest.java+++ b/solr/core/src/test/org/apache/solr/cli/PackageToolTest.java@@ -94,7 +94,8 @@ public class PackageToolTest extends SolrCloudTestCase {@Testpublic void testPackageTool() throws Exception {- PackageTool tool = new PackageTool();+ ToolRuntime runtime = new CLITestHelper.TestingRuntime(false);+ PackageTool tool = new PackageTool(runtime);String solrUrl = cluster.getJettySolrRunner(0).getBaseUrl().toString();@@ -355,7 +356,8 @@ public class PackageToolTest extends SolrCloudTestCase {boolean success = false;- ApiTool apiTool = new ApiTool();+ ToolRuntime runtime = new CLITestHelper.TestingRuntime(false);+ ApiTool apiTool = new ApiTool(runtime);String response = apiTool.callGet(testServerBaseUrl + uri, credentials);LinkedHashMapWriter m =diff --git a/solr/core/src/test/org/apache/solr/cli/PostToolTest.java b/solr/core/src/test/org/apache/solr/cli/PostToolTest.javaindex 758ae9ccd51..4783cacf1f7 100644--- a/solr/core/src/test/org/apache/solr/cli/PostToolTest.java+++ b/solr/core/src/test/org/apache/solr/cli/PostToolTest.java@@ -17,9 +17,6 @@package org.apache.solr.cli;-import static org.apache.solr.cli.SolrCLI.findTool;-import static org.apache.solr.cli.SolrCLI.parseCmdLine;-import java.io.ByteArrayInputStream;import java.io.File;import java.io.FileWriter;@@ -35,7 +32,6 @@ import java.util.HashMap;import java.util.HashSet;import java.util.Map;import java.util.Set;-import org.apache.commons.cli.CommandLine;import org.apache.solr.SolrTestCaseJ4;import org.apache.solr.client.solrj.SolrRequest;import org.apache.solr.client.solrj.SolrResponse;@@ -93,7 +89,7 @@ public class PostToolTest extends SolrCloudTestCase {SecurityJson.USER_PASS,jsonDoc.getAbsolutePath()};- assertEquals(0, runTool(args));+ assertEquals(0, CLITestHelper.runTool(args, PostTool.class));int numFound = 0;int expectedDocCount = 1;@@ -130,7 +126,7 @@ public class PostToolTest extends SolrCloudTestCase {String[] args = {"post", "-c", collection, "--credentials", SecurityJson.USER_PASS, jsonDoc.getAbsolutePath()};- assertEquals(0, runTool(args));+ assertEquals(0, CLITestHelper.runTool(args, PostTool.class));int numFound = 0;int expectedDocCount = 1;@@ -176,7 +172,7 @@ public class PostToolTest extends SolrCloudTestCase {"text/csv",tsvDoc.getAbsolutePath()};- assertEquals(0, runTool(args));+ assertEquals(0, CLITestHelper.runTool(args, PostTool.class));int numFound = 0;int expectedDocCount = 1;@@ -194,13 +190,6 @@ public class PostToolTest extends SolrCloudTestCase {assertEquals("*:* found unexpected number of documents", expectedDocCount, numFound);}- private int runTool(String[] args) throws Exception {- Tool tool = findTool(args);- assertTrue(tool instanceof PostTool);- CommandLine cli = parseCmdLine(tool, args);- return tool.runTool(cli);- }-@Testpublic void testNormalizeUrlEnding() {assertEquals("http://[ff01::114]", PostTool.normalizeUrlEnding("http://[ff01::114]/"));@@ -235,7 +224,8 @@ public class PostToolTest extends SolrCloudTestCase {@Testpublic void testTypeSupported() {- PostTool postTool = new PostTool();+ CLITestHelper.TestingRuntime runtime = new CLITestHelper.TestingRuntime(false);+ PostTool postTool = new PostTool(runtime);assertTrue(postTool.typeSupported("application/pdf"));assertTrue(postTool.typeSupported("application/xml"));@@ -290,7 +280,8 @@ public class PostToolTest extends SolrCloudTestCase {@Testpublic void testDoFilesMode() throws IOException {- PostTool postTool = new PostTool();+ ToolRuntime runtime = new CLITestHelper.TestingRuntime(false);+ PostTool postTool = new PostTool(runtime);postTool.recursive = 0;postTool.dryRun = true;postTool.solrUpdateUrl = URI.create("http://localhost:8983/solr/fake/update");@@ -302,7 +293,8 @@ public class PostToolTest extends SolrCloudTestCase {@Testpublic void testDetectingIfRecursionPossibleInFilesMode() throws IOException {- PostTool postTool = new PostTool();+ ToolRuntime runtime = new CLITestHelper.TestingRuntime(false);+ PostTool postTool = new PostTool(runtime);postTool.recursive = 1; // This is the defaultFile dir = getFile("exampledocs").toFile();File doc = File.createTempFile("temp", ".json");@@ -313,7 +305,8 @@ public class PostToolTest extends SolrCloudTestCase {@Testpublic void testRecursionAppliesToFilesMode() throws IOException {- PostTool postTool = new PostTool();+ ToolRuntime runtime = new CLITestHelper.TestingRuntime(false);+ PostTool postTool = new PostTool(runtime);postTool.recursive = 1; // This is the defaultpostTool.dryRun = true;postTool.solrUpdateUrl = URI.create("http://localhost:8983/solr/fake/update");@@ -325,8 +318,9 @@ public class PostToolTest extends SolrCloudTestCase {@Testpublic void testDoWebMode() throws IOException, URISyntaxException {- PostTool postTool = new PostTool();- postTool.pageFetcher = new MockPageFetcher();+ ToolRuntime runtime = new CLITestHelper.TestingRuntime(false);+ PostTool postTool = new PostTool(runtime);+ postTool.pageFetcher = new MockPageFetcher(runtime);postTool.dryRun = true;postTool.solrUpdateUrl = URI.create("http://user:password@localhost:5150/solr/fake/update");@@ -349,8 +343,9 @@ public class PostToolTest extends SolrCloudTestCase {@Testpublic void testRobotsExclusion() throws IOException, URISyntaxException {- PostTool postTool = new PostTool();- postTool.pageFetcher = new MockPageFetcher();+ ToolRuntime runtime = new CLITestHelper.TestingRuntime(false);+ PostTool postTool = new PostTool(runtime);+ postTool.pageFetcher = new MockPageFetcher(runtime);postTool.dryRun = true;assertFalse(@@ -368,8 +363,8 @@ public class PostToolTest extends SolrCloudTestCase {HashMap<String, String> htmlMap = new HashMap<>();HashMap<String, Set<URI>> linkMap = new HashMap<>();- public MockPageFetcher() throws IOException, URISyntaxException {- (new PostTool()).super();+ public MockPageFetcher(ToolRuntime runtime) throws IOException, URISyntaxException {+ (new PostTool(runtime)).super();htmlMap.put("http://[ff01::114]","<html><body><a href=\"http://[ff01::114]/page1\">page1</a><a href=\"http://[ff01::114]/page2\">page2</a></body></html>");diff --git a/solr/core/src/test/org/apache/solr/cli/SolrCLIZkToolsTest.java b/solr/core/src/test/org/apache/solr/cli/SolrCLIZkToolsTest.javaindex 6644acde895..75ab1e96150 100644--- a/solr/core/src/test/org/apache/solr/cli/SolrCLIZkToolsTest.java+++ b/solr/core/src/test/org/apache/solr/cli/SolrCLIZkToolsTest.java@@ -17,10 +17,8 @@package org.apache.solr.cli;-import java.io.ByteArrayOutputStream;import java.io.File;import java.io.IOException;-import java.io.PrintStream;import java.nio.charset.StandardCharsets;import java.nio.file.FileVisitResult;import java.nio.file.Files;@@ -86,20 +84,27 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {File confDir = new File(configSet.toFile(), "cloud-subdirs");String[] args =new String[] {- "--conf-name", "upconfig2", "--conf-dir", confDir.getAbsolutePath(), "-z", zkAddr+ "upconfig",+ "--conf-name",+ "upconfig2",+ "--conf-dir",+ confDir.getAbsolutePath(),+ "-z",+ zkAddr};- ConfigSetUploadTool tool = new ConfigSetUploadTool();-- int res = tool.runTool(SolrCLI.processCommandLineArgs(tool, args));+ int res = CLITestHelper.runTool(args, ConfigSetUploadTool.class);assertEquals("tool should have returned 0 for success ", 0, res);// Now do we have that config up on ZK?verifyZkLocalPathsMatch(srcPathCheck, "/configs/upconfig2");// do we barf on a bogus path?- args = new String[] {"--conf-name", "upconfig3", "--conf-dir", "nothinghere", "-z", zkAddr};+ args =+ new String[] {+ "upconfig", "--conf-name", "upconfig3", "--conf-dir", "nothinghere", "-z", zkAddr+ };- res = tool.runTool(SolrCLI.processCommandLineArgs(tool, args));+ res = CLITestHelper.runTool(args, ConfigSetUploadTool.class);assertTrue("tool should have returned non-zero for failure ", 0 != res);String content =@@ -125,11 +130,16 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {String[] args =new String[] {- "--conf-name", "downconfig1", "--conf-dir", tmp.toAbsolutePath().toString(), "-z", zkAddr,+ "downconfig",+ "--conf-name",+ "downconfig1",+ "--conf-dir",+ tmp.toAbsolutePath().toString(),+ "-z",+ zkAddr,};- ConfigSetDownloadTool downTool = new ConfigSetDownloadTool();- int res = downTool.runTool(SolrCLI.processCommandLineArgs(downTool, args));+ int res = CLITestHelper.runTool(args, ConfigSetDownloadTool.class);assertEquals("Download should have succeeded.", 0, res);verifyZkLocalPathsMatch(Paths.get(tmp.toAbsolutePath().toString(), "conf"), "/configs/downconfig1");@@ -142,9 +152,9 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {// Now copy it up and back and insure it's still a file in the new placeAbstractDistribZkTestBase.copyConfigUp(tmp.getParent(), "myconfset", "downconfig2", zkAddr);Path tmp2 = createTempDir("downConfigNewPlace2");- downTool = new ConfigSetDownloadTool();args =new String[] {+ "downconfig","--conf-name","downconfig2","--conf-dir",@@ -153,7 +163,7 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {zkAddr,};- res = downTool.runTool(SolrCLI.processCommandLineArgs(downTool, args));+ res = CLITestHelper.runTool(args, ConfigSetDownloadTool.class);assertEquals("Download should have succeeded.", 0, res);verifyZkLocalPathsMatch(Paths.get(tmp.toAbsolutePath().toString(), "conf"), "/configs/downconfig2");@@ -172,11 +182,10 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {AbstractDistribZkTestBase.copyConfigUp(configSet, "cloud-subdirs", "cp1", zkAddr);// Now copy it somewhere else on ZK.- String[] args = new String[] {"--recursive", "--zk-host", zkAddr, "zk:/configs/cp1", "zk:/cp2"};-- ZkCpTool cpTool = new ZkCpTool();+ String[] args =+ new String[] {"cp", "--recursive", "--zk-host", zkAddr, "zk:/configs/cp1", "zk:/cp2"};- int res = cpTool.runTool(SolrCLI.processCommandLineArgs(cpTool, args));+ int res = CLITestHelper.runTool(args, ZkCpTool.class);assertEquals("Copy from zk -> zk should have succeeded.", 0, res);verifyZnodesMatch("/configs/cp1", "/cp2");@@ -184,10 +193,15 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {Path tmp = createTempDir("tmpNewPlace2");args =new String[] {- "--recursive", "--zk-host", zkAddr, "zk:/configs/cp1", "file:" + tmp.toAbsolutePath()+ "cp",+ "--recursive",+ "--zk-host",+ zkAddr,+ "zk:/configs/cp1",+ "file:" + tmp.toAbsolutePath()};- res = cpTool.runTool(SolrCLI.processCommandLineArgs(cpTool, args));+ res = CLITestHelper.runTool(args, ZkCpTool.class);assertEquals("Copy should have succeeded.", 0, res);verifyZkLocalPathsMatch(tmp, "/configs/cp1");@@ -195,38 +209,55 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {tmp = createTempDir("tmpNewPlace3");args =new String[] {- "--recursive", "--zk-host", zkAddr, "zk:/configs/cp1", tmp.toAbsolutePath().toString()+ "cp",+ "--recursive",+ "--zk-host",+ zkAddr,+ "zk:/configs/cp1",+ tmp.toAbsolutePath().toString()};- res = cpTool.runTool(SolrCLI.processCommandLineArgs(cpTool, args));+ res = CLITestHelper.runTool(args, ZkCpTool.class);assertEquals("Copy should have succeeded.", 0, res);verifyZkLocalPathsMatch(tmp, "/configs/cp1");// try with local->zkargs =new String[] {- "--recursive", "--zk-host", zkAddr, srcPathCheck.toAbsolutePath().toString(), "zk:/cp3"+ "cp",+ "--recursive",+ "--zk-host",+ zkAddr,+ srcPathCheck.toAbsolutePath().toString(),+ "zk:/cp3"};- res = cpTool.runTool(SolrCLI.processCommandLineArgs(cpTool, args));+ res = CLITestHelper.runTool(args, ZkCpTool.class);assertEquals("Copy should have succeeded.", 0, res);verifyZkLocalPathsMatch(srcPathCheck, "/cp3");// try with local->zk, file: specifiedargs =new String[] {- "--recursive", "--zk-host", zkAddr, "file:" + srcPathCheck.toAbsolutePath(), "zk:/cp4"+ "cp",+ "--recursive",+ "--zk-host",+ zkAddr,+ "file:" + srcPathCheck.toAbsolutePath(),+ "zk:/cp4"};- res = cpTool.runTool(SolrCLI.processCommandLineArgs(cpTool, args));+ res = CLITestHelper.runTool(args, ZkCpTool.class);assertEquals("Copy should have succeeded.", 0, res);verifyZkLocalPathsMatch(srcPathCheck, "/cp4");// try with recursive not specified, and therefore not happeningargs =- new String[] {"--zk-host", zkAddr, "file:" + srcPathCheck.toAbsolutePath(), "zk:/cp5Fail"};+ new String[] {+ "cp", "--zk-host", zkAddr, "file:" + srcPathCheck.toAbsolutePath(), "zk:/cp5Fail"+ };- res = cpTool.runTool(SolrCLI.processCommandLineArgs(cpTool, args));+ res = CLITestHelper.runTool(args, ZkCpTool.class);assertTrue("Copy should NOT have succeeded, recursive not specified.", 0 != res);// NOTE: really can't test copying to '.' because the test framework doesn't allow altering the@@ -235,9 +266,9 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {// copy to local ending in separator// src and cp3 and cp4 are validString localSlash = tmp.normalize() + File.separator + "cpToLocal" + File.separator;- args = new String[] {"--zk-host", zkAddr, "zk:/cp3/schema.xml", localSlash};+ args = new String[] {"cp", "--zk-host", zkAddr, "zk:/cp3/schema.xml", localSlash};- res = cpTool.runTool(SolrCLI.processCommandLineArgs(cpTool, args));+ res = CLITestHelper.runTool(args, ZkCpTool.class);assertEquals("Copy should nave created intermediate directory locally.", 0, res);assertTrue("File should have been copied to a directory successfully",@@ -247,13 +278,14 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {// src and cp3 are validargs =new String[] {+ "cp","--zk-host",zkAddr,"file:" + srcPathCheck.normalize().toAbsolutePath() + File.separator + "solrconfig.xml","zk:/powerup/"};- res = cpTool.runTool(SolrCLI.processCommandLineArgs(cpTool, args));+ res = CLITestHelper.runTool(args, ZkCpTool.class);assertEquals("Copy up to intermediate file should have succeeded.", 0, res);assertTrue("Should have created an intermediate node on ZK",@@ -263,13 +295,14 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {// src and cp3 are validargs =new String[] {+ "cp","--zk-host",zkAddr,"file:" + srcPathCheck.normalize().toAbsolutePath() + File.separator + "solrconfig.xml","zk:/copyUpFile.xml"};- res = cpTool.runTool(SolrCLI.processCommandLineArgs(cpTool, args));+ res = CLITestHelper.runTool(args, ZkCpTool.class);assertEquals("Copy up to named file should have succeeded.", 0, res);assertTrue("Should NOT have created an intermediate node on ZK",@@ -280,9 +313,9 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {String localNamed =tmp.normalize() + File.separator + "localnamed" + File.separator + "renamed.txt";- args = new String[] {"--zk-host", zkAddr, "zk:/cp4/solrconfig.xml", "file:" + localNamed};+ args = new String[] {"cp", "--zk-host", zkAddr, "zk:/cp4/solrconfig.xml", "file:" + localNamed};- res = cpTool.runTool(SolrCLI.processCommandLineArgs(cpTool, args));+ res = CLITestHelper.runTool(args, ZkCpTool.class);assertEquals("Copy to local named file should have succeeded.", 0, res);Path locPath = Paths.get(localNamed);assertTrue("Should have found file: " + localNamed, Files.exists(locPath));@@ -298,9 +331,9 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {assertTrue("Should have found Apache Software Foundation in the file! ", foundApache);// Test copy from somwehere in ZK to the root of ZK.- args = new String[] {"--zk-host", zkAddr, "zk:/cp4/solrconfig.xml", "zk:/"};+ args = new String[] {"cp", "--zk-host", zkAddr, "zk:/cp4/solrconfig.xml", "zk:/"};- res = cpTool.runTool(SolrCLI.processCommandLineArgs(cpTool, args));+ res = CLITestHelper.runTool(args, ZkCpTool.class);assertEquals("Copy from somewhere in ZK to ZK root should have succeeded.", 0, res);assertTrue("Should have found znode /solrconfig.xml: ", zkClient.exists("/solrconfig.xml", true));@@ -309,10 +342,15 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {// source path to the dstargs =new String[] {- "--recursive", "--zk-host", zkAddr, "file:" + srcPathCheck.toAbsolutePath(), "zk:/cp7/"+ "cp",+ "--recursive",+ "--zk-host",+ zkAddr,+ "file:" + srcPathCheck.toAbsolutePath(),+ "zk:/cp7/"};- res = cpTool.runTool(SolrCLI.processCommandLineArgs(cpTool, args));+ res = CLITestHelper.runTool(args, ZkCpTool.class);assertEquals("Copy should have succeeded.", 0, res);verifyZkLocalPathsMatch(srcPathCheck, "/cp7/" + srcPathCheck.getFileName().toString());@@ -325,10 +363,10 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {// First, just copy the data up the cp7 since it's a directory.args =new String[] {- "--zk-host", zkAddr, "file:" + file.toAbsolutePath(), "zk:/cp7/conf/stopwords/"+ "cp", "--zk-host", zkAddr, "file:" + file.toAbsolutePath(), "zk:/cp7/conf/stopwords/"};- res = cpTool.runTool(SolrCLI.processCommandLineArgs(cpTool, args));+ res = CLITestHelper.runTool(args, ZkCpTool.class);assertEquals("Copy should have succeeded.", 0, res);String content =@@ -336,15 +374,15 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {zkClient.getData("/cp7/conf/stopwords", null, null, true), StandardCharsets.UTF_8);assertTrue("There should be content in the node! ", content.contains("{Some Arbitrary Data}"));- res = cpTool.runTool(SolrCLI.processCommandLineArgs(cpTool, args));+ res = CLITestHelper.runTool(args, ZkCpTool.class);assertEquals("Copy should have succeeded.", 0, res);tmp = createTempDir("cp8");args =new String[] {- "--recursive", "--zk-host", zkAddr, "zk:/cp7", "file:" + tmp.toAbsolutePath()+ "cp", "--recursive", "--zk-host", zkAddr, "zk:/cp7", "file:" + tmp.toAbsolutePath()};- res = cpTool.runTool(SolrCLI.processCommandLineArgs(cpTool, args));+ res = CLITestHelper.runTool(args, ZkCpTool.class);assertEquals("Copy should have succeeded.", 0, res);// Next, copy cp7 down and verify that zknode.data exists for cp7@@ -354,10 +392,10 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {// Finally, copy up to cp8 and verify that the data is up there.args =new String[] {- "--recursive", "--zk-host", zkAddr, "file:" + tmp.toAbsolutePath(), "zk:/cp9"+ "cp", "--recursive", "--zk-host", zkAddr, "file:" + tmp.toAbsolutePath(), "zk:/cp9"};- res = cpTool.runTool(SolrCLI.processCommandLineArgs(cpTool, args));+ res = CLITestHelper.runTool(args, ZkCpTool.class);assertEquals("Copy should have succeeded.", 0, res);content =@@ -371,25 +409,27 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {args =new String[] {+ "cp","--zk-host",zkAddr,"file:" + emptyFile.toAbsolutePath(),"zk:/cp7/conf/stopwords/emptyfile"};- res = cpTool.runTool(SolrCLI.processCommandLineArgs(cpTool, args));+ res = CLITestHelper.runTool(args, ZkCpTool.class);assertEquals("Copy should have succeeded.", 0, res);Path tmp2 = createTempDir("cp9");Path emptyDest = Paths.get(tmp2.toAbsolutePath().toString(), "emptyfile");args =new String[] {+ "cp","--zk-host",zkAddr,"zk:/cp7/conf/stopwords/emptyfile","file:" + emptyDest.toAbsolutePath()};- res = cpTool.runTool(SolrCLI.processCommandLineArgs(cpTool, args));+ res = CLITestHelper.runTool(args, ZkCpTool.class);assertEquals("Copy should have succeeded.", 0, res);assertTrue("Empty files should NOT be copied down as directories", emptyDest.toFile().isFile());@@ -398,6 +438,7 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {args =new String[] {+ "cp","--recursive","--zk-host",zkAddr,@@ -405,16 +446,16 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {"zk:/cp10"};- res = cpTool.runTool(SolrCLI.processCommandLineArgs(cpTool, args));+ res = CLITestHelper.runTool(args, ZkCpTool.class);assertEquals("Copy should have succeeded.", 0, res);// Now copy it all back and make sure empty file is still a file when recursively copying.tmp2 = createTempDir("cp10");args =new String[] {- "--recursive", "--zk-host", zkAddr, "zk:/cp10", "file:" + tmp2.toAbsolutePath()+ "cp", "--recursive", "--zk-host", zkAddr, "zk:/cp10", "file:" + tmp2.toAbsolutePath()};- res = cpTool.runTool(SolrCLI.processCommandLineArgs(cpTool, args));+ res = CLITestHelper.runTool(args, ZkCpTool.class);assertEquals("Copy should have succeeded.", 0, res);Path locEmpty = Paths.get(tmp2.toAbsolutePath().toString(), "stopwords", "emptyfile");@@ -432,11 +473,9 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {AbstractDistribZkTestBase.copyConfigUp(configSet, "cloud-subdirs", "mv1", zkAddr);// Now move it somewhere else.- String[] args = new String[] {"--zk-host", zkAddr, "zk:/configs/mv1", "zk:/mv2"};+ String[] args = new String[] {"mv", "--zk-host", zkAddr, "zk:/configs/mv1", "zk:/mv2"};- ZkMvTool mvTool = new ZkMvTool();-- int res = mvTool.runTool(SolrCLI.processCommandLineArgs(mvTool, args));+ int res = CLITestHelper.runTool(args, ZkMvTool.class);assertEquals("Move should have succeeded.", 0, res);// Now does the moved directory match the original on disk?@@ -446,16 +485,16 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {// Files are in mv2// Now fail if we specify "file:". Everything should still be in /mv2- args = new String[] {"--zk-host", zkAddr, "file:" + File.separator + "mv2", "/mv3"};+ args = new String[] {"mv", "--zk-host", zkAddr, "file:" + File.separator + "mv2", "/mv3"};// Still in mv2- res = mvTool.runTool(SolrCLI.processCommandLineArgs(mvTool, args));+ res = CLITestHelper.runTool(args, ZkMvTool.class);assertTrue("Move should NOT have succeeded with file: specified.", 0 != res);// Let's move it to yet another place with no zk: prefix.- args = new String[] {"--zk-host", zkAddr, "/mv2", "/mv4"};+ args = new String[] {"mv", "--zk-host", zkAddr, "/mv2", "/mv4"};- res = mvTool.runTool(SolrCLI.processCommandLineArgs(mvTool, args));+ res = CLITestHelper.runTool(args, ZkMvTool.class);assertEquals("Move should have succeeded.", 0, res);assertFalse("Znode /mv3 really should be gone", zkClient.exists("/mv3", true));@@ -463,9 +502,9 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {// Now does the moved directory match the original on disk?verifyZkLocalPathsMatch(srcPathCheck, "/mv4");- args = new String[] {"-z", zkAddr, "/mv4/solrconfig.xml", "/testmvsingle/solrconfig.xml"};+ args = new String[] {"mv", "-z", zkAddr, "/mv4/solrconfig.xml", "/testmvsingle/solrconfig.xml"};- res = mvTool.runTool(SolrCLI.processCommandLineArgs(mvTool, args));+ res = CLITestHelper.runTool(args, ZkMvTool.class);assertEquals("Move should have succeeded.", 0, res);assertTrue("Should be able to move a single file",@@ -474,9 +513,9 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {zkClient.makePath("/parentNode", true);// what happens if the destination ends with a slash?- args = new String[] {"--zk-host", zkAddr, "/mv4/schema.xml", "/parentnode/"};+ args = new String[] {"mv", "--zk-host", zkAddr, "/mv4/schema.xml", "/parentnode/"};- res = mvTool.runTool(SolrCLI.processCommandLineArgs(mvTool, args));+ res = CLITestHelper.runTool(args, ZkMvTool.class);assertEquals("Move should have succeeded.", 0, res);assertTrue("Should be able to move a single file to a parent znode",@@ -496,61 +535,64 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {AbstractDistribZkTestBase.copyConfigUp(configSet, "cloud-subdirs", "lister", zkAddr);// Should only find a single level.- String[] args = new String[] {"--zk-host", zkAddr, "/configs"};+ String[] args = new String[] {"ls", "--zk-host", zkAddr, "/configs"};- ByteArrayOutputStream baos = new ByteArrayOutputStream();- PrintStream ps = new PrintStream(baos, false, StandardCharsets.UTF_8.name());- ZkLsTool tool = new ZkLsTool(ps);+ CLITestHelper.TestingRuntime runtime = new CLITestHelper.TestingRuntime(true);- int res = tool.runTool(SolrCLI.processCommandLineArgs(tool, args));- String content = baos.toString(StandardCharsets.UTF_8);+ int res = CLITestHelper.runTool(args, runtime, ZkLsTool.class);+ String content = runtime.getOutput();assertEquals("List should have succeeded", res, 0);assertTrue("Return should contain the conf directory", content.contains("lister"));assertFalse("Return should NOT contain a child node", content.contains("solrconfig.xml"));// simple ls with no recursion- args = new String[] {"--zk-host", zkAddr, "/configs"};+ args = new String[] {"ls", "--zk-host", zkAddr, "/configs"};- res = tool.runTool(SolrCLI.processCommandLineArgs(tool, args));- content = baos.toString(StandardCharsets.UTF_8);+ runtime.clearOutput();+ res = CLITestHelper.runTool(args, runtime, ZkLsTool.class);+ content = runtime.getOutput();assertEquals("List should have succeeded", res, 0);assertTrue("Return should contain the conf directory", content.contains("lister"));assertFalse("Return should NOT contain a child node", content.contains("solrconfig.xml"));// ls with recursion- args = new String[] {"--recursive", "--zk-host", zkAddr, "/configs"};+ args = new String[] {"ls", "--recursive", "--zk-host", zkAddr, "/configs"};- res = tool.runTool(SolrCLI.processCommandLineArgs(tool, args));- content = baos.toString(StandardCharsets.UTF_8);+ runtime.clearOutput();+ res = CLITestHelper.runTool(args, runtime, ZkLsTool.class);+ content = runtime.getOutput();assertEquals("List should have succeeded", res, 0);assertTrue("Return should contain the conf directory", content.contains("lister"));assertTrue("Return should contain a child node", content.contains("solrconfig.xml"));// Saw a case where going from root didn't work, so test it.- args = new String[] {"--recursive", "--zk-host", zkAddr, "/"};+ args = new String[] {"ls", "--recursive", "--zk-host", zkAddr, "/"};- res = tool.runTool(SolrCLI.processCommandLineArgs(tool, args));- content = baos.toString(StandardCharsets.UTF_8);+ runtime.clearOutput();+ res = CLITestHelper.runTool(args, runtime, ZkLsTool.class);+ content = runtime.getOutput();assertEquals("List should have succeeded", res, 0);assertTrue("Return should contain the conf directory", content.contains("lister"));assertTrue("Return should contain a child node", content.contains("solrconfig.xml"));- args = new String[] {"--zk-host", zkAddr, "/"};+ args = new String[] {"ls", "--zk-host", zkAddr, "/"};- res = tool.runTool(SolrCLI.processCommandLineArgs(tool, args));- content = baos.toString(StandardCharsets.UTF_8);+ runtime.clearOutput();+ res = CLITestHelper.runTool(args, runtime, ZkLsTool.class);+ content = runtime.getOutput();assertEquals("List should have succeeded", res, 0);assertFalse("Return should not contain /zookeeper", content.contains("/zookeeper"));// Saw a case where ending in slash didn't work, so test it.- args = new String[] {"--recursive", "--zk-host", zkAddr, "/configs/"};+ args = new String[] {"ls", "--recursive", "--zk-host", zkAddr, "/configs/"};- res = tool.runTool(SolrCLI.processCommandLineArgs(tool, args));- content = baos.toString(StandardCharsets.UTF_8);+ runtime.clearOutput();+ res = CLITestHelper.runTool(args, runtime, ZkLsTool.class);+ content = runtime.getOutput();assertEquals("List should have succeeded", res, 0);assertTrue("Return should contain the conf directory", content.contains("lister"));@@ -567,11 +609,9 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {AbstractDistribZkTestBase.copyConfigUp(configSet, "cloud-subdirs", "rm2", zkAddr);// Should fail if recursive not set.- String[] args = new String[] {"--zk-host", zkAddr, "/configs/rm1"};-- ZkRmTool tool = new ZkRmTool();+ String[] args = new String[] {"rm", "--zk-host", zkAddr, "/configs/rm1"};- int res = tool.runTool(SolrCLI.processCommandLineArgs(tool, args));+ int res = CLITestHelper.runTool(args, ZkRmTool.class);assertTrue("Should have failed to remove node with children unless --recursive is set", res != 0);@@ -580,33 +620,33 @@ public class SolrCLIZkToolsTest extends SolrCloudTestCase {verifyZkLocalPathsMatch(srcPathCheck, "/configs/rm1");// run without recursive specified- args = new String[] {"--zk-host", zkAddr, "zk:/configs/rm1"};+ args = new String[] {"rm", "--zk-host", zkAddr, "zk:/configs/rm1"};- res = tool.runTool(SolrCLI.processCommandLineArgs(tool, args));+ res = CLITestHelper.runTool(args, ZkRmTool.class);assertTrue("Should have failed to remove node with children if --recursive is set to false", res != 0);- args = new String[] {"--recursive", "--zk-host", zkAddr, "/configs/rm1"};+ args = new String[] {"rm", "--recursive", "--zk-host", zkAddr, "/configs/rm1"};- res = tool.runTool(SolrCLI.processCommandLineArgs(tool, args));+ res = CLITestHelper.runTool(args, ZkRmTool.class);assertEquals("Should have removed node /configs/rm1", res, 0);assertFalse("Znode /configs/toremove really should be gone", zkClient.exists("/configs/rm1", true));// Check that zk prefix also works.- args = new String[] {"--recursive", "--zk-host", zkAddr, "zk:/configs/rm2"};+ args = new String[] {"rm", "--recursive", "--zk-host", zkAddr, "zk:/configs/rm2"};- res = tool.runTool(SolrCLI.processCommandLineArgs(tool, args));+ res = CLITestHelper.runTool(args, ZkRmTool.class);assertEquals("Should have removed node /configs/rm2", res, 0);assertFalse("Znode /configs/toremove2 really should be gone", zkClient.exists("/configs/rm2", true));// This should silently just refuse to do anything to the / or /zookeeper- args = new String[] {"--recursive", "--zk-host", zkAddr, "zk:/"};+ args = new String[] {"rm", "--recursive", "--zk-host", zkAddr, "zk:/"};AbstractDistribZkTestBase.copyConfigUp(configSet, "cloud-subdirs", "rm3", zkAddr);- res = tool.runTool(SolrCLI.processCommandLineArgs(tool, args));+ res = CLITestHelper.runTool(args, ZkRmTool.class);assertNotEquals("Should fail when trying to remove /.", 0, res);}diff --git a/solr/core/src/test/org/apache/solr/cli/StatusToolTest.java b/solr/core/src/test/org/apache/solr/cli/StatusToolTest.javanew file mode 100644index 00000000000..e035db8495c--- /dev/null+++ b/solr/core/src/test/org/apache/solr/cli/StatusToolTest.java@@ -0,0 +1,51 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package org.apache.solr.cli;++import java.util.Map;+import org.apache.solr.cloud.SolrCloudTestCase;+import org.apache.solr.common.util.Utils;+import org.apache.solr.embedded.JettySolrRunner;+import org.junit.BeforeClass;+import org.junit.Test;++public class StatusToolTest extends SolrCloudTestCase {++ @BeforeClass+ public static void setupCluster() throws Exception {+ configureCluster(2).configure();+ }++ /** Check the tool returns expected details by specifying Solr URL on the command line. */+ @Test+ public void testSolrUrlStatus() throws Exception {++ JettySolrRunner randomJetty = cluster.getRandomJetty(random());+ String baseUrl = randomJetty.getBaseUrl().toString();++ String[] toolArgs = new String[] {"status", "--solr-url", baseUrl};+ CLITestHelper.TestingRuntime runtime = new CLITestHelper.TestingRuntime(true);+ StatusTool tool = new StatusTool(runtime);+ tool.runTool(SolrCLI.processCommandLineArgs(tool, toolArgs));++ Map<?, ?> obj = (Map<?, ?>) Utils.fromJSON(runtime.getReader());+ assertTrue(obj.containsKey("version"));+ assertTrue(obj.containsKey("startTime"));+ assertTrue(obj.containsKey("uptime"));+ assertTrue(obj.containsKey("memory"));+ }+}diff --git a/solr/core/src/test/org/apache/solr/cli/StreamToolTest.java b/solr/core/src/test/org/apache/solr/cli/StreamToolTest.javaindex 926e8aa91e3..5c37e521bbe 100644--- a/solr/core/src/test/org/apache/solr/cli/StreamToolTest.java+++ b/solr/core/src/test/org/apache/solr/cli/StreamToolTest.java@@ -17,9 +17,6 @@package org.apache.solr.cli;-import static org.apache.solr.cli.SolrCLI.findTool;-import static org.apache.solr.cli.SolrCLI.parseCmdLine;-import java.io.BufferedWriter;import java.io.ByteArrayInputStream;import java.io.File;@@ -79,7 +76,8 @@ public class StreamToolTest extends SolrCloudTestCase {new String[] {"--fields", "field9, field2, field3, field4",};- StreamTool streamTool = new StreamTool();+ ToolRuntime runtime = new CLITestHelper.TestingRuntime(false);+ StreamTool streamTool = new StreamTool(runtime);CommandLine cli = SolrCLI.processCommandLineArgs(streamTool, args);String[] outputFields = StreamTool.getOutputFields(cli);assert outputFields != null;@@ -243,7 +241,7 @@ public class StreamToolTest extends SolrCloudTestCase {cluster.getZkClient().getZkServerAddress(),expression};- assertEquals(1, runTool(args));+ assertEquals(1, CLITestHelper.runTool(args, StreamTool.class));}@Test@@ -260,7 +258,7 @@ public class StreamToolTest extends SolrCloudTestCase {cluster.getZkClient().getZkServerAddress(),expression};- assertEquals(0, runTool(args));+ assertEquals(0, CLITestHelper.runTool(args, StreamTool.class));}@Test@@ -284,7 +282,7 @@ public class StreamToolTest extends SolrCloudTestCase {expressionFile.getAbsolutePath()};- assertEquals(0, runTool(args));+ assertEquals(0, CLITestHelper.runTool(args, StreamTool.class));// test passing in the expression directlyargs =@@ -298,7 +296,7 @@ public class StreamToolTest extends SolrCloudTestCase {expression};- assertEquals(0, runTool(args));+ assertEquals(0, CLITestHelper.runTool(args, StreamTool.class));}@Test@@ -332,7 +330,7 @@ public class StreamToolTest extends SolrCloudTestCase {expressionFile.getAbsolutePath()};- assertEquals(0, runTool(args));+ assertEquals(0, CLITestHelper.runTool(args, StreamTool.class));// test passing in the expression directlyargs =@@ -350,14 +348,7 @@ public class StreamToolTest extends SolrCloudTestCase {expression};- assertEquals(0, runTool(args));- }-- private int runTool(String[] args) throws Exception {- Tool tool = findTool(args);- assertTrue(tool instanceof StreamTool);- CommandLine cli = parseCmdLine(tool, args);- return tool.runTool(cli);+ assertEquals(0, CLITestHelper.runTool(args, StreamTool.class));}// Copied from StreamExpressionTest.javadiff --git a/solr/core/src/test/org/apache/solr/cli/TestExportTool.java b/solr/core/src/test/org/apache/solr/cli/TestExportTool.javaindex 6347c4a47e7..57db19f4e28 100644--- a/solr/core/src/test/org/apache/solr/cli/TestExportTool.java+++ b/solr/core/src/test/org/apache/solr/cli/TestExportTool.java@@ -17,9 +17,6 @@package org.apache.solr.cli;-import static org.apache.solr.cli.SolrCLI.findTool;-import static org.apache.solr.cli.SolrCLI.parseCmdLine;-import java.io.File;import java.io.FileInputStream;import java.io.IOException;@@ -30,7 +27,6 @@ import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.function.Predicate;-import org.apache.commons.cli.CommandLine;import org.apache.lucene.tests.util.TestUtil;import org.apache.solr.SolrTestCaseJ4;import org.apache.solr.client.solrj.SolrClient;@@ -86,8 +82,9 @@ public class TestExportTool extends SolrCloudTestCase {assertEquals(docCount, qr.getResults().getNumFound());String url = cluster.getRandomJetty(random()).getBaseUrl() + "/" + COLLECTION_NAME;+ ToolRuntime runtime = new CLITestHelper.TestingRuntime(false);- ExportTool.Info info = new ExportTool.MultiThreadedRunner(url, null);+ ExportTool.Info info = new ExportTool.MultiThreadedRunner(runtime, url, null);String absolutePath = tmpFileLoc + COLLECTION_NAME + random().nextInt(100000) + ".jsonl";info.setOutFormat(absolutePath, "jsonl", false);info.setLimit("200");@@ -96,7 +93,7 @@ public class TestExportTool extends SolrCloudTestCase {assertJsonDocsCount(info, 200, record -> "2019-09-30T05:58:03Z".equals(record.get("a_dt")));- info = new ExportTool.MultiThreadedRunner(url, null);+ info = new ExportTool.MultiThreadedRunner(runtime, url, null);absolutePath = tmpFileLoc + COLLECTION_NAME + random().nextInt(100000) + ".jsonl";info.setOutFormat(absolutePath, "jsonl", false);info.setLimit("-1");@@ -105,7 +102,7 @@ public class TestExportTool extends SolrCloudTestCase {assertJsonDocsCount(info, 1000, null);- info = new ExportTool.MultiThreadedRunner(url, null);+ info = new ExportTool.MultiThreadedRunner(runtime, url, null);absolutePath = tmpFileLoc + COLLECTION_NAME + random().nextInt(100000) + ".javabin";info.setOutFormat(absolutePath, "javabin", false);info.setLimit("200");@@ -114,7 +111,7 @@ public class TestExportTool extends SolrCloudTestCase {assertJavabinDocsCount(info, 200);- info = new ExportTool.MultiThreadedRunner(url, null);+ info = new ExportTool.MultiThreadedRunner(runtime, url, null);absolutePath = tmpFileLoc + COLLECTION_NAME + random().nextInt(100000) + ".javabin";info.setOutFormat(absolutePath, "javabin", false);info.setLimit("-1");@@ -122,7 +119,7 @@ public class TestExportTool extends SolrCloudTestCase {info.exportDocs();assertJavabinDocsCount(info, 1000);- info = new ExportTool.MultiThreadedRunner(url, null);+ info = new ExportTool.MultiThreadedRunner(runtime, url, null);absolutePath = tmpFileLoc + COLLECTION_NAME + random().nextInt(100000) + ".json";info.setOutFormat(absolutePath, "json", false);info.setLimit("200");@@ -131,7 +128,7 @@ public class TestExportTool extends SolrCloudTestCase {assertJsonDocsCount2(info, 200);- info = new ExportTool.MultiThreadedRunner(url, null);+ info = new ExportTool.MultiThreadedRunner(runtime, url, null);absolutePath = tmpFileLoc + COLLECTION_NAME + random().nextInt(100000) + ".json";info.setOutFormat(absolutePath, "json", false);info.setLimit("-1");@@ -194,11 +191,11 @@ public class TestExportTool extends SolrCloudTestCase {}assertEquals(docCount, totalDocsFromCores);+ ToolRuntime runtime = new CLITestHelper.TestingRuntime(false);ExportTool.MultiThreadedRunner info;String absolutePath;- info = new ExportTool.MultiThreadedRunner(url, null);- info.output = System.out;+ info = new ExportTool.MultiThreadedRunner(runtime, url, null);absolutePath = tmpFileLoc + COLLECTION_NAME + random().nextInt(100000) + ".javabin";info.setOutFormat(absolutePath, "javabin", false);info.setLimit("-1");@@ -208,8 +205,7 @@ public class TestExportTool extends SolrCloudTestCase {assertEquals(e.getValue().longValue(), info.corehandlers.get(e.getKey()).receivedDocs.get());}- info = new ExportTool.MultiThreadedRunner(url, null);- info.output = System.out;+ info = new ExportTool.MultiThreadedRunner(runtime, url, null);absolutePath = tmpFileLoc + COLLECTION_NAME + random().nextInt(100000) + ".jsonl";info.setOutFormat(absolutePath, "jsonl", false);info.fields = "id,desc_s";@@ -254,19 +250,12 @@ public class TestExportTool extends SolrCloudTestCase {"--verbose"};- assertEquals(0, runTool(args));+ assertEquals(0, CLITestHelper.runTool(args, ExportTool.class));} finally {cluster.shutdown();}}- private int runTool(String[] args) throws Exception {- Tool tool = findTool(args);- assertTrue(tool instanceof ExportTool);- CommandLine cli = parseCmdLine(tool, args);- return tool.runTool(cli);- }-private void assertJavabinDocsCount(ExportTool.Info info, int expected) throws IOException {assertTrue("" + info.docsWritten.get() + " expected " + expected, info.docsWritten.get() >= expected);diff --git a/solr/core/src/test/org/apache/solr/cli/TestSolrCLIRunExample.java b/solr/core/src/test/org/apache/solr/cli/TestSolrCLIRunExample.javaindex c98662a6100..558831242d3 100644--- a/solr/core/src/test/org/apache/solr/cli/TestSolrCLIRunExample.java+++ b/solr/core/src/test/org/apache/solr/cli/TestSolrCLIRunExample.java@@ -17,12 +17,10 @@package org.apache.solr.cli;import java.io.ByteArrayInputStream;-import java.io.ByteArrayOutputStream;import java.io.Closeable;import java.io.File;import java.io.IOException;import java.io.InputStream;-import java.io.PrintStream;import java.lang.invoke.MethodHandles;import java.net.ServerSocket;import java.nio.charset.Charset;@@ -83,16 +81,10 @@ public class TestSolrCLIRunExample extends SolrTestCaseJ4 {*/private static class RunExampleExecutor extends DefaultExecutor implements Closeable {- private PrintStream stdout;private final List<CommandLine> commandsExecuted = new ArrayList<>();private MiniSolrCloudCluster solrCloudCluster;private JettySolrRunner standaloneSolr;- RunExampleExecutor(PrintStream stdout) {- super();- this.stdout = stdout;- }-/*** Override the call to execute a command asynchronously to occur synchronously during a unit* test.@@ -370,13 +362,12 @@ public class TestSolrCLIRunExample extends SolrTestCaseJ4 {};// capture tool output to stdout- ByteArrayOutputStream baos = new ByteArrayOutputStream();- PrintStream stdoutSim = new PrintStream(baos, true, StandardCharsets.UTF_8.name());+ CLITestHelper.TestingRuntime runtime = new CLITestHelper.TestingRuntime(true);- RunExampleExecutor executor = new RunExampleExecutor(stdoutSim);+ RunExampleExecutor executor = new RunExampleExecutor();closeables.add(executor);- RunExampleTool tool = new RunExampleTool(executor, System.in, stdoutSim);+ RunExampleTool tool = new RunExampleTool(executor, System.in, runtime);try {int status = tool.runTool(SolrCLI.processCommandLineArgs(tool, toolArgs));@@ -394,11 +385,11 @@ public class TestSolrCLIRunExample extends SolrTestCaseJ4 {log.error("RunExampleTool failed due to: {}; stdout from tool prior to failure: {}",e,- baos.toString(StandardCharsets.UTF_8.name())); // nowarn+ runtime.getOutput()); // nowarnthrow e;}- String toolOutput = baos.toString(StandardCharsets.UTF_8.name());+ String toolOutput = runtime.getOutput();// dump all the output written by the SolrCLI commands to stdout// System.out.println("\n\n"+toolOutput+"\n\n");@@ -475,13 +466,12 @@ public class TestSolrCLIRunExample extends SolrTestCaseJ4 {InputStream userInputSim = new ByteArrayInputStream(userInput.getBytes(StandardCharsets.UTF_8));// capture tool output to stdout- ByteArrayOutputStream baos = new ByteArrayOutputStream();- PrintStream stdoutSim = new PrintStream(baos, true, StandardCharsets.UTF_8.name());+ CLITestHelper.TestingRuntime runtime = new CLITestHelper.TestingRuntime(true);- RunExampleExecutor executor = new RunExampleExecutor(stdoutSim);+ RunExampleExecutor executor = new RunExampleExecutor();closeables.add(executor);- RunExampleTool tool = new RunExampleTool(executor, userInputSim, stdoutSim);+ RunExampleTool tool = new RunExampleTool(executor, userInputSim, runtime);try {tool.runTool(SolrCLI.processCommandLineArgs(tool, toolArgs));} catch (Exception e) {@@ -489,11 +479,11 @@ public class TestSolrCLIRunExample extends SolrTestCaseJ4 {"RunExampleTool failed due to: "+ e+ "; stdout from tool prior to failure: "- + baos.toString(StandardCharsets.UTF_8.name()));+ + runtime.getOutput());throw e;}- String toolOutput = baos.toString(StandardCharsets.UTF_8.name());+ String toolOutput = runtime.getOutput();// verify Solr is running on the expected port and verify the collection existsString solrUrl = "http://localhost:" + bindPort + "/solr";@@ -545,7 +535,7 @@ public class TestSolrCLIRunExample extends SolrTestCaseJ4 {}// delete the collection- DeleteTool deleteTool = new DeleteTool(stdoutSim);+ DeleteTool deleteTool = new DeleteTool(runtime);String[] deleteArgs = new String[] {"--name", collectionName, "--solr-url", solrUrl};deleteTool.runTool(SolrCLI.processCommandLineArgs(deleteTool, deleteArgs));@@ -586,13 +576,10 @@ public class TestSolrCLIRunExample extends SolrTestCaseJ4 {"--script", toExecute.getAbsolutePath()};- // capture tool output to stdout- ByteArrayOutputStream baos = new ByteArrayOutputStream();- PrintStream stdoutSim = new PrintStream(baos, true, StandardCharsets.UTF_8.name());-DefaultExecutor executor = DefaultExecutor.builder().get();- RunExampleTool tool = new RunExampleTool(executor, System.in, stdoutSim);+ ToolRuntime runtime = new CLITestHelper.TestingRuntime(false);+ RunExampleTool tool = new RunExampleTool(executor, System.in, runtime);int code = tool.runTool(SolrCLI.processCommandLineArgs(tool, toolArgs));assertEquals("Execution should have failed with return code 1", 1, code);}diff --git a/solr/core/src/test/org/apache/solr/cli/ZkSubcommandsTest.java b/solr/core/src/test/org/apache/solr/cli/ZkSubcommandsTest.javaindex af092aa6210..78904038f86 100644--- a/solr/core/src/test/org/apache/solr/cli/ZkSubcommandsTest.java+++ b/solr/core/src/test/org/apache/solr/cli/ZkSubcommandsTest.java@@ -16,9 +16,6 @@*/package org.apache.solr.cli;-import static org.apache.solr.cli.SolrCLI.parseCmdLine;--import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileWriter;import java.io.PrintStream;@@ -30,7 +27,6 @@ import java.nio.file.Paths;import java.util.Collection;import java.util.List;import java.util.concurrent.TimeUnit;-import org.apache.commons.cli.CommandLine;import org.apache.commons.io.FileUtils;import org.apache.commons.io.filefilter.RegexFileFilter;import org.apache.commons.io.filefilter.TrueFileFilter;@@ -131,8 +127,7 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {"cp", "-z", zkServer.getZkAddress(), localFile.getAbsolutePath(), "zk:/data.txt"};- ZkCpTool tool = new ZkCpTool();- assertEquals(0, runTool(args, tool));+ assertEquals(0, CLITestHelper.runTool(args, ZkCpTool.class));assertArrayEquals(zkClient.getData("/data.txt", null, null, true), data.getBytes(StandardCharsets.UTF_8));@@ -145,7 +140,7 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {writer.write(data);writer.close();- assertEquals(0, runTool(args, tool));+ assertEquals(0, CLITestHelper.runTool(args, ZkCpTool.class));assertArrayEquals(zkClient.getData("/data.txt", null, null, true), data.getBytes(StandardCharsets.UTF_8));@@ -172,8 +167,8 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {new String[] {"cp", "-z", zkServer.getZkAddress(), localFile.getAbsolutePath(), "zk:/state.json"};- ZkCpTool tool = new ZkCpTool();- assertEquals(0, runTool(args, tool));++ assertEquals(0, CLITestHelper.runTool(args, ZkCpTool.class));assertArrayEquals(dataBytes, zkClient.getCuratorFramework().getData().forPath("/state.json"));assertArrayEquals(@@ -198,7 +193,7 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {new String[] {"cp", "-z", zkServer.getZkAddress(), localFile.getAbsolutePath(), "zk:/state.json"};- assertEquals(0, runTool(args, tool));+ assertEquals(0, CLITestHelper.runTool(args, ZkCpTool.class));byte[] fromZkRaw =zkClient.getCuratorFramework().getData().undecompressed().forPath("/state.json");@@ -231,8 +226,7 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {"zk:/foo.xml"};- ZkCpTool tool = new ZkCpTool();- assertEquals(0, runTool(args, tool));+ assertEquals(0, CLITestHelper.runTool(args, ZkCpTool.class));String fromZk =new String(zkClient.getData("/foo.xml", null, null, true), StandardCharsets.UTF_8);@@ -253,8 +247,7 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {"zk:foo.xml"};- ZkCpTool tool = new ZkCpTool();- assertEquals(0, runTool(args, tool));+ assertEquals(0, CLITestHelper.runTool(args, ZkCpTool.class));String fromZk =new String(zkClient.getData("/foo.xml", null, null, true), StandardCharsets.UTF_8);@@ -278,8 +271,7 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {"zk:/state.json"};- ZkCpTool tool = new ZkCpTool();- assertEquals(0, runTool(args, tool));+ assertEquals(0, CLITestHelper.runTool(args, ZkCpTool.class));Path locFile = Path.of(SOLR_HOME, "solr-stress-new.xml");byte[] fileBytes = Files.readAllBytes(locFile);@@ -296,7 +288,7 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {"Should get back an uncompressed version what we put in ZK", fileBytes, fromZk);// Lets do it again- assertEquals(0, runTool(args, tool));+ assertEquals(0, CLITestHelper.runTool(args, ZkCpTool.class));locFile = Path.of(SOLR_HOME, "solr-stress-new.xml");fileBytes = Files.readAllBytes(locFile);@@ -323,8 +315,7 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {"zk:/foo.xml"};- ZkCpTool tool = new ZkCpTool();- assertEquals(1, runTool(args, tool));+ assertEquals(1, CLITestHelper.runTool(args, ZkCpTool.class));}@Test@@ -334,13 +325,10 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {// test what happens when path arg "/" isn't the last one.String[] args = new String[] {"ls", "/", "-r", "true", "-z", zkServer.getZkAddress()};- ByteArrayOutputStream byteStream = new ByteArrayOutputStream();- final PrintStream myOut = new PrintStream(byteStream, false, StandardCharsets.UTF_8);+ CLITestHelper.TestingRuntime runtime = new CLITestHelper.TestingRuntime(true);+ assertEquals(0, CLITestHelper.runTool(args, runtime, ZkLsTool.class));- ZkLsTool tool = new ZkLsTool(myOut);- assertEquals(0, runTool(args, tool));-- final String standardOutput2 = byteStream.toString(StandardCharsets.UTF_8);+ final String standardOutput2 = runtime.getOutput();String separator2 = System.lineSeparator();assertEquals(@@ -366,8 +354,7 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {zkServer.getZkAddress()};- ConfigSetUploadTool configSetUploadTool = new ConfigSetUploadTool();- assertEquals(0, runTool(args, configSetUploadTool));+ assertEquals(0, CLITestHelper.runTool(args, ConfigSetUploadTool.class));assertTrue(zkClient.exists(ZkConfigSetService.CONFIGS_ZKNODE + "/" + confsetname, true));File confDir = new File(ExternalPaths.TECHPRODUCTS_CONFIGSET);@@ -388,8 +375,7 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {zkServer.getZkAddress()};- LinkConfigTool linkConfigTool = new LinkConfigTool();- assertEquals(0, runTool(args, linkConfigTool));+ assertEquals(0, CLITestHelper.runTool(args, LinkConfigTool.class));ZkNodeProps collectionProps =ZkNodeProps.load(@@ -414,8 +400,7 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {zkServer.getZkAddress()};- ConfigSetDownloadTool configSetDownloadTool = new ConfigSetDownloadTool();- assertEquals(0, runTool(args, configSetDownloadTool));+ assertEquals(0, CLITestHelper.runTool(args, ConfigSetDownloadTool.class));confDir = new File(configSetDir, "conf");files = confDir.listFiles();@@ -463,8 +448,7 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {// test reset zkargs = new String[] {"rm", "-r", "-z", zkServer.getZkAddress(), "zk:/configs/confsetone"};- ZkRmTool zkRmTool = new ZkRmTool();- assertEquals(0, runTool(args, zkRmTool));+ assertEquals(0, CLITestHelper.runTool(args, ZkRmTool.class));assertEquals(0, zkClient.getChildren("/configs", null, true).size());}@@ -482,13 +466,10 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {"cp", "-z", zkServer.getZkAddress(), "zk:" + getNode, localFile.getAbsolutePath()};- ByteArrayOutputStream byteStream2 = new ByteArrayOutputStream();- final PrintStream myOut2 = new PrintStream(byteStream2, false, StandardCharsets.UTF_8);-- ZkCpTool tool = new ZkCpTool(myOut2);- assertEquals(0, runTool(args, tool));+ CLITestHelper.TestingRuntime runtime = new CLITestHelper.TestingRuntime(true);+ assertEquals(0, CLITestHelper.runTool(args, runtime, ZkCpTool.class));- final String standardOutput2 = byteStream2.toString(StandardCharsets.UTF_8);+ final String standardOutput2 = runtime.getOutput();assertTrue(standardOutput2.startsWith("Copying from 'zk:/getNode'"));byte[] fileBytes = Files.readAllBytes(Paths.get(localFile.getAbsolutePath()));assertArrayEquals(data, fileBytes);@@ -515,8 +496,7 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {"cp", "-z", zkServer.getZkAddress(), "zk:" + getNode, localFile.getAbsolutePath()};- ZkCpTool tool = new ZkCpTool();- assertEquals(0, runTool(args, tool));+ assertEquals(0, CLITestHelper.runTool(args, ZkCpTool.class));assertArrayEquals(data, Files.readAllBytes(Path.of(localFile.getAbsolutePath())));}@@ -537,8 +517,7 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {"cp", "-z", zkServer.getZkAddress(), "zk:" + getNode, file.toAbsolutePath().toString()};- ZkCpTool tool = new ZkCpTool();- assertEquals(0, runTool(args, tool));+ assertEquals(0, CLITestHelper.runTool(args, ZkCpTool.class));assertArrayEquals(data, Files.readAllBytes(file));}@@ -563,8 +542,7 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {"cp", "-z", zkServer.getZkAddress(), "zk:" + getNode, file.toAbsolutePath().toString()};- ZkCpTool tool = new ZkCpTool();- assertEquals(0, runTool(args, tool));+ assertEquals(0, CLITestHelper.runTool(args, ZkCpTool.class));assertArrayEquals(data, Files.readAllBytes(file));}@@ -578,8 +556,7 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {String[] args =new String[] {"cp", "-z", zkServer.getZkAddress(), "zk:" + getNode, file.getAbsolutePath()};- ZkCpTool tool = new ZkCpTool();- assertEquals(1, runTool(args, tool));+ assertEquals(1, CLITestHelper.runTool(args, ZkCpTool.class));}@Test@@ -587,11 +564,7 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {String[] args = new String[] {"ls", "/", "-r", "-z", "----------:33332"};- ByteArrayOutputStream byteStream2 = new ByteArrayOutputStream();- final PrintStream myOut2 = new PrintStream(byteStream2, false, StandardCharsets.UTF_8);-- ZkLsTool tool = new ZkLsTool(myOut2);- assertEquals(1, runTool(args, tool));+ assertEquals(1, CLITestHelper.runTool(args, ZkLsTool.class));}@Test@@ -602,13 +575,12 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {new String[] {"cluster", "--property", "urlScheme", "--value", "http", "-z", zkServer.getZkAddress()};- ClusterTool tool = new ClusterTool();- assertEquals(0, runTool(args, tool));+ assertEquals(0, CLITestHelper.runTool(args, ClusterTool.class));assertEquals("http", properties.getClusterProperty("urlScheme", "none"));args = new String[] {"cluster", "--property", "urlScheme", "-z", zkServer.getZkAddress()};- assertEquals(0, runTool(args, tool));+ assertEquals(0, CLITestHelper.runTool(args, ClusterTool.class));assertNull(properties.getClusterProperty("urlScheme", (String) null));}@@ -633,8 +605,7 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {"pass");String[] args = new String[] {"updateacls", "/", "-z", zkServer.getZkAddress()};- UpdateACLTool tool = new UpdateACLTool();- assertEquals(0, runTool(args, tool));+ assertEquals(0, CLITestHelper.runTool(args, UpdateACLTool.class));} finally {// Need to clear these before we open the next SolrZkClientSystem.clearProperty(SolrZkClient.ZK_ACL_PROVIDER_CLASS_NAME_VM_PARAM_NAME);@@ -658,11 +629,6 @@ public class ZkSubcommandsTest extends SolrTestCaseJ4 {assertTrue("Did not fail to read.", excepted);}- private int runTool(String[] args, Tool tool) throws Exception {- CommandLine cli = parseCmdLine(tool, args);- return tool.runTool(cli);- }-@Overridepublic void tearDown() throws Exception {if (zkClient != null) {diff --git a/solr/core/src/test/org/apache/solr/cloud/SolrCloudExampleTest.java b/solr/core/src/test/org/apache/solr/cloud/SolrCloudExampleTest.javaindex 36ce7aa7930..b186da20296 100644--- a/solr/core/src/test/org/apache/solr/cloud/SolrCloudExampleTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/SolrCloudExampleTest.java@@ -24,12 +24,14 @@ import java.util.Set;import java.util.concurrent.TimeUnit;import org.apache.commons.cli.CommandLine;import org.apache.solr.SolrTestCaseJ4;+import org.apache.solr.cli.CLITestHelper;import org.apache.solr.cli.CLIUtils;import org.apache.solr.cli.CreateTool;import org.apache.solr.cli.DeleteTool;import org.apache.solr.cli.HealthcheckTool;import org.apache.solr.cli.PostTool;import org.apache.solr.cli.SolrCLI;+import org.apache.solr.cli.ToolRuntime;import org.apache.solr.client.solrj.SolrQuery;import org.apache.solr.client.solrj.response.QueryResponse;import org.apache.solr.common.cloud.ZkStateReader;@@ -91,7 +93,8 @@ public class SolrCloudExampleTest extends AbstractFullDistribZkTestBase {// NOTE: not calling SolrCLI.main as the script does because it calls System.exit which is a// no-no in a JUnit test- CreateTool tool = new CreateTool();+ ToolRuntime runtime = new CLITestHelper.TestingRuntime(false);+ CreateTool tool = new CreateTool(runtime);CommandLine cli = SolrCLI.processCommandLineArgs(tool, args);log.info("Creating the '{}' collection using SolrCLI with: {}", testCollectionName, solrUrl);tool.runTool(cli);@@ -125,7 +128,7 @@ public class SolrCloudExampleTest extends AbstractFullDistribZkTestBase {exampleDocsDir.toAbsolutePath().toString()};- PostTool postTool = new PostTool();+ PostTool postTool = new PostTool(runtime);CommandLine postCli = SolrCLI.processCommandLineArgs(postTool, argsForPost);postTool.runTool(postCli);@@ -145,33 +148,36 @@ public class SolrCloudExampleTest extends AbstractFullDistribZkTestBase {assertEquals("*:* found unexpected number of documents", expectedXmlDocCount, numFound);log.info("Running healthcheck for {}", testCollectionName);- doTestHealthcheck(testCollectionName, cloudClient.getClusterStateProvider().getQuorumHosts());+ doTestHealthcheck(+ testCollectionName, cloudClient.getClusterStateProvider().getQuorumHosts(), runtime);// verify the delete action works toolog.info("Running delete for {}", testCollectionName);- doTestDeleteAction(testCollectionName, solrUrl);+ doTestDeleteAction(testCollectionName, solrUrl, runtime);log.info("testLoadDocsIntoGettingStartedCollection succeeded ... shutting down now!");}- protected void doTestHealthcheck(String testCollectionName, String zkHost) throws Exception {+ protected void doTestHealthcheck(String testCollectionName, String zkHost, ToolRuntime runtime)+ throws Exception {String[] args =new String[] {"--name", testCollectionName,"--zk-host", zkHost};- HealthcheckTool tool = new HealthcheckTool();+ HealthcheckTool tool = new HealthcheckTool(runtime);CommandLine cli = SolrCLI.processCommandLineArgs(tool, args);assertEquals("Healthcheck action failed!", 0, tool.runTool(cli));}- protected void doTestDeleteAction(String testCollectionName, String solrUrl) throws Exception {+ protected void doTestDeleteAction(String testCollectionName, String solrUrl, ToolRuntime runtime)+ throws Exception {String[] args =new String[] {"--name", testCollectionName,"--solr-url", solrUrl};- DeleteTool tool = new DeleteTool();+ DeleteTool tool = new DeleteTool(runtime);CommandLine cli = SolrCLI.processCommandLineArgs(tool, args);assertEquals("Delete action failed!", 0, tool.runTool(cli));assertFalse(diff --git a/solr/core/src/test/org/apache/solr/packagemanager/TestPackageManager.java b/solr/core/src/test/org/apache/solr/packagemanager/TestPackageManager.javaindex 270e4fb665d..2d4892239f0 100644--- a/solr/core/src/test/org/apache/solr/packagemanager/TestPackageManager.java+++ b/solr/core/src/test/org/apache/solr/packagemanager/TestPackageManager.java@@ -21,6 +21,9 @@ import java.io.IOException;import java.net.URL;import java.util.Collections;import java.util.Map;+import org.apache.solr.cli.CLITestHelper;+import org.apache.solr.cli.ToolRuntime;+import org.apache.solr.client.solrj.SolrClient;import org.apache.solr.client.solrj.impl.Http2SolrClient;import org.apache.solr.client.solrj.request.CollectionAdminRequest;import org.apache.solr.cloud.SolrCloudTestCase;@@ -47,7 +50,8 @@ public class TestPackageManager extends SolrCloudTestCase {SolrZkClient zkClient = cluster.getZkClient();URL baseURLV2 = cluster.getJettySolrRunner(0).getBaseURLV2();try (Http2SolrClient solrClient = new Http2SolrClient.Builder(baseURLV2.toString()).build()) {- try (PackageManager manager = new StubPackageManager(solrClient, zkClient)) {+ ToolRuntime runtime = new CLITestHelper.TestingRuntime(false);+ try (PackageManager manager = new StubPackageManager(runtime, solrClient, zkClient)) {SolrPackage.Plugin plugin = new SolrPackage.Plugin();if (random().nextBoolean()) {plugin.type = "cluster";@@ -77,8 +81,9 @@ public class TestPackageManager extends SolrCloudTestCase {}private static class StubPackageManager extends PackageManager {- public StubPackageManager(Http2SolrClient solrClient, SolrZkClient zkClient) {+ public StubPackageManager(ToolRuntime runtime, SolrClient solrClient, SolrZkClient zkClient) {super(+ runtime,solrClient,SolrCloudTestCase.cluster.getJettySolrRunners().get(0).getBaseUrl().toString(),zkClient.getZkServerAddress());diff --git a/solr/core/src/test/org/apache/solr/security/BasicAuthIntegrationTest.java b/solr/core/src/test/org/apache/solr/security/BasicAuthIntegrationTest.javaindex b9652574f50..77ee3536959 100644--- a/solr/core/src/test/org/apache/solr/security/BasicAuthIntegrationTest.java+++ b/solr/core/src/test/org/apache/solr/security/BasicAuthIntegrationTest.java@@ -20,10 +20,7 @@ import static java.nio.charset.StandardCharsets.UTF_8;import static java.util.Collections.singletonMap;import com.codahale.metrics.MetricRegistry;-import java.io.ByteArrayInputStream;-import java.io.ByteArrayOutputStream;import java.io.IOException;-import java.io.PrintStream;import java.lang.invoke.MethodHandles;import java.nio.charset.StandardCharsets;import java.util.ArrayList;@@ -36,7 +33,7 @@ import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.ByteArrayEntity;-import org.apache.solr.cli.SolrCLI;+import org.apache.solr.cli.CLITestHelper;import org.apache.solr.cli.StatusTool;import org.apache.solr.client.solrj.SolrClient;import org.apache.solr.client.solrj.SolrRequest;@@ -298,23 +295,10 @@ public class BasicAuthIntegrationTest extends SolrCloudAuthTestCase {verifySecurityStatus(cl, baseUrl + "/admin/info/key", "key", NOT_NULL_PREDICATE, 20);assertAuthMetricsMinimums(17, 8, 8, 1, 0, 0);- String[] toolArgs =- new String[] {"status", "--solr-url", baseUrl, "--credentials", "harry:HarryIsUberCool"};- ByteArrayOutputStream baos = new ByteArrayOutputStream();- PrintStream stdoutSim = new PrintStream(baos, true, StandardCharsets.UTF_8.name());- StatusTool tool = new StatusTool(stdoutSim);- try {- tool.runTool(SolrCLI.processCommandLineArgs(tool, toolArgs));- Map<?, ?> obj = (Map<?, ?>) Utils.fromJSON(new ByteArrayInputStream(baos.toByteArray()));- assertTrue(obj.containsKey("version"));- assertTrue(obj.containsKey("startTime"));- assertTrue(obj.containsKey("uptime"));- assertTrue(obj.containsKey("memory"));- } catch (Exception e) {- log.error(- "StatusTool failed due to: {}; stdout from tool prior to failure: {}",- e,- baos.toString(StandardCharsets.UTF_8.name())); // nowarn+ String[] toolArgs = new String[] {"status", "--solr-url", baseUrl};+ int res = CLITestHelper.runTool(toolArgs, StatusTool.class);+ if (res == 0) {+ fail("Request should have failed because of missing auth");}SolrParams params = new MapSolrParams(Collections.singletonMap("q", "*:*"));diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/StartSolrJetty.java b/solr/solrj/src/test/org/apache/solr/client/solrj/StartSolrJetty.javaindex ad308589d34..8f02c40abd7 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/StartSolrJetty.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/StartSolrJetty.java@@ -17,6 +17,7 @@package org.apache.solr.client.solrj;import java.lang.invoke.MethodHandles;+import org.apache.solr.common.util.SuppressForbidden;import org.eclipse.jetty.server.Connector;import org.eclipse.jetty.server.HttpConnectionFactory;import org.eclipse.jetty.server.Server;@@ -66,7 +67,12 @@ public class StartSolrJetty {server.join();} catch (Exception e) {log.error("failed to start", e);- System.exit(100);+ exit(100);}}++ @SuppressForbidden(reason = "This is a CLI tool, allow to exit the JVM")+ private static void exit(int status) {+ System.exit(status);+ }}diff --git a/solr/test-framework/src/java/org/apache/solr/cloud/AbstractDistribZkTestBase.java b/solr/test-framework/src/java/org/apache/solr/cloud/AbstractDistribZkTestBase.javaindex f256a5fb937..bc378039ec7 100644--- a/solr/test-framework/src/java/org/apache/solr/cloud/AbstractDistribZkTestBase.java+++ b/solr/test-framework/src/java/org/apache/solr/cloud/AbstractDistribZkTestBase.java@@ -28,7 +28,9 @@ import java.util.concurrent.atomic.AtomicInteger;import org.apache.commons.io.FileUtils;import org.apache.solr.BaseDistributedSearchTestCase;import org.apache.solr.cli.ConfigSetUploadTool;+import org.apache.solr.cli.DefaultToolRuntime;import org.apache.solr.cli.SolrCLI;+import org.apache.solr.cli.ToolRuntime;import org.apache.solr.client.solrj.impl.CloudSolrClient;import org.apache.solr.client.solrj.request.CollectionAdminRequest;import org.apache.solr.common.cloud.ClusterState;@@ -394,7 +396,8 @@ public abstract class AbstractDistribZkTestBase extends BaseDistributedSearchTes"-z", zkAddr};- ConfigSetUploadTool tool = new ConfigSetUploadTool();+ ToolRuntime runtime = new DefaultToolRuntime();+ ConfigSetUploadTool tool = new ConfigSetUploadTool(runtime);int res = tool.runTool(SolrCLI.processCommandLineArgs(tool, args));assertEquals("Tool should have returned 0 for success, returned: " + res, res, 0);