Package com.unboundid.util
Class CommandLineTool
java.lang.Object
com.unboundid.util.CommandLineTool
- Direct Known Subclasses:
Base64Tool,GenerateSchemaFromSource,IndentLDAPFilter,InMemoryDirectoryServerTool,LDAPCommandLineTool,LDAPResultCode,LDIFDiff,LDIFModify,LDIFSearch,ManageCertificates,MultiServerLDAPCommandLineTool,OIDLookup,SplitLDIF,SummarizeAccessLog,TestLDAPSDKPerformance,TLSCipherSuiteSelector,TransformLDIF,ValidateLDAPSchema
@Extensible
@ThreadSafety(level=INTERFACE_NOT_THREADSAFE)
public abstract class CommandLineTool
extends Object
This class provides a framework for developing command-line tools that use
the argument parser provided as part of the UnboundID LDAP SDK for Java.
This tool adds a "-H" or "--help" option, which can be used to display usage
information for the program, and may also add a "-V" or "--version" option,
which can display the tool version.
Subclasses should include their own
Note that in general, methods in this class are not threadsafe. However, the
Subclasses should include their own
main method that creates an
instance of a CommandLineTool and should invoke the
runTool(java.lang.String...) method with the provided arguments. For
example:
public class ExampleCommandLineTool
extends CommandLineTool
{
public static void main(String[] args)
{
ExampleCommandLineTool tool = new ExampleCommandLineTool();
ResultCode resultCode = tool.runTool(args);
if (resultCode != ResultCode.SUCCESS)
{
System.exit(resultCode.intValue());
}
}
public ExampleCommandLineTool()
{
super(System.out, System.err);
}
// The rest of the tool implementation goes here.
...
}
.
Note that in general, methods in this class are not threadsafe. However, the
out(Object...) and err(Object...) methods may be invoked
concurrently by any number of threads.-
Constructor Summary
ConstructorsConstructorDescriptionCommandLineTool(OutputStream outStream, OutputStream errStream) Creates a new instance of this command-line tool with the provided information. -
Method Summary
Modifier and TypeMethodDescriptionprotected voidaddEnableSSLDebuggingArgument(BooleanArgument enableSSLDebuggingArgument) Adds the provided argument to the set of arguments that may be used to enable JVM SSL/TLS debugging.abstract voidaddToolArguments(ArgumentParser parser) Adds the command-line arguments supported for use with this tool to the provided argument parser.final ArgumentParserCreates a parser that can be used to to parse arguments accepted by this tool.booleanIndicates whether this tool defaults to launching in interactive mode if the tool is invoked without any command-line arguments.voidPerforms any necessary processing that should be done to ensure that the provided set of command-line arguments were valid.protected voiddoShutdownHookProcessing(ResultCode resultCode) Performs any processing that may be needed when the JVM is shutting down, whether because tool processing has completed or because it has been interrupted (e.g., by a kill or break signal).abstract ResultCodePerforms the core set of processing for this tool.final voidWrites the provided message to the standard error stream for this tool.Retrieves additional paragraphs that should be included in the description for this tool.final PrintStreamgetErr()Retrieves the print stream that will be used for standard error.Retrieves a set of information that may be used to generate example usage information.intRetrieves the maximum number of unnamed trailing arguments that may be provided for this tool.intRetrieves the minimum number of unnamed trailing arguments that must be provided for this tool.final PrintStreamRetrieves the print stream that may be used to write to the original standard error.final PrintStreamRetrieves the print stream that may be used to write to the original standard output.final PrintStreamgetOut()Retrieves the print stream that will be used for standard output.final PasswordFileReaderRetrieves the password file reader for this tool, which may be used to read passwords from (optionally compressed and encrypted) files.protected StringRetrieves an optional message that may provide additional information about the way that the tool completed its processing.abstract StringRetrieves a human-readable description for this tool.abstract StringRetrieves the name of this tool.Retrieves a version string for this tool, if available.Retrieves a placeholder string that should be used for trailing arguments in the usage information for this tool.protected booleanIndicates whether to log messages about the launch and completion of this tool into the invocation log of Ping Identity server products that may include it.final voidWrites the provided message to the standard output stream for this tool.protected booleanIndicates whether this tool should register a shutdown hook with the JVM.Interactively prompts the user for information needed to invoke this tool and returns an appropriate list of arguments that should be used to run it.final ResultCodePerforms all processing for this command-line tool.protected booleanIndicates whether this tool supports the ability to generate a debug log file.booleanIndicates whether this tool should provide support for an interactive mode, in which the tool offers a mode in which the arguments can be provided in a text-driven menu rather than requiring them to be given on the command line.protected booleanIndicates whether this tool should provide arguments for redirecting output to a file.booleanIndicates whether this tool supports the use of a properties file for specifying default values for arguments that aren't specified on the command line.final voidWrites the provided message to the standard error stream for this tool, optionally wrapping and/or indenting the text in the process.final voidWrites the provided message to the standard output stream for this tool, optionally wrapping and/or indenting the text in the process.
-
Constructor Details
-
CommandLineTool
Creates a new instance of this command-line tool with the provided information.- Parameters:
outStream- The output stream to use for standard output. It may beSystem.outfor the JVM's default standard output stream,nullif no output should be generated, or a custom output stream if the output should be sent to an alternate location.errStream- The output stream to use for standard error. It may beSystem.errfor the JVM's default standard error stream,nullif no output should be generated, or a custom output stream if the output should be sent to an alternate location.
-
-
Method Details
-
runTool
Performs all processing for this command-line tool. This includes:- Creating the argument parser and populating it using the
addToolArguments(com.unboundid.util.args.ArgumentParser)method. - Parsing the provided set of command line arguments, including any
additional validation using the
doExtendedArgumentValidation()method. - Invoking the
doToolProcessing()method to do the appropriate work for this tool.
- Parameters:
args- The command-line arguments provided to this program.- Returns:
- The result of processing this tool. It should be
ResultCode.SUCCESSif the tool completed its work successfully, or some other result if a problem occurred.
- Creating the argument parser and populating it using the
-
getToolName
Retrieves the name of this tool. It should be the name of the command used to invoke this tool.- Returns:
- The name for this tool.
-
getToolDescription
Retrieves a human-readable description for this tool. If the description should include multiple paragraphs, then this method should return the text for the first paragraph, and thegetAdditionalDescriptionParagraphs()method should be used to return the text for the subsequent paragraphs.- Returns:
- A human-readable description for this tool.
-
getAdditionalDescriptionParagraphs
Retrieves additional paragraphs that should be included in the description for this tool. If the tool description should include multiple paragraphs, then thegetToolDescription()method should return the text of the first paragraph, and each item in the list returned by this method should be the text for each subsequent paragraph. If the tool description should only have a single paragraph, then this method may returnnullor an empty list.- Returns:
- Additional paragraphs that should be included in the description
for this tool, or
nullor an empty list if only a single description paragraph (whose text is returned by thegetToolDescriptionmethod) is needed.
-
getToolVersion
Retrieves a version string for this tool, if available.- Returns:
- A version string for this tool, or
nullif none is available.
-
getMinTrailingArguments
Retrieves the minimum number of unnamed trailing arguments that must be provided for this tool. If a tool requires the use of trailing arguments, then it must override this method and thegetMaxTrailingArguments()arguments to return nonzero values, and it must also override thegetTrailingArgumentsPlaceholder()method to return a non-nullvalue.- Returns:
- The minimum number of unnamed trailing arguments that may be provided for this tool. A value of zero indicates that the tool may be invoked without any trailing arguments.
-
getMaxTrailingArguments
Retrieves the maximum number of unnamed trailing arguments that may be provided for this tool. If a tool supports trailing arguments, then it must override this method to return a nonzero value, and must also override thegetTrailingArgumentsPlaceholder()method to return a non-nullvalue.- Returns:
- The maximum number of unnamed trailing arguments that may be provided for this tool. A value of zero indicates that trailing arguments are not allowed. A negative value indicates that there should be no limit on the number of trailing arguments.
-
getTrailingArgumentsPlaceholder
Retrieves a placeholder string that should be used for trailing arguments in the usage information for this tool.- Returns:
- A placeholder string that should be used for trailing arguments in
the usage information for this tool, or
nullif trailing arguments are not supported.
-
supportsInteractiveMode
Indicates whether this tool should provide support for an interactive mode, in which the tool offers a mode in which the arguments can be provided in a text-driven menu rather than requiring them to be given on the command line. If interactive mode is supported, it may be invoked using the "--interactive" argument. Alternately, if interactive mode is supported anddefaultsToInteractiveMode()returnstrue, then interactive mode may be invoked by simply launching the tool without any arguments.- Returns:
trueif this tool supports interactive mode, orfalseif not.
-
defaultsToInteractiveMode
Indicates whether this tool defaults to launching in interactive mode if the tool is invoked without any command-line arguments. This will only be used ifsupportsInteractiveMode()returnstrue.- Returns:
trueif this tool defaults to using interactive mode if launched without any command-line arguments, orfalseif not.
-
requestToolArgumentsInteractively
@Nullable protected List<String> requestToolArgumentsInteractively(@NotNull ArgumentParser parser) throws LDAPException Interactively prompts the user for information needed to invoke this tool and returns an appropriate list of arguments that should be used to run it.
This method will only be invoked ifsupportsInteractiveMode()returnstrue, and if one of the following conditions is satisfied:- The
--interactiveargument is explicitly provided on the command line. - The tool was invoked without any command-line arguments and
defaultsToInteractiveMode()returnstrue.
null, then the LDAP SDK's default interactive mode processing will be performed. Otherwise, the tool will be invoked with only the arguments in the list that is returned.- Parameters:
parser- The argument parser that has been used to parse any command-line arguments that were provided before the interactive mode processing was invoked. If this method returns a non-nullvalue, then this parser will be reset before parsing the new set of arguments.- Returns:
- Retrieves a list of command-line arguments that may be used to
invoke this tool, or
nullif the LDAP SDK's default interactive mode processing should be performed. - Throws:
LDAPException- If a problem is encountered while interactively obtaining the arguments that should be used to run the tool.
- The
-
supportsPropertiesFile
Indicates whether this tool supports the use of a properties file for specifying default values for arguments that aren't specified on the command line.- Returns:
trueif this tool supports the use of a properties file for specifying default values for arguments that aren't specified on the command line, orfalseif not.
-
supportsOutputFile
Indicates whether this tool should provide arguments for redirecting output to a file. If this method returnstrue, then the tool will offer an "--outputFile" argument that will specify the path to a file to which all standard output and standard error content will be written, and it will also offer a "--teeToStandardOut" argument that can only be used if the "--outputFile" argument is present and will cause all output to be written to both the specified output file and to standard output.- Returns:
trueif this tool should provide arguments for redirecting output to a file, orfalseif not.
-
supportsDebugLogging
Indicates whether this tool supports the ability to generate a debug log file. If this method returnstrue, then the tool will expose additional arguments that can control debug logging.- Returns:
trueif this tool supports the ability to generate a debug log file, orfalseif not.
-
logToolInvocationByDefault
Indicates whether to log messages about the launch and completion of this tool into the invocation log of Ping Identity server products that may include it. This method is not needed for tools that are not expected to be part of the Ping Identity server products suite. Further, this value may be overridden by settings in the server's tool-invocation-logging.properties file.
This method should generally returntruefor tools that may alter the server configuration, data, or other state information, andfalsefor tools that do not make any changes.- Returns:
trueif Ping Identity server products should include messages about the launch and completion of this tool in tool invocation log files by default, orfalseif not.
-
getToolCompletionMessage
Retrieves an optional message that may provide additional information about the way that the tool completed its processing. For example if the tool exited with an error message, it may be useful for this method to return that error message.
The message returned by this method is intended for informational purposes and is not meant to be parsed or programmatically interpreted.- Returns:
- An optional message that may provide additional information about
the completion state for this tool, or
nullif no completion message is available.
-
createArgumentParser
Creates a parser that can be used to to parse arguments accepted by this tool.- Returns:
- ArgumentParser that can be used to parse arguments for this tool.
- Throws:
ArgumentException- If there was a problem initializing the parser for this tool.
-
addEnableSSLDebuggingArgument
Adds the provided argument to the set of arguments that may be used to enable JVM SSL/TLS debugging.- Parameters:
enableSSLDebuggingArgument- The argument to add to the set of arguments that may be used to enable JVM SSL/TLS debugging.
-
addToolArguments
Adds the command-line arguments supported for use with this tool to the provided argument parser. The tool may need to retain references to the arguments (and/or the argument parser, if trailing arguments are allowed) to it in order to obtain their values for use in later processing.- Parameters:
parser- The argument parser to which the arguments are to be added.- Throws:
ArgumentException- If a problem occurs while adding any of the tool-specific arguments to the provided argument parser.
-
doExtendedArgumentValidation
Performs any necessary processing that should be done to ensure that the provided set of command-line arguments were valid. This method will be called after the basic argument parsing has been performed and immediately before thedoToolProcessing()method is invoked. Note that if the tool supports interactive mode, then this method may be invoked multiple times to allow the user to interactively fix validation errors.- Throws:
ArgumentException- If there was a problem with the command-line arguments provided to this program.
-
doToolProcessing
Performs the core set of processing for this tool.- Returns:
- A result code that indicates whether the processing completed successfully.
-
registerShutdownHook
Indicates whether this tool should register a shutdown hook with the JVM. Shutdown hooks allow for a best-effort attempt to perform a specified set of processing when the JVM is shutting down under various conditions, including:- When all non-daemon threads have stopped running (i.e., the tool has completed processing).
- When
System.exit()orRuntime.exit()is called. - When the JVM receives an external kill signal (e.g., via the use of the kill tool or interrupting the JVM with Ctrl+C).
System.halt()orRuntime.halt()methods).
If this method is overridden to returntrue, then thedoShutdownHookProcessing(ResultCode)method should also be overridden to contain the logic that will be invoked when the JVM is shutting down in a manner that calls shutdown hooks.- Returns:
trueif this tool should register a shutdown hook, orfalseif not.
-
doShutdownHookProcessing
Performs any processing that may be needed when the JVM is shutting down, whether because tool processing has completed or because it has been interrupted (e.g., by a kill or break signal).
Note that because shutdown hooks run at a delicate time in the life of the JVM, they should complete quickly and minimize access to external resources. See the documentation for thejava.lang.Runtime.addShutdownHookmethod for recommendations and restrictions about writing shutdown hooks.- Parameters:
resultCode- The result code returned by the tool. It may benullif the tool was interrupted before it completed processing.
-
getExampleUsages
@ThreadSafety(level=METHOD_THREADSAFE) @Nullable public LinkedHashMap<String[],String> getExampleUsages()Retrieves a set of information that may be used to generate example usage information. Each element in the returned map should consist of a map between an example set of arguments and a string that describes the behavior of the tool when invoked with that set of arguments.- Returns:
- A set of information that may be used to generate example usage
information. It may be
nullor empty if no example usage information is available.
-
getPasswordFileReader
Retrieves the password file reader for this tool, which may be used to read passwords from (optionally compressed and encrypted) files.- Returns:
- The password file reader for this tool.
-
getOut
Retrieves the print stream that will be used for standard output.- Returns:
- The print stream that will be used for standard output.
-
getOriginalOut
Retrieves the print stream that may be used to write to the original standard output. This may be different from the current standard output stream if an output file has been configured.- Returns:
- The print stream that may be used to write to the original standard output.
-
out
Writes the provided message to the standard output stream for this tool.
This method is completely threadsafe and my be invoked concurrently by any number of threads.- Parameters:
msg- The message components that will be written to the standard output stream. They will be concatenated together on the same line, and that line will be followed by an end-of-line sequence.
-
wrapOut
@ThreadSafety(level=METHOD_THREADSAFE) public final void wrapOut(int indent, int wrapColumn, @NotNull Object... msg) Writes the provided message to the standard output stream for this tool, optionally wrapping and/or indenting the text in the process.
This method is completely threadsafe and my be invoked concurrently by any number of threads.- Parameters:
indent- The number of spaces each line should be indented. A value less than or equal to zero indicates that no indent should be used.wrapColumn- The column at which to wrap long lines. A value less than or equal to two indicates that no wrapping should be performed. If both an indent and a wrap column are to be used, then the wrap column must be greater than the indent.msg- The message components that will be written to the standard output stream. They will be concatenated together on the same line, and that line will be followed by an end-of-line sequence.
-
getErr
Retrieves the print stream that will be used for standard error.- Returns:
- The print stream that will be used for standard error.
-
getOriginalErr
Retrieves the print stream that may be used to write to the original standard error. This may be different from the current standard error stream if an output file has been configured.- Returns:
- The print stream that may be used to write to the original standard error.
-
err
Writes the provided message to the standard error stream for this tool.
This method is completely threadsafe and my be invoked concurrently by any number of threads.- Parameters:
msg- The message components that will be written to the standard error stream. They will be concatenated together on the same line, and that line will be followed by an end-of-line sequence.
-
wrapErr
@ThreadSafety(level=METHOD_THREADSAFE) public final void wrapErr(int indent, int wrapColumn, @NotNull Object... msg) Writes the provided message to the standard error stream for this tool, optionally wrapping and/or indenting the text in the process.
This method is completely threadsafe and my be invoked concurrently by any number of threads.- Parameters:
indent- The number of spaces each line should be indented. A value less than or equal to zero indicates that no indent should be used.wrapColumn- The column at which to wrap long lines. A value less than or equal to two indicates that no wrapping should be performed. If both an indent and a wrap column are to be used, then the wrap column must be greater than the indent.msg- The message components that will be written to the standard output stream. They will be concatenated together on the same line, and that line will be followed by an end-of-line sequence.
-