use of com.unboundid.util.args.ArgumentException in project ldapsdk by pingidentity.
the class LDIFSearch method readFilterFile.
/**
* Uses the contents of any specified filter files, along with the configured
* base DN, scope, and requested attributes, to populate the set of search
* URLs.
*
* @throws ArgumentException If a problem is encountered while constructing
* the search URLs.
*/
private void readFilterFile() throws ArgumentException {
DN dn = baseDN.getValue();
if (dn == null) {
dn = DN.NULL_DN;
}
SearchScope searchScope = scope.getValue();
if (searchScope == null) {
searchScope = SearchScope.SUB;
}
final String[] requestedAttributes = parser.getTrailingArguments().toArray(StaticUtils.NO_STRINGS);
for (final File f : filterFile.getValues()) {
final InputStream inputStream;
try {
inputStream = openInputStream(f);
} catch (final LDAPException e) {
Debug.debugException(e);
throw new ArgumentException(e.getMessage(), e);
}
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
while (true) {
final String line = reader.readLine();
if (line == null) {
break;
}
if (line.isEmpty() || line.startsWith("#")) {
continue;
}
try {
final Filter filter = Filter.create(line.trim());
searchURLs.add(new LDAPURL("ldap", null, null, dn, requestedAttributes, searchScope, filter));
} catch (final LDAPException e) {
Debug.debugException(e);
throw new ArgumentException(ERR_LDIFSEARCH_FILTER_FILE_INVALID_FILTER.get(line, f.getAbsolutePath(), e.getMessage()), e);
}
}
} catch (final IOException e) {
Debug.debugException(e);
throw new ArgumentException(ERR_LDIFSEARCH_ERROR_READING_FILTER_FILE.get(f.getAbsolutePath(), StaticUtils.getExceptionMessage(e)), e);
} finally {
try {
inputStream.close();
} catch (final Exception e) {
Debug.debugException(e);
}
}
}
if (searchURLs.isEmpty()) {
throw new ArgumentException(ERR_LDIFSEARCH_NO_FILTERS_FROM_FILE.get(filterFile.getValues().get(0).getAbsolutePath()));
}
}
use of com.unboundid.util.args.ArgumentException 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();
}
}
}
use of com.unboundid.util.args.ArgumentException in project ldapsdk by pingidentity.
the class CommandLineToolInteractiveModeProcessor method promptForControl.
/**
* Prompts for one or more control values.
*
* @param a The control argument for which to prompt.
*
* @throws LDAPException If a problem is encountered while interacting with
* the user, or if the user wants to quit.
*/
private void promptForControl(@NotNull final ControlArgument a) throws LDAPException {
final List<Control> values = a.getValues();
ArgumentHelper.reset(a);
if (a.getMaxOccurrences() == 1) {
if (!values.isEmpty()) {
tool.out();
tool.wrapStandardOut(0, 0, wrapColumn, true, INFO_INTERACTIVE_ARG_DESC_CURRENT_VALUE.get());
tool.wrapStandardOut(5, 10, wrapColumn, true, values.get(0));
}
while (true) {
final String newValue = promptForString(INFO_INTERACTIVE_ARG_PROMPT_NEW_VALUE.get(), null, false);
try {
if (newValue == null) {
ArgumentHelper.addValue(a, "");
} else {
ArgumentHelper.addValue(a, newValue);
}
return;
} catch (final ArgumentException ae) {
Debug.debugException(ae);
tool.wrapErr(0, wrapColumn, ERR_INTERACTIVE_ARG_PROMPT_INVALID_VALUE.get(ae.getMessage()));
}
}
} else {
if (!values.isEmpty()) {
tool.out();
tool.wrapStandardOut(0, 0, wrapColumn, true, INFO_INTERACTIVE_ARG_DESC_CURRENT_VALUES.get());
for (final Control c : values) {
tool.wrapStandardOut(5, 10, wrapColumn, true, c);
}
}
tool.out();
tool.wrapStandardOut(0, 0, wrapColumn, true, INFO_INTERACTIVE_ARG_PROMPT_NEW_VALUES.get());
boolean first = true;
while (true) {
final String s = promptForString(INFO_INTERACTIVE_ARG_PROMPT_NEW_VALUE.get(), null, (first && a.isRequired()));
if (s == null) {
return;
}
try {
ArgumentHelper.addValue(a, s);
first = false;
} catch (final ArgumentException ae) {
Debug.debugException(ae);
tool.wrapErr(0, wrapColumn, ERR_INTERACTIVE_ARG_PROMPT_INVALID_VALUE.get(ae.getMessage()));
}
}
}
}
use of com.unboundid.util.args.ArgumentException in project ldapsdk by pingidentity.
the class LDAPCompare method doExtendedNonLDAPArgumentValidation.
/**
* {@inheritDoc}
*/
@Override()
public void doExtendedNonLDAPArgumentValidation() throws ArgumentException {
// There must have been at least two trailing arguments provided. The first
// must be in the form "attr:value". All subsequent trailing arguments
// must be parsable as valid DNs.
final List<String> trailingArgs = parser.getTrailingArguments();
if (trailingArgs.size() < 2) {
throw new ArgumentException("At least two trailing argument must be " + "provided to specify the assertion criteria in the form " + "'attr:value'. All additional trailing arguments must be the " + "DNs of the entries against which to perform the compare.");
}
final Iterator<String> argIterator = trailingArgs.iterator();
final String ava = argIterator.next();
if (ava.indexOf(':') < 1) {
throw new ArgumentException("The first trailing argument value must " + "specify the assertion criteria in the form 'attr:value'.");
}
while (argIterator.hasNext()) {
final String arg = argIterator.next();
try {
new DN(arg);
} catch (final Exception e) {
Debug.debugException(e);
throw new ArgumentException("Unable to parse trailing argument '" + arg + "' as a valid DN.", e);
}
}
}
use of com.unboundid.util.args.ArgumentException in project ldapsdk by pingidentity.
the class CollectSupportData method doExtendedNonLDAPArgumentValidation.
/**
* {@inheritDoc}
*/
@Override()
public void doExtendedNonLDAPArgumentValidation() throws ArgumentException {
// to the start time.
if (logTimeRangeArg.isPresent()) {
try {
parseTimeRange(logTimeRangeArg.getValue(), useRemoteServerArg.isPresent());
} catch (final LDAPException e) {
Debug.debugException(e);
toolCompletionMessage.set(e.getMessage());
throw new ArgumentException(e.getMessage(), e);
}
}
// --generatePassphrase argument, then make sure the file exists.
if (passphraseFileArg.isPresent() && (!generatePassphraseArg.isPresent())) {
final File passphraseFile = passphraseFileArg.getValue();
if (!passphraseFile.exists()) {
final String message = ERR_CSD_PASSPHRASE_FILE_MISSING.get(passphraseFile.getAbsolutePath());
toolCompletionMessage.set(message);
throw new ArgumentException(message);
}
}
// also have been provided.
if (noPromptArg.isPresent() && (encryptArg.isPresent() || decryptArg.isPresent()) && (!passphraseFileArg.isPresent())) {
final String message = ERR_CSD_NO_PASSPHRASE_WITH_NO_PROMPT.get();
toolCompletionMessage.set(message);
throw new ArgumentException(message);
}
}
Aggregations