use of com.unboundid.util.args.ArgumentException in project ldapsdk by pingidentity.
the class SplitLDIF method doExtendedArgumentValidation.
/**
* {@inheritDoc}
*/
@Override()
public void doExtendedArgumentValidation() throws ArgumentException {
// If multiple sourceLDIF values were provided, then a target LDIF base path
// must have been given.
final List<File> sourceLDIFValues = sourceLDIF.getValues();
if (sourceLDIFValues.size() > 1) {
if (!targetLDIFBasePath.isPresent()) {
throw new ArgumentException(ERR_SPLIT_LDIF_NO_TARGET_BASE_PATH.get(sourceLDIF.getIdentifierString(), targetLDIFBasePath.getIdentifierString()));
}
}
// equivalent to any of the others.
if (splitUsingFilter.isPresent()) {
final List<Filter> filterList = splitUsingFilterFilter.getValues();
final Set<Filter> filterSet = new LinkedHashSet<>(StaticUtils.computeMapCapacity(filterList.size()));
for (final Filter f : filterList) {
if (filterSet.contains(f)) {
throw new ArgumentException(ERR_SPLIT_LDIF_NON_UNIQUE_FILTER.get(splitUsingFilterFilter.getIdentifierString(), f.toString()));
} else {
filterSet.add(f);
}
}
if (filterSet.size() < 2) {
throw new ArgumentException(ERR_SPLIT_LDIF_NOT_ENOUGH_FILTERS.get(splitUsingFilter.getPrimaryName(), splitUsingFilterFilter.getIdentifierString()));
}
}
}
use of com.unboundid.util.args.ArgumentException in project ldapsdk by pingidentity.
the class CommandLineToolInteractiveModeProcessor method displayInteractiveMenu.
/**
* Displays a menu that allows the user to supply values for the command-line
* arguments. Note that this will not include arguments automatically added
* by the {@link LDAPCommandLineTool} API.
*
* @param ldapArgs A list of the arguments used to connect and authenticate
* to the LDAP server(s) in non-interactive mode. The
* contents of this list may be altered if the user opts to
* change the LDAP connection settings.
*
* @return The tool-specific arguments configured by the user.
*
* @throws LDAPException If a problem is encountered while interacting with
* the user, or if the user wants to quit.
*/
@NotNull()
private List<String> displayInteractiveMenu(@NotNull final List<String> ldapArgs) throws LDAPException {
final ArrayList<Argument> args = new ArrayList<>(parser.getNamedArguments());
if (parser.getSelectedSubCommand() != null) {
args.addAll(parser.getSelectedSubCommand().getArgumentParser().getNamedArguments());
}
final Set<String> usageArguments = CommandLineTool.getUsageArgumentIdentifiers(tool);
final Set<String> ldapArguments;
if (tool instanceof LDAPCommandLineTool) {
ldapArguments = LDAPCommandLineTool.getLongLDAPArgumentIdentifiers(((LDAPCommandLineTool) tool));
} else {
ldapArguments = Collections.emptySet();
}
int maxIdentifierLength = 0;
final String trailingArgsIdentifier = INFO_INTERACTIVE_MENU_TRAILING_ARGS_IDENTIFIER.get();
if (parser.allowsTrailingArguments()) {
maxIdentifierLength = trailingArgsIdentifier.length();
}
final Iterator<Argument> argIterator = args.iterator();
while (argIterator.hasNext()) {
final Argument a = argIterator.next();
final String longID = a.getLongIdentifier();
if (usageArguments.contains(longID) || ldapArguments.contains(longID)) {
argIterator.remove();
} else {
maxIdentifierLength = Math.max(maxIdentifierLength, a.getIdentifierString().length());
}
}
if (args.isEmpty() && (!parser.allowsTrailingArguments())) {
return Collections.emptyList();
} else {
// value.
for (final Argument arg : args) {
if (!arg.isRequired()) {
continue;
}
final List<String> valueStrings = arg.getValueStringRepresentations(true);
if (!valueStrings.isEmpty()) {
continue;
}
promptForArgument(arg);
}
// If the tool requires trailing arguments, then prompt for them.
if (parser.requiresTrailingArguments()) {
promptForTrailingArguments();
}
argsLoop: while (true) {
final int maxNumberLength = String.valueOf(args.size()).length();
final int subsequentIndent = maxNumberLength + maxIdentifierLength + 4;
tool.out();
tool.wrapStandardOut(0, 0, wrapColumn, true, INFO_INTERACTIVE_ARG_MENU_PROMPT.get());
int optionNumber = 1;
for (final Argument arg : args) {
List<String> valueStrings = arg.getValueStringRepresentations(true);
if (arg.isSensitive()) {
final int size = valueStrings.size();
switch(size) {
case 0:
// No need to do any thing.
break;
case 1:
valueStrings = Collections.singletonList("***REDACTED***");
break;
default:
valueStrings = new ArrayList<>(size);
for (int i = 0; i <= size; i++) {
valueStrings.add("***REDACTED" + i + "***");
}
break;
}
}
switch(valueStrings.size()) {
case 0:
tool.wrapStandardOut(0, subsequentIndent, wrapColumn, true, rightAlign(String.valueOf(optionNumber), maxNumberLength), ' ', leftAlign(arg.getIdentifierString(), maxIdentifierLength), " -");
break;
case 1:
tool.wrapStandardOut(0, subsequentIndent, wrapColumn, true, rightAlign(String.valueOf(optionNumber), maxNumberLength), ' ', leftAlign(arg.getIdentifierString(), maxIdentifierLength), " - ", valueStrings.get(0));
break;
default:
tool.wrapStandardOut(0, subsequentIndent, wrapColumn, true, rightAlign(String.valueOf(optionNumber), maxNumberLength), ' ', leftAlign(arg.getIdentifierString(), maxIdentifierLength), " - ", valueStrings.get(0));
for (int i = 1; i < valueStrings.size(); i++) {
tool.wrapStandardOut(0, subsequentIndent, wrapColumn, true, rightAlign("", maxNumberLength), ' ', leftAlign("", maxIdentifierLength), " - ", valueStrings.get(i));
}
break;
}
optionNumber++;
}
if (parser.allowsTrailingArguments()) {
final List<String> trailingArgs = parser.getTrailingArguments();
switch(trailingArgs.size()) {
case 0:
tool.wrapStandardOut(0, subsequentIndent, wrapColumn, true, rightAlign("t", maxNumberLength), ' ', leftAlign(trailingArgsIdentifier, maxIdentifierLength), " -");
break;
case 1:
tool.wrapStandardOut(0, subsequentIndent, wrapColumn, true, rightAlign("t", maxNumberLength), ' ', leftAlign(trailingArgsIdentifier, maxIdentifierLength), " - ", trailingArgs.get(0));
break;
default:
tool.wrapStandardOut(0, subsequentIndent, wrapColumn, true, rightAlign("t", maxNumberLength), ' ', leftAlign(trailingArgsIdentifier, maxIdentifierLength), " - ", trailingArgs.get(0));
for (int i = 1; i < trailingArgs.size(); i++) {
tool.wrapStandardOut(0, subsequentIndent, wrapColumn, true, rightAlign("", maxNumberLength), ' ', leftAlign("", maxIdentifierLength), " - ", trailingArgs.get(i));
}
break;
}
}
tool.out();
if (tool instanceof LDAPCommandLineTool) {
final LDAPCommandLineTool ldapTool = (LDAPCommandLineTool) tool;
if (ldapTool.supportsAuthentication()) {
tool.wrapStandardOut((maxNumberLength - 1), subsequentIndent, wrapColumn, true, "l - ", INFO_INTERACTIVE_MENU_OPTION_REPROMPT_FOR_CONN_AUTH_ARGS.get());
} else {
tool.wrapStandardOut((maxNumberLength - 1), subsequentIndent, wrapColumn, true, "l - ", INFO_INTERACTIVE_MENU_OPTION_REPROMPT_FOR_CONN_ARGS.get());
}
} else if (tool instanceof MultiServerLDAPCommandLineTool) {
tool.wrapStandardOut((maxNumberLength - 1), subsequentIndent, wrapColumn, true, "l - ", INFO_INTERACTIVE_MENU_OPTION_REPROMPT_FOR_CONN_AUTH_ARGS.get());
}
tool.wrapStandardOut((maxNumberLength - 1), subsequentIndent, wrapColumn, true, "d - ", INFO_INTERACTIVE_MENU_OPTION_DISPLAY_ARGS.get(tool.getToolName()));
tool.wrapStandardOut((maxNumberLength - 1), subsequentIndent, wrapColumn, true, "r - ", INFO_INTERACTIVE_MENU_OPTION_RUN.get(tool.getToolName()));
tool.wrapStandardOut((maxNumberLength - 1), subsequentIndent, wrapColumn, true, "q - ", INFO_INTERACTIVE_MENU_OPTION_QUIT.get());
tool.out();
tool.getOut().print(INFO_INTERACTIVE_MENU_ENTER_CHOICE_WITHOUT_DEFAULT.get() + ' ');
final Argument selectedArg;
try {
while (true) {
final String line = systemInReader.readLine().trim();
if (line.equalsIgnoreCase("t") && (tool.getMaxTrailingArguments() != 0)) {
promptForTrailingArguments();
continue argsLoop;
} else if (line.equalsIgnoreCase("l")) {
if (tool instanceof LDAPCommandLineTool) {
promptForLDAPArguments(ldapArgs, true);
} else if (tool instanceof MultiServerLDAPCommandLineTool) {
promptForMultiServerLDAPArguments(ldapArgs, true);
} else {
tool.wrapErr(0, wrapColumn, ERR_INTERACTIVE_ARG_MENU_INVALID_CHOICE.get());
tool.getOut().print(INFO_INTERACTIVE_MENU_ENTER_CHOICE_WITHOUT_DEFAULT.get() + ' ');
}
continue argsLoop;
} else if (line.equalsIgnoreCase("d")) {
try {
validateRequiredExclusiveAndDependentArgumentSets();
tool.doExtendedArgumentValidation();
final ArrayList<String> argStrings = new ArrayList<>(2 * args.size());
final SubCommand subcommand = parser.getSelectedSubCommand();
if (subcommand != null) {
argStrings.add(subcommand.getPrimaryName());
}
argStrings.addAll(ldapArgs);
for (final Argument a : args) {
ArgumentHelper.addToCommandLine(a, argStrings);
}
argStrings.addAll(parser.getTrailingArguments());
if (argStrings.isEmpty()) {
tool.wrapStandardOut(0, 0, wrapColumn, true, INFO_INTERACTIVE_MENU_NO_CURRENT_ARGS.get(tool.getToolName()));
} else {
tool.wrapStandardOut(0, 0, wrapColumn, true, INFO_INTERACTIVE_MENU_CURRENT_ARGS_HEADER.get(tool.getToolName()));
printArgs(argStrings);
}
tool.out();
promptForString(INFO_INTERACTIVE_MENU_PROMPT_PRESS_ENTER_TO_CONTINUE.get(), null, false);
continue argsLoop;
} catch (final ArgumentException ae) {
Debug.debugException(ae);
tool.err();
tool.wrapErr(0, wrapColumn, ERR_INTERACTIVE_MENU_EXTENDED_VALIDATION_ERRORS.get(ae.getMessage()));
tool.err();
tool.wrapErr(0, wrapColumn, ERR_INTERACTIVE_MENU_CORRECT_VALIDATION_ERRORS.get());
tool.err();
promptForString(INFO_INTERACTIVE_MENU_PROMPT_PRESS_ENTER_TO_CONTINUE.get(), null, false);
continue argsLoop;
}
} else if (line.equalsIgnoreCase("r")) {
try {
validateRequiredExclusiveAndDependentArgumentSets();
tool.doExtendedArgumentValidation();
break argsLoop;
} catch (final ArgumentException ae) {
Debug.debugException(ae);
tool.err();
tool.wrapErr(0, wrapColumn, ERR_INTERACTIVE_MENU_EXTENDED_VALIDATION_ERRORS.get(ae.getMessage()));
tool.err();
tool.wrapErr(0, wrapColumn, ERR_INTERACTIVE_MENU_CORRECT_VALIDATION_ERRORS.get());
tool.err();
promptForString(INFO_INTERACTIVE_MENU_PROMPT_PRESS_ENTER_TO_CONTINUE.get(), null, false);
continue argsLoop;
}
} else if (line.equalsIgnoreCase("q")) {
throw new LDAPException(ResultCode.SUCCESS, "");
}
int selectedValue = -1;
try {
selectedValue = Integer.parseInt(line);
} catch (final Exception e) {
Debug.debugException(e);
}
if ((selectedValue < 1) || (selectedValue > args.size())) {
tool.wrapErr(0, wrapColumn, ERR_INTERACTIVE_ARG_MENU_INVALID_CHOICE.get());
tool.getOut().print(INFO_INTERACTIVE_MENU_ENTER_CHOICE_WITHOUT_DEFAULT.get() + ' ');
} else {
selectedArg = args.get(selectedValue - 1);
break;
}
}
} catch (final LDAPException le) {
Debug.debugException(le);
throw le;
} catch (final Exception e) {
Debug.debugException(e);
throw new LDAPException(ResultCode.LOCAL_ERROR, ERR_INTERACTIVE_MENU_CANNOT_READ_CHOICE.get(StaticUtils.getExceptionMessage(e)), e);
}
promptForArgument(selectedArg);
}
final ArrayList<String> argStrings = new ArrayList<>(2 * args.size());
for (final Argument a : args) {
ArgumentHelper.addToCommandLine(a, argStrings);
}
argStrings.addAll(parser.getTrailingArguments());
return argStrings;
}
}
use of com.unboundid.util.args.ArgumentException in project ldapsdk by pingidentity.
the class LDAPDiff method setArgumentPresent.
/**
* Updates the specified argument to indicate that it was provided on the
* command line.
*
* @param argumentName The name of the argument to update as present. It
* must not be {@code null} and must reference a defined
* Boolean argument.
*
* @throws ArgumentException If a problem occurs while attempting to mark
* the specified argument as present.
*/
private void setArgumentPresent(@NotNull final String argumentName) throws ArgumentException {
try {
final BooleanArgument argument = parser.getBooleanArgument(argumentName);
final Method incrementOccurrencesMethod = Argument.class.getDeclaredMethod("incrementOccurrences");
incrementOccurrencesMethod.setAccessible(true);
incrementOccurrencesMethod.invoke(argument);
} catch (final Exception e) {
Debug.debugException(e);
throw new ArgumentException(ERR_LDAP_DIFF_CANNOT_SET_ARG_PRESENT.get(argumentName, StaticUtils.getExceptionMessage(e)), e);
}
}
use of com.unboundid.util.args.ArgumentException in project ldapsdk by pingidentity.
the class LDAPDelete method doExtendedNonLDAPArgumentValidation.
/**
* {@inheritDoc}
*/
@Override()
public void doExtendedNonLDAPArgumentValidation() throws ArgumentException {
// to identify entries to delete are provided.
if (!parser.getTrailingArguments().isEmpty()) {
for (final Argument a : Arrays.asList(entryDN, dnFile, deleteEntriesMatchingFilter, deleteEntriesMatchingFiltersFromFile)) {
if (a.isPresent()) {
throw new ArgumentException(ERR_LDAPDELETE_TRAILING_ARG_CONFLICT.get(a.getIdentifierString()));
}
}
}
// and pre-create those controls.
if (routeToBackendSet.isPresent()) {
final List<String> values = routeToBackendSet.getValues();
final Map<String, List<String>> idsByRP = new LinkedHashMap<>(StaticUtils.computeMapCapacity(values.size()));
for (final String value : values) {
final int colonPos = value.indexOf(':');
if (colonPos <= 0) {
throw new ArgumentException(ERR_LDAPDELETE_ROUTE_TO_BACKEND_SET_INVALID_FORMAT.get(value, routeToBackendSet.getIdentifierString()));
}
final String rpID = value.substring(0, colonPos);
final String bsID = value.substring(colonPos + 1);
List<String> idsForRP = idsByRP.get(rpID);
if (idsForRP == null) {
idsForRP = new ArrayList<>(values.size());
idsByRP.put(rpID, idsForRP);
}
idsForRP.add(bsID);
}
for (final Map.Entry<String, List<String>> e : idsByRP.entrySet()) {
final String rpID = e.getKey();
final List<String> bsIDs = e.getValue();
routeToBackendSetRequestControls.add(RouteToBackendSetRequestControl.createAbsoluteRoutingRequest(true, rpID, bsIDs));
}
}
}
use of com.unboundid.util.args.ArgumentException in project ldapsdk by pingidentity.
the class LDIFSearch method doExtendedArgumentValidation.
/**
* {@inheritDoc}
*/
@Override()
public void doExtendedArgumentValidation() throws ArgumentException {
// If the output file exists and either compressOutput or encryptOutput is
// present, then the overwrite argument must also be present.
final File outFile = outputFile.getValue();
if ((outFile != null) && outFile.exists() && (compressOutput.isPresent() || encryptOutput.isPresent()) && (!overwriteExistingOutputFile.isPresent())) {
throw new ArgumentException(ERR_LDIFSEARCH_APPEND_WITH_COMPRESSION_OR_ENCRYPTION.get(compressOutput.getIdentifierString(), encryptOutput.getIdentifierString(), overwriteExistingOutputFile.getIdentifierString()));
}
// Create the set of LDAP URLs to use when issuing the searches.
final List<String> trailingArgs = parser.getTrailingArguments();
final List<String> requestedAttributes = new ArrayList<>();
if (filterFile.isPresent()) {
// valid filter.
if (!trailingArgs.isEmpty()) {
try {
Filter.create(trailingArgs.get(0));
throw new ArgumentException(ERR_LDIFSEARCH_FILTER_FILE_WITH_TRAILING_FILTER.get());
} catch (final LDAPException e) {
// This was expected.
}
}
requestedAttributes.addAll(trailingArgs);
readFilterFile();
} else if (ldapURLFile.isPresent()) {
// Make sure there aren't any trailing arguments.
if (!trailingArgs.isEmpty()) {
throw new ArgumentException(ERR_LDIFSEARCH_LDAP_URL_FILE_WITH_TRAILING_ARGS.get());
}
readLDAPURLFile();
// requested attributes.
if ((searchURLs.size() > 1) && (!separateOutputFilePerSearch.isPresent())) {
final Iterator<LDAPURL> iterator = searchURLs.iterator();
final Set<String> requestedAttrs = new HashSet<>(Arrays.asList(iterator.next().getAttributes()));
while (iterator.hasNext()) {
final Set<String> attrSet = new HashSet<>(Arrays.asList(iterator.next().getAttributes()));
if (!requestedAttrs.equals(attrSet)) {
throw new ArgumentException(ERR_LDIFSEARCH_DIFFERENT_URL_ATTRS_IN_SAME_FILE.get(ldapURLFile.getIdentifierString(), separateOutputFilePerSearch.getIdentifierString()));
}
}
}
} else {
// requested arguments.
if (trailingArgs.isEmpty()) {
throw new ArgumentException(ERR_LDIFSEARCH_NO_FILTER.get());
}
final Filter filter;
try {
final List<String> trailingArgList = new ArrayList<>(trailingArgs);
final Iterator<String> trailingArgIterator = trailingArgList.iterator();
filter = Filter.create(trailingArgIterator.next());
while (trailingArgIterator.hasNext()) {
requestedAttributes.add(trailingArgIterator.next());
}
} catch (final LDAPException e) {
Debug.debugException(e);
throw new ArgumentException(ERR_LDIFSEARCH_FIRST_TRAILING_ARG_NOT_FILTER.get(), e);
}
DN dn = baseDN.getValue();
if (dn == null) {
dn = DN.NULL_DN;
}
SearchScope searchScope = scope.getValue();
if (searchScope == null) {
searchScope = SearchScope.SUB;
}
try {
searchURLs.add(new LDAPURL("ldap", null, null, dn, requestedAttributes.toArray(StaticUtils.NO_STRINGS), searchScope, filter));
} catch (final LDAPException e) {
Debug.debugException(e);
// This should never happen.
throw new ArgumentException(StaticUtils.getExceptionMessage(e), e);
}
}
// Create the result writer.
final String outputFormatStr = StaticUtils.toLowerCase(outputFormat.getValue());
if (outputFormatStr.equals("json")) {
resultWriter = new JSONLDAPResultWriter(getOut());
} else if (outputFormatStr.equals("csv") || outputFormatStr.equals("multi-valued-csv") || outputFormatStr.equals("tab-delimited") || outputFormatStr.equals("multi-valued-tab-delimited")) {
// These output formats cannot be used with the --ldapURLFile argument.
if (ldapURLFile.isPresent()) {
throw new ArgumentException(ERR_LDIFSEARCH_OUTPUT_FORMAT_NOT_SUPPORTED_WITH_URLS.get(outputFormat.getValue(), ldapURLFile.getIdentifierString()));
}
// These output formats require a set of requested attributes.
if (requestedAttributes.isEmpty()) {
throw new ArgumentException(ERR_LDIFSEARCH_OUTPUT_FORMAT_REQUIRES_REQUESTED_ATTRS.get(outputFormat.getValue()));
}
final OutputFormat format;
final boolean includeAllValues;
switch(outputFormatStr) {
case "multi-valued-csv":
format = OutputFormat.CSV;
includeAllValues = true;
break;
case "tab-delimited":
format = OutputFormat.TAB_DELIMITED_TEXT;
includeAllValues = false;
break;
case "multi-valued-tab-delimited":
format = OutputFormat.TAB_DELIMITED_TEXT;
includeAllValues = true;
break;
case "csv":
default:
format = OutputFormat.CSV;
includeAllValues = false;
break;
}
resultWriter = new ColumnBasedLDAPResultWriter(getOut(), format, requestedAttributes, WRAP_COLUMN, includeAllValues);
} else if (outputFormatStr.equals("dns-only")) {
resultWriter = new DNsOnlyLDAPResultWriter(getOut());
} else if (outputFormatStr.equals("values-only")) {
resultWriter = new ValuesOnlyLDAPResultWriter(getOut());
} else {
final int wc;
if (doNotWrap.isPresent()) {
wc = Integer.MAX_VALUE;
} else if (wrapColumn.isPresent()) {
wc = wrapColumn.getValue();
} else {
wc = WRAP_COLUMN;
}
resultWriter = new LDIFLDAPResultWriter(getOut(), wc);
}
}
Aggregations