Search in sources :

Example 1 with ToolInvocationLogShutdownHook

use of com.unboundid.ldap.sdk.unboundidds.tools.ToolInvocationLogShutdownHook in project ldapsdk by pingidentity.

the class CommandLineTool method runTool.

/**
 * Performs all processing for this command-line tool.  This includes:
 * <UL>
 *   <LI>Creating the argument parser and populating it using the
 *       {@link #addToolArguments} method.</LI>
 *   <LI>Parsing the provided set of command line arguments, including any
 *       additional validation using the {@link #doExtendedArgumentValidation}
 *       method.</LI>
 *   <LI>Invoking the {@link #doToolProcessing} method to do the appropriate
 *       work for this tool.</LI>
 * </UL>
 *
 * @param  args  The command-line arguments provided to this program.
 *
 * @return  The result of processing this tool.  It should be
 *          {@link ResultCode#SUCCESS} if the tool completed its work
 *          successfully, or some other result if a problem occurred.
 */
@NotNull()
public final ResultCode runTool(@Nullable final String... args) {
    final ArgumentParser parser;
    try {
        parser = createArgumentParser();
        boolean exceptionFromParsingWithNoArgumentsExplicitlyProvided = false;
        if (supportsInteractiveMode() && defaultsToInteractiveMode() && ((args == null) || (args.length == 0))) {
            // arguments when run non-interactively.
            try {
                parser.parse(StaticUtils.NO_STRINGS);
            } catch (final Exception e) {
                Debug.debugException(e);
                exceptionFromParsingWithNoArgumentsExplicitlyProvided = true;
            }
        } else if (args == null) {
            parser.parse(StaticUtils.NO_STRINGS);
        } else {
            parser.parse(args);
        }
        final File generatedPropertiesFile = parser.getGeneratedPropertiesFile();
        if (supportsPropertiesFile() && (generatedPropertiesFile != null)) {
            wrapOut(0, StaticUtils.TERMINAL_WIDTH_COLUMNS - 1, INFO_CL_TOOL_WROTE_PROPERTIES_FILE.get(generatedPropertiesFile.getAbsolutePath()));
            return ResultCode.SUCCESS;
        }
        if (helpArgument.isPresent()) {
            out(parser.getUsageString(StaticUtils.TERMINAL_WIDTH_COLUMNS - 1));
            displayExampleUsages(parser);
            return ResultCode.SUCCESS;
        }
        if ((helpSASLArgument != null) && helpSASLArgument.isPresent()) {
            String mechanism = null;
            final Argument saslOptionArgument = parser.getNamedArgument("saslOption");
            if ((saslOptionArgument != null) && saslOptionArgument.isPresent()) {
                for (final String value : saslOptionArgument.getValueStringRepresentations(false)) {
                    final String lowerValue = StaticUtils.toLowerCase(value);
                    if (lowerValue.startsWith("mech=")) {
                        final String mech = value.substring(5).trim();
                        if (!mech.isEmpty()) {
                            mechanism = mech;
                            break;
                        }
                    }
                }
            }
            out(SASLUtils.getUsageString(mechanism, StaticUtils.TERMINAL_WIDTH_COLUMNS - 1));
            return ResultCode.SUCCESS;
        }
        if ((helpSubcommandsArgument != null) && helpSubcommandsArgument.isPresent()) {
            final TreeMap<String, SubCommand> subCommands = getSortedSubCommands(parser);
            for (final SubCommand sc : subCommands.values()) {
                final StringBuilder nameBuffer = new StringBuilder();
                final Iterator<String> nameIterator = sc.getNames(false).iterator();
                while (nameIterator.hasNext()) {
                    nameBuffer.append(nameIterator.next());
                    if (nameIterator.hasNext()) {
                        nameBuffer.append(", ");
                    }
                }
                out(nameBuffer.toString());
                for (final String descriptionLine : StaticUtils.wrapLine(sc.getDescription(), (StaticUtils.TERMINAL_WIDTH_COLUMNS - 3))) {
                    out("  " + descriptionLine);
                }
                out();
            }
            wrapOut(0, (StaticUtils.TERMINAL_WIDTH_COLUMNS - 1), INFO_CL_TOOL_USE_SUBCOMMAND_HELP.get(getToolName()));
            return ResultCode.SUCCESS;
        }
        if ((versionArgument != null) && versionArgument.isPresent()) {
            out(getToolVersion());
            return ResultCode.SUCCESS;
        }
        // connection attempt is made.
        for (final BooleanArgument a : enableSSLDebuggingArguments) {
            if (a.isPresent()) {
                StaticUtils.setSystemProperty("javax.net.debug", "all");
            }
        }
        boolean extendedValidationDone = false;
        if (interactiveArgument != null) {
            if (interactiveArgument.isPresent() || (defaultsToInteractiveMode() && ((args == null) || (args.length == 0)) && (parser.getArgumentsSetFromPropertiesFile().isEmpty() || exceptionFromParsingWithNoArgumentsExplicitlyProvided))) {
                try {
                    final List<String> interactiveArgs = requestToolArgumentsInteractively(parser);
                    if (interactiveArgs == null) {
                        final CommandLineToolInteractiveModeProcessor processor = new CommandLineToolInteractiveModeProcessor(this, parser);
                        processor.doInteractiveModeProcessing();
                        extendedValidationDone = true;
                    } else {
                        ArgumentHelper.reset(parser);
                        parser.parse(StaticUtils.toArray(interactiveArgs, String.class));
                    }
                } catch (final LDAPException le) {
                    Debug.debugException(le);
                    final String message = le.getMessage();
                    if ((message != null) && (!message.isEmpty())) {
                        err(message);
                    }
                    return le.getResultCode();
                }
            }
        }
        if (!extendedValidationDone) {
            doExtendedArgumentValidation();
        }
    } catch (final ArgumentException ae) {
        Debug.debugException(ae);
        err(ae.getMessage());
        return ResultCode.PARAM_ERROR;
    }
    PrintStream outputFileStream = null;
    if ((outputFileArgument != null) && outputFileArgument.isPresent()) {
        final File outputFile = outputFileArgument.getValue();
        final boolean append = ((appendToOutputFileArgument != null) && appendToOutputFileArgument.isPresent());
        try {
            final FileOutputStream fos = new FileOutputStream(outputFile, append);
            outputFileStream = new PrintStream(fos, true, "UTF-8");
        } catch (final Exception e) {
            Debug.debugException(e);
            err(ERR_CL_TOOL_ERROR_CREATING_OUTPUT_FILE.get(outputFile.getAbsolutePath(), StaticUtils.getExceptionMessage(e)));
            return ResultCode.LOCAL_ERROR;
        }
        if ((teeOutputArgument != null) && teeOutputArgument.isPresent()) {
            out = new PrintStream(new TeeOutputStream(out, outputFileStream));
            err = new PrintStream(new TeeOutputStream(err, outputFileStream));
        } else {
            out = outputFileStream;
            err = outputFileStream;
        }
    }
    try {
        // If any values were selected using a properties file, then display
        // information about them.
        final List<String> argsSetFromPropertiesFiles = parser.getArgumentsSetFromPropertiesFile();
        if ((!argsSetFromPropertiesFiles.isEmpty()) && (!parser.suppressPropertiesFileComment())) {
            for (final String line : StaticUtils.wrapLine(INFO_CL_TOOL_ARGS_FROM_PROPERTIES_FILE.get(parser.getPropertiesFileUsed().getPath()), (StaticUtils.TERMINAL_WIDTH_COLUMNS - 3))) {
                out("# ", line);
            }
            final StringBuilder buffer = new StringBuilder();
            for (final String s : argsSetFromPropertiesFiles) {
                if (s.startsWith("-")) {
                    if (buffer.length() > 0) {
                        out(buffer);
                        buffer.setLength(0);
                    }
                    buffer.append("#      ");
                    buffer.append(s);
                } else {
                    if (buffer.length() == 0) {
                        // This should never happen.
                        buffer.append("#      ");
                    } else {
                        buffer.append(' ');
                    }
                    buffer.append(StaticUtils.cleanExampleCommandLineArgument(s));
                }
            }
            if (buffer.length() > 0) {
                out(buffer);
            }
            out();
        }
        CommandLineToolShutdownHook shutdownHook = null;
        final AtomicReference<ResultCode> exitCode = new AtomicReference<>();
        if (registerShutdownHook()) {
            shutdownHook = new CommandLineToolShutdownHook(this, exitCode);
            Runtime.getRuntime().addShutdownHook(shutdownHook);
        }
        final ToolInvocationLogDetails logDetails = ToolInvocationLogger.getLogMessageDetails(getToolName(), logToolInvocationByDefault(), getErr());
        ToolInvocationLogShutdownHook logShutdownHook = null;
        if (logDetails.logInvocation()) {
            final HashSet<Argument> argumentsSetFromPropertiesFile = new HashSet<>(StaticUtils.computeMapCapacity(10));
            final ArrayList<ObjectPair<String, String>> propertiesFileArgList = new ArrayList<>(10);
            getToolInvocationPropertiesFileArguments(parser, argumentsSetFromPropertiesFile, propertiesFileArgList);
            final ArrayList<ObjectPair<String, String>> providedArgList = new ArrayList<>(10);
            getToolInvocationProvidedArguments(parser, argumentsSetFromPropertiesFile, providedArgList);
            logShutdownHook = new ToolInvocationLogShutdownHook(logDetails);
            Runtime.getRuntime().addShutdownHook(logShutdownHook);
            final String propertiesFilePath;
            if (propertiesFileArgList.isEmpty()) {
                propertiesFilePath = "";
            } else {
                final File propertiesFile = parser.getPropertiesFileUsed();
                if (propertiesFile == null) {
                    propertiesFilePath = "";
                } else {
                    propertiesFilePath = propertiesFile.getAbsolutePath();
                }
            }
            ToolInvocationLogger.logLaunchMessage(logDetails, providedArgList, propertiesFileArgList, propertiesFilePath);
        }
        try {
            exitCode.set(doToolProcessing());
        } catch (final Exception e) {
            Debug.debugException(e);
            err(StaticUtils.getExceptionMessage(e));
            exitCode.set(ResultCode.LOCAL_ERROR);
        } finally {
            if (logShutdownHook != null) {
                Runtime.getRuntime().removeShutdownHook(logShutdownHook);
                String completionMessage = getToolCompletionMessage();
                if (completionMessage == null) {
                    completionMessage = exitCode.get().getName();
                }
                ToolInvocationLogger.logCompletionMessage(logDetails, exitCode.get().intValue(), completionMessage);
            }
            if (shutdownHook != null) {
                Runtime.getRuntime().removeShutdownHook(shutdownHook);
            }
        }
        return exitCode.get();
    } finally {
        if (outputFileStream != null) {
            outputFileStream.close();
        }
    }
}
Also used : ToolInvocationLogShutdownHook(com.unboundid.ldap.sdk.unboundidds.tools.ToolInvocationLogShutdownHook) FileArgument(com.unboundid.util.args.FileArgument) Argument(com.unboundid.util.args.Argument) BooleanArgument(com.unboundid.util.args.BooleanArgument) ArrayList(java.util.ArrayList) ArgumentParser(com.unboundid.util.args.ArgumentParser) ArgumentException(com.unboundid.util.args.ArgumentException) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) PrintStream(java.io.PrintStream) SubCommand(com.unboundid.util.args.SubCommand) ToolInvocationLogDetails(com.unboundid.ldap.sdk.unboundidds.tools.ToolInvocationLogDetails) BooleanArgument(com.unboundid.util.args.BooleanArgument) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArgumentException(com.unboundid.util.args.ArgumentException) LDAPException(com.unboundid.ldap.sdk.LDAPException) LDAPException(com.unboundid.ldap.sdk.LDAPException) FileOutputStream(java.io.FileOutputStream) File(java.io.File) ResultCode(com.unboundid.ldap.sdk.ResultCode)

Aggregations

LDAPException (com.unboundid.ldap.sdk.LDAPException)1 ResultCode (com.unboundid.ldap.sdk.ResultCode)1 ToolInvocationLogDetails (com.unboundid.ldap.sdk.unboundidds.tools.ToolInvocationLogDetails)1 ToolInvocationLogShutdownHook (com.unboundid.ldap.sdk.unboundidds.tools.ToolInvocationLogShutdownHook)1 Argument (com.unboundid.util.args.Argument)1 ArgumentException (com.unboundid.util.args.ArgumentException)1 ArgumentParser (com.unboundid.util.args.ArgumentParser)1 BooleanArgument (com.unboundid.util.args.BooleanArgument)1 FileArgument (com.unboundid.util.args.FileArgument)1 SubCommand (com.unboundid.util.args.SubCommand)1 File (java.io.File)1 FileOutputStream (java.io.FileOutputStream)1 PrintStream (java.io.PrintStream)1 ArrayList (java.util.ArrayList)1 HashSet (java.util.HashSet)1 LinkedHashSet (java.util.LinkedHashSet)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1