From 2173aa3140a1a35176921dfb8f2f9278b6973d73 Mon Sep 17 00:00:00 2001
From: jvergara <jvergara@localhost>
Date: Mon, 12 Nov 2007 04:26:49 +0000
Subject: [PATCH] Update the dsreplication command-line to be consistent with dsconfig in the use of menus and in the order that questions to connect to the servers. Update the upgrade to use the same menus as the other command-lines. Do some minor changes in the uninstall command-line in order to be more consistent with dsconfig in the order where the connection parameters are provided. Fix a bug in ApplicationTrustManager related to the accepted certificates when there is a mismatch between the certificate and the host name. Do some refactorization of the code and remove the CliApplicationHelper class so that we use ConsoleApplication everywhere.
---
opends/src/server/org/opends/server/tools/InstallDS.java | 55
opends/src/server/org/opends/server/tools/dsconfig/LDAPManagementContextFactory.java | 21
opends/src/server/org/opends/server/admin/client/cli/SecureConnectionCliParser.java | 10
opends/src/server/org/opends/server/util/cli/LDAPConnectionConsoleInteraction.java | 440 ++++-
opends/src/guitools/org/opends/guitools/uninstaller/UninstallerArgumentParser.java | 32
opends/src/messages/messages/quicksetup.properties | 8
opends/src/guitools/org/opends/guitools/replicationcli/ReplicationCliMain.java | 1942 ++++++++++++------------
opends/src/guitools/org/opends/guitools/replicationcli/ReplicationCliArgumentParser.java | 69
opends/src/messages/messages/utility.properties | 3
/dev/null | 1008 -------------
opends/src/quicksetup/org/opends/quicksetup/upgrader/Reverter.java | 44
opends/src/guitools/org/opends/guitools/uninstaller/UninstallCliHelper.java | 235 --
opends/src/quicksetup/org/opends/quicksetup/upgrader/BuildExtractorCliHelper.java | 55
opends/src/ads/org/opends/admin/ads/util/ApplicationTrustManager.java | 20
opends/src/messages/messages/admin_tool.properties | 70
opends/src/quicksetup/org/opends/quicksetup/upgrader/UpgraderCliHelper.java | 60
opends/src/server/org/opends/server/util/cli/ConsoleApplication.java | 357 ++++
opends/src/quicksetup/org/opends/quicksetup/CliUserInteraction.java | 93 +
opends/src/server/org/opends/server/admin/client/cli/SecureConnectionCliArgs.java | 48
19 files changed, 2,078 insertions(+), 2,492 deletions(-)
diff --git a/opends/src/ads/org/opends/admin/ads/util/ApplicationTrustManager.java b/opends/src/ads/org/opends/admin/ads/util/ApplicationTrustManager.java
index 6e0ef96..6add477 100644
--- a/opends/src/ads/org/opends/admin/ads/util/ApplicationTrustManager.java
+++ b/opends/src/ads/org/opends/admin/ads/util/ApplicationTrustManager.java
@@ -79,6 +79,7 @@
private String lastRefusedAuthType;
private X509Certificate[] lastRefusedChain;
private Cause lastRefusedCause = null;
+ private KeyStore keystore = null;
/*
* The following ArrayList contain information about the certificates
@@ -101,6 +102,7 @@
TrustManagerFactory tmf = null;
String algo = "SunX509";
String provider = "SunJSSE";
+ this.keystore = keystore;
try
{
tmf = TrustManagerFactory.getInstance(algo, provider);
@@ -306,7 +308,7 @@
*/
public ApplicationTrustManager createCopy()
{
- ApplicationTrustManager copy = new ApplicationTrustManager(null);
+ ApplicationTrustManager copy = new ApplicationTrustManager(keystore);
copy.lastRefusedAuthType = lastRefusedAuthType;
copy.lastRefusedChain = lastRefusedChain;
copy.lastRefusedCause = lastRefusedCause;
@@ -370,6 +372,22 @@
Rdn rdn = dn.getRdn(0);
String value = rdn.getValue().toString();
matches = host.equalsIgnoreCase(value);
+ if (!matches)
+ {
+ // Try with the accepted hosts names
+ for (int i =0; i<acceptedHosts.size() && !matches; i++)
+ {
+ if (host.equalsIgnoreCase(acceptedHosts.get(i)))
+ {
+ X509Certificate[] current = acceptedChains.get(i);
+ matches = current.length == chain.length;
+ for (int j=0; j<chain.length && matches; j++)
+ {
+ matches = chain[j].equals(current[j]);
+ }
+ }
+ }
+ }
}
catch (Throwable t)
{
diff --git a/opends/src/guitools/org/opends/guitools/replicationcli/ReplicationCliArgumentParser.java b/opends/src/guitools/org/opends/guitools/replicationcli/ReplicationCliArgumentParser.java
index 64138aa..e35937b 100644
--- a/opends/src/guitools/org/opends/guitools/replicationcli/ReplicationCliArgumentParser.java
+++ b/opends/src/guitools/org/opends/guitools/replicationcli/ReplicationCliArgumentParser.java
@@ -40,6 +40,7 @@
import org.opends.quicksetup.Constants;
import org.opends.quicksetup.UserData;
import org.opends.quicksetup.util.Utils;
+import org.opends.server.admin.client.cli.SecureConnectionCliArgs;
import org.opends.server.admin.client.cli.SecureConnectionCliParser;
import org.opends.server.util.args.Argument;
import org.opends.server.util.args.ArgumentException;
@@ -218,21 +219,6 @@
private StringArgument baseDNsArg = null;
/**
- * The 'admin UID' global argument.
- */
- private StringArgument adminUidArg;
-
- /**
- * The 'admin Password' global argument.
- */
- private StringArgument adminPasswordArg;
-
- /**
- * The 'admin Password File' global argument.
- */
- private FileBasedArgument adminPasswordFileArg;
-
- /**
* The 'quiet' argument.
*/
private BooleanArgument quietArg;
@@ -328,10 +314,11 @@
int returnValue;
super.validateGlobalOptions(buf);
ArrayList<Message> errors = new ArrayList<Message>();
- if (adminPasswordArg.isPresent() && adminPasswordFileArg.isPresent()) {
+ if (secureArgsList.bindPasswordArg.isPresent() &&
+ secureArgsList.bindPasswordFileArg.isPresent()) {
Message message = ERR_TOOL_CONFLICTING_ARGS.get(
- adminPasswordArg.getLongIdentifier(),
- adminPasswordFileArg.getLongIdentifier());
+ secureArgsList.bindPasswordArg.getLongIdentifier(),
+ secureArgsList.bindPasswordFileArg.getLongIdentifier());
errors.add(message);
}
@@ -345,8 +332,8 @@
if (getBindPasswordAdmin() == null)
{
errors.add(ERR_REPLICATION_NO_ADMINISTRATOR_PASSWORD_PROVIDED.get(
- adminPasswordArg.getLongIdentifier(),
- adminPasswordFileArg.getLongIdentifier()));
+ secureArgsList.bindPasswordArg.getLongIdentifier(),
+ secureArgsList.bindPasswordFileArg.getLongIdentifier()));
}
}
@@ -411,6 +398,8 @@
}
defaultArgs.remove(noPropertiesFileArg);
defaultArgs.remove(propertiesFileArg);
+ // Remove it from the default location and redefine it.
+ defaultArgs.remove(secureArgsList.adminUidArg);
int index = 0;
@@ -420,25 +409,27 @@
baseDNsArg.setPropertyName(OPTION_LONG_BASEDN);
defaultArgs.add(index++, baseDNsArg);
- adminUidArg = new StringArgument("adminUID", 'I',
+ secureArgsList.adminUidArg = new StringArgument("adminUID", 'I',
"adminUID", false, false, true, "adminUID",
Constants.GLOBAL_ADMIN_UID, null,
INFO_DESCRIPTION_REPLICATION_ADMIN_UID.get(
ENABLE_REPLICATION_SUBCMD_NAME));
- adminUidArg.setPropertyName("adminUID");
- defaultArgs.add(index++, adminUidArg);
+ secureArgsList.adminUidArg.setPropertyName("adminUID");
+ secureArgsList.adminUidArg.setHidden(false);
+ defaultArgs.add(index++, secureArgsList.adminUidArg);
- adminPasswordArg = new StringArgument("adminPassword",
+ secureArgsList.bindPasswordArg = new StringArgument("adminPassword",
OPTION_SHORT_BINDPWD, "adminPassword", false, false, true,
OPTION_VALUE_BINDPWD, null, null,
INFO_DESCRIPTION_REPLICATION_ADMIN_BINDPASSWORD.get());
- defaultArgs.add(index++, adminPasswordArg);
+ defaultArgs.add(index++, secureArgsList.bindPasswordArg);
- adminPasswordFileArg = new FileBasedArgument("adminPasswordFile",
+ secureArgsList.bindPasswordFileArg = new FileBasedArgument(
+ "adminPasswordFile",
OPTION_SHORT_BINDPWD_FILE, "adminPasswordFile", false, false,
OPTION_VALUE_BINDPWD_FILE, null, null,
INFO_DESCRIPTION_REPLICATION_ADMIN_BINDPASSWORDFILE.get());
- defaultArgs.add(index++, adminPasswordFileArg);
+ defaultArgs.add(index++, secureArgsList.bindPasswordFileArg);
defaultArgs.remove(verboseArg);
noPromptArg = new BooleanArgument(
@@ -792,7 +783,8 @@
*/
public String getBindPasswordAdmin()
{
- return getBindPassword(adminPasswordArg, adminPasswordFileArg);
+ return getBindPassword(secureArgsList.bindPasswordArg,
+ secureArgsList.bindPasswordFileArg);
}
/**
@@ -857,8 +849,8 @@
public String getBindPasswordAdmin(
String dn, OutputStream out, OutputStream err)
{
- return getBindPassword(dn, out, err, adminPasswordArg,
- adminPasswordFileArg);
+ return getBindPassword(dn, out, err, secureArgsList.bindPasswordArg,
+ secureArgsList.bindPasswordFileArg);
}
/**
@@ -1039,7 +1031,7 @@
*/
public String getAdministratorUID()
{
- return getValue(adminUidArg);
+ return getValue(secureArgsList.adminUidArg);
}
/**
@@ -1048,7 +1040,7 @@
*/
public String getDefaultAdministratorUID()
{
- return getDefaultValue(adminUidArg);
+ return getDefaultValue(secureArgsList.adminUidArg);
}
/**
@@ -1774,7 +1766,7 @@
Argument[][] conflictingPairs =
{
{secureArgsList.useStartTLSArg, secureArgsList.useSSLArg},
- {adminUidArg, secureArgsList.bindDnArg}
+ {secureArgsList.adminUidArg, secureArgsList.bindDnArg}
};
for (int i=0; i< conflictingPairs.length; i++)
@@ -1913,4 +1905,15 @@
}
return defaultLocalHostValue;
}
+
+ /**
+ * Returns the SecureConnectionCliArgs object containing the arguments
+ * of this parser.
+ * @return the SecureConnectionCliArgs object containing the arguments
+ * of this parser.
+ */
+ SecureConnectionCliArgs getSecureArgsList()
+ {
+ return secureArgsList;
+ }
}
diff --git a/opends/src/guitools/org/opends/guitools/replicationcli/ReplicationCliMain.java b/opends/src/guitools/org/opends/guitools/replicationcli/ReplicationCliMain.java
index 68bf385..5c82604 100644
--- a/opends/src/guitools/org/opends/guitools/replicationcli/ReplicationCliMain.java
+++ b/opends/src/guitools/org/opends/guitools/replicationcli/ReplicationCliMain.java
@@ -31,10 +31,9 @@
import static org.opends.messages.AdminToolMessages.*;
import static org.opends.messages.QuickSetupMessages.*;
import static org.opends.messages.ToolMessages.*;
+import static org.opends.messages.UtilityMessages.*;
import static org.opends.quicksetup.util.Utils.getFirstValue;
import static org.opends.quicksetup.util.Utils.getThrowableMsg;
-import static org.opends.server.util.ServerConstants.MAX_LINE_WIDTH;
-import static org.opends.server.util.StaticUtils.wrapText;
import java.io.File;
import java.io.InputStream;
@@ -64,6 +63,7 @@
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
+import javax.net.ssl.TrustManager;
import org.opends.admin.ads.ADSContext;
import org.opends.admin.ads.ADSContextException;
@@ -77,8 +77,8 @@
import org.opends.admin.ads.util.ServerLoader;
import org.opends.messages.Message;
import org.opends.messages.MessageBuilder;
+import org.opends.messages.UtilityMessages;
import org.opends.quicksetup.ApplicationException;
-import org.opends.quicksetup.CliApplicationHelper;
import org.opends.quicksetup.Constants;
import org.opends.quicksetup.QuickSetupLog;
import org.opends.quicksetup.ReturnCode;
@@ -101,12 +101,22 @@
import org.opends.server.admin.std.client.*;
import org.opends.server.admin.std.meta.*;
import org.opends.server.core.DirectoryServer;
+import org.opends.server.tools.ClientException;
+import org.opends.server.tools.ToolConstants;
import org.opends.server.types.DN;
import org.opends.server.types.InitializationException;
import org.opends.server.types.NullOutputStream;
import org.opends.server.types.OpenDsException;
import org.opends.server.util.SetupUtils;
import org.opends.server.util.args.ArgumentException;
+import org.opends.server.util.cli.CLIException;
+import org.opends.server.util.cli.ConsoleApplication;
+import org.opends.server.util.cli.LDAPConnectionConsoleInteraction;
+import org.opends.server.util.cli.Menu;
+import org.opends.server.util.cli.MenuBuilder;
+import org.opends.server.util.cli.MenuResult;
+import org.opends.server.util.table.TableBuilder;
+import org.opends.server.util.table.TextTablePrinter;
/**
* This class provides a tool that can be used to enable and disable replication
@@ -114,7 +124,7 @@
* of another suffix. It also allows to display the replicated status of the
* different base DNs of the servers that are registered in the ADS.
*/
-public class ReplicationCliMain extends CliApplicationHelper
+public class ReplicationCliMain extends ConsoleApplication
{
/**
* The fully-qualified name of this class.
@@ -128,11 +138,11 @@
static public final String LOG_FILE_SUFFIX = ".log";
private static final Logger LOG =
- Logger.getLogger(CliApplicationHelper.class.getName());
+ Logger.getLogger(ReplicationCliMain.class.getName());
// The argument parser to be used.
private ReplicationCliArgumentParser argParser;
-
+ private LDAPConnectionConsoleInteraction ci = null;
// The message formatter
PlainTextProgressMessageFormatter formatter =
new PlainTextProgressMessageFormatter();
@@ -146,7 +156,7 @@
*/
public ReplicationCliMain(PrintStream out, PrintStream err, InputStream in)
{
- super(out, err, in);
+ super(in, out, err);
}
/**
@@ -248,12 +258,13 @@
try
{
argParser = new ReplicationCliArgumentParser(CLASS_NAME);
- argParser.initializeParser(out);
+ argParser.initializeParser(getOutputStream());
}
catch (ArgumentException ae)
{
- Message message = ERR_CANNOT_INITIALIZE_ARGS.get(ae.getMessage());
- printErrorMessage(message);
+ Message message =
+ UtilityMessages.ERR_CANNOT_INITIALIZE_ARGS.get(ae.getMessage());
+ println(message);
LOG.log(Level.SEVERE, "Complete error stack:", ae);
returnValue = CANNOT_INITIALIZE_ARGS;
}
@@ -269,9 +280,9 @@
{
Message message = ERR_ERROR_PARSING_ARGS.get(ae.getMessage());
- printErrorMessage(message);
- printLineBreak();
- printErrorMessage(argParser.getUsage());
+ println(message);
+ println();
+ println(Message.raw(argParser.getUsage()));
LOG.log(Level.SEVERE, "Complete error stack:", ae);
returnValue = ERROR_USER_DATA;
}
@@ -287,8 +298,8 @@
argParser.validateOptions(buf);
if (buf.length() > 0)
{
- err.println(wrapText(buf.toMessage(), MAX_LINE_WIDTH));
- err.println(argParser.getUsage());
+ println(buf.toMessage());
+ println(Message.raw(argParser.getUsage()));
returnValue = ERROR_USER_DATA;
}
}
@@ -308,13 +319,20 @@
}
catch (InitializationException ie)
{
- printErrorMessage(ie.getMessage());
+ println(ie.getMessageObject());
returnValue = ERROR_INITIALIZING_ADMINISTRATION_FRAMEWORK;
}
}
if (returnValue == SUCCESSFUL_NOP)
{
+ ci = new LDAPConnectionConsoleInteraction(this,
+ argParser.getSecureArgsList());
+ ci.setDisplayLdapIfSecureParameters(
+ !argParser.isInitializeAllReplicationSubcommand());
+ }
+ if (returnValue == SUCCESSFUL_NOP)
+ {
if (argParser.isEnableReplicationSubcommand())
{
returnValue = enableReplication();
@@ -337,9 +355,8 @@
}
else
{
- err.println(wrapText(ERR_REPLICATION_VALID_SUBCOMMAND_NOT_FOUND.get(),
- MAX_LINE_WIDTH));
- err.println(argParser.getUsage());
+ println(ERR_REPLICATION_VALID_SUBCOMMAND_NOT_FOUND.get());
+ println(Message.raw(argParser.getUsage()));
returnValue = ERROR_USER_DATA;
}
}
@@ -348,14 +365,6 @@
}
/**
- * {@inheritDoc}
- */
- protected boolean isQuiet()
- {
- return argParser.isQuiet();
- }
-
- /**
* Based on the data provided in the command-line it enables replication
* between two servers.
* @return the error code if the operation failed and 0 if it was successful.
@@ -380,8 +389,8 @@
catch (ReplicationCliException rce)
{
returnValue = rce.getErrorCode();
- printLineBreak();
- printErrorMessage(getCriticalExceptionMessage(rce));
+ println();
+ println(getCriticalExceptionMessage(rce));
}
}
else
@@ -418,8 +427,8 @@
catch (ReplicationCliException rce)
{
returnValue = rce.getErrorCode();
- printLineBreak();
- printErrorMessage(getCriticalExceptionMessage(rce));
+ println();
+ println(getCriticalExceptionMessage(rce));
}
}
else
@@ -486,8 +495,8 @@
catch (ReplicationCliException rce)
{
returnValue = rce.getErrorCode();
- printLineBreak();
- printErrorMessage(getCriticalExceptionMessage(rce));
+ println();
+ println(getCriticalExceptionMessage(rce));
}
}
else
@@ -545,128 +554,69 @@
boolean administratorDefined = false;
+ ci.setUseAdminOrBindDn(true);
+
String adminPwd = argParser.getBindPasswordAdmin();
String adminUid = argParser.getAdministratorUID();
- boolean prompted = false;
- /*
- * Prompt for information on the first server.
- */
- String host1 = argParser.getHostName1();
- if (host1 == null)
- {
- host1 = promptForString(
- INFO_REPLICATION_ENABLE_HOSTNAME1_PROMPT.get(),
- argParser.getDefaultHostName1(), false);
- prompted = true;
- }
- int port1 = argParser.getPort1();
- if (port1 == -1)
- {
- port1 = promptForPort(
- INFO_REPLICATION_ENABLE_PORT1_PROMPT.get(),
- argParser.getDefaultPort1(), false);
- prompted = true;
- }
- boolean useSSL1 = argParser.useSSL1();
- boolean useStartTLS1 = argParser.useStartTLS1();
- if (!useSSL1 && !useStartTLS1)
- {
- useSSL1 = confirm(INFO_REPLICATION_ENABLE_USESSL1_PROMPT.get(), false);
- prompted = true;
- if (!useSSL1)
- {
- useStartTLS1 =
- confirm(INFO_REPLICATION_ENABLE_USESTARTTLS1_PROMPT.get(), false);
- prompted = true;
- }
- }
-
- String bindDn1 = argParser.getBindDn1();
- String pwd1 = argParser.getBindPassword1();
- if ((bindDn1 == null) && (pwd1 == null) && (adminPwd != null) &&
- (adminUid != null))
- {
- // No information provided to connect to the first server. Try
- // to use global administrator.
- bindDn1 = ADSContext.getAdministratorDN(adminUid);
- pwd1 = adminPwd;
- }
- else
- {
- // Ask for the bind dn to connect to server 1.
- if (bindDn1 == null)
- {
- bindDn1 = promptForString(
- INFO_REPLICATION_ENABLE_BINDDN1_PROMPT.get(),
- getValue(bindDn1, argParser.getDefaultBindDn1()), false);
- prompted = true;
- }
- if (pwd1 == null)
- {
- pwd1 = promptForPassword(
- INFO_REPLICATION_ENABLE_PASSWORD1_PROMPT.get(bindDn1));
- prompted = true;
- }
- }
-
/*
* Try to connect to the first server.
*/
+ String host1 = argParser.getHostName1();
+ int port1 = argParser.getPort1();
+ boolean useSSL1 = argParser.useSSL1();
+ boolean useStartTLS1 = argParser.useStartTLS1();
+ String bindDn1 = argParser.getBindDn1();
+ String pwd1 = argParser.getBindPassword1();
+
+ initializeGlobalArguments(host1, port1, useSSL1,
+ useStartTLS1, adminUid, bindDn1, (pwd1 != null) ? pwd1 : adminPwd);
InitialLdapContext ctx1 = null;
- // Boolean used to only ask for the information that was not explicitly
- // provided the first time we ask. After we ask for all the information.
while ((ctx1 == null) && !cancelled)
{
try
{
- ctx1 = createContext(host1, port1, useSSL1, useStartTLS1, bindDn1,
- pwd1, getTrustManager());
+ ci.setHeadingMessage(
+ INFO_REPLICATION_ENABLE_HOST1_CONNECTION_PARAMETERS.get());
+ ci.run();
+ useSSL1 = ci.useSSL();
+ useStartTLS1 = ci.useStartTLS();
+ host1 = ci.getHostName();
+ port1 = ci.getPortNumber();
+ adminUid = ci.getAdministratorUID();
+ if (adminUid != null)
+ {
+ adminPwd = ci.getBindPassword();
+ }
+ bindDn1 = ci.getBindDN();
+ pwd1 = ci.getBindPassword();
+
+ ctx1 = createInitialLdapContextInteracting(ci);
+
+ if (ctx1 == null)
+ {
+ cancelled = true;
+ }
}
- catch (NamingException ne)
+ catch (ClientException ce)
{
- prompted = true;
- LOG.log(Level.WARNING, "Error connecting to "+host1+":"+port1, ne);
- if (Utils.isCertificateException(ne))
- {
- String usedUrl = ConnectionUtils.getLDAPUrl(host1, port1, useSSL1);
- if (!promptForCertificateConfirmation(ne, getTrustManager(), usedUrl,
- getTrustManager()))
- {
- cancelled = true;
- }
- }
- else
- {
- printLineBreak();
- printErrorMessage(ERR_ERROR_CONNECTING_TO_SERVER_PROMPT_AGAIN.get(
- host1+":"+port1, ne.toString()));
-
- printLineBreak();
- host1 = promptForString(
- INFO_REPLICATION_ENABLE_HOSTNAME1_PROMPT.get(),
- getValue(host1, argParser.getDefaultHostName1()), false);
- port1 = promptForPort(INFO_REPLICATION_ENABLE_PORT1_PROMPT.get(),
- getValue(port1, argParser.getDefaultPort1()), false);
-
- bindDn1 = promptForString(
- INFO_REPLICATION_ENABLE_BINDDN1_PROMPT.get(),
- getValue(bindDn1, argParser.getDefaultBindDn1()), false);
- pwd1 = promptForPassword(
- INFO_REPLICATION_ENABLE_PASSWORD1_PROMPT.get(bindDn1));
-
- useSSL1 = confirm(INFO_REPLICATION_ENABLE_USESSL1_PROMPT.get(),
- useSSL1);
- if (!useSSL1)
- {
- useStartTLS1 = confirm(
- INFO_REPLICATION_ENABLE_USESTARTTLS1_PROMPT.get(),
- useStartTLS1);
- }
- }
+ LOG.log(Level.WARNING, "Client exception "+ce);
+ println();
+ println(ce.getMessageObject());
+ println();
+ resetConnectionArguments();
+ }
+ catch (ArgumentException ae)
+ {
+ LOG.log(Level.WARNING, "Argument exception "+ae);
+ println();
+ println(ae.getMessageObject());
+ println();
+ cancelled = true;
}
}
+
if (!cancelled)
{
uData.setHostName1(host1);
@@ -693,17 +643,18 @@
}
else
{
- replicationPort1 = promptForPort(
+ replicationPort1 = askPort(
INFO_REPLICATION_ENABLE_REPLICATIONPORT1_PROMPT.get(),
- argParser.getDefaultReplicationPort1(), false);
+ argParser.getDefaultReplicationPort1());
+ println();
}
if (!argParser.skipReplicationPortCheck() && isLocalHost(host1))
{
if (!SetupUtils.canUseAsPort(replicationPort1))
{
- printLineBreak();
- printErrorMessage(getCannotBindToPortError(replicationPort1));
- printLineBreak();
+ println();
+ println(getCannotBindToPortError(replicationPort1));
+ println();
replicationPort1 = -1;
}
}
@@ -713,10 +664,11 @@
// already included when we call SetupUtils.canUseAsPort
if (replicationPort1 == port1)
{
- printLineBreak();
- printErrorMessage(
+ println();
+ println(
ERR_REPLICATION_PORT_AND_REPLICATION_PORT_EQUAL.get(
host1, String.valueOf(replicationPort1)));
+ println();
replicationPort1 = -1;
}
}
@@ -724,8 +676,9 @@
if (!secureReplication1)
{
secureReplication1 =
- confirm(INFO_REPLICATION_ENABLE_SECURE1_PROMPT.get(
- String.valueOf(replicationPort1)), false);
+ askConfirmation(INFO_REPLICATION_ENABLE_SECURE1_PROMPT.get(
+ String.valueOf(replicationPort1)), false, LOG);
+ println();
}
}
// If the server contains an ADS. Try to load it and only load it: if
@@ -739,6 +692,10 @@
if (!cancelled)
{
administratorDefined |= hasAdministrator(ctx1);
+ if (uData.getAdminPwd() != null)
+ {
+ adminPwd = uData.getAdminPwd();
+ }
}
}
uData.setReplicationPort1(replicationPort1);
@@ -753,25 +710,50 @@
String pwd2 = null;
boolean useSSL2 = false;
boolean useStartTLS2 = false;
+ ci.resetHeadingDisplayed();
if (!cancelled)
{
host2 = argParser.getHostName2();
- if (prompted)
- {
- printLineBreak();
- }
- if (host2 == null)
- {
- host2 = promptForString(
- INFO_REPLICATION_ENABLE_HOSTNAME2_PROMPT.get(),
- argParser.getDefaultHostName2(), false);
- }
port2 = argParser.getPort2();
- while (port2 == -1)
+ useSSL2 = argParser.useSSL2();
+ useStartTLS2 = argParser.useStartTLS2();
+ bindDn2 = argParser.getBindDn2();
+ pwd2 = argParser.getBindPassword2();
+ String pwd;
+ if (pwd2 != null)
{
- port2 = promptForPort(
- INFO_REPLICATION_ENABLE_PORT2_PROMPT.get(),
- argParser.getDefaultPort2(), false);
+ pwd = pwd2;
+ }
+ else if (bindDn2 != null)
+ {
+ pwd = null;
+ }
+ else
+ {
+ pwd = adminPwd;
+ }
+
+ initializeGlobalArguments(host2, port2, useSSL2, useStartTLS2, adminUid,
+ bindDn2, pwd);
+ }
+ InitialLdapContext ctx2 = null;
+
+ while ((ctx2 == null) && !cancelled)
+ {
+ try
+ {
+ ci.setHeadingMessage(
+ INFO_REPLICATION_ENABLE_HOST2_CONNECTION_PARAMETERS.get());
+ ci.run();
+ useSSL2 = ci.useSSL();
+ useStartTLS2 = ci.useStartTLS();
+ host2 = ci.getHostName();
+ port2 = ci.getPortNumber();
+ adminUid = ci.getAdministratorUID();
+ bindDn2 = ci.getBindDN();
+ pwd2 = ci.getBindPassword();
+
+ boolean error = false;
if (host1.equalsIgnoreCase(host2))
{
if (port1 == port2)
@@ -779,105 +761,41 @@
port2 = -1;
Message message = ERR_REPLICATION_ENABLE_SAME_SERVER_PORT.get(
host1, String.valueOf(port1));
- printLineBreak();
- printErrorMessage(message);
- printLineBreak();
+ println();
+ println(message);
+ println();
+ error = true;
}
}
- }
- useSSL2 = argParser.useSSL2();
- useStartTLS2 = argParser.useStartTLS2();
- if (!useSSL2 && !useStartTLS2)
- {
- useSSL2 = confirm(INFO_REPLICATION_ENABLE_USESSL2_PROMPT.get(), false);
- if (!useSSL2)
- {
- useStartTLS2 =
- confirm(INFO_REPLICATION_ENABLE_USESTARTTLS2_PROMPT.get(), false);
- }
- }
- bindDn2 = argParser.getBindDn2();
- pwd2 = argParser.getBindPassword2();
- if ((bindDn2 == null) && (pwd2 == null) && (adminPwd != null) &&
- (adminUid != null))
- {
- // No information provided to connect to the first server. Try
- // to use global administrator.
- bindDn2 = ADSContext.getAdministratorDN(adminUid);
- pwd2 = adminPwd;
- }
- else
- {
- // Ask for the bind dn to connect to server 2.
- if (bindDn2 == null)
+ if (!error)
{
- bindDn2 = promptForString(
- INFO_REPLICATION_ENABLE_BINDDN2_PROMPT.get(),
- getValue(bindDn2, argParser.getDefaultBindDn2()), false);
- }
- if (pwd2 == null)
- {
- pwd2 = promptForPassword(
- INFO_REPLICATION_ENABLE_PASSWORD2_PROMPT.get(bindDn1));
- }
- }
- }
- /**
- * Try to connect to second server
- */
- InitialLdapContext ctx2 = null;
+ ctx2 = createInitialLdapContextInteracting(ci);
- while ((ctx2 == null) && !cancelled)
- {
- try
- {
- ctx2 = createContext(host2, port2, useSSL2, useStartTLS2, bindDn2,
- pwd2, getTrustManager());
- }
- catch (NamingException ne)
- {
- LOG.log(Level.WARNING, "Error connecting to "+host2+":"+port2, ne);
- if (Utils.isCertificateException(ne))
- {
- String usedUrl = ConnectionUtils.getLDAPUrl(host2, port2, useSSL2);
- if (!promptForCertificateConfirmation(ne, getTrustManager(), usedUrl,
- getTrustManager()))
+ if (ctx2 == null)
{
cancelled = true;
}
}
- else
- {
- if (pwd2 != null)
- {
- printLineBreak();
- printErrorMessage(ERR_ERROR_CONNECTING_TO_SERVER_PROMPT_AGAIN.get(
- host2+":"+port2, ne.toString()));
- }
- printLineBreak();
-
- host2 = promptForString(
- INFO_REPLICATION_ENABLE_HOSTNAME2_PROMPT.get(),
- getValue(host2, argParser.getDefaultHostName2()), false);
- port2 = promptForPort(INFO_REPLICATION_ENABLE_PORT2_PROMPT.get(),
- getValue(port2, argParser.getDefaultPort2()), false);
- bindDn2 = promptForString(
- INFO_REPLICATION_ENABLE_BINDDN2_PROMPT.get(),
- getValue(bindDn2, argParser.getDefaultBindDn2()), false);
- pwd2 = promptForPassword(
- INFO_REPLICATION_ENABLE_PASSWORD2_PROMPT.get(bindDn2));
- useSSL2 = confirm(INFO_REPLICATION_ENABLE_USESSL2_PROMPT.get(),
- useSSL2);
- if (!useSSL2)
- {
- useStartTLS2 = confirm(
- INFO_REPLICATION_ENABLE_USESTARTTLS2_PROMPT.get(),
- useStartTLS2);
- }
- }
+ }
+ catch (ClientException ce)
+ {
+ LOG.log(Level.WARNING, "Client exception "+ce);
+ println();
+ println(ce.getMessageObject());
+ println();
+ resetConnectionArguments();
+ }
+ catch (ArgumentException ae)
+ {
+ LOG.log(Level.WARNING, "Argument exception "+ae);
+ println();
+ println(ae.getMessageObject());
+ println();
+ cancelled = true;
}
}
+
if (!cancelled)
{
uData.setHostName2(host2);
@@ -887,6 +805,7 @@
uData.setUseSSL2(useSSL2);
uData.setUseStartTLS2(useStartTLS2);
}
+
int replicationPort2 = -1;
boolean secureReplication2 = argParser.isSecureReplication2();
if (ctx2 != null)
@@ -903,17 +822,18 @@
}
else
{
- replicationPort2 = promptForPort(
+ replicationPort2 = askPort(
INFO_REPLICATION_ENABLE_REPLICATIONPORT2_PROMPT.get(),
- argParser.getDefaultReplicationPort2(), false);
+ argParser.getDefaultReplicationPort2());
+ println();
}
if (!argParser.skipReplicationPortCheck() && isLocalHost(host2))
{
if (!SetupUtils.canUseAsPort(replicationPort2))
{
- printLineBreak();
- printErrorMessage(getCannotBindToPortError(replicationPort2));
- printLineBreak();
+ println();
+ println(getCannotBindToPortError(replicationPort2));
+ println();
replicationPort2 = -1;
}
}
@@ -923,8 +843,8 @@
// already included when we call SetupUtils.canUseAsPort
if (replicationPort2 == port2)
{
- printLineBreak();
- printErrorMessage(
+ println();
+ println(
ERR_REPLICATION_PORT_AND_REPLICATION_PORT_EQUAL.get(
host2, String.valueOf(replicationPort2)));
replicationPort2 = -1;
@@ -935,10 +855,10 @@
if ((replicationPort1 > 0) &&
(replicationPort1 == replicationPort2))
{
- printLineBreak();
- printErrorMessage(ERR_REPLICATION_SAME_REPLICATION_PORT.get(
+ println();
+ println(ERR_REPLICATION_SAME_REPLICATION_PORT.get(
String.valueOf(replicationPort2), host1));
- printLineBreak();
+ println();
replicationPort2 = -1;
}
}
@@ -946,8 +866,9 @@
if (!secureReplication2)
{
secureReplication2 =
- confirm(INFO_REPLICATION_ENABLE_SECURE2_PROMPT.get(
- String.valueOf(replicationPort2)), false);
+ askConfirmation(INFO_REPLICATION_ENABLE_SECURE2_PROMPT.get(
+ String.valueOf(replicationPort2)), false, LOG);
+ println();
}
}
// If the server contains an ADS. Try to load it and only load it: if
@@ -979,33 +900,43 @@
{
if (adminUid == null)
{
- printLine(INFO_REPLICATION_ENABLE_ADMINISTRATOR_MUST_BE_CREATED.get(),
- true);
+ println(INFO_REPLICATION_ENABLE_ADMINISTRATOR_MUST_BE_CREATED.get());
promptedForAdmin = true;
adminUid= askForAdministratorUID(
argParser.getDefaultAdministratorUID());
+ println();
}
uData.setAdminUid(adminUid);
}
if (!cancelled && (uData.getAdminPwd() == null) && !administratorDefined)
{
+ adminPwd = null;
while (adminPwd == null)
{
if (!promptedForAdmin)
{
- printLineBreak();
- printLine(INFO_REPLICATION_ENABLE_ADMINISTRATOR_MUST_BE_CREATED.get(),
- true);
+ println();
+ println(INFO_REPLICATION_ENABLE_ADMINISTRATOR_MUST_BE_CREATED.get());
+ println();
}
- adminPwd = askForAdministratorPwd();
- String adminPwdConfirm =
- promptForPassword(INFO_ADMINISTRATOR_PWD_CONFIRM_PROMPT.get());
+ while (adminPwd == null)
+ {
+ adminPwd = askForAdministratorPwd();
+ println();
+ }
+ String adminPwdConfirm = null;
+ while (adminPwdConfirm == null)
+ {
+ adminPwdConfirm =
+ readPassword(INFO_ADMINISTRATOR_PWD_CONFIRM_PROMPT.get(), LOG);
+ println();
+ }
if (!adminPwd.equals(adminPwdConfirm))
{
- printLineBreak();
- printErrorMessage(ERR_ADMINISTRATOR_PWD_DO_NOT_MATCH.get());
- printLineBreak();
+ println();
+ println(ERR_ADMINISTRATOR_PWD_DO_NOT_MATCH.get());
+ println();
adminPwd = null;
}
}
@@ -1068,48 +999,12 @@
String adminUid = argParser.getAdministratorUID();
String bindDn = argParser.getBindDNToDisable();
+ // This is done because we want to ask explicitly for this
+
String host = argParser.getHostNameToDisable();
- if (host == null)
- {
- host = promptForString(
- INFO_REPLICATION_DISABLE_HOSTNAME_PROMPT.get(),
- argParser.getDefaultHostNameToDisable(), false);
- }
int port = argParser.getPortToDisable();
- if (port == -1)
- {
- port = promptForPort(
- INFO_REPLICATION_DISABLE_PORT_PROMPT.get(),
- argParser.getDefaultPortToDisable(), false);
- }
boolean useSSL = argParser.useSSLToDisable();
boolean useStartTLS = argParser.useStartTLSToDisable();
- if (!useSSL && !useStartTLS)
- {
- useSSL = confirm(INFO_CLI_USESSL_PROMPT.get(), false);
- if (!useSSL)
- {
- useStartTLS =
- confirm(INFO_CLI_USESTARTTLS_PROMPT.get(), false);
- }
- }
- if ((adminUid == null) && (bindDn == null))
- {
- String v = askForBindDnDisable(argParser.getDefaultAdministratorUID());
- if (Utils.isDn(v))
- {
- bindDn = v;
- }
- else
- {
- adminUid = v;
- }
- }
-
- if (adminPwd == null)
- {
- adminPwd = askForPasswordDisable(adminUid != null ? adminUid : bindDn);
- }
/*
* Try to connect to the server.
@@ -1118,66 +1013,43 @@
while ((ctx == null) && !cancelled)
{
- String lastBindDn;
- if (adminUid != null)
- {
- lastBindDn = ADSContext.getAdministratorDN(adminUid);
- }
- else
- {
- lastBindDn = bindDn;
- }
try
{
- ctx = createContext(host, port, useSSL, useStartTLS, lastBindDn,
- adminPwd, getTrustManager());
+ ci.setUseAdminOrBindDn(true);
+ ci.run();
+ useSSL = ci.useSSL();
+ useStartTLS = ci.useStartTLS();
+ host = ci.getHostName();
+ port = ci.getPortNumber();
+ bindDn = ci.getBindDN();
+ adminUid = ci.getAdministratorUID();
+ adminPwd = ci.getBindPassword();
+
+ ctx = createInitialLdapContextInteracting(ci);
+
+ if (ctx == null)
+ {
+ cancelled = true;
+ }
}
- catch (NamingException ne)
+ catch (ClientException ce)
{
- LOG.log(Level.WARNING, "Error connecting to "+host+":"+port, ne);
- if (Utils.isCertificateException(ne))
- {
- String usedUrl = ConnectionUtils.getLDAPUrl(host, port, useSSL);
- if (!promptForCertificateConfirmation(ne, getTrustManager(), usedUrl,
- getTrustManager()))
- {
- cancelled = true;
- }
- }
- else
- {
- printLineBreak();
- printErrorMessage(ERR_ERROR_CONNECTING_TO_SERVER_PROMPT_AGAIN.get(
- host+":"+port, ne.toString()));
- printLineBreak();
- host = promptForString(
- INFO_REPLICATION_DISABLE_HOSTNAME_PROMPT.get(),
- getValue(host, argParser.getDefaultHostNameToDisable()), false);
- port = promptForPort(
- INFO_REPLICATION_DISABLE_PORT_PROMPT.get(),
- getValue(port, argParser.getDefaultPortToDisable()), false);
- useSSL = confirm(INFO_CLI_USESSL_PROMPT.get(), useSSL);
- if (!useSSL)
- {
- useStartTLS =
- confirm(INFO_CLI_USESTARTTLS_PROMPT.get(), useStartTLS);
- }
- adminUid = null;
- bindDn = null;
- String v = askForBindDnDisable(lastBindDn);
- if (Utils.isDn(v))
- {
- bindDn = v;
- }
- else
- {
- adminUid = v;
- }
- adminPwd = askForPasswordDisable(adminUid != null ?
- adminUid : bindDn);
- }
+ LOG.log(Level.WARNING, "Client exception "+ce);
+ println();
+ println(ce.getMessageObject());
+ println();
+ resetConnectionArguments();
+ }
+ catch (ArgumentException ae)
+ {
+ LOG.log(Level.WARNING, "Argument exception "+ae);
+ println();
+ println(ae.getMessageObject());
+ println();
+ cancelled = true;
}
}
+
if (!cancelled)
{
uData.setHostName(host);
@@ -1227,19 +1099,24 @@
}
if (disableADS)
{
- printLineBreak();
- cancelled = !confirm(INFO_REPLICATION_CONFIRM_DISABLE_ADS.get(
- ADSContext.getAdministrationSuffixDN()));
+ println();
+ cancelled = !askConfirmation(INFO_REPLICATION_CONFIRM_DISABLE_ADS.get(
+ ADSContext.getAdministrationSuffixDN()), true, LOG);
+ println();
}
if (disableSchema)
{
- printLineBreak();
- cancelled = !confirm(INFO_REPLICATION_CONFIRM_DISABLE_SCHEMA.get());
+ println();
+ cancelled = !askConfirmation(
+ INFO_REPLICATION_CONFIRM_DISABLE_SCHEMA.get(), true, LOG);
+ println();
}
if (!disableSchema && !disableADS)
{
- printLineBreak();
- cancelled = !confirm(INFO_REPLICATION_CONFIRM_DISABLE_GENERIC.get());
+ println();
+ cancelled = !askConfirmation(
+ INFO_REPLICATION_CONFIRM_DISABLE_GENERIC.get(), true, LOG);
+ println();
}
}
@@ -1274,40 +1151,9 @@
String adminUid = argParser.getAdministratorUID();
String host = argParser.getHostNameToInitializeAll();
- if (host == null)
- {
- host = promptForString(
- INFO_REPLICATION_INITIALIZE_ALL_HOSTNAME_PROMPT.get(),
- argParser.getDefaultHostNameToInitializeAll(), false);
- }
int port = argParser.getPortToInitializeAll();
- if (port == -1)
- {
- port = promptForPort(
- INFO_REPLICATION_INITIALIZE_ALL_PORT_PROMPT.get(),
- argParser.getDefaultPortToInitializeAll(), false);
- }
boolean useSSL = argParser.useSSLToInitializeAll();
boolean useStartTLS = argParser.useStartTLSToInitializeAll();
- if (!useSSL && !useStartTLS)
- {
- useSSL = confirm(INFO_CLI_USESSL_PROMPT.get(), false);
- if (!useSSL)
- {
- useStartTLS =
- confirm(INFO_CLI_USESTARTTLS_PROMPT.get(), false);
- }
- }
-
- if (adminUid == null)
- {
- adminUid = askForAdministratorUID(argParser.getDefaultAdministratorUID());
- }
-
- if (adminPwd == null)
- {
- adminPwd = askForAdministratorPwd();
- }
/*
* Try to connect to the server.
@@ -1318,44 +1164,38 @@
{
try
{
- ctx = createContext(host, port, useSSL, useStartTLS,
- ADSContext.getAdministratorDN(adminUid), adminPwd,
- getTrustManager());
+ ci.setHeadingMessage(
+ INFO_REPLICATION_INITIALIZE_SOURCE_CONNECTION_PARAMETERS.get());
+ ci.run();
+ useSSL = ci.useSSL();
+ useStartTLS = ci.useStartTLS();
+ host = ci.getHostName();
+ port = ci.getPortNumber();
+ adminUid = ci.getAdministratorUID();
+ adminPwd = ci.getBindPassword();
+
+ ctx = createInitialLdapContextInteracting(ci);
+
+ if (ctx == null)
+ {
+ cancelled = true;
+ }
}
- catch (NamingException ne)
+ catch (ClientException ce)
{
- LOG.log(Level.WARNING, "Error connecting to "+host+":"+port, ne);
- if (Utils.isCertificateException(ne))
- {
- String usedUrl = ConnectionUtils.getLDAPUrl(host, port, useSSL);
- if (!promptForCertificateConfirmation(ne, getTrustManager(), usedUrl,
- getTrustManager()))
- {
- cancelled = true;
- }
- }
- else
- {
- printLineBreak();
- printErrorMessage(ERR_ERROR_CONNECTING_TO_SERVER_PROMPT_AGAIN.get(
- host+":"+port, ne.toString()));
- printLineBreak();
- host = promptForString(
- INFO_REPLICATION_INITIALIZE_ALL_HOSTNAME_PROMPT.get(),
- getValue(host, argParser.getDefaultHostNameToInitializeAll()),
- false);
- port = promptForPort(
- INFO_REPLICATION_INITIALIZE_ALL_PORT_PROMPT.get(),
- getValue(port, argParser.getDefaultPortToInitializeAll()), false);
- useSSL = confirm(INFO_CLI_USESSL_PROMPT.get(), useSSL);
- if (!useSSL)
- {
- useStartTLS =
- confirm(INFO_CLI_USESTARTTLS_PROMPT.get(), useStartTLS);
- }
- adminUid = askForAdministratorUID(adminUid);
- adminPwd = askForAdministratorPwd();
- }
+ LOG.log(Level.WARNING, "Client exception "+ce);
+ println();
+ println(ce.getMessageObject());
+ println();
+ resetConnectionArguments();
+ }
+ catch (ArgumentException ae)
+ {
+ LOG.log(Level.WARNING, "Argument exception "+ae);
+ println();
+ println(ae.getMessageObject());
+ println();
+ cancelled = true;
}
}
if (!cancelled)
@@ -1391,16 +1231,19 @@
String hostPortSource = ConnectionUtils.getHostPort(ctx);
if (initializeADS)
{
- printLineBreak();
- cancelled = !confirm(INFO_REPLICATION_CONFIRM_INITIALIZE_ALL_ADS.get(
- ADSContext.getAdministrationSuffixDN(), hostPortSource));
+ println();
+ cancelled = !askConfirmation(
+ INFO_REPLICATION_CONFIRM_INITIALIZE_ALL_ADS.get(
+ ADSContext.getAdministrationSuffixDN(), hostPortSource), true, LOG);
+ println();
}
else
{
- printLineBreak();
- cancelled = !confirm(
+ println();
+ cancelled = !askConfirmation(
INFO_REPLICATION_CONFIRM_INITIALIZE_ALL_GENERIC.get(
- hostPortSource));
+ hostPortSource), true, LOG);
+ println();
}
}
@@ -1438,40 +1281,9 @@
String adminUid = argParser.getAdministratorUID();
String host = argParser.getHostNameToStatus();
- if (host == null)
- {
- host = promptForString(
- INFO_REPLICATION_STATUS_HOSTNAME_PROMPT.get(),
- argParser.getDefaultHostNameToStatus(), false);
- }
int port = argParser.getPortToStatus();
- if (port == -1)
- {
- port = promptForPort(
- INFO_REPLICATION_STATUS_PORT_PROMPT.get(),
- argParser.getDefaultPortToStatus(), false);
- }
boolean useSSL = argParser.useSSLToStatus();
boolean useStartTLS = argParser.useStartTLSToStatus();
- if (!useSSL && !useStartTLS)
- {
- useSSL = confirm(INFO_CLI_USESSL_PROMPT.get(), false);
- if (!useSSL)
- {
- useStartTLS =
- confirm(INFO_CLI_USESTARTTLS_PROMPT.get(), false);
- }
- }
-
- if (adminUid == null)
- {
- adminUid = askForAdministratorUID(argParser.getDefaultAdministratorUID());
- }
-
- if (adminPwd == null)
- {
- adminPwd = askForAdministratorPwd();
- }
/*
* Try to connect to the server.
@@ -1482,43 +1294,36 @@
{
try
{
- ctx = createContext(host, port, useSSL, useStartTLS,
- ADSContext.getAdministratorDN(adminUid), adminPwd,
- getTrustManager());
+ ci.run();
+ useSSL = ci.useSSL();
+ useStartTLS = ci.useStartTLS();
+ host = ci.getHostName();
+ port = ci.getPortNumber();
+ adminUid = ci.getAdministratorUID();
+ adminPwd = ci.getBindPassword();
+
+ ctx = createInitialLdapContextInteracting(ci);
+
+ if (ctx == null)
+ {
+ cancelled = true;
+ }
}
- catch (NamingException ne)
+ catch (ClientException ce)
{
- LOG.log(Level.WARNING, "Error connecting to "+host+":"+port, ne);
- if (Utils.isCertificateException(ne))
- {
- String usedUrl = ConnectionUtils.getLDAPUrl(host, port, useSSL);
- if (!promptForCertificateConfirmation(ne, getTrustManager(), usedUrl,
- getTrustManager()))
- {
- cancelled = true;
- }
- }
- else
- {
- printLineBreak();
- printErrorMessage(ERR_ERROR_CONNECTING_TO_SERVER_PROMPT_AGAIN.get(
- host+":"+port, ne.toString()));
- printLineBreak();
- host = promptForString(
- INFO_REPLICATION_STATUS_HOSTNAME_PROMPT.get(),
- getValue(host, argParser.getDefaultHostNameToStatus()), false);
- port = promptForPort(
- INFO_REPLICATION_STATUS_PORT_PROMPT.get(),
- getValue(port, argParser.getDefaultPortToStatus()), false);
- useSSL = confirm(INFO_CLI_USESSL_PROMPT.get(), useSSL);
- if (!useSSL)
- {
- useStartTLS =
- confirm(INFO_CLI_USESTARTTLS_PROMPT.get(), useStartTLS);
- }
- adminUid = askForAdministratorUID(adminUid);
- adminPwd = askForAdministratorPwd();
- }
+ LOG.log(Level.WARNING, "Client exception "+ce);
+ println();
+ println(ce.getMessageObject());
+ println();
+ resetConnectionArguments();
+ }
+ catch (ArgumentException ae)
+ {
+ LOG.log(Level.WARNING, "Argument exception "+ae);
+ println();
+ println(ae.getMessageObject());
+ println();
+ cancelled = true;
}
}
if (!cancelled)
@@ -1578,113 +1383,55 @@
String adminPwd = argParser.getBindPasswordAdmin();
String adminUid = argParser.getAdministratorUID();
- boolean promptedForAdmin = false;
- if (adminUid == null)
- {
- adminUid = askForAdministratorUID(argParser.getDefaultAdministratorUID());
- promptedForAdmin = true;
- }
- if (adminPwd == null)
- {
- adminPwd = askForAdministratorPwd();
- promptedForAdmin = true;
- }
-
- boolean promptedFor1 = false;
String hostSource = argParser.getHostNameSource();
- if (hostSource == null)
- {
- if (promptedForAdmin)
- {
- printLineBreak();
- }
- hostSource = promptForString(
- INFO_REPLICATION_INITIALIZE_HOSTNAMESOURCE_PROMPT.get(),
- argParser.getDefaultHostNameSource(), false);
- promptedFor1 = true;
- }
int portSource = argParser.getPortSource();
- if (portSource == -1)
- {
- if (promptedForAdmin && !promptedFor1)
- {
- printLineBreak();
- }
- portSource = promptForPort(
- INFO_REPLICATION_INITIALIZE_PORTSOURCE_PROMPT.get(),
- argParser.getDefaultPortSource(), false);
- promptedFor1 = true;
- }
boolean useSSLSource = argParser.useSSLSource();
boolean useStartTLSSource = argParser.useStartTLSSource();
- if (!useSSLSource && !useStartTLSSource)
- {
- if (promptedForAdmin && !promptedFor1)
- {
- printLineBreak();
- }
- useSSLSource = confirm(
- INFO_REPLICATION_INITIALIZE_USESSLSOURCE_PROMPT.get(), false);
- if (!useSSLSource)
- {
- useStartTLSSource =
- confirm(INFO_REPLICATION_INITIALIZE_USESTARTTLSSOURCE_PROMPT.get(),
- false);
- }
- promptedFor1 = true;
- }
+
+ initializeGlobalArguments(hostSource, portSource, useSSLSource,
+ useStartTLSSource, adminUid, null, adminPwd);
/*
* Try to connect to the source server.
*/
InitialLdapContext ctxSource = null;
+
while ((ctxSource == null) && !cancelled)
{
try
{
- ctxSource = createContext(hostSource, portSource, useSSLSource,
- useStartTLSSource, ADSContext.getAdministratorDN(adminUid),
- adminPwd, getTrustManager());
+ ci.setHeadingMessage(
+ INFO_REPLICATION_INITIALIZE_SOURCE_CONNECTION_PARAMETERS.get());
+ ci.run();
+ useSSLSource = ci.useSSL();
+ useStartTLSSource = ci.useStartTLS();
+ hostSource = ci.getHostName();
+ portSource = ci.getPortNumber();
+ adminUid = ci.getAdministratorUID();
+ adminPwd = ci.getBindPassword();
+
+ ctxSource = createInitialLdapContextInteracting(ci);
+
+ if (ctxSource == null)
+ {
+ cancelled = true;
+ }
}
- catch (NamingException ne)
+ catch (ClientException ce)
{
- LOG.log(Level.WARNING, "Error connecting to "+hostSource+":"+portSource,
- ne);
- if (Utils.isCertificateException(ne))
- {
- String usedUrl = ConnectionUtils.getLDAPUrl(hostSource, portSource,
- useSSLSource);
- if (!promptForCertificateConfirmation(ne, getTrustManager(), usedUrl,
- getTrustManager()))
- {
- cancelled = true;
- }
- }
- else
- {
- printLineBreak();
- printErrorMessage(ERR_ERROR_CONNECTING_TO_SERVER_PROMPT_AGAIN.get(
- hostSource+":"+portSource, ne.toString()));
- printLineBreak();
- hostSource = promptForString(
- INFO_REPLICATION_INITIALIZE_HOSTNAMESOURCE_PROMPT.get(),
- getValue(hostSource, argParser.getDefaultHostNameSource()),
- false);
- portSource = promptForPort(
- INFO_REPLICATION_INITIALIZE_PORTSOURCE_PROMPT.get(),
- getValue(portSource, argParser.getDefaultPortSource()), false);
- adminUid = askForAdministratorUID(adminUid);
- adminPwd = askForAdministratorPwd();
- useSSLSource = confirm(
- INFO_REPLICATION_INITIALIZE_USESSLSOURCE_PROMPT.get(),
- useSSLSource);
- if (!useSSLSource)
- {
- useStartTLSSource = confirm(
- INFO_REPLICATION_INITIALIZE_USESTARTTLSSOURCE_PROMPT.get(),
- useStartTLSSource);
- }
- }
+ LOG.log(Level.WARNING, "Client exception "+ce);
+ println();
+ println(ce.getMessageObject());
+ println();
+ resetConnectionArguments();
+ }
+ catch (ArgumentException ae)
+ {
+ LOG.log(Level.WARNING, "Argument exception "+ae);
+ println();
+ println(ae.getMessageObject());
+ println();
+ cancelled = true;
}
}
if (!cancelled)
@@ -1699,116 +1446,54 @@
/* Prompt for destination server credentials */
String hostDestination = argParser.getHostNameDestination();
- boolean promptedFor2 = false;
- if (hostDestination == null)
- {
- if (promptedFor1 || promptedForAdmin)
- {
- printLineBreak();
- }
- hostDestination = promptForString(
- INFO_REPLICATION_INITIALIZE_HOSTNAMEDESTINATION_PROMPT.get(),
- argParser.getDefaultHostNameDestination(), false);
- promptedFor2 = true;
- }
int portDestination = argParser.getPortDestination();
- while (portDestination == -1)
- {
- if ((promptedFor1 || promptedForAdmin) && !promptedFor2)
- {
- printLineBreak();
- }
- portDestination = promptForPort(
- INFO_REPLICATION_INITIALIZE_PORTDESTINATION_PROMPT.get(),
- argParser.getDefaultPortDestination(), false);
- if (hostSource.equalsIgnoreCase(hostDestination))
- {
- if (portSource == portDestination)
- {
- portDestination = -1;
- Message message = ERR_REPLICATION_INITIALIZE_SAME_SERVER_PORT.get(
- hostSource, String.valueOf(portSource));
- printLineBreak();
- printErrorMessage(message);
- printLineBreak();
- }
- }
- promptedFor2 = true;
- }
-
boolean useSSLDestination = argParser.useSSLDestination();
boolean useStartTLSDestination = argParser.useStartTLSDestination();
- if (!useSSLDestination && !useStartTLSDestination)
- {
- if ((promptedFor1 || promptedForAdmin) && !promptedFor2)
- {
- printLineBreak();
- }
- useSSLDestination = confirm(
- INFO_REPLICATION_INITIALIZE_USESSLDESTINATION_PROMPT.get(), false);
- if (!useSSLDestination)
- {
- useStartTLSDestination = confirm(
- INFO_REPLICATION_INITIALIZE_USESTARTTLSDESTINATION_PROMPT.get(),
- false);
- }
- promptedFor2 = true;
- }
+
+ initializeGlobalArguments(hostDestination, portDestination,
+ useSSLDestination, useStartTLSDestination, adminUid, null, adminPwd);
/*
* Try to connect to the destination server.
*/
InitialLdapContext ctxDestination = null;
+
+ ci.resetHeadingDisplayed();
while ((ctxDestination == null) && !cancelled)
{
try
{
- ctxDestination = createContext(hostDestination, portDestination,
- useSSLDestination, useStartTLSDestination,
- ADSContext.getAdministratorDN(adminUid),
- adminPwd, getTrustManager());
- }
- catch (NamingException ne)
- {
- LOG.log(Level.WARNING, "Error connecting to "+hostDestination+":"+
- portDestination, ne);
+ ci.setHeadingMessage(
+ INFO_REPLICATION_INITIALIZE_DESTINATION_CONNECTION_PARAMETERS.get());
+ ci.run();
+ useSSLDestination = ci.useSSL();
+ useStartTLSDestination = ci.useStartTLS();
+ hostDestination = ci.getHostName();
+ portDestination = ci.getPortNumber();
- if (Utils.isCertificateException(ne))
+ ctxDestination = createInitialLdapContextInteracting(ci);
+
+ if (ctxDestination == null)
{
- String usedUrl = ConnectionUtils.getLDAPUrl(hostDestination,
- portDestination, useSSLDestination);
- if (!promptForCertificateConfirmation(ne, getTrustManager(), usedUrl,
- getTrustManager()))
- {
- cancelled = true;
- }
- }
- else
- {
- printLineBreak();
- printErrorMessage(ERR_ERROR_CONNECTING_TO_SERVER_PROMPT_AGAIN.get(
- hostDestination+":"+portDestination, ne.toString()));
- printLineBreak();
- hostDestination = promptForString(
- INFO_REPLICATION_INITIALIZE_HOSTNAMEDESTINATION_PROMPT.get(),
- getValue(hostDestination,
- argParser.getDefaultHostNameDestination()), false);
- portDestination = promptForPort(
- INFO_REPLICATION_INITIALIZE_PORTDESTINATION_PROMPT.get(),
- getValue(portDestination,
- argParser.getDefaultPortDestination()), false);
- useSSLDestination = confirm(
- INFO_REPLICATION_INITIALIZE_USESSLDESTINATION_PROMPT.get(),
- useSSLDestination);
- if (!useSSLDestination)
- {
- useStartTLSDestination = confirm(
- INFO_REPLICATION_INITIALIZE_USESTARTTLSDESTINATION_PROMPT.get(),
- useStartTLSDestination);
- }
+ cancelled = true;
}
}
- }
- if (!cancelled)
+ catch (ClientException ce)
+ {
+ LOG.log(Level.WARNING, "Client exception "+ce);
+ println();
+ println(ce.getMessageObject());
+ println();
+ resetConnectionArguments();
+ }
+ catch (ArgumentException ae)
+ {
+ LOG.log(Level.WARNING, "Argument exception "+ae);
+ println();
+ println(ae.getMessageObject());
+ println();
+ cancelled = true;
+ }
+ } if (!cancelled)
{
uData.setHostNameDestination(hostDestination);
uData.setPortDestination(portDestination);
@@ -1842,16 +1527,20 @@
String hostPortDestination = ConnectionUtils.getHostPort(ctxDestination);
if (initializeADS)
{
- printLineBreak();
- cancelled = !confirm(INFO_REPLICATION_CONFIRM_INITIALIZE_ADS.get(
+ println();
+ cancelled = !askConfirmation(
+ INFO_REPLICATION_CONFIRM_INITIALIZE_ADS.get(
ADSContext.getAdministrationSuffixDN(), hostPortDestination,
- hostPortSource));
+ hostPortSource), true, LOG);
+ println();
}
else
{
- printLineBreak();
- cancelled = !confirm(INFO_REPLICATION_CONFIRM_INITIALIZE_GENERIC.get(
- hostPortDestination, hostPortSource));
+ println();
+ cancelled = !askConfirmation(
+ INFO_REPLICATION_CONFIRM_INITIALIZE_GENERIC.get(
+ hostPortDestination, hostPortSource), true, LOG);
+ println();
}
}
@@ -1927,7 +1616,28 @@
*/
private ApplicationTrustManager getTrustManager()
{
- return argParser.getTrustManager();
+ ApplicationTrustManager trust;
+ if (isInteractive())
+ {
+ TrustManager t = ci.getTrustManager();
+ if (t == null)
+ {
+ trust = null;
+ }
+ else if (t instanceof ApplicationTrustManager)
+ {
+ trust = (ApplicationTrustManager)t;
+ }
+ else
+ {
+ trust = new ApplicationTrustManager(ci.getKeyStore());
+ }
+ }
+ else
+ {
+ trust = argParser.getTrustManager();
+ }
+ return trust;
}
/**
@@ -1964,10 +1674,10 @@
// Best-effort: try to use admin, if it does not work, use bind DN.
try
{
- InitialLdapContext ctx = createContext(uData.getHostName1(),
- uData.getPort1(), uData.useSSL1(), uData.useStartTLS1(),
- ADSContext.getAdministratorDN(adminUid), adminPwd,
- getTrustManager());
+ InitialLdapContext ctx = createAdministrativeContext(
+ uData.getHostName1(), uData.getPort1(), uData.useSSL1(),
+ uData.useStartTLS1(), ADSContext.getAdministratorDN(adminUid),
+ adminPwd, getTrustManager());
uData.setBindDn1(ADSContext.getAdministratorDN(adminUid));
uData.setPwd1(adminPwd);
ctx.close();
@@ -2004,10 +1714,10 @@
// Best-effort: try to use admin, if it does not work, use bind DN.
try
{
- InitialLdapContext ctx = createContext(uData.getHostName2(),
- uData.getPort2(), uData.useSSL2(), uData.useStartTLS2(),
- ADSContext.getAdministratorDN(adminUid), adminPwd,
- getTrustManager());
+ InitialLdapContext ctx = createAdministrativeContext(
+ uData.getHostName2(), uData.getPort2(), uData.useSSL2(),
+ uData.useStartTLS2(), ADSContext.getAdministratorDN(adminUid),
+ adminPwd, getTrustManager());
uData.setBindDn2(ADSContext.getAdministratorDN(adminUid));
uData.setPwd2(adminPwd);
ctx.close();
@@ -2225,11 +1935,14 @@
ADSContext adsContext = new ADSContext(ctx[0]);
if (adsContext.hasAdminData())
{
- TopologyCache cache = new TopologyCache(adsContext, getTrustManager());
boolean reloadTopology = true;
LinkedList<Message> exceptionMsgs = new LinkedList<Message>();
while (reloadTopology && !cancelled)
{
+ // We must recreate the cache because the trust manager in the
+ // LDAPConnectionConsoleInteraction object might have changed.
+ TopologyCache cache = new TopologyCache(adsContext,
+ getTrustManager());
cache.reloadTopology();
reloadTopology = false;
@@ -2282,14 +1995,16 @@
{
if (!errorDisplayed)
{
- printLineBreak();
- printErrorMessage(
+ println();
+ println(
INFO_NOT_GLOBAL_ADMINISTRATOR_PROVIDED.get());
errorDisplayed = true;
}
adminUid = askForAdministratorUID(
argParser.getDefaultAdministratorUID());
+ println();
adminPwd = askForAdministratorPwd();
+ println();
}
try
{
@@ -2300,21 +2015,21 @@
}
try
{
- ctx[0] = createContext(host, port, isSSL, isStartTLS,
- ADSContext.getAdministratorDN(adminUid), adminPwd,
- getTrustManager());
+ ctx[0] = createAdministrativeContext(host, port, isSSL,
+ isStartTLS, ADSContext.getAdministratorDN(adminUid),
+ adminPwd, getTrustManager());
adsContext = new ADSContext(ctx[0]);
cache = new TopologyCache(adsContext, getTrustManager());
connected = true;
}
catch (Throwable t)
{
- printLineBreak();
- printErrorMessage(
+ println();
+ println(
ERR_ERROR_CONNECTING_TO_SERVER_PROMPT_AGAIN.get(
host+":"+port, t.getMessage()));
LOG.log(Level.WARNING, "Complete error stack:", t);
- printLineBreak();
+ println();
}
}
uData.setAdminUid(adminUid);
@@ -2343,8 +2058,8 @@
Utils.isCertificateException(e.getCause()))
{
reloadTopology = true;
- cancelled = !promptForCertificateConfirmation(e.getCause(),
- e.getTrustManager(), e.getLdapUrl(), getTrustManager());
+ cancelled = !ci.promptForCertificateConfirmation(e.getCause(),
+ e.getTrustManager(), e.getLdapUrl(), true, LOG);
}
else
{
@@ -2360,18 +2075,18 @@
{
if (uData instanceof StatusReplicationUserData)
{
- printWarningMessage(
+ println(
ERR_REPLICATION_STATUS_READING_REGISTERED_SERVERS.get(
Utils.getMessageFromCollection(exceptionMsgs,
Constants.LINE_SEPARATOR).toString()));
- printLineBreak();
+ println();
}
else
{
- cancelled = !confirm(
+ cancelled = !askConfirmation(
ERR_REPLICATION_READING_REGISTERED_SERVERS_CONFIRM_UPDATE_REMOTE.
get(Utils.getMessageFromCollection(exceptionMsgs,
- Constants.LINE_SEPARATOR).toString()));
+ Constants.LINE_SEPARATOR).toString()), true, LOG);
}
}
}
@@ -2607,13 +2322,14 @@
LinkedList<Message> errorMessages = new LinkedList<Message>();
- printProgressLineBreak();
- printProgressMessage(
+ printlnProgress();
+ printProgress(
formatter.getFormattedWithPoints(INFO_REPLICATION_CONNECTING.get()));
try
{
- ctx1 = createContext(host1, port1, uData.useSSL1(), uData.useStartTLS1(),
- uData.getBindDn1(), uData.getPwd1(), getTrustManager());
+ ctx1 = createAdministrativeContext(host1, port1, uData.useSSL1(),
+ uData.useStartTLS1(), uData.getBindDn1(), uData.getPwd1(),
+ getTrustManager());
}
catch (NamingException ne)
{
@@ -2624,8 +2340,9 @@
}
try
{
- ctx2 = createContext(host2, port2, uData.useSSL2(), uData.useStartTLS2(),
- uData.getBindDn2(), uData.getPwd2(), getTrustManager());
+ ctx2 = createAdministrativeContext(host2, port2, uData.useSSL2(),
+ uData.useStartTLS2(), uData.getBindDn2(), uData.getPwd2(),
+ getTrustManager());
}
catch (NamingException ne)
{
@@ -2643,8 +2360,8 @@
if (errorMessages.isEmpty())
{
// This done is for the message informing that we are connecting.
- printProgressMessage(formatter.getFormattedDone());
- printProgressMessage(formatter.getLineBreak());
+ printProgress(formatter.getFormattedDone());
+ printlnProgress();
// If we are not in interactive mode do some checks...
if (!argParser.isInteractive())
@@ -2720,8 +2437,8 @@
catch (ReplicationCliException rce)
{
returnValue = rce.getErrorCode();
- printLineBreak();
- printErrorMessage(getCriticalExceptionMessage(rce));
+ println();
+ println(getCriticalExceptionMessage(rce));
LOG.log(Level.SEVERE, "Complete error stack:", rce);
}
}
@@ -2735,8 +2452,8 @@
for (Message msg : errorMessages)
{
- printLineBreak();
- printErrorMessage(msg);
+ println();
+ println(msg);
}
long time1 = Utils.getServerClock(ctx1);
@@ -2746,7 +2463,7 @@
if (Math.abs(time1 - time2) >
(Installer.WARNING_CLOCK_DIFFERENCE_THRESOLD_MINUTES * 60 * 1000))
{
- printWarningMessage(INFO_WARNING_SERVERS_CLOCK_DIFFERENCE.get(
+ println(INFO_WARNING_SERVERS_CLOCK_DIFFERENCE.get(
ConnectionUtils.getHostPort(ctx1),
ConnectionUtils.getHostPort(ctx2),
String.valueOf(
@@ -2792,29 +2509,29 @@
{
ReplicationCliReturnCode returnValue = SUCCESSFUL_NOP;
InitialLdapContext ctx = null;
- printProgressMessage(
+ printProgress(
formatter.getFormattedWithPoints(INFO_REPLICATION_CONNECTING.get()));
String bindDn = uData.getAdminUid() == null ? uData.getBindDn() :
ADSContext.getAdministratorDN(uData.getAdminUid());
try
{
- ctx = createContext(uData.getHostName(), uData.getPort(),
+ ctx = createAdministrativeContext(uData.getHostName(), uData.getPort(),
uData.useSSL(), uData.useStartTLS(), bindDn, uData.getAdminPwd(),
getTrustManager());
}
catch (NamingException ne)
{
String hostPort = uData.getHostName()+":"+uData.getPort();
- printLineBreak();
- printErrorMessage(getMessageForException(ne, hostPort));
+ println();
+ println(getMessageForException(ne, hostPort));
LOG.log(Level.SEVERE, "Complete error stack:", ne);
}
if (ctx != null)
{
// This done is for the message informing that we are connecting.
- printProgressMessage(formatter.getFormattedDone());
- printProgressMessage(formatter.getLineBreak());
+ printProgress(formatter.getFormattedDone());
+ printlnProgress();
LinkedList<String> suffixes = uData.getBaseDNs();
checkSuffixesForDisableReplication(suffixes, ctx, false);
if (!suffixes.isEmpty())
@@ -2828,8 +2545,8 @@
catch (ReplicationCliException rce)
{
returnValue = rce.getErrorCode();
- printLineBreak();
- printErrorMessage(getCriticalExceptionMessage(rce));
+ println();
+ println(getCriticalExceptionMessage(rce));
LOG.log(Level.SEVERE, "Complete error stack:", rce);
}
}
@@ -2872,7 +2589,7 @@
InitialLdapContext ctx = null;
try
{
- ctx = createContext(uData.getHostName(), uData.getPort(),
+ ctx = createAdministrativeContext(uData.getHostName(), uData.getPort(),
uData.useSSL(), uData.useStartTLS(),
ADSContext.getAdministratorDN(uData.getAdminUid()),
uData.getAdminPwd(), getTrustManager());
@@ -2880,8 +2597,8 @@
catch (NamingException ne)
{
String hostPort = uData.getHostName()+":"+uData.getPort();
- printLineBreak();
- printErrorMessage(getMessageForException(ne, hostPort));
+ println();
+ println(getMessageForException(ne, hostPort));
LOG.log(Level.SEVERE, "Complete error stack:", ne);
}
@@ -2896,8 +2613,8 @@
catch (ReplicationCliException rce)
{
returnValue = rce.getErrorCode();
- printLineBreak();
- printErrorMessage(getCriticalExceptionMessage(rce));
+ println();
+ println(getCriticalExceptionMessage(rce));
LOG.log(Level.SEVERE, "Complete error stack:", rce);
}
}
@@ -2937,7 +2654,7 @@
InitialLdapContext ctxDestination = null;
try
{
- ctxSource = createContext(uData.getHostNameSource(),
+ ctxSource = createAdministrativeContext(uData.getHostNameSource(),
uData.getPortSource(), uData.useSSLSource(),
uData.useStartTLSSource(),
ADSContext.getAdministratorDN(uData.getAdminUid()),
@@ -2946,13 +2663,14 @@
catch (NamingException ne)
{
String hostPort = uData.getHostNameSource()+":"+uData.getPortSource();
- printLineBreak();
- printErrorMessage(getMessageForException(ne, hostPort));
+ println();
+ println(getMessageForException(ne, hostPort));
LOG.log(Level.SEVERE, "Complete error stack:", ne);
}
try
{
- ctxDestination = createContext(uData.getHostNameDestination(),
+ ctxDestination = createAdministrativeContext(
+ uData.getHostNameDestination(),
uData.getPortDestination(), uData.useSSLDestination(),
uData.useStartTLSDestination(),
ADSContext.getAdministratorDN(uData.getAdminUid()),
@@ -2962,8 +2680,8 @@
{
String hostPort = uData.getHostNameDestination()+":"+
uData.getPortDestination();
- printLineBreak();
- printErrorMessage(getMessageForException(ne, hostPort));
+ println();
+ println(getMessageForException(ne, hostPort));
LOG.log(Level.SEVERE, "Complete error stack:", ne);
}
if ((ctxSource != null) && (ctxDestination != null))
@@ -2977,18 +2695,18 @@
{
try
{
- printProgressLineBreak();
+ printlnProgress();
Message msg = formatter.getFormattedProgress(
INFO_PROGRESS_INITIALIZING_SUFFIX.get(baseDN,
ConnectionUtils.getHostPort(ctxSource)));
- printProgressMessage(msg);
- printProgressLineBreak();
+ printProgress(msg);
+ printlnProgress();
initializeSuffix(baseDN, ctxSource, ctxDestination, true);
}
catch (ReplicationCliException rce)
{
- printLineBreak();
- printErrorMessage(getCriticalExceptionMessage(rce));
+ println();
+ println(getCriticalExceptionMessage(rce));
returnValue = rce.getErrorCode();
LOG.log(Level.SEVERE, "Complete error stack:", rce);
}
@@ -3045,16 +2763,16 @@
InitialLdapContext ctx = null;
try
{
- ctx = createContext(uData.getHostName(), uData.getPort(), uData.useSSL(),
- uData.useStartTLS(),
+ ctx = createAdministrativeContext(uData.getHostName(), uData.getPort(),
+ uData.useSSL(), uData.useStartTLS(),
ADSContext.getAdministratorDN(uData.getAdminUid()),
uData.getAdminPwd(), getTrustManager());
}
catch (NamingException ne)
{
String hostPort = uData.getHostName()+":"+uData.getPort();
- printLineBreak();
- printErrorMessage(getMessageForException(ne, hostPort));
+ println();
+ println(getMessageForException(ne, hostPort));
LOG.log(Level.SEVERE, "Complete error stack:", ne);
}
if (ctx != null)
@@ -3067,18 +2785,18 @@
{
try
{
- printProgressLineBreak();
+ printlnProgress();
Message msg = formatter.getFormattedProgress(
INFO_PROGRESS_INITIALIZING_SUFFIX.get(baseDN,
ConnectionUtils.getHostPort(ctx)));
- printProgressMessage(msg);
- printProgressLineBreak();
+ printProgress(msg);
+ println();
initializeAllSuffix(baseDN, ctx, true);
}
catch (ReplicationCliException rce)
{
- printLineBreak();
- printErrorMessage(getCriticalExceptionMessage(rce));
+ println();
+ println(getCriticalExceptionMessage(rce));
returnValue = rce.getErrorCode();
LOG.log(Level.SEVERE, "Complete error stack:", rce);
}
@@ -3133,8 +2851,8 @@
if (availableSuffixes.size() == 0)
{
- printLineBreak();
- printErrorMessage(
+ println();
+ println(
ERR_NO_SUFFIXES_AVAILABLE_TO_ENABLE_REPLICATION.get());
LinkedList<String> userProvidedSuffixes = argParser.getBaseDNs();
@@ -3152,8 +2870,8 @@
}
if (userProvidedReplicatedSuffixes.size() > 0)
{
- printLineBreak();
- printErrorMessage(
+ println();
+ println(
INFO_ALREADY_REPLICATED_SUFFIXES.get(
Utils.getStringFromCollection(userProvidedReplicatedSuffixes,
Constants.LINE_SEPARATOR)));
@@ -3201,15 +2919,15 @@
suffixes.removeAll(alreadyReplicated);
if (notFound.size() > 0)
{
- printLineBreak();
- printErrorMessage(ERR_REPLICATION_ENABLE_SUFFIXES_NOT_FOUND.get(
+ println();
+ println(ERR_REPLICATION_ENABLE_SUFFIXES_NOT_FOUND.get(
Utils.getStringFromCollection(notFound,
Constants.LINE_SEPARATOR)));
}
if (alreadyReplicated.size() > 0)
{
- printLineBreak();
- printErrorMessage(INFO_ALREADY_REPLICATED_SUFFIXES.get(
+ println();
+ println(INFO_ALREADY_REPLICATED_SUFFIXES.get(
Utils.getStringFromCollection(alreadyReplicated,
Constants.LINE_SEPARATOR)));
}
@@ -3232,15 +2950,15 @@
{
// In interactive mode we do not propose to manage the
// administration suffix.
- printLineBreak();
- printErrorMessage(
+ println();
+ println(
ERR_NO_SUFFIXES_AVAILABLE_TO_ENABLE_REPLICATION.get());
break;
}
else
{
- printLineBreak();
- printErrorMessage(ERR_NO_SUFFIXES_SELECTED_TO_REPLICATE.get());
+ println();
+ println(ERR_NO_SUFFIXES_SELECTED_TO_REPLICATE.get());
for (String dn : availableSuffixes)
{
if (!Utils.areDnsEqual(dn,
@@ -3248,7 +2966,8 @@
!Utils.areDnsEqual(dn, Constants.SCHEMA_DN) &&
!Utils.areDnsEqual(dn, Constants.REPLICATION_CHANGES_DN))
{
- if (confirm(INFO_REPLICATION_ENABLE_SUFFIX_PROMPT.get(dn)))
+ if (askConfirmation(
+ INFO_REPLICATION_ENABLE_SUFFIX_PROMPT.get(dn), true, LOG))
{
suffixes.add(dn);
}
@@ -3291,9 +3010,8 @@
}
if (availableSuffixes.size() == 0)
{
- printLineBreak();
- printErrorMessage(
- ERR_NO_SUFFIXES_AVAILABLE_TO_DISABLE_REPLICATION.get());
+ println();
+ println(ERR_NO_SUFFIXES_AVAILABLE_TO_DISABLE_REPLICATION.get());
LinkedList<String> userProvidedSuffixes = argParser.getBaseDNs();
TreeSet<String> userProvidedNotReplicatedSuffixes =
new TreeSet<String>();
@@ -3309,12 +3027,11 @@
}
if (userProvidedNotReplicatedSuffixes.size() > 0)
{
- printLineBreak();
- printErrorMessage(
- INFO_ALREADY_NOT_REPLICATED_SUFFIXES.get(
- Utils.getStringFromCollection(
- userProvidedNotReplicatedSuffixes,
- Constants.LINE_SEPARATOR)));
+ println();
+ println(INFO_ALREADY_NOT_REPLICATED_SUFFIXES.get(
+ Utils.getStringFromCollection(
+ userProvidedNotReplicatedSuffixes,
+ Constants.LINE_SEPARATOR)));
}
suffixes.clear();
}
@@ -3359,15 +3076,15 @@
suffixes.removeAll(alreadyNotReplicated);
if (notFound.size() > 0)
{
- printLineBreak();
- printErrorMessage(ERR_REPLICATION_DISABLE_SUFFIXES_NOT_FOUND.get(
+ println();
+ println(ERR_REPLICATION_DISABLE_SUFFIXES_NOT_FOUND.get(
Utils.getStringFromCollection(notFound,
Constants.LINE_SEPARATOR)));
}
if (alreadyNotReplicated.size() > 0)
{
- printLineBreak();
- printErrorMessage(INFO_ALREADY_NOT_REPLICATED_SUFFIXES.get(
+ println();
+ println(INFO_ALREADY_NOT_REPLICATED_SUFFIXES.get(
Utils.getStringFromCollection(alreadyNotReplicated,
Constants.LINE_SEPARATOR)));
}
@@ -3389,15 +3106,14 @@
{
// In interactive mode we do not propose to manage the
// administration suffix.
- printLineBreak();
- printErrorMessage(
- ERR_NO_SUFFIXES_AVAILABLE_TO_DISABLE_REPLICATION.get());
+ println();
+ println(ERR_NO_SUFFIXES_AVAILABLE_TO_DISABLE_REPLICATION.get());
break;
}
else
{
- printLineBreak();
- printErrorMessage(ERR_NO_SUFFIXES_SELECTED_TO_DISABLE.get());
+ println();
+ println(ERR_NO_SUFFIXES_SELECTED_TO_DISABLE.get());
for (String dn : availableSuffixes)
{
if (!Utils.areDnsEqual(dn,
@@ -3405,7 +3121,8 @@
!Utils.areDnsEqual(dn, Constants.SCHEMA_DN) &&
!Utils.areDnsEqual(dn, Constants.REPLICATION_CHANGES_DN))
{
- if (confirm(INFO_REPLICATION_DISABLE_SUFFIX_PROMPT.get(dn)))
+ if (askConfirmation(
+ INFO_REPLICATION_DISABLE_SUFFIX_PROMPT.get(dn), true, LOG))
{
suffixes.add(dn);
}
@@ -3448,9 +3165,8 @@
}
if (availableSuffixes.size() == 0)
{
- printLineBreak();
- printErrorMessage(
- ERR_NO_SUFFIXES_AVAILABLE_TO_INITIALIZE_ALL_REPLICATION.get());
+ println();
+ println(ERR_NO_SUFFIXES_AVAILABLE_TO_INITIALIZE_ALL_REPLICATION.get());
LinkedList<String> userProvidedSuffixes = argParser.getBaseDNs();
TreeSet<String> userProvidedNotReplicatedSuffixes =
new TreeSet<String>();
@@ -3466,12 +3182,11 @@
}
if (userProvidedNotReplicatedSuffixes.size() > 0)
{
- printLineBreak();
- printErrorMessage(
- INFO_ALREADY_NOT_REPLICATED_SUFFIXES.get(
- Utils.getStringFromCollection(
- userProvidedNotReplicatedSuffixes,
- Constants.LINE_SEPARATOR)));
+ println();
+ println(INFO_ALREADY_NOT_REPLICATED_SUFFIXES.get(
+ Utils.getStringFromCollection(
+ userProvidedNotReplicatedSuffixes,
+ Constants.LINE_SEPARATOR)));
}
suffixes.clear();
}
@@ -3516,15 +3231,15 @@
suffixes.removeAll(alreadyNotReplicated);
if (notFound.size() > 0)
{
- printLineBreak();
- printErrorMessage(ERR_REPLICATION_INITIALIZE_ALL_SUFFIXES_NOT_FOUND.get(
+ println();
+ println(ERR_REPLICATION_INITIALIZE_ALL_SUFFIXES_NOT_FOUND.get(
Utils.getStringFromCollection(notFound,
Constants.LINE_SEPARATOR)));
}
if (alreadyNotReplicated.size() > 0)
{
- printLineBreak();
- printErrorMessage(INFO_ALREADY_NOT_REPLICATED_SUFFIXES.get(
+ println();
+ println(INFO_ALREADY_NOT_REPLICATED_SUFFIXES.get(
Utils.getStringFromCollection(alreadyNotReplicated,
Constants.LINE_SEPARATOR)));
}
@@ -3546,15 +3261,15 @@
{
// In interactive mode we do not propose to manage the
// administration suffix.
- printLineBreak();
- printErrorMessage(
+ println();
+ println(
ERR_NO_SUFFIXES_AVAILABLE_TO_INITIALIZE_ALL_REPLICATION.get());
break;
}
else
{
- printLineBreak();
- printErrorMessage(ERR_NO_SUFFIXES_SELECTED_TO_INITIALIZE_ALL.get());
+ println();
+ println(ERR_NO_SUFFIXES_SELECTED_TO_INITIALIZE_ALL.get());
for (String dn : availableSuffixes)
{
if (!Utils.areDnsEqual(dn,
@@ -3562,8 +3277,9 @@
!Utils.areDnsEqual(dn, Constants.SCHEMA_DN) &&
!Utils.areDnsEqual(dn, Constants.REPLICATION_CHANGES_DN))
{
- if (confirm(INFO_REPLICATION_INITIALIZE_ALL_SUFFIX_PROMPT.get(
- dn)))
+ if (askConfirmation(
+ INFO_REPLICATION_INITIALIZE_ALL_SUFFIX_PROMPT.get(dn),
+ true, LOG))
{
suffixes.add(dn);
}
@@ -3595,9 +3311,8 @@
SuffixRelationType.REPLICATED));
if (availableSuffixes.size() == 0)
{
- printLineBreak();
- printErrorMessage(
- ERR_NO_SUFFIXES_AVAILABLE_TO_INITIALIZE_REPLICATION.get());
+ println();
+ println(ERR_NO_SUFFIXES_AVAILABLE_TO_INITIALIZE_REPLICATION.get());
suffixes.clear();
}
else
@@ -3623,8 +3338,8 @@
suffixes.removeAll(notFound);
if (notFound.size() > 0)
{
- printLineBreak();
- printErrorMessage(ERR_SUFFIXES_CANNOT_BE_INITIALIZED.get(
+ println();
+ println(ERR_SUFFIXES_CANNOT_BE_INITIALIZED.get(
Utils.getStringFromCollection(notFound,
Constants.LINE_SEPARATOR)));
}
@@ -3646,15 +3361,14 @@
{
// In interactive mode we do not propose to manage the
// administration suffix.
- printLineBreak();
- printErrorMessage(
- ERR_NO_SUFFIXES_AVAILABLE_TO_INITIALIZE_REPLICATION.get());
+ println();
+ println(ERR_NO_SUFFIXES_AVAILABLE_TO_INITIALIZE_REPLICATION.get());
break;
}
else
{
- printLineBreak();
- printErrorMessage(ERR_NO_SUFFIXES_SELECTED_TO_INITIALIZE.get());
+ println();
+ println(ERR_NO_SUFFIXES_SELECTED_TO_INITIALIZE.get());
for (String dn : availableSuffixes)
{
@@ -3663,7 +3377,9 @@
!Utils.areDnsEqual(dn, Constants.SCHEMA_DN) &&
!Utils.areDnsEqual(dn, Constants.REPLICATION_CHANGES_DN))
{
- if (confirm(INFO_REPLICATION_INITIALIZE_SUFFIX_PROMPT.get(dn)))
+ if (askConfirmation(
+ INFO_REPLICATION_INITIALIZE_SUFFIX_PROMPT.get(dn), true,
+ LOG))
{
suffixes.add(dn);
}
@@ -3757,8 +3473,7 @@
}
if (!messages.isEmpty())
{
- printWarningMessage(
- ERR_REPLICATION_READING_REGISTERED_SERVERS_WARNING.get(
+ println(ERR_REPLICATION_READING_REGISTERED_SERVERS_WARNING.get(
Utils.getMessageFromCollection(messages,
Constants.LINE_SEPARATOR).toString()));
}
@@ -3772,7 +3487,7 @@
boolean adsAlreadyReplicated = false;
- printProgressMessage(formatter.getFormattedWithPoints(
+ printProgress(formatter.getFormattedWithPoints(
INFO_REPLICATION_ENABLE_UPDATING_ADS_CONTENTS.get()));
try
{
@@ -3905,8 +3620,8 @@
ERROR_SEEDING_TRUSTORE, t);
}
}
- printProgressMessage(formatter.getFormattedDone());
- printProgressMessage(formatter.getLineBreak());
+ printProgress(formatter.getFormattedDone());
+ printlnProgress();
LinkedList<String> baseDNs = uData.getBaseDNs();
if (!adsAlreadyReplicated)
@@ -4134,15 +3849,15 @@
// done).
if ((ctxSource != null) && (ctxDestination != null))
{
- printProgressMessage(formatter.getFormattedWithPoints(
+ printProgress(formatter.getFormattedWithPoints(
INFO_ENABLE_REPLICATION_INITIALIZING_ADS.get(
ConnectionUtils.getHostPort(ctxDestination),
ConnectionUtils.getHostPort(ctxSource))));
initializeSuffix(ADSContext.getAdministrationSuffixDN(), ctxSource,
ctxDestination, false);
- printProgressMessage(formatter.getFormattedDone());
- printProgressMessage(formatter.getLineBreak());
+ printProgress(formatter.getFormattedDone());
+ printlnProgress();
}
// If we must initialize the schema do so.
@@ -4158,14 +3873,14 @@
ctxSource = ctx1;
ctxDestination = ctx2;
}
- printProgressMessage(formatter.getFormattedWithPoints(
+ printProgress(formatter.getFormattedWithPoints(
INFO_ENABLE_REPLICATION_INITIALIZING_SCHEMA.get(
ConnectionUtils.getHostPort(ctxDestination),
ConnectionUtils.getHostPort(ctxSource))));
initializeSuffix(Constants.SCHEMA_DN, ctxSource,
ctxDestination, false);
- printProgressMessage(formatter.getFormattedDone());
- printProgressMessage(formatter.getLineBreak());
+ printProgress(formatter.getFormattedDone());
+ printlnProgress();
}
}
@@ -4228,7 +3943,7 @@
}
if (!messages.isEmpty())
{
- printWarningMessage(
+ println(
ERR_REPLICATION_READING_REGISTERED_SERVERS_WARNING.get(
Utils.getMessageFromCollection(messages,
Constants.LINE_SEPARATOR).toString()));
@@ -4324,7 +4039,7 @@
ERR_REPLICATION_STATUS_READING_REGISTERED_SERVERS.get(
Utils.getMessageFromCollection(messages,
Constants.LINE_SEPARATOR).toString());
- printWarningMessage(msg);
+ println(msg);
}
}
@@ -4392,8 +4107,8 @@
if (replicaLists.isEmpty())
{
- printProgressMessage(INFO_REPLICATION_STATUS_NO_BASEDNS.get());
- printProgressLineBreak();
+ printProgress(INFO_REPLICATION_STATUS_NO_BASEDNS.get());
+ printlnProgress();
}
else
{
@@ -4420,14 +4135,14 @@
}
for (Set<ReplicaDescriptor> replicas : orderedReplicaLists)
{
- printProgressLineBreak();
+ printlnProgress();
displayStatus(replicas, uData.isScriptFriendly());
}
if (oneReplicated && !uData.isScriptFriendly())
{
- printProgressLineBreak();
- printProgressMessage(INFO_REPLICATION_STATUS_REPLICATED_LEGEND.get());
- printProgressLineBreak();
+ printlnProgress();
+ printProgress(INFO_REPLICATION_STATUS_REPLICATED_LEGEND.get());
+ printlnProgress();
}
}
}
@@ -4516,14 +4231,7 @@
}
Message[][] values = new Message[orderedReplicas.size()][headers.length];
- int[] maxWidths = new int[headers.length];
- int i;
- for (i=0; i<maxWidths.length; i++)
- {
- maxWidths[i] = Message.toString(headers[i]).length();
- }
-
- i = 0;
+ int i = 0;
for (ReplicaDescriptor replica : orderedReplicas)
{
Message v;
@@ -4592,21 +4300,10 @@
throw new IllegalStateException("Unknown index: "+j);
}
values[i][j] = v;
- maxWidths[j] = Math.max(maxWidths[j], v.toString().length());
}
i++;
}
- int totalWidth = 0;
- for (i=0; i<maxWidths.length; i++)
- {
- if (i < maxWidths.length - 1)
- {
- maxWidths[i] += 5;
- }
- totalWidth += maxWidths[i];
- }
-
String dn = replicas.iterator().next().getSuffix().getDN();
if (scriptFriendly)
{
@@ -4621,80 +4318,59 @@
};
for (i=0; i<labels.length; i++)
{
- printProgressMessage(labels[i]+" "+vs[i]);
- printProgressLineBreak();
+ printProgress(Message.raw(labels[i]+" "+vs[i]));
+ printlnProgress();
}
for (i=0; i<values.length; i++)
{
- printProgressMessage("-");
- printProgressLineBreak();
+ printProgress(Message.raw("-"));
+ printlnProgress();
for (int j=0; j<values[i].length; j++)
{
- printProgressMessage(headers[j]+" "+values[i][j]);
- printProgressLineBreak();
+ printProgress(Message.raw(headers[j]+" "+values[i][j]));
+ printlnProgress();
}
}
}
else
{
+ Message msg;
if (isReplicated)
{
- printProgressMessageNoWrap(
- INFO_REPLICATION_STATUS_REPLICATED.get(dn));
- printProgressLineBreak();
+ msg = INFO_REPLICATION_STATUS_REPLICATED.get(dn);
}
else
{
- printProgressMessageNoWrap(
- INFO_REPLICATION_STATUS_NOT_REPLICATED.get(dn));
- printProgressLineBreak();
+ msg = INFO_REPLICATION_STATUS_NOT_REPLICATED.get(dn);
}
+ printProgressMessageNoWrap(msg);
+ printlnProgress();
+ int length = msg.length();
+ StringBuffer buf = new StringBuffer();
+ for (i=0; i<length; i++)
+ {
+ buf.append("=");
+ }
+ printProgressMessageNoWrap(Message.raw(buf.toString()));
+ printlnProgress();
- MessageBuilder headerLine = new MessageBuilder();
- for (i=0; i<maxWidths.length; i++)
+ TableBuilder table = new TableBuilder();
+ for (i=0; i< headers.length; i++)
{
- String header = headers[i].toString();
- headerLine.append(header);
- int extra = maxWidths[i] - header.length();
- for (int j=0; j<extra; j++)
- {
- headerLine.append(" ");
- }
+ table.appendHeading(headers[i]);
}
- StringBuilder builder = new StringBuilder();
- for (i=0; i<headerLine.length(); i++)
- {
- builder.append("=");
- }
- printProgressMessageNoWrap(builder.toString());
- printProgressLineBreak();
- printProgressMessageNoWrap(headerLine.toMessage());
- printProgressLineBreak();
- builder = new StringBuilder();
- for (i=0; i<headerLine.length(); i++)
- {
- builder.append("-");
- }
- printProgressMessageNoWrap(builder.toString());
- printProgressLineBreak();
-
for (i=0; i<values.length; i++)
{
- MessageBuilder line = new MessageBuilder();
- for (int j=0; j<values[i].length; j++)
+ table.startRow();
+ for (int j=0; j<headers.length; j++)
{
- int extra = maxWidths[j];
- line.append(values[i][j]);
- extra -= values[i][j].length();
- for (int k=0; k<extra; k++)
- {
- line.append(" ");
- }
+ table.appendCell(values[i][j]);
}
- printProgressMessageNoWrap(line.toMessage());
- printProgressLineBreak();
}
+ TextTablePrinter printer = new TextTablePrinter(getOutputStream());
+ printer.setColumnSeparator(ToolConstants.LIST_TABLE_SEPARATOR);
+ table.print(printer);
}
}
@@ -4837,7 +4513,7 @@
LinkedHashSet<String> replicationServers,
Set<Integer> usedReplicationServerIds) throws OpenDsException
{
- printProgressMessage(formatter.getFormattedWithPoints(
+ printProgress(formatter.getFormattedWithPoints(
INFO_REPLICATION_ENABLE_CONFIGURING_REPLICATION_SERVER.get(
ConnectionUtils.getHostPort(ctx))));
@@ -4929,8 +4605,8 @@
replicationServer.commit();
}
- printProgressMessage(formatter.getFormattedDone());
- printProgressMessage(formatter.getLineBreak());
+ printProgress(formatter.getFormattedDone());
+ printlnProgress();
}
/**
@@ -4944,7 +4620,7 @@
private void updateReplicationServer(InitialLdapContext ctx,
LinkedHashSet<String> replicationServers) throws OpenDsException
{
- printProgressMessage(formatter.getFormattedWithPoints(
+ printProgress(formatter.getFormattedWithPoints(
INFO_REPLICATION_ENABLE_UPDATING_REPLICATION_SERVER.get(
ConnectionUtils.getHostPort(ctx))));
@@ -4975,8 +4651,8 @@
replicationServer.commit();
}
- printProgressMessage(formatter.getFormattedDone());
- printProgressMessage(formatter.getLineBreak());
+ printProgress(formatter.getFormattedDone());
+ printlnProgress();
}
/**
@@ -5032,13 +4708,13 @@
if (!userSpecifiedAdminBaseDN && Utils.areDnsEqual(baseDN,
ADSContext.getAdministrationSuffixDN()))
{
- printProgressMessage(formatter.getFormattedWithPoints(
+ printProgress(formatter.getFormattedWithPoints(
INFO_REPLICATION_ENABLE_CONFIGURING_ADS.get(
ConnectionUtils.getHostPort(ctx))));
}
else
{
- printProgressMessage(formatter.getFormattedWithPoints(
+ printProgress(formatter.getFormattedWithPoints(
INFO_REPLICATION_ENABLE_CONFIGURING_BASEDN.get(baseDN,
ConnectionUtils.getHostPort(ctx))));
}
@@ -5106,8 +4782,8 @@
domain.commit();
}
- printProgressMessage(formatter.getFormattedDone());
- printProgressMessage(formatter.getLineBreak());
+ printProgress(formatter.getFormattedDone());
+ printlnProgress();
}
/**
@@ -5257,8 +4933,8 @@
if ((newLogDetails != null) &&
!newLogDetails.toString().trim().equals(""))
{
- printProgressMessage(newLogDetails);
- printProgressLineBreak();
+ printProgress(newLogDetails);
+ printlnProgress();
}
}
});
@@ -5502,9 +5178,9 @@
if (((currentTime - minRefreshPeriod) > lastTimeMsgDisplayed) &&
!msg.equals(lastDisplayedMsg))
{
- printProgressMessage(msg);
+ printProgress(msg);
lastDisplayedMsg = msg;
- printProgressLineBreak();
+ printlnProgress();
lastTimeMsgDisplayed = currentTime;
}
}
@@ -5529,9 +5205,9 @@
LOG.log(Level.INFO, "Last task entry: "+sr);
if (displayProgress && (msg != null) && !msg.equals(lastDisplayedMsg))
{
- printProgressMessage(msg);
+ printProgress(msg);
lastDisplayedMsg = msg;
- printProgressLineBreak();
+ printlnProgress();
}
if (lastLogMsg == null)
{
@@ -5549,7 +5225,7 @@
{
if (displayProgress)
{
- printWarningMessage(errorMsg);
+ println(errorMsg);
}
}
else if (!helper.isSuccessful(state) ||
@@ -5576,8 +5252,8 @@
{
if (displayProgress)
{
- printProgressMessage(INFO_SUFFIX_INITIALIZED_SUCCESSFULLY.get());
- printProgressLineBreak();
+ printProgress(INFO_SUFFIX_INITIALIZED_SUCCESSFULLY.get());
+ printlnProgress();
}
LOG.log(Level.INFO, "Initialization completed successfully.");
}
@@ -5589,8 +5265,8 @@
LOG.log(Level.INFO, "Initialization entry not found.");
if (displayProgress)
{
- printProgressMessage(INFO_SUFFIX_INITIALIZED_SUCCESSFULLY.get());
- printProgressLineBreak();
+ printProgress(INFO_SUFFIX_INITIALIZED_SUCCESSFULLY.get());
+ printlnProgress();
}
}
catch (NamingException ne)
@@ -5708,7 +5384,7 @@
if (Utils.areDnsEqual(domain.getBaseDN().toString(),
baseDN))
{
- printProgressMessage(formatter.getFormattedWithPoints(
+ printProgress(formatter.getFormattedWithPoints(
INFO_REPLICATION_REMOVING_REFERENCES_ON_REMOTE.get(baseDN,
hostPort)));
Set<String> replServers = domain.getReplicationServer();
@@ -5740,8 +5416,8 @@
}
}
}
- printProgressMessage(formatter.getFormattedDone());
- printProgressMessage(formatter.getLineBreak());
+ printProgress(formatter.getFormattedDone());
+ printlnProgress();
}
}
}
@@ -5825,14 +5501,14 @@
sync.getReplicationDomain(domainNames[i]);
if (Utils.areDnsEqual(domain.getBaseDN().toString(), baseDN))
{
- printProgressMessage(formatter.getFormattedWithPoints(
+ printProgress(formatter.getFormattedWithPoints(
INFO_REPLICATION_DISABLING_BASEDN.get(baseDN,
hostPort)));
sync.removeReplicationDomain(domainNames[i]);
sync.commit();
- printProgressMessage(formatter.getFormattedDone());
- printProgressMessage(formatter.getLineBreak());
+ printProgress(formatter.getFormattedDone());
+ printlnProgress();
}
}
}
@@ -5929,31 +5605,7 @@
}
/**
- * Asks the user to provide the global administrator UID or the bindDN to
- * be used to bind to the server and disable replication.
- * @param defaultValue the default value to be proposed.
- * @return the UID or DN provided by the user.
- */
- private String askForBindDnDisable(String defaultValue)
- {
- return promptForString(INFO_REPLICATION_DISABLE_BINDDN_PROMPT.get(),
- defaultValue, false);
- }
-
- /**
- * Asks the user to provide the password to be used to bind to the server and
- * disable replication.
- * @param userId the user we are asking the password for.
- * @return the password provided by the user.
- */
- private String askForPasswordDisable(String userId)
- {
- return promptForPassword(INFO_REPLICATION_DISABLE_PASSWORD_PROMPT.get(
- userId));
- }
-
- /**
- * REturns a message informing the user that the provided port cannot be used.
+ * Returns a message informing the user that the provided port cannot be used.
* @param port the port that cannot be used.
* @return a message informing the user that the provided port cannot be used.
*/
@@ -6140,4 +5792,344 @@
}
}
}
+
+ /**
+ * {@inheritDoc}
+ */
+ public boolean isAdvancedMode() {
+ return false;
+ }
+
+
+
+ /**
+ * {@inheritDoc}
+ */
+ public boolean isInteractive() {
+ return argParser.isInteractive();
+ }
+
+
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean isMenuDrivenMode() {
+ return true;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public boolean isQuiet()
+ {
+ return argParser.isQuiet();
+ }
+
+
+
+ /**
+ * {@inheritDoc}
+ */
+ public boolean isScriptFriendly() {
+ return argParser.isScriptFriendly();
+ }
+
+
+
+ /**
+ * {@inheritDoc}
+ */
+ public boolean isVerbose() {
+ return true;
+ }
+
+ /**
+ * Prompts the user to give a value.
+ * @param defaultValue the default value that will be proposed in the prompt
+ * message.
+ * @return the String as provided by the user or the defaultValue if an error.
+ * occurred reading the input.
+ */
+ private String promptForString(Message prompt, String defaultValue)
+ {
+ String s = defaultValue;
+ try
+ {
+ s = readInput(prompt, defaultValue);
+ }
+ catch (CLIException ce)
+ {
+ LOG.log(Level.WARNING, "Error reading input: "+ce, ce);
+ }
+ return s;
+ }
+
+ /**
+ * Commodity method used to repeatidly ask the user to provide a port value.
+ * @param prompt the prompt message.
+ * @param defaultValue the default value of the port to be proposed to the
+ * user.
+ * @return the port value provided by the user.
+ */
+ private int askPort(Message prompt, int defaultValue)
+ {
+ int port = -1;
+ while (port == -1)
+ {
+ try
+ {
+ port = readPort(prompt, defaultValue);
+ }
+ catch (CLIException ce)
+ {
+ port = -1;
+ LOG.log(Level.WARNING, "Error reading input: "+ce, ce);
+ }
+ }
+ return port;
+ }
+
+ /**
+ * Prompts the user to give the Global Administrator UID.
+ * @param defaultValue the default value that will be proposed in the prompt
+ * message.
+ * @return the Global Administrator UID as provided by the user.
+ */
+ private String askForAdministratorUID(String defaultValue)
+ {
+ String s = defaultValue;
+ try
+ {
+ s = readInput(INFO_ADMINISTRATOR_UID_PROMPT.get(), defaultValue);
+ }
+ catch (CLIException ce)
+ {
+ LOG.log(Level.WARNING, "Error reading input: "+ce, ce);
+ }
+ return s;
+ }
+
+ /**
+ * Prompts the user to give the Global Administrator password.
+ * @return the Global Administrator password as provided by the user.
+ */
+ private String askForAdministratorPwd()
+ {
+ String pwd = readPassword(INFO_ADMINISTRATOR_PWD_PROMPT.get(), LOG);
+ return pwd;
+ }
+
+ /**
+ * Prints a message to the output with no wrapping if we are not in quiet
+ * mode.
+ * @param msg the message to be displayed.
+ */
+ private void printProgressMessageNoWrap(Message msg)
+ {
+ if (!isQuiet())
+ {
+ getOutputStream().print(msg.toString());
+ }
+ }
+
+ /**
+ * Enumeration description protocols for interactive CLI choices.
+ */
+ private enum Protocols
+ {
+ LDAP(1, INFO_LDAP_CONN_PROMPT_SECURITY_LDAP.get()), SSL(2,
+ INFO_LDAP_CONN_PROMPT_SECURITY_USE_SSL.get()), START_TLS(3,
+ INFO_LDAP_CONN_PROMPT_SECURITY_USE_START_TLS.get());
+
+ private Integer choice;
+
+ private Message msg;
+
+ /**
+ * Private constructor.
+ *
+ * @param i
+ * the menu return value.
+ * @param msg
+ * the message message.
+ */
+ private Protocols(int i, Message msg)
+ {
+ choice = i;
+ this.msg = msg;
+ }
+
+ /**
+ * Returns the choice number.
+ *
+ * @return the attribute name.
+ */
+ public Integer getChoice()
+ {
+ return choice;
+ }
+
+ /**
+ * Return the menu message.
+ *
+ * @return the menu message.
+ */
+ public Message getMenuMessage()
+ {
+ return msg;
+ }
+ }
+
+ private Protocols askProtocol(Message prompt, boolean isSecure,
+ boolean isStartTLS)
+ {
+ Protocols protocol;
+ MenuBuilder<Integer> builder = new MenuBuilder<Integer>(this);
+ builder.setPrompt(prompt);
+
+ Protocols defaultProtocol = Protocols.LDAP;
+ if (isSecure)
+ {
+ defaultProtocol = Protocols.SSL;
+ }
+ else if (isStartTLS)
+ {
+ defaultProtocol = Protocols.START_TLS;
+ }
+ for (Protocols p : Protocols.values())
+ {
+ int i = builder.addNumberedOption(p.getMenuMessage(), MenuResult
+ .success(p.getChoice()));
+ if (p.equals(defaultProtocol))
+ {
+ builder.setDefault(
+ INFO_LDAP_CONN_PROMPT_SECURITY_PROTOCOL_DEFAULT_CHOICE
+ .get(i), MenuResult.success(p.getChoice()));
+ }
+ }
+
+ Menu<Integer> menu = builder.toMenu();
+ try
+ {
+ MenuResult<Integer> result = menu.run();
+ if (result.isSuccess())
+ {
+ if (result.getValue().equals(Protocols.SSL.getChoice()))
+ {
+ protocol = Protocols.SSL;
+ }
+ else if (result.getValue()
+ .equals(Protocols.START_TLS.getChoice()))
+ {
+ protocol = Protocols.START_TLS;
+ }
+ else
+ {
+ protocol = Protocols.LDAP;
+ }
+ }
+ else
+ {
+ // Should never happen.
+ throw new RuntimeException();
+ }
+ }
+ catch (CLIException e)
+ {
+ throw new RuntimeException(e);
+ }
+ return protocol;
+ }
+
+ /**
+ * Displays the provided header if is was not already displayed. This method
+ * just is used for refactoring this small bit of code.
+ * @param msg the heading to be displayed.
+ * @param wasDisplayed whether this heading was already displayed or not.
+ * @return <CODE>true</CODE> if the message was displayed and
+ * <CODE>false</CODE> otherwise.
+ */
+ private boolean checkHeadingDisplay(Message msg, boolean wasDisplayed)
+ {
+ if (!wasDisplayed)
+ {
+ println(msg);
+ println();
+ println();
+ }
+ wasDisplayed = true;
+ return wasDisplayed;
+ }
+
+ /**
+ * Resets the connection parameters for the LDAPConsoleInteraction object.
+ * The reset does not apply to the certificate parameters. This is called
+ * in order the LDAPConnectionConsoleInteraction object to ask for all this
+ * connection parameters next time we call
+ * LDAPConnectionConsoleInteraction.run().
+ */
+ private void resetConnectionArguments()
+ {
+ argParser.getSecureArgsList().hostNameArg.clearValues();
+ argParser.getSecureArgsList().hostNameArg.setPresent(false);
+ argParser.getSecureArgsList().portArg.clearValues();
+ argParser.getSecureArgsList().portArg.setPresent(false);
+ // This is done to be able to call IntegerArgument.getIntValue()
+ argParser.getSecureArgsList().portArg.addValue(
+ argParser.getSecureArgsList().portArg.getDefaultValue());
+ argParser.getSecureArgsList().bindDnArg.clearValues();
+ argParser.getSecureArgsList().bindDnArg.setPresent(false);
+ argParser.getSecureArgsList().bindPasswordArg.clearValues();
+ argParser.getSecureArgsList().bindPasswordArg.setPresent(false);
+ argParser.getSecureArgsList().bindPasswordFileArg.clearValues();
+ argParser.getSecureArgsList().bindPasswordFileArg.setPresent(false);
+ argParser.getSecureArgsList().adminUidArg.clearValues();
+ argParser.getSecureArgsList().adminUidArg.setPresent(false);
+ }
+
+ /**
+ * Initializes the global arguments in the parser with the provided values.
+ */
+ private void initializeGlobalArguments(String hostName, int port,
+ boolean useSSL, boolean useStartTLS, String adminUid, String bindDn,
+ String bindPwd)
+ {
+ resetConnectionArguments();
+ if (hostName != null)
+ {
+ argParser.getSecureArgsList().hostNameArg.addValue(hostName);
+ argParser.getSecureArgsList().hostNameArg.setPresent(true);
+ }
+ if (port != -1)
+ {
+ argParser.getSecureArgsList().portArg.addValue(String.valueOf(port));
+ argParser.getSecureArgsList().portArg.setPresent(true);
+ }
+ else
+ {
+ argParser.getSecureArgsList().portArg.clearValues();
+ // This is done to be able to call IntegerArgument.getIntValue()
+ argParser.getSecureArgsList().portArg.addValue(
+ argParser.getSecureArgsList().portArg.getDefaultValue());
+ }
+ argParser.getSecureArgsList().useSSLArg.setPresent(useSSL);
+ argParser.getSecureArgsList().useStartTLSArg.setPresent(useStartTLS);
+ if (adminUid != null)
+ {
+ argParser.getSecureArgsList().adminUidArg.addValue(adminUid);
+ argParser.getSecureArgsList().adminUidArg.setPresent(true);
+ }
+ if (bindDn != null)
+ {
+ argParser.getSecureArgsList().bindDnArg.addValue(bindDn);
+ argParser.getSecureArgsList().bindDnArg.setPresent(true);
+ }
+ if (bindPwd != null)
+ {
+ argParser.getSecureArgsList().bindPasswordArg.addValue(bindPwd);
+ argParser.getSecureArgsList().bindPasswordArg.setPresent(true);
+ }
+ }
}
diff --git a/opends/src/guitools/org/opends/guitools/uninstaller/UninstallCliHelper.java b/opends/src/guitools/org/opends/guitools/uninstaller/UninstallCliHelper.java
index 95713db..cc7600d 100644
--- a/opends/src/guitools/org/opends/guitools/uninstaller/UninstallCliHelper.java
+++ b/opends/src/guitools/org/opends/guitools/uninstaller/UninstallCliHelper.java
@@ -35,7 +35,6 @@
import org.opends.admin.ads.TopologyCache;
import org.opends.admin.ads.TopologyCacheException;
import org.opends.admin.ads.util.ApplicationTrustManager;
-import org.opends.admin.ads.util.ConnectionUtils;
import org.opends.guitools.statuspanel.ConfigException;
import org.opends.guitools.statuspanel.ConfigFromFile;
import org.opends.guitools.statuspanel.ConnectionProtocolPolicy;
@@ -63,7 +62,6 @@
import org.opends.server.util.cli.MenuResult;
-import java.security.cert.X509Certificate;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
@@ -74,7 +72,6 @@
import java.net.URI;
import javax.naming.NamingException;
-import javax.naming.NoPermissionException;
import javax.naming.ldap.InitialLdapContext;
import javax.net.ssl.TrustManager;
@@ -705,27 +702,8 @@
while (!couldConnect && accepted)
{
- boolean prompted = false;
- while (uid == null)
- {
- println();
- uid = askForAdministratorUID(parser.getDefaultAdministratorUID());
- prompted = true;
- }
- while (pwd == null)
- {
- if (!prompted)
- {
- println();
- }
- pwd = askForAdministratorPwd();
- }
- userData.setAdminUID(uid);
- userData.setAdminPwd(pwd);
- userData.setUseSSL(useSSL);
- userData.setUseStartTLS(useStartTLS);
- // This is done because we do not need to ask the user about these
+ // This is done because we do not need to ask the user about these
// parameters. If we force their presence the class
// LDAPConnectionConsoleInteraction will not prompt the user for
// them.
@@ -779,6 +757,7 @@
{
ci =
new LDAPConnectionConsoleInteraction(this, parser.getSecureArgsList());
+ ci.setDisplayLdapIfSecureParameters(true);
}
InitialLdapContext ctx = null;
@@ -787,6 +766,10 @@
ci.run(canUseSSL, canUseStartTLS);
useSSL = ci.useSSL();
useStartTLS = ci.useStartTLS();
+ userData.setAdminUID(ci.getAdministratorUID());
+ userData.setAdminPwd(ci.getBindPassword());
+ userData.setUseSSL(useSSL);
+ userData.setUseStartTLS(useStartTLS);
String ldapUrl = conf.getURL(
ConnectionProtocolPolicy.getConnectionPolicy(
@@ -1037,8 +1020,8 @@
{
LOG.log(Level.SEVERE, "Error parsing url: "+ldapUrl);
}
- ctx = createContext(host, port, useSSL, useStartTLS, dn, pwd,
- userData.getTrustManager());
+ ctx = createAdministrativeContext(host, port, useSSL, useStartTLS, dn,
+ pwd, userData.getTrustManager());
ADSContext adsContext = new ADSContext(ctx);
TopologyCache cache = new TopologyCache(adsContext,
@@ -1104,7 +1087,7 @@
if (forceOnError)
{
println(ERR_UNINSTALL_ERROR_UPDATING_REMOTE_FORCE.get(
- parser.adminUidArg.getLongIdentifier(),
+ parser.getSecureArgsList().adminUidArg.getLongIdentifier(),
ToolConstants.OPTION_LONG_BINDPWD,
ToolConstants.OPTION_LONG_BINDPWD_FILE));
}
@@ -1112,7 +1095,7 @@
{
println(
ERR_UNINSTALL_ERROR_UPDATING_REMOTE_NO_FORCE.get(
- parser.adminUidArg.getLongIdentifier(),
+ parser.getSecureArgsList().adminUidArg.getLongIdentifier(),
ToolConstants.OPTION_LONG_BINDPWD,
ToolConstants.OPTION_LONG_BINDPWD_FILE,
parser.forceOnErrorArg.getLongIdentifier()));
@@ -1182,8 +1165,8 @@
if (interactive)
{
println();
- if (promptForCertificateConfirmation(e.getCause(),
- e.getTrustManager(), e.getLdapUrl(), true))
+ if (ci.promptForCertificateConfirmation(e.getCause(),
+ e.getTrustManager(), e.getLdapUrl(), true, LOG))
{
stopProcessing = true;
reloadTopologyCache = true;
@@ -1301,200 +1284,6 @@
}
/**
- * Prompts the user to give the Global Administrator UID.
- * @param defaultValue the default value that will be proposed in the prompt
- * message.
- * @return the Global Administrator UID as provided by the user.
- */
- private String askForAdministratorUID(String defaultValue)
- {
- String s = defaultValue;
- try
- {
- s = readInput(INFO_ADMINISTRATOR_UID_PROMPT.get(), defaultValue);
- }
- catch (CLIException ce)
- {
- LOG.log(Level.WARNING, "Error reading input: "+ce, ce);
- }
- return s;
- }
-
- /**
- * Prompts the user to give the Global Administrator password.
- * @return the Global Administrator password as provided by the user.
- */
- private String askForAdministratorPwd()
- {
- String pwd = null;
- try
- {
- pwd = readPassword(INFO_ADMINISTRATOR_PWD_PROMPT.get());
- }
- catch (CLIException ce)
- {
- LOG.log(Level.WARNING, "Error reading input: "+ce, ce);
- }
- return pwd;
- }
-
- /**
- * Returns an InitialLdapContext using the provided parameters. We try
- * to guarantee that the connection is able to read the configuration.
- * @param host the host name.
- * @param port the port to connect.
- * @param useSSL whether to use SSL or not.
- * @param useStartTLS whether to use StartTLS or not.
- * @param bindDn the bind dn to be used.
- * @param pwd the password.
- * @param trustManager the trust manager.
- * @return an InitialLdapContext connected.
- * @throws NamingException if there was an error establishing the connection.
- */
- private InitialLdapContext createContext(String host, int port,
- boolean useSSL, boolean useStartTLS, String bindDn, String pwd,
- ApplicationTrustManager trustManager)
- throws NamingException
- {
- InitialLdapContext ctx;
- String ldapUrl = ConnectionUtils.getLDAPUrl(host, port, useSSL);
- if (useSSL)
- {
- ctx = Utils.createLdapsContext(ldapUrl, bindDn, pwd,
- Utils.getDefaultLDAPTimeout(), null, trustManager);
- }
- else if (useStartTLS)
- {
- ctx = Utils.createStartTLSContext(ldapUrl, bindDn, pwd,
- Utils.getDefaultLDAPTimeout(), null, trustManager,
- null);
- }
- else
- {
- ctx = Utils.createLdapContext(ldapUrl, bindDn, pwd,
- Utils.getDefaultLDAPTimeout(), null);
- }
- if (!ConnectionUtils.connectedAsAdministrativeUser(ctx))
- {
- throw new NoPermissionException(
- ERR_NOT_ADMINISTRATIVE_USER.get().toString());
- }
- return ctx;
- }
-
- /**
- * Prompts the user to accept the certificate.
- * @param t the throwable that was generated because the certificate was
- * not trusted.
- * @param usedTrustManager the trustManager used when trying to establish the
- * connection.
- * @param usedUrl the LDAP URL used to connect to the server.
- * @param displayErrorMessage whether to display an error message before
- * asking to accept the certificate or not.
- * @return <CODE>true</CODE> if the user accepted the certificate and
- * <CODE>false</CODE> otherwise.
- */
- private boolean promptForCertificateConfirmation(Throwable t,
- ApplicationTrustManager usedTrustManager, String usedUrl,
- boolean displayErrorMessage)
- {
- boolean returnValue = false;
- ApplicationTrustManager.Cause cause;
- if (usedTrustManager != null)
- {
- cause = usedTrustManager.getLastRefusedCause();
- }
- else
- {
- cause = null;
- }
-
- LOG.log(Level.INFO, "Certificate exception cause: "+cause);
- UserDataCertificateException.Type excType = null;
- if (cause == ApplicationTrustManager.Cause.NOT_TRUSTED)
- {
- excType = UserDataCertificateException.Type.NOT_TRUSTED;
- }
- else if (cause ==
- ApplicationTrustManager.Cause.HOST_NAME_MISMATCH)
- {
- excType = UserDataCertificateException.Type.HOST_NAME_MISMATCH;
- }
- else
- {
- Message msg = Utils.getThrowableMsg(INFO_ERROR_CONNECTING_TO_LOCAL.get(),
- t);
- println(msg);
- }
-
- if (excType != null)
- {
- String h;
- int p;
- try
- {
- URI uri = new URI(usedUrl);
- h = uri.getHost();
- p = uri.getPort();
- }
- catch (Throwable t1)
- {
- LOG.log(Level.WARNING, "Error parsing ldap url of ldap url.", t1);
- h = INFO_NOT_AVAILABLE_LABEL.get().toString();
- p = -1;
- }
- UserDataCertificateException udce =
- new UserDataCertificateException(Step.REPLICATION_OPTIONS,
- INFO_CERTIFICATE_EXCEPTION.get(h, String.valueOf(p)), t, h, p,
- usedTrustManager.getLastRefusedChain(),
- usedTrustManager.getLastRefusedAuthType(), excType);
-
- Message msg;
- if (udce.getType() == UserDataCertificateException.Type.NOT_TRUSTED)
- {
- msg = INFO_CERTIFICATE_NOT_TRUSTED_TEXT_CLI.get(
- udce.getHost(), String.valueOf(udce.getPort()),
- udce.getHost(), String.valueOf(udce.getPort()));
- }
- else
- {
- msg = INFO_CERTIFICATE_NAME_MISMATCH_TEXT_CLI.get(
- udce.getHost(), String.valueOf(udce.getPort()),
- udce.getHost(),
- udce.getHost(), String.valueOf(udce.getPort()),
- udce.getHost(), String.valueOf(udce.getPort()));
- }
- if (displayErrorMessage)
- {
- println(msg);
- }
- X509Certificate[] chain = udce.getChain();
- String authType = udce.getAuthType();
- String host = udce.getHost();
- if (chain == null)
- {
- LOG.log(Level.WARNING,
- "The chain is null for the UserDataCertificateException");
- }
- if (authType == null)
- {
- LOG.log(Level.WARNING,
- "The auth type is null for the UserDataCertificateException");
- }
- if (host == null)
- {
- LOG.log(Level.WARNING,
- "The host is null for the UserDataCertificateException");
- }
- if (chain != null)
- {
- returnValue = ci.checkServerCertificate(chain, authType, host);
- }
- }
- return returnValue;
- }
-
- /**
* Commodity method to update the user data with the trust manager in the
* LDAPConnectionConsoleInteraction object.
* @param userData the user data to be updated.
diff --git a/opends/src/guitools/org/opends/guitools/uninstaller/UninstallerArgumentParser.java b/opends/src/guitools/org/opends/guitools/uninstaller/UninstallerArgumentParser.java
index 8eccf45..48daa75 100644
--- a/opends/src/guitools/org/opends/guitools/uninstaller/UninstallerArgumentParser.java
+++ b/opends/src/guitools/org/opends/guitools/uninstaller/UninstallerArgumentParser.java
@@ -38,7 +38,6 @@
import org.opends.messages.Message;
import org.opends.messages.MessageBuilder;
-import org.opends.quicksetup.Constants;
import org.opends.quicksetup.UserData;
import org.opends.server.admin.client.cli.SecureConnectionCliArgs;
import org.opends.server.admin.client.cli.SecureConnectionCliParser;
@@ -66,10 +65,6 @@
private BooleanArgument removeBackupFilesArg;
private BooleanArgument removeLDIFFilesArg;
- /**
- * The 'admin UID' global argument.
- */
- StringArgument adminUidArg;
private StringArgument referencedHostNameArg;
/**
@@ -180,22 +175,19 @@
INFO_UNINSTALLDS_DESCRIPTION_QUIET.get());
args.add(quietArg);
- adminUidArg = new StringArgument("adminUID", 'I',
- OPTION_LONG_ADMIN_UID, false, false, true, "adminUID",
- Constants.GLOBAL_ADMIN_UID, null, INFO_DESCRIPTION_ADMIN_UID.get());
-
ArrayList<Argument> defaultArgs =
- new ArrayList<Argument>(createGlobalArguments(System.err));
+ new ArrayList<Argument>(createGlobalArguments(outStream));
int index = defaultArgs.indexOf(secureArgsList.bindDnArg);
if (index != -1)
{
- defaultArgs.add(index, adminUidArg);
+ defaultArgs.add(index, secureArgsList.adminUidArg);
defaultArgs.remove(secureArgsList.bindDnArg);
}
else
{
- defaultArgs.add(adminUidArg);
+ defaultArgs.add(secureArgsList.adminUidArg);
}
+ secureArgsList.adminUidArg.setHidden(false);
defaultArgs.remove(secureArgsList.hostNameArg);
defaultArgs.remove(secureArgsList.portArg);
defaultArgs.remove(verboseArg);
@@ -324,26 +316,12 @@
}
/**
- * Returns the Administrator UID provided in the command-line.
- * @return the Administrator UID provided in the command-line.
- */
- public String getAdministratorUID()
- {
- String uid = null;
- if (adminUidArg.isPresent())
- {
- uid = adminUidArg.getValue();
- }
- return uid;
- }
-
- /**
* Returns the default Administrator UID value.
* @return the default Administrator UID value.
*/
public String getDefaultAdministratorUID()
{
- return adminUidArg.getDefaultValue();
+ return secureArgsList.adminUidArg.getDefaultValue();
}
/**
diff --git a/opends/src/messages/messages/admin_tool.properties b/opends/src/messages/messages/admin_tool.properties
index f21a510..0832225 100644
--- a/opends/src/messages/messages/admin_tool.properties
+++ b/opends/src/messages/messages/admin_tool.properties
@@ -121,22 +121,10 @@
INFO_CLI_DO_YOU_WANT_TO_CONTINUE=Do you want to continue?
INFO_CLI_NUMBER_PROMPT=Enter a number or press Enter to accept the default
INFO_CLI_INVALID_RESPONSE=Invalid response
-INFO_CLI_YES_LONG=yes
-INFO_CLI_YES_SHORT=y
-INFO_CLI_NO_LONG=no
-INFO_CLI_NO_SHORT=n
INFO_CLOSE_BUTTON_UNINSTALL_TOOLTIP=Close Uninstall Window
INFO_CONFIRM_CLOSE_UNINSTALL_MSG=OpenDS Uninstall has not yet completed.%nAre \
you sure you want to close the Uninstall Window?
INFO_CONFIRM_CLOSE_UNINSTALL_TITLE=Confirmation Required
-INFO_CLI_ACCEPT_CERTIFICATE_LONG=accept
-INFO_CLI_ACCEPT_CERTIFICATE_SHORT=a
-INFO_CLI_REJECT_CERTIFICATE_LONG=reject
-INFO_CLI_REJECT_CERTIFICATE_SHORT=r
-INFO_CLI_VIEW_CERTIFICATE_LONG=view
-INFO_CLI_VIEW_CERTIFICATE_SHORT=v
-INFO_CLI_ACCEPT_CERTIFICATE_PROMPT=Do you want to accept, view or reject the \
-certificate?
INFO_CONFIRM_RESTART_MESSAGE=Are you sure you want to Restart the Directory \
Server?
INFO_CONFIRM_RESTART_TITLE=Confirmation Required
@@ -473,6 +461,8 @@
communication with the source server
INFO_DESCRIPTION_INITIALIZE_REPLICATION_STARTTLS_SOURCE=Use StartTLS to \
secure communication with the source server
+INFO_REPLICATION_INITIALIZE_PROTOCOL_SOURCE=How do you want to connect to the \
+ source server?
INFO_DESCRIPTION_INITIALIZE_REPLICATION_HOST_DESTINATION=Directory server \
hostname or IP address of the destination server whose contents will be \
initialized
@@ -556,55 +546,34 @@
MILD_ERR_ERROR_CONNECTING_TO_SERVER_PROMPT_AGAIN=Could not connect to the \
Directory Server %s with the provided credentials.%nError details: %s%n%n\
Provide again the required information to connect to the server:
+INFO_REPLICATION_ENABLE_HOST1_CONNECTION_PARAMETERS=>>>> Specify OpenDS LDAP \
+ connection parameters for the first server
INFO_REPLICATION_ENABLE_HOSTNAME1_PROMPT=Host name of the first server
INFO_REPLICATION_ENABLE_PORT1_PROMPT=LDAP port of the first server
+INFO_REPLICATION_ENABLE_PROTOCOL1=How do you want to connect to the first \
+ server?
INFO_REPLICATION_ENABLE_REPLICATIONPORT1_PROMPT=Replication port for the first \
server (the port must be free)
-INFO_REPLICATION_ENABLE_SECURE1_PROMPT=Use encrypted communication with \
- replication port %s for the first server?
+INFO_REPLICATION_ENABLE_SECURE1_PROMPT=Do want replication to use encrypted \
+ communication when connecting to replication port %s on the first server?
INFO_REPLICATION_ENABLE_BINDDN1_PROMPT=Bind DN for the first server
INFO_REPLICATION_ENABLE_PASSWORD1_PROMPT=Password for %s on the first server:
-INFO_REPLICATION_ENABLE_USESSL1_PROMPT=Use SSL to connect to the first server?
-INFO_REPLICATION_ENABLE_USESTARTTLS1_PROMPT=Use StartTLS to connect to the \
- first server?
+INFO_REPLICATION_ENABLE_HOST2_CONNECTION_PARAMETERS=>>>> Specify OpenDS LDAP \
+ connection parameters for the second server
INFO_REPLICATION_ENABLE_HOSTNAME2_PROMPT=Host name of the second server
INFO_REPLICATION_ENABLE_PORT2_PROMPT=LDAP port of the second server
+INFO_REPLICATION_ENABLE_PROTOCOL2=How do you want to connect to the second \
+ server?
INFO_REPLICATION_ENABLE_REPLICATIONPORT2_PROMPT=Replication port for the \
second server (the port must be free)
-INFO_REPLICATION_ENABLE_SECURE2_PROMPT=Use encrypted communication with \
- replication port %s for the second server?
+INFO_REPLICATION_ENABLE_SECURE2_PROMPT=Do want replication to use encrypted \
+ communication when connecting to replication port %s on the second server?
INFO_REPLICATION_ENABLE_BINDDN2_PROMPT=Bind DN for the second server
INFO_REPLICATION_ENABLE_PASSWORD2_PROMPT=Password for %s on the second server:
-INFO_REPLICATION_ENABLE_USESSL2_PROMPT=Use SSL to connect to the second server?
-INFO_REPLICATION_ENABLE_USESTARTTLS2_PROMPT=Use StartTLS to connect to the \
- second server?
-INFO_REPLICATION_INITIALIZE_HOSTNAMESOURCE_PROMPT=Host name of the source \
- server
-INFO_REPLICATION_INITIALIZE_PORTSOURCE_PROMPT=LDAP port of the source server
-INFO_REPLICATION_INITIALIZE_USESSLSOURCE_PROMPT=Use SSL to connect to the \
- source server?
-INFO_REPLICATION_INITIALIZE_USESTARTTLSSOURCE_PROMPT=Use StartTLS to connect \
- to the source server?
-INFO_REPLICATION_DISABLE_HOSTNAME_PROMPT=Host name of the server
-INFO_REPLICATION_DISABLE_PORT_PROMPT=LDAP port of the server
-INFO_REPLICATION_DISABLE_BINDDN_PROMPT=Global Administrator User ID (or bind \
- DN if no Global Administrator is defined)
-INFO_REPLICATION_DISABLE_PASSWORD_PROMPT=Password for %s:
-INFO_REPLICATION_INITIALIZE_ALL_HOSTNAME_PROMPT=Host name of the server
-INFO_REPLICATION_INITIALIZE_ALL_PORT_PROMPT=LDAP port of the server
-INFO_REPLICATION_STATUS_HOSTNAME_PROMPT=Host name of the server
-INFO_REPLICATION_STATUS_PORT_PROMPT=LDAP port of the server
-INFO_REPLICATION_INITIALIZE_HOSTNAMEDESTINATION_PROMPT=Host name of the \
- destination server
-INFO_REPLICATION_INITIALIZE_PORTDESTINATION_PROMPT=LDAP port of the \
- destination server
-INFO_REPLICATION_INITIALIZE_USESSLDESTINATION_PROMPT=Use SSL to connect to \
- the destination server?
-INFO_REPLICATION_INITIALIZE_USESTARTTLSDESTINATION_PROMPT=Use StartTLS to \
- connect to the destination server?
-INFO_CLI_USESSL_PROMPT=Use SSL to connect?
-INFO_CLI_INVALID_PORT=The provided value is not a valid port
-INFO_CLI_USESTARTTLS_PROMPT=Use StartTLS to connect?
+INFO_REPLICATION_INITIALIZE_SOURCE_CONNECTION_PARAMETERS=>>>> Specify OpenDS \
+ LDAP connection parameters for the source server
+INFO_REPLICATION_INITIALIZE_DESTINATION_CONNECTION_PARAMETERS=>>>> Specify \
+ OpenDS LDAP connection parameters for the destination server
SEVERE_ERR_NO_SUFFIXES_AVAILABLE_TO_ENABLE_REPLICATION=There are no base DNs \
available to enable replication between the two servers.
INFO_ALREADY_REPLICATED_SUFFIXES=The following base DNs are already replicated \
@@ -747,4 +716,5 @@
INFO_REPLICATION_STATUS_SECURITY_ENABLED=Enabled
INFO_REPLICATION_STATUS_SECURITY_DISABLED=Disabled
INFO_REPLICATION_CRITICAL_ERROR_DETAILS=Details: %s
-
+
+
diff --git a/opends/src/messages/messages/quicksetup.properties b/opends/src/messages/messages/quicksetup.properties
index 4d2c5e1..992a3f1 100644
--- a/opends/src/messages/messages/quicksetup.properties
+++ b/opends/src/messages/messages/quicksetup.properties
@@ -130,8 +130,7 @@
the server (%s) and the subject DN of the certificate. This could be caused \
because you are connected to a server pretending to be %s:%s.\n\
Before accepting this certificate, you should examine the server's \
- certificate carefully.\nAre you willing to accept this certificate for \
- the purpose of identifying the server %s:%s?
+ certificate carefully.
INFO_CERTIFICATE_NOT_TRUSTED_TEXT=The Certificate presented by the server \
%s:%s could not be trusted.<br><br>Possible reasons for this \
error:<br> -The Certificate Authority that issued the \
@@ -147,8 +146,7 @@
is the case of the self-signed certificates).\n-The server's certificate is \
incomplete due to a misconfiguration.\n-The server's certificate has \
expired.\nBefore accepting this certificate, you should examine the server's \
- certificate carefully.\nAre you willing to accept this certificate for the \
- purpose of identifying the server %s:%s?
+ certificate carefully.
INFO_CERTIFICATE_NOT_VALID_YET=%s - Not valid yet
INFO_CERTIFICATE_SERIAL_NUMBER_LABEL=Serial Number:
INFO_CERTIFICATE_SHOW_DETAILS_TEXT=<br><br><a href="">Show Certificate \
@@ -160,8 +158,6 @@
INFO_CERTIFICATE_TYPE_LABEL=Type:
INFO_CERTIFICATE_VALID_FROM_LABEL=Valid From:
INFO_CHECKBOX_COLOR=000,000,000
-INFO_CLI_ERROR_READING_STDIN=Unexpected error reading standard input.
-INFO_CLI_UNKNOWN_ARGUMENT=Unknown argument %s
INFO_CLI_UPGRADE_UNKNOWN_ARGUMENT=Unknown argument %s
INFO_CLOSE_BUTTON_INSTALL_TOOLTIP=Close Setup Window
INFO_CLOSE_BUTTON_LABEL=Close
diff --git a/opends/src/messages/messages/utility.properties b/opends/src/messages/messages/utility.properties
index 947d647..9ee010e 100644
--- a/opends/src/messages/messages/utility.properties
+++ b/opends/src/messages/messages/utility.properties
@@ -547,3 +547,6 @@
INFO_LDAP_CONN_PROMPT_SECURITY_CERTIFICATE_ALIAS_259=%s (%s)
INFO_SUBCMDPARSER_GLOBAL_HEADING_PREFIX_260=Global %s
INFO_PROMPT_SINGLE_DEFAULT_261=%s [%s]:
+INFO_LDAP_CONN_PROMPT_ADMINISTRATOR_UID_262=Global Administrator User ID [%s]:
+INFO_LDAP_CONN_GLOBAL_ADMINISTRATOR_OR_BINDDN_PROMPT_263=Global Administrator \
+ User ID (or bind DN if no Global Administrator is defined) [%s]:
\ No newline at end of file
diff --git a/opends/src/quicksetup/org/opends/quicksetup/CliApplicationHelper.java b/opends/src/quicksetup/org/opends/quicksetup/CliApplicationHelper.java
deleted file mode 100644
index ccb23a1..0000000
--- a/opends/src/quicksetup/org/opends/quicksetup/CliApplicationHelper.java
+++ /dev/null
@@ -1,1008 +0,0 @@
-/*
- * CDDL HEADER START
- *
- * The contents of this file are subject to the terms of the
- * Common Development and Distribution License, Version 1.0 only
- * (the "License"). You may not use this file except in compliance
- * with the License.
- *
- * You can obtain a copy of the license at
- * trunk/opends/resource/legal-notices/OpenDS.LICENSE
- * or https://OpenDS.dev.java.net/OpenDS.LICENSE.
- * See the License for the specific language governing permissions
- * and limitations under the License.
- *
- * When distributing Covered Code, include this CDDL HEADER in each
- * file and include the License file at
- * trunk/opends/resource/legal-notices/OpenDS.LICENSE. If applicable,
- * add the following below this CDDL HEADER, with the fields enclosed
- * by brackets "[]" replaced with your own identifying information:
- * Portions Copyright [yyyy] [name of copyright owner]
- *
- * CDDL HEADER END
- *
- *
- * Portions Copyright 2007 Sun Microsystems, Inc.
- */
-
-package org.opends.quicksetup;
-
-
-import org.opends.admin.ads.util.ApplicationTrustManager;
-import org.opends.admin.ads.util.ConnectionUtils;
-import org.opends.guitools.statuspanel.ConnectionProtocolPolicy;
-import org.opends.quicksetup.ui.CertificateDialog;
-import org.opends.messages.Message;
-import org.opends.messages.MessageBuilder;
-import static org.opends.messages.AdminToolMessages.*;
-import static org.opends.messages.ToolMessages.*;
-import static org.opends.messages.QuickSetupMessages.*;
-import static org.opends.server.tools.ToolConstants.*;
-
-import org.opends.quicksetup.util.Utils;
-import org.opends.server.util.args.ArgumentParser;
-import org.opends.server.util.args.ArgumentException;
-import org.opends.server.util.args.BooleanArgument;
-import org.opends.server.util.PasswordReader;
-import org.opends.server.util.StaticUtils;
-
-import java.io.ByteArrayOutputStream;
-import java.io.InputStream;
-import java.io.PrintStream;
-import java.net.URI;
-import java.security.cert.X509Certificate;
-import java.util.Set;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.logging.Logger;
-import java.util.logging.Level;
-
-import javax.naming.NamingException;
-import javax.naming.NoPermissionException;
-import javax.naming.ldap.InitialLdapContext;
-
-/**
- * Helper class containing useful methods for processing input and output
- * for a CliApplication.
- */
-public abstract class CliApplicationHelper {
-
- static private final Logger LOG =
- Logger.getLogger(CliApplicationHelper.class.getName());
-
- /** Format string used for deriving the console prompt. */
- static public final String PROMPT_DEFAULT_FORMAT = "%s%n[%s]:";
-
- /** Format string used for deriving the console prompt. */
- static public final String PROMPT_NO_DEFAULT_FORMAT = "%s";
-
- private BooleanArgument noPromptArg = null;
-
- private BooleanArgument quietArg = null;
-
- /** The print stream to use for standard error. */
- protected PrintStream err;
-
- /** The print stream to use for standard output. */
- protected PrintStream out;
-
- /** The input stream. */
- protected InputStream in;
-
- /**
- * Constructor for the CliApplicationHelper object.
- *
- * @param out the print stream to use for standard output.
- * @param err the print stream to use for standard error.
- * @param in the input stream to use for standard input.
- */
- protected CliApplicationHelper(PrintStream out, PrintStream err,
- InputStream in)
- {
- this.out = out;
- this.err = err;
- this.in = in;
- }
-
- /**
- * Interactively prompts (on standard output) the user to provide a string
- * value. Any non-empty string will be allowed (the empty string will
- * indicate that the default should be used). The method will display the
- * message until the user provides one of the values in the validValues
- * parameter.
- *
- * @param prompt The prompt to present to the user.
- * @param defaultValue The default value returned if the user clicks enter.
- * @param validValues The valid values that can be accepted as user input.
- *
- * @return The string value read from the user.
- */
- protected Message promptConfirm(Message prompt,
- Message defaultValue,
- Message[] validValues) {
-
- boolean isValid = false;
- Message response = null;
- while (!isValid)
- {
-
- Message msg;
-
- if (defaultValue == null)
- {
-
- msg = Message.raw(PROMPT_NO_DEFAULT_FORMAT, prompt, defaultValue);
- }
- else
- {
- msg = Message.raw(PROMPT_DEFAULT_FORMAT, prompt, defaultValue);
- }
-
- out.print(msg);
- out.flush();
-
- response = Message.raw(readLine());
- if (response.toString().equals(""))
- {
- response = defaultValue;
- }
- for (int i=0; i<validValues.length && !isValid; i++)
- {
- isValid = validValues[i].toString().
- equalsIgnoreCase(response.toString());
- }
- }
- return response;
- }
-
- /**
- * Interactively prompts (on standard output) the user to provide select
- * one option from a set of options.
- *
- * @param prompt The prompt to present to the user.
- * @param defaultOption The default value returned if the user clicks enter.
- * @param options The valid values that can be accepted as user input.
- *
- * @return index of options that was chosen or -1 if none where chosen
- */
- public int promptOptions(Message prompt,
- Message defaultOption,
- Message[] options) {
- Message choiceDefault = null;
- List<Message> choiceList = new ArrayList<Message>();
- MessageBuilder mb = new MessageBuilder(prompt);
- for (int i = 0; i < options.length; i++) {
- Message choice = Message.raw(Integer.toString(i + 1));
- choiceList.add(choice);
- if (options[i].equals(defaultOption)) {
- choiceDefault = choice;
- }
- mb.append("\n");
- mb.append(choice);
- mb.append(". ");
- mb.append(options[i]);
- }
- int ret = -1;
- Message resp = promptConfirm(mb.toMessage(), choiceDefault,
- choiceList.toArray(new Message[0]));
- if (resp != null) {
- for (int i = 0; i < choiceList.size(); i++) {
- if (resp.equals(choiceList.get(i))) {
- ret = i;
- break;
- }
- }
- }
- return ret;
- }
-
- /**
- * Interactively prompts (on standard output) the user to provide a string
- * value. Any non-empty string will be allowed (the empty string will
- * indicate that the default should be used, if there is one).
- *
- * @param prompt The prompt to present to the user.
- * @param defaultValue The default value to assume if the user presses ENTER
- * without typing anything, or <CODE>null</CODE> if
- * there should not be a default and the user must
- * explicitly provide a value.
- *
- * @return The string value read from the user.
- */
- public String promptForString(Message prompt, String defaultValue) {
- return promptForString(prompt, defaultValue, true);
- }
-
- /**
- * Interactively prompts (on standard output) the user to provide a string
- * value. Any non-empty string will be allowed (the empty string will
- * indicate that the default should be used, if there is one).
- *
- * @param prompt The prompt to present to the user.
- * @param defaultValue The default value to assume if the user presses ENTER
- * without typing anything, or <CODE>null</CODE> if
- * there should not be a default and the user must
- * explicitly provide a value.
- * @param addLineBreakIfDefault adds a line break between the prompt and the
- * default value if this is not <CODE>null</CODE>.
- * @return The string value read from the user.
- */
- protected String promptForString(Message prompt, String defaultValue,
- boolean addLineBreakIfDefault) {
- String wrappedPrompt = StaticUtils.wrapText(prompt,
- Utils.getCommandLineMaxLineWidth());
-
- while (true) {
- if (defaultValue == null) {
- out.print(wrappedPrompt);
- out.print(" ");
- } else {
- if (addLineBreakIfDefault)
- {
- out.println(wrappedPrompt);
- out.print("[");
- out.print(defaultValue);
- out.print("]: ");
- }
- else
- {
- out.print(wrappedPrompt);
- out.print(" [");
- out.print(defaultValue);
- out.print("]: ");
- }
- }
- out.flush();
-
- String response = readLine();
- if (response.equals("")) {
- if (defaultValue == null) {
- Message message = INFO_ERROR_EMPTY_RESPONSE.get();
- err.println(StaticUtils.wrapText(message,
- Utils.getCommandLineMaxLineWidth()));
- } else {
- return defaultValue;
- }
- } else {
- return response;
- }
- }
- }
-
- /**
- * Interactively prompts (on standard output) the user to provide a password
- * value.
- *
- * @param msg The prompt to present to the user.
- *
- * @return The string value read from the user.
- */
- protected String promptForPassword(Message msg)
- {
- String pwd;
- String wrappedPrompt = StaticUtils.wrapText(msg,
- Utils.getCommandLineMaxLineWidth());
- out.print(wrappedPrompt+" ");
- out.flush();
- try
- {
- char[] pwChars = PasswordReader.readPassword();
- if ((pwChars == null) || pwChars.length == 0)
- {
- pwd = null;
- }
- else
- {
- pwd = new String(pwChars);
- }
- out.flush();
- }
- catch (Throwable t)
- {
- LOG.log(Level.WARNING, "Error reading password: "+t, t);
- pwd = null;
- }
- return pwd;
- }
-
- /**
- * Prompts the user to provide a port.
- * @param msg the message to be displayed.
- * @param defaultValue the default value to be proposed.
- * @return the user to provide a port.
- */
- protected int promptForPort(Message msg, int defaultValue)
- {
- return promptForPort(msg, defaultValue, true);
- }
-
- /**
- * Prompts the user to provide a port.
- * @param msg the message to be displayed.
- * @param defaultValue the default value to be proposed.
- * @param addLineBreakIfDefault adds a line break between the prompt and the
- * default value if this is not <CODE>null</CODE>.
- * @return the user to provide a port.
- */
- protected int promptForPort(Message msg, int defaultValue,
- boolean addLineBreakIfDefault)
- {
- int port = -1;
- while (port == -1)
- {
- String s = promptForString(msg, String.valueOf(defaultValue),
- addLineBreakIfDefault);
- if ((s != null) && (s.trim().length() > 0))
- {
- try
- {
- port = Integer.parseInt(s);
- if ((port < 0) || (port > 65535))
- {
- port = -1;
- }
- }
- catch (Throwable t)
- {
- port = -1;
- }
- if (port == -1)
- {
- Message message = INFO_CLI_INVALID_PORT.get();
- err.println(StaticUtils.wrapText(message,
- Utils.getCommandLineMaxLineWidth()));
- }
- }
- }
- return port;
- }
-
- /**
- * Reads a line of text from standard input.
- * @return The line of text read from standard input, or <CODE>null</CODE>
- * if the end of the stream is reached or an error occurs while
- * attempting to read the response.
- */
- public String readLine() {
- return readLine(in, err);
- }
-
- /**
- * Reads a line of text from standard input.
- * @param in InputSteam from which line will be read
- * @param err PrintSteam where any errors will be printed
- * @return The line of text read from standard input, or <CODE>null</CODE>
- * if the end of the stream is reached or an error occurs while
- * attempting to read the response.
- */
- public String readLine(InputStream in, PrintStream err)
- {
- try
- {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
-
- while (true)
- {
- int b = in.read();
- if ((b < 0) || (b == '\n'))
- {
- break;
- }
- else if (b == '\r')
- {
- int b2 = in.read();
- if (b2 == '\n')
- {
- break;
- }
- else
- {
- baos.write(b);
- baos.write(b2);
- }
- }
- else
- {
- baos.write(b);
- }
- }
-
- return new String(baos.toByteArray(), "UTF-8");
- }
- catch (Exception e)
- {
- err.println(INFO_CLI_ERROR_READING_STDIN.get().toString());
- return null;
- }
- }
-
- /**
- * Returns <CODE>true</CODE> if this is a quiet uninstall and
- * <CODE>false</CODE> otherwise.
- * @param args the arguments passed in the command line.
- * @return <CODE>true</CODE> if this is a quiet uninstall and
- * <CODE>false</CODE> otherwise.
- */
- protected boolean isQuiet(String[] args)
- {
- boolean isQuiet = false;
- for (int i=0; i<args.length && !isQuiet; i++)
- {
- if (args[i].equalsIgnoreCase("--quiet") ||
- args[i].equalsIgnoreCase("-Q"))
- {
- isQuiet = true;
- }
- }
- return isQuiet;
- }
-
- /**
- * Commodity method used to validate the arguments provided by the user in
- * the command line and updating the UserData object accordingly.
- * @param userData the UserData object to be updated.
- * @param args the arguments passed in the command line.
- * @param validArgs arguments that are acceptable by this application.
- * @throws org.opends.quicksetup.UserDataException if there is an error with
- * the data provided by the user.
- */
- protected void validateArguments(UserData userData,
- String[] args,
- Set<String> validArgs) throws UserDataException
- {
- ArrayList<Message> errors = new ArrayList<Message>();
-
- for (String arg1 : args) {
- if (validArgs.contains(arg1)) {
- // Ignore
- } else {
- errors.add(INFO_CLI_UNKNOWN_ARGUMENT.get(arg1));
- }
- }
-
- if (errors.size() > 0)
- {
- MessageBuilder mb = new MessageBuilder();
- for (Message error : errors) {
- mb.append(error);
- mb.append(Constants.LINE_SEPARATOR);
- mb.append(Constants.LINE_SEPARATOR);
- }
- throw new UserDataException(null, mb.toMessage());
- }
- }
-
- /**
- * Returns <CODE>true</CODE> if this is a quiet session and
- * <CODE>false</CODE> otherwise. This method relies on the a previous
- * call to createArgumentParser having been made and the parser
- * having been used to parse the arguments.
- * @return <CODE>true</CODE> if this is a quiet uninstall and
- * <CODE>false</CODE> otherwise.
- */
- protected boolean isQuiet() {
- return quietArg != null && quietArg.isPresent();
- }
-
- /**
- * Returns <CODE>true</CODE> if this is a noninteractive sessions and
- * <CODE>false</CODE> otherwise. This method relies on the a previous
- * call to createArgumentParser having been made and the parser
- * having been used to parse the arguments.
- * @return <CODE>true</CODE> if this is a noninteractive session and
- * <CODE>false</CODE> otherwise.
- */
- protected boolean isInteractive() {
- return noPromptArg == null || !noPromptArg.isPresent();
- }
-
- /**
- * Creates an argument parser having common arguments.
- * @param mainClass class of the tool
- * @param description localized description of the tool
- * @param caseSensitive whether long args are case sensitive
- * @return ArgumentParser ready for app specific customization
- * @see org.opends.server.util.args.ArgumentParser#ArgumentParser(String,
- * Message,boolean)
- */
- protected ArgumentParser createArgumentParser(String mainClass,
- Message description,
- boolean caseSensitive) {
-
- // TODO: get rid of this method and user launcher.getArgumentParser
-
- // Create the command-line argument parser for use with this program.
- ArgumentParser argParser =
- new ArgumentParser(mainClass, description, caseSensitive);
-
- // Initialize all the common command-line argument types and register
- // them with the parser.
- try {
- noPromptArg = new BooleanArgument(
- OPTION_LONG_NO_PROMPT,
- OPTION_SHORT_NO_PROMPT,
- OPTION_LONG_NO_PROMPT,
- INFO_DESCRIPTION_NO_PROMPT.get());
- argParser.addArgument(noPromptArg);
-
- quietArg =
- new BooleanArgument(
- OPTION_LONG_QUIET,
- OPTION_SHORT_QUIET,
- OPTION_LONG_QUIET,
- INFO_DESCRIPTION_QUIET.get());
- argParser.addArgument(quietArg);
-
- } catch (ArgumentException e) {
- LOG.log(Level.INFO, "error", e);
- }
-
- return argParser;
- }
-
- /**
- * Displays an error message in the error output (wrapping it if necessary).
- * @param msg the error message to be displayed.
- */
- protected void printErrorMessage(Message msg)
- {
- err.println(org.opends.server.util.StaticUtils.wrapText(msg,
- Utils.getCommandLineMaxLineWidth()));
- LOG.log(Level.SEVERE, msg.toString());
- }
-
- /**
- * Displays a progress message in the error output (wrapping it if necessary).
- * @param msg the error message to be displayed.
- */
- protected void printProgressMessage(Message msg)
- {
- if (!isQuiet())
- {
- out.print(org.opends.server.util.StaticUtils.wrapText(msg,
- Utils.getCommandLineMaxLineWidth()));
- out.flush();
- }
- LOG.log(Level.INFO, msg.toString());
- }
-
- /**
- * Displays a progress message in the error output (wrapping it if necessary).
- * @param msg the error message to be displayed.
- */
- protected void printProgressMessage(String msg)
- {
- if (!isQuiet())
- {
- out.print(org.opends.server.util.StaticUtils.wrapText(msg,
- Utils.getCommandLineMaxLineWidth()));
- out.flush();
- }
- LOG.log(Level.INFO, msg);
- }
-
- /**
- * Displays a progress message in the error output.
- * @param msg the error message to be displayed.
- */
- protected void printProgressMessageNoWrap(String msg)
- {
- if (!isQuiet())
- {
- out.print(msg);
- out.flush();
- }
- LOG.log(Level.INFO, msg);
- }
-
- /**
- * Displays a progress message in the error output.
- * @param msg the error message to be displayed.
- */
- protected void printProgressMessageNoWrap(Message msg)
- {
- if (!isQuiet())
- {
- out.print(msg);
- out.flush();
- }
- LOG.log(Level.INFO, msg.toString());
- }
-
- /**
- * Prints a line break in the standard output if we are not in quite mode.
- */
- protected void printProgressLineBreak()
- {
- if (!isQuiet())
- {
- out.println();
- }
- }
-
- /**
- * Displays a warning message in the error output (wrapping it if necessary).
- * @param msg the warning message to be displayed.
- */
- protected void printWarningMessage(Message msg)
- {
- if (!isQuiet())
- {
- // TODO: decide if even in quiet mode we must display this message or not.
- out.println(org.opends.server.util.StaticUtils.wrapText(msg,
- Utils.getCommandLineMaxLineWidth()));
- out.flush();
- }
- LOG.log(Level.WARNING, msg.toString());
- }
-
- /**
- * Displays an error message in the error output (wrapping it if necessary).
- * @param msg the error message to be displayed.
- */
- protected void printErrorMessage(String msg)
- {
- err.println(org.opends.server.util.StaticUtils.wrapText(msg,
- Utils.getCommandLineMaxLineWidth()));
- }
-
- /**
- * Prints a line break in the standard output.
- */
- protected void printLineBreak()
- {
- out.println();
- }
-
- /**
- * Prints a line message in the standard output.
- * @param msg the error message to be displayed.
- * @param overrideQuietMode whether to override the quiet mode or not.
- */
- protected void printLine(Message msg, boolean overrideQuietMode)
- {
- if (!isQuiet() || overrideQuietMode)
- {
- out.println(org.opends.server.util.StaticUtils.wrapText(msg,
- Utils.getCommandLineMaxLineWidth()));
- }
- }
-
- /**
- * Prompts the user to give the Global Administrator UID.
- * @param defaultValue the default value that will be proposed in the prompt
- * message.
- * @return the Global Administrator UID as provided by the user.
- */
- protected String askForAdministratorUID(String defaultValue)
- {
- return promptForString(INFO_ADMINISTRATOR_UID_PROMPT.get(), defaultValue,
- false);
- }
-
- /**
- * Prompts the user to give the Global Administrator password.
- * @return the Global Administrator password as provided by the user.
- */
- protected String askForAdministratorPwd()
- {
- return promptForPassword(INFO_ADMINISTRATOR_PWD_PROMPT.get());
- }
-
- /**
- * Prompts the user to confirm a question. The default proposed value as
- * answer is to confirm the question.
- * @param msg the message to be displayed to the user.
- * @return <CODE>true</CODE> if the user accepted the message and
- * <CODE>false</CODE> otherwise.
- */
- protected boolean confirm(Message msg)
- {
- return confirm(msg, true);
- }
-
- /**
- * Prompts the user to confirm a question.
- * @param msg the message to be displayed to the user.
- * @param defaultTrue whether the default proposed value as answer is to
- * accept the message or not.
- * @return <CODE>true</CODE> if the user accepted the message and
- * <CODE>false</CODE> otherwise.
- */
- protected boolean confirm(Message msg, boolean defaultTrue) {
- boolean confirm = true;
- Message[] validValues = {
- INFO_CLI_YES_SHORT.get(),
- INFO_CLI_NO_SHORT.get(),
- INFO_CLI_YES_LONG.get(),
- INFO_CLI_NO_LONG.get(),
- };
- Message defaultMessage;
- if (defaultTrue)
- {
- defaultMessage = validValues[2];
- }
- else
- {
- defaultMessage = validValues[3];
- }
- Message answer = promptConfirm(msg, defaultMessage, validValues);
- if (INFO_CLI_NO_SHORT.get().toString()
- .equalsIgnoreCase(answer.toString()) ||
- INFO_CLI_NO_LONG.get().toString()
- .equalsIgnoreCase(answer.toString()))
- {
- confirm = false;
- }
- return confirm;
- }
-
- /**
- * Returns an InitialLdapContext using the provided parameters. We try
- * to guarantee that the connection is able to read the configuration.
- * @param host the host name.
- * @param port the port to connect.
- * @param useSSL whether to use SSL or not.
- * @param useStartTLS whether to use StartTLS or not.
- * @param bindDn the bind dn to be used.
- * @param pwd the password.
- * @param trustManager the trust manager.
- * @return an InitialLdapContext connected.
- * @throws NamingException if there was an error establishing the connection.
- */
- protected InitialLdapContext createContext(String host, int port,
- boolean useSSL, boolean useStartTLS, String bindDn, String pwd,
- ApplicationTrustManager trustManager)
- throws NamingException
- {
- InitialLdapContext ctx;
- String ldapUrl = ConnectionUtils.getLDAPUrl(host, port, useSSL);
- if (useSSL)
- {
- ctx = Utils.createLdapsContext(ldapUrl, bindDn, pwd,
- Utils.getDefaultLDAPTimeout(), null, trustManager);
- }
- else if (useStartTLS)
- {
- ctx = Utils.createStartTLSContext(ldapUrl, bindDn, pwd,
- Utils.getDefaultLDAPTimeout(), null, trustManager,
- null);
- }
- else
- {
- ctx = Utils.createLdapContext(ldapUrl, bindDn, pwd,
- Utils.getDefaultLDAPTimeout(), null);
- }
- if (!ConnectionUtils.connectedAsAdministrativeUser(ctx))
- {
- throw new NoPermissionException(
- ERR_NOT_ADMINISTRATIVE_USER.get().toString());
- }
- return ctx;
- }
-
- /**
- * Prompts the user to accept the certificate.
- * @param t the throwable that was generated because the certificate was
- * not trusted.
- * @param usedTrustManager the trustManager used when trying to establish the
- * connection.
- * @param usedUrl the LDAP URL used to connect to the server.
- * @param trustManager the global trustManager that contains the certificates
- * accepted by the user and that will be updated.
- * @return <CODE>true</CODE> if the user accepted the certificate and
- * <CODE>false</CODE> otherwise.
- */
- protected boolean promptForCertificateConfirmation(Throwable t,
- ApplicationTrustManager usedTrustManager, String usedUrl,
- ApplicationTrustManager trustManager)
- {
- boolean returnValue = false;
- ApplicationTrustManager.Cause cause;
- if (usedTrustManager != null)
- {
- cause = usedTrustManager.getLastRefusedCause();
- }
- else
- {
- cause = null;
- }
-
- LOG.log(Level.INFO, "Certificate exception cause: "+cause);
- UserDataCertificateException.Type excType = null;
- if (cause == ApplicationTrustManager.Cause.NOT_TRUSTED)
- {
- excType = UserDataCertificateException.Type.NOT_TRUSTED;
- }
- else if (cause ==
- ApplicationTrustManager.Cause.HOST_NAME_MISMATCH)
- {
- excType = UserDataCertificateException.Type.HOST_NAME_MISMATCH;
- }
- else
- {
- Message msg = Utils.getThrowableMsg(INFO_ERROR_CONNECTING_TO_LOCAL.get(),
- t);
- printErrorMessage(msg);
- }
-
- if (excType != null)
- {
- String h;
- int p;
- try
- {
- URI uri = new URI(usedUrl);
- h = uri.getHost();
- p = uri.getPort();
- }
- catch (Throwable t1)
- {
- LOG.log(Level.WARNING, "Error parsing ldap url of ldap url.", t1);
- h = INFO_NOT_AVAILABLE_LABEL.get().toString();
- p = -1;
- }
- UserDataCertificateException udce =
- new UserDataCertificateException(Step.REPLICATION_OPTIONS,
- INFO_CERTIFICATE_EXCEPTION.get(h, String.valueOf(p)), t, h, p,
- usedTrustManager.getLastRefusedChain(),
- usedTrustManager.getLastRefusedAuthType(), excType);
-
- returnValue = handleCertificateException(udce, trustManager, true);
- }
- return returnValue;
- }
-
- /**
- * Returns the ConnectionPolicy to be used with the parameters provided
- * by the user.
- * @param useSSL whether the user asked to use SSL or not.
- * @param useStartTLS whether the user asked to use Start TLS or not.
- * @return the ConnectionPolicy to be used with the parameters provided
- * by the user.
- */
- protected ConnectionProtocolPolicy getConnectionPolicy(boolean useSSL,
- boolean useStartTLS)
- {
- return ConnectionProtocolPolicy.getConnectionPolicy(useSSL, useStartTLS);
- }
-
- /**
- * Prompts the user to accept the certificate that generated the provided
- * UserDataCertificateException.
- * @param trustManager the global trustManager that contains the certificates
- * accepted by the user.
- * @param udce the UserDataCertificateException that was generated.
- * @param trustManager the global trustManager that contains the certificates
- * accepted by the user and that will be updated if the user accepts the
- * certificate.
- * @param displayErrorMessage whether to display the message describing
- * the error encountered (certificate not trusted) or only prompt to accept
- * the certificate.
- * @return <CODE>true</CODE> if the user accepted the certificate and
- * <CODE>false</CODE> otherwise.
- */
- private boolean handleCertificateException(
- UserDataCertificateException udce, ApplicationTrustManager trustManager,
- boolean displayErrorMessage)
- {
- boolean accepted = false;
- Message msg;
- if (udce.getType() == UserDataCertificateException.Type.NOT_TRUSTED)
- {
- msg = INFO_CERTIFICATE_NOT_TRUSTED_TEXT_CLI.get(
- udce.getHost(), String.valueOf(udce.getPort()),
- udce.getHost(), String.valueOf(udce.getPort()));
- }
- else
- {
- msg = INFO_CERTIFICATE_NAME_MISMATCH_TEXT_CLI.get(
- udce.getHost(), String.valueOf(udce.getPort()),
- udce.getHost(),
- udce.getHost(), String.valueOf(udce.getPort()),
- udce.getHost(), String.valueOf(udce.getPort()));
- }
- if (displayErrorMessage)
- {
- printErrorMessage(msg);
- }
- Message[] validValues = {
- INFO_CLI_ACCEPT_CERTIFICATE_LONG.get(),
- INFO_CLI_REJECT_CERTIFICATE_LONG.get(),
- INFO_CLI_VIEW_CERTIFICATE_LONG.get(),
- INFO_CLI_ACCEPT_CERTIFICATE_SHORT.get(),
- INFO_CLI_REJECT_CERTIFICATE_SHORT.get(),
- INFO_CLI_VIEW_CERTIFICATE_SHORT.get()
- };
- Message answer = promptConfirm(INFO_CLI_ACCEPT_CERTIFICATE_PROMPT.get(),
- validValues[0], validValues);
-
- if (INFO_CLI_REJECT_CERTIFICATE_LONG.get().toString().equalsIgnoreCase(
- answer.toString()) ||
- INFO_CLI_REJECT_CERTIFICATE_SHORT.get().toString().equalsIgnoreCase(
- answer.toString()))
- {
- accepted = false;
- }
- else if (INFO_CLI_VIEW_CERTIFICATE_LONG.get().toString().equalsIgnoreCase(
- answer.toString()) ||
- INFO_CLI_VIEW_CERTIFICATE_SHORT.get().toString().equalsIgnoreCase(
- answer.toString()))
- {
- printLineBreak();
- displayCertificate(udce);
- accepted = handleCertificateException(udce, trustManager, false);
- }
- else
- {
- X509Certificate[] chain = udce.getChain();
- String authType = udce.getAuthType();
- String host = udce.getHost();
-
- if ((chain != null) && (authType != null) && (host != null))
- {
- LOG.log(Level.INFO, "Accepting certificate presented by host "+host);
- if (trustManager != null)
- {
- trustManager.acceptCertificate(chain, authType, host);
- }
- accepted = true;
- }
- else
- {
- if (chain == null)
- {
- LOG.log(Level.WARNING,
- "The chain is null for the UserDataCertificateException");
- }
- if (authType == null)
- {
- LOG.log(Level.WARNING,
- "The auth type is null for the UserDataCertificateException");
- }
- if (host == null)
- {
- LOG.log(Level.WARNING,
- "The host is null for the UserDataCertificateException");
- }
- }
- }
- return accepted;
- }
-
- private void displayCertificate(UserDataCertificateException udce)
- {
- Message[] labels =
- {
- INFO_CERTIFICATE_SUBJECT_LABEL.get(),
- INFO_CERTIFICATE_ISSUED_BY_LABEL.get(),
- INFO_CERTIFICATE_VALID_FROM_LABEL.get(),
- INFO_CERTIFICATE_EXPIRES_ON_LABEL.get(),
- INFO_CERTIFICATE_TYPE_LABEL.get(),
- INFO_CERTIFICATE_SERIAL_NUMBER_LABEL.get(),
- INFO_CERTIFICATE_MD5_FINGERPRINT_LABEL.get(),
- INFO_CERTIFICATE_SHA1_FINGERPRINT_LABEL.get()
- };
- for (int i=0; i<udce.getChain().length; i++)
- {
- X509Certificate cert = udce.getChain()[i];
- String[] values =
- {
- cert.getSubjectX500Principal().getName().toString(),
- cert.getIssuerX500Principal().getName().toString(),
- CertificateDialog.getValidFrom(cert),
- CertificateDialog.getExpiresOn(cert),
- cert.getType(),
- String.valueOf(cert.getSerialNumber()),
- CertificateDialog.getMD5FingerPrint(cert).toString(),
- CertificateDialog.getSHA1FingerPrint(cert).toString()
- };
- for (int j=0; j<labels.length; j++)
- {
- out.println(StaticUtils.wrapText(labels[j]+" "+values[j],
- Utils.getCommandLineMaxLineWidth()));
- }
- }
- out.flush();
- }
-}
diff --git a/opends/src/quicksetup/org/opends/quicksetup/CliUserInteraction.java b/opends/src/quicksetup/org/opends/quicksetup/CliUserInteraction.java
index 1f0eb14..0a05d66 100644
--- a/opends/src/quicksetup/org/opends/quicksetup/CliUserInteraction.java
+++ b/opends/src/quicksetup/org/opends/quicksetup/CliUserInteraction.java
@@ -32,22 +32,29 @@
import org.opends.quicksetup.util.Utils;
import org.opends.server.util.StaticUtils;
+import org.opends.server.util.cli.CLIException;
+import org.opends.server.util.cli.ConsoleApplication;
import java.util.List;
import java.util.ArrayList;
+import java.util.logging.Level;
+import java.util.logging.Logger;
import java.io.PrintStream;
import java.io.InputStream;
/**
* Supports user interactions for a command line driven application.
*/
-public class CliUserInteraction extends CliApplicationHelper
+public class CliUserInteraction extends ConsoleApplication
implements UserInteraction {
+ static private final Logger LOG =
+ Logger.getLogger(CliUserInteraction.class.getName());
+
/**
* Creates an instance that will use standard streams for interaction.
*/
public CliUserInteraction() {
- super(System.out, System.err, System.in);
+ super(System.in, System.out, System.err);
}
/**
@@ -57,7 +64,7 @@
* @param in InputStream from which information will be read
*/
public CliUserInteraction(PrintStream out, PrintStream err, InputStream in) {
- super(out, err, in);
+ super(in, out, err);
}
/**
@@ -90,9 +97,9 @@
INFO_CLI_VIEW_DETAILS.get().toString()));
}
- println(String.valueOf(summary));
+ println(summary);
println();
- println(String.valueOf(details));
+ println(details);
Object returnValue = null;
while (returnValue == null) {
@@ -100,14 +107,20 @@
for (String o : sOptions) {
println(o);
}
- System.out.print(
- Message.raw(CliApplicationHelper.PROMPT_DEFAULT_FORMAT,
+ print(
+ Message.raw("%s%n[%s]:",
INFO_CLI_NUMBER_PROMPT.get().toString(),
Integer.toString(defInt)));
- System.out.flush();
-
- String response = readLine(in, err);
+ String response = "";
+ try
+ {
+ response = readLineOfInput(null);
+ }
+ catch (CLIException ce)
+ {
+ LOG.log(Level.WARNING, "Error reading input: "+ce, ce);
+ }
int respInt = -1;
if (response.equals("")) {
respInt = defInt;
@@ -150,7 +163,7 @@
public String promptForString(Message prompt, Message title,
String defaultValue) {
- return promptForString(prompt, defaultValue);
+ return readInput(prompt, defaultValue, LOG);
}
private String createOption(int index, String option) {
@@ -160,15 +173,63 @@
append(option).toString();
}
- private void println() {
- out.println();
- }
-
private void println(String text) {
text = Utils.convertHtmlBreakToLineSeparator(text);
text = Utils.stripHtml(text);
text = StaticUtils.wrapText(text, Utils.getCommandLineMaxLineWidth());
- out.println(text);
+ getErrorStream().println(text);
}
+ /**
+ * {@inheritDoc}
+ */
+ public boolean isAdvancedMode() {
+ return false;
+ }
+
+
+
+ /**
+ * {@inheritDoc}
+ */
+ public boolean isInteractive() {
+ return true;
+ }
+
+
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean isMenuDrivenMode() {
+ return true;
+ }
+
+
+
+ /**
+ * {@inheritDoc}
+ */
+ public boolean isQuiet() {
+ return false;
+ }
+
+
+
+ /**
+ * {@inheritDoc}
+ */
+ public boolean isScriptFriendly() {
+ return false;
+ }
+
+
+
+ /**
+ * {@inheritDoc}
+ */
+ public boolean isVerbose() {
+ return true;
+ }
}
diff --git a/opends/src/quicksetup/org/opends/quicksetup/upgrader/BuildExtractorCliHelper.java b/opends/src/quicksetup/org/opends/quicksetup/upgrader/BuildExtractorCliHelper.java
index ec58cdd..31c53cc 100644
--- a/opends/src/quicksetup/org/opends/quicksetup/upgrader/BuildExtractorCliHelper.java
+++ b/opends/src/quicksetup/org/opends/quicksetup/upgrader/BuildExtractorCliHelper.java
@@ -31,6 +31,10 @@
import org.opends.messages.Message;
import org.opends.quicksetup.UserDataException;
+import org.opends.server.util.cli.CLIException;
+import org.opends.server.util.cli.Menu;
+import org.opends.server.util.cli.MenuBuilder;
+import org.opends.server.util.cli.MenuResult;
import java.util.logging.Logger;
import java.util.logging.Level;
@@ -65,19 +69,52 @@
if (launcher.isInteractive()) {
if (!launcher.isNoPrompt()) {
LOG.log(Level.INFO, "obtaining file information interactively");
+ final int UPGRADE = 1;
+ final int REVERT = 2;
+ int[] indexes = {UPGRADE, REVERT};
Message[] options = new Message[] {
- INFO_UPGRADE_OPERATION_UPGRADE.get(),
- INFO_UPGRADE_OPERATION_REVERSION.get()
+ INFO_UPGRADE_OPERATION_UPGRADE.get(),
+ INFO_UPGRADE_OPERATION_REVERSION.get()
};
- int response = promptOptions(
- INFO_UPGRADE_OPERATION_PROMPT.get(),
- options[0],
- options);
- if (response == 0) {
+
+ MenuBuilder<Integer> builder = new MenuBuilder<Integer>(this);
+
+ builder.setPrompt(INFO_UPGRADE_OPERATION_PROMPT.get());
+
+ for (int i=0; i<indexes.length; i++)
+ {
+ builder.addNumberedOption(options[i], MenuResult.success(indexes[i]));
+ }
+
+ builder.setDefault(Message.raw(String.valueOf(UPGRADE)),
+ MenuResult.success(UPGRADE));
+
+ Menu<Integer> menu = builder.toMenu();
+ int choice;
+ try
+ {
+ MenuResult<Integer> m = menu.run();
+ if (m.isSuccess())
+ {
+ choice = m.getValue();
+ }
+ else
+ {
+ // Should never happen.
+ throw new RuntimeException();
+ }
+ }
+ catch (CLIException ce)
+ {
+ choice = UPGRADE;
+ LOG.log(Level.WARNING, "Error reading input: "+ce, ce);
+ }
+
+ if (choice == UPGRADE) {
uud.setOperation(UpgradeUserData.Operation.UPGRADE);
while(true) {
- String fileName = promptForString(
- INFO_UPGRADE_FILE_PROMPT.get(), null);
+ String fileName = readInput(
+ INFO_UPGRADE_FILE_PROMPT.get(), null, LOG);
try {
uud.setInstallPackage(validateInstallPackFile(fileName));
LOG.log(Level.INFO, "file specified interactively: " +
diff --git a/opends/src/quicksetup/org/opends/quicksetup/upgrader/Reverter.java b/opends/src/quicksetup/org/opends/quicksetup/upgrader/Reverter.java
index 82d5a90..b99f88f 100644
--- a/opends/src/quicksetup/org/opends/quicksetup/upgrader/Reverter.java
+++ b/opends/src/quicksetup/org/opends/quicksetup/upgrader/Reverter.java
@@ -52,6 +52,10 @@
import org.opends.quicksetup.util.Utils;
import org.opends.quicksetup.util.ServerController;
import org.opends.quicksetup.util.FileManager;
+import org.opends.server.util.cli.CLIException;
+import org.opends.server.util.cli.Menu;
+import org.opends.server.util.cli.MenuBuilder;
+import org.opends.server.util.cli.MenuResult;
import java.io.File;
import java.io.IOException;
@@ -183,11 +187,41 @@
Message[] raDirChoices =
raDirChoiceList.toArray(new Message[0]);
if (raDirChoices.length > 0) {
- int resp = ui.promptOptions(
- INFO_REVERSION_DIR_PROMPT.get(),
- raDirChoices[0],
- raDirChoices);
- File raDir = raDirs[resp];
+ MenuBuilder<Integer> builder = new MenuBuilder<Integer>(ui);
+
+ builder.setPrompt(INFO_REVERSION_DIR_PROMPT.get());
+
+ for (int i=0; i<raDirChoices.length; i++)
+ {
+ builder.addNumberedOption(raDirChoices[i],
+ MenuResult.success(i+1));
+ }
+
+ builder.setDefault(Message.raw(String.valueOf("1")),
+ MenuResult.success(1));
+
+ Menu<Integer> menu = builder.toMenu();
+ int resp;
+ try
+ {
+ MenuResult<Integer> m = menu.run();
+ if (m.isSuccess())
+ {
+ resp = m.getValue();
+ }
+ else
+ {
+ // Should never happen.
+ throw new RuntimeException();
+ }
+ }
+ catch (CLIException ce)
+ {
+ resp = 1;
+ LOG.log(Level.WARNING, "Error reading input: "+ce, ce);
+ }
+
+ File raDir = raDirs[resp - 1];
raDir = appendFilesDirIfNeccessary(raDir);
try {
ud.setReversionArchiveDirectory(
diff --git a/opends/src/quicksetup/org/opends/quicksetup/upgrader/UpgraderCliHelper.java b/opends/src/quicksetup/org/opends/quicksetup/upgrader/UpgraderCliHelper.java
index 20d8945..f5fdb76 100644
--- a/opends/src/quicksetup/org/opends/quicksetup/upgrader/UpgraderCliHelper.java
+++ b/opends/src/quicksetup/org/opends/quicksetup/upgrader/UpgraderCliHelper.java
@@ -27,15 +27,15 @@
package org.opends.quicksetup.upgrader;
-import org.opends.quicksetup.CliApplicationHelper;
import org.opends.quicksetup.UserDataException;
+import org.opends.server.util.cli.ConsoleApplication;
import java.util.logging.Logger;
/**
* Assists Upgrader utility in CLI drudgery.
*/
-public class UpgraderCliHelper extends CliApplicationHelper {
+public class UpgraderCliHelper extends ConsoleApplication {
static private final Logger LOG =
Logger.getLogger(UpgraderCliHelper.class.getName());
@@ -49,7 +49,7 @@
*/
public UpgraderCliHelper(UpgradeLauncher launcher)
{
- super(System.out, System.err, System.in);
+ super(System.in, System.out, System.err);
this.launcher = launcher;
}
@@ -63,7 +63,7 @@
public UpgradeUserData createUserData(String[] args)
throws UserDataException {
// It is assumed that if we got here that the build
- // exptractor took care of extracting the file and
+ // extractor took care of extracting the file and
// putting it in tmp/upgrade for us. So there's
// not too much to do at this point.
UpgradeUserData uud = new UpgradeUserData();
@@ -72,4 +72,56 @@
return uud;
}
+ /**
+ * {@inheritDoc}
+ */
+ public boolean isAdvancedMode() {
+ return false;
+ }
+
+
+
+ /**
+ * {@inheritDoc}
+ */
+ public boolean isInteractive() {
+ return launcher.isInteractive();
+ }
+
+
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public boolean isMenuDrivenMode() {
+ return true;
+ }
+
+
+
+ /**
+ * {@inheritDoc}
+ */
+ public boolean isQuiet() {
+ return launcher.isQuiet();
+ }
+
+
+
+ /**
+ * {@inheritDoc}
+ */
+ public boolean isScriptFriendly() {
+ return false;
+ }
+
+
+
+ /**
+ * {@inheritDoc}
+ */
+ public boolean isVerbose() {
+ return true;
+ }
}
diff --git a/opends/src/server/org/opends/server/admin/client/cli/SecureConnectionCliArgs.java b/opends/src/server/org/opends/server/admin/client/cli/SecureConnectionCliArgs.java
index 5d28633..961dadf 100644
--- a/opends/src/server/org/opends/server/admin/client/cli/SecureConnectionCliArgs.java
+++ b/opends/src/server/org/opends/server/admin/client/cli/SecureConnectionCliArgs.java
@@ -30,6 +30,7 @@
import static org.opends.server.admin.client.cli.DsFrameworkCliReturnCode.*;
import static org.opends.server.loggers.debug.DebugLogger.debugEnabled;
import static org.opends.server.loggers.debug.DebugLogger.getTracer;
+import static org.opends.messages.AdminToolMessages.*;
import static org.opends.messages.ToolMessages.*;
import org.opends.messages.Message;
import org.opends.messages.MessageBuilder;
@@ -54,6 +55,7 @@
import org.opends.admin.ads.util.ApplicationKeyManager;
import org.opends.admin.ads.util.ApplicationTrustManager;
+import org.opends.quicksetup.Constants;
import org.opends.server.loggers.debug.DebugTracer;
import org.opends.server.types.DebugLogLevel;
import org.opends.server.util.PasswordReader;
@@ -85,11 +87,16 @@
public IntegerArgument portArg = null;
/**
- * The 'binDN' global argument.
+ * The 'bindDN' global argument.
*/
public StringArgument bindDnArg = null;
/**
+ * The 'adminUID' global argument.
+ */
+ public StringArgument adminUidArg = null;
+
+ /**
* The 'bindPasswordFile' global argument.
*/
public FileBasedArgument bindPasswordFileArg = null;
@@ -205,6 +212,35 @@
}
/**
+ * Get the admin UID which has to be used for the command.
+ *
+ * @return The admin UID specified by the command line argument, or the
+ * default value, if not specified.
+ */
+ public String getAdministratorUID()
+ {
+ if (adminUidArg.isPresent())
+ {
+ return adminUidArg.getValue();
+ }
+ else
+ {
+ return adminUidArg.getDefaultValue();
+ }
+ }
+
+ /**
+ * Tells whether this parser uses the Administrator UID (instead of the
+ * bind DN) or not.
+ * @return <CODE>true</CODE> if this parser uses the Administrator UID and
+ * <CODE>false</CODE> otherwise.
+ */
+ public boolean useAdminUID()
+ {
+ return !adminUidArg.isHidden();
+ }
+
+ /**
* Get the bindDN which has to be used for the command.
*
* @return The bindDN specified by the command line argument, or the
@@ -414,6 +450,16 @@
bindDnArg.setPropertyName(OPTION_LONG_BINDDN);
argList.add(bindDnArg);
+ // It is up to the classes that required admin UID to make this argument
+ // visible
+ adminUidArg = new StringArgument("adminUID", 'I',
+ "adminUID", false, false, true, "adminUID",
+ Constants.GLOBAL_ADMIN_UID, null,
+ INFO_DESCRIPTION_ADMIN_UID.get());
+ adminUidArg.setPropertyName("adminUID");
+ adminUidArg.setHidden(true);
+ argList.add(adminUidArg);
+
bindPasswordArg = new StringArgument("bindPassword",
OPTION_SHORT_BINDPWD, OPTION_LONG_BINDPWD, false, false, true,
OPTION_VALUE_BINDPWD, null, null, INFO_DESCRIPTION_BINDPASSWORD.get());
diff --git a/opends/src/server/org/opends/server/admin/client/cli/SecureConnectionCliParser.java b/opends/src/server/org/opends/server/admin/client/cli/SecureConnectionCliParser.java
index 0c13825..8459510 100644
--- a/opends/src/server/org/opends/server/admin/client/cli/SecureConnectionCliParser.java
+++ b/opends/src/server/org/opends/server/admin/client/cli/SecureConnectionCliParser.java
@@ -141,6 +141,16 @@
return secureArgsList.getBindDN();
}
+
+ /**
+ * Returns the Administrator UID provided in the command-line.
+ * @return the Administrator UID provided in the command-line.
+ */
+ public String getAdministratorUID()
+ {
+ return secureArgsList.getAdministratorUID();
+ }
+
/**
* Get the password which has to be used for the command.
*
diff --git a/opends/src/server/org/opends/server/tools/InstallDS.java b/opends/src/server/org/opends/server/tools/InstallDS.java
index 8fbf9dc..a5a8813 100644
--- a/opends/src/server/org/opends/server/tools/InstallDS.java
+++ b/opends/src/server/org/opends/server/tools/InstallDS.java
@@ -863,41 +863,32 @@
String pwd = argParser.getDirectoryManagerPassword();
while (pwd == null)
{
- println();
String pwd1 = null;
// Prompt for password and confirm.
while (pwd1 == null)
{
- try
- {
- pwd1 = readPassword(INFO_INSTALLDS_PROMPT_ROOT_PASSWORD.get());
- if ("".equals(pwd1))
- {
- pwd1 = null;
- println();
- println(INFO_EMPTY_PWD.get());
- }
-
- String pwd2 =
- readPassword(INFO_INSTALLDS_PROMPT_CONFIRM_ROOT_PASSWORD.get());
-
- if (pwd1.equals(pwd2))
- {
- pwd = pwd1;
- }
- else
- {
- println();
- println(ERR_INSTALLDS_PASSWORDS_DONT_MATCH.get());
- }
- }
- catch (CLIException ce)
+ pwd1 = readPassword(INFO_INSTALLDS_PROMPT_ROOT_PASSWORD.get(), LOG);
+ if ((pwd1 == null) || "".equals(pwd1))
{
pwd1 = null;
- LOG.log(Level.WARNING, "Unexpected error reading passwords: "+ce, ce);
+ println();
+ println(INFO_EMPTY_PWD.get());
+ println();
}
}
+ String pwd2 =
+ readPassword(INFO_INSTALLDS_PROMPT_CONFIRM_ROOT_PASSWORD.get(), LOG);
+
+ if (pwd1.equals(pwd2))
+ {
+ pwd = pwd1;
+ }
+ else
+ {
+ println();
+ println(ERR_INSTALLDS_PASSWORDS_DONT_MATCH.get());
+ }
}
uData.setDirectoryManagerPwd(pwd);
}
@@ -1859,16 +1850,8 @@
ERR_INSTALLDS_TOO_MANY_KEYSTORE_PASSWORD_TRIES.get(
String.valueOf(LIMIT_KEYSTORE_PASSWORD_PROMPT)));
}
- try
- {
- pwd = readPassword(
- INFO_INSTALLDS_PROMPT_KEYSTORE_PASSWORD.get());
- }
- catch (CLIException ce)
- {
- LOG.log(Level.WARNING, "Error reading input: "+ce, ce);
- pwd = null;
- }
+ pwd = readPassword(
+ INFO_INSTALLDS_PROMPT_KEYSTORE_PASSWORD.get(), LOG);
nPasswordPrompts ++;
}
}
diff --git a/opends/src/server/org/opends/server/tools/dsconfig/LDAPManagementContextFactory.java b/opends/src/server/org/opends/server/tools/dsconfig/LDAPManagementContextFactory.java
index e30b15c..5be487c 100644
--- a/opends/src/server/org/opends/server/tools/dsconfig/LDAPManagementContextFactory.java
+++ b/opends/src/server/org/opends/server/tools/dsconfig/LDAPManagementContextFactory.java
@@ -26,6 +26,7 @@
*/
package org.opends.server.tools.dsconfig;
+import org.opends.admin.ads.util.ApplicationTrustManager;
import org.opends.admin.ads.util.ConnectionUtils;
import org.opends.admin.ads.util.OpendsCertificateException;
@@ -152,7 +153,15 @@
{
OpendsCertificateException oce =
(OpendsCertificateException) e.getRootCause().getCause();
- if (ci.checkServerCertificate(oce.getChain()))
+ String authType = null;
+ if (trustManager instanceof ApplicationTrustManager)
+ {
+ ApplicationTrustManager appTrustManager =
+ (ApplicationTrustManager)trustManager;
+ authType = appTrustManager.getLastRefusedAuthType();
+ }
+ if (ci.checkServerCertificate(oce.getChain(), authType,
+ hostName))
{
// If the certificate is trusted, update the trust manager.
trustManager = ci.getTrustManager();
@@ -199,9 +208,17 @@
&& (e.getRootCause().getCause()
instanceof OpendsCertificateException))
{
+ String authType = null;
+ if (trustManager instanceof ApplicationTrustManager)
+ {
+ ApplicationTrustManager appTrustManager =
+ (ApplicationTrustManager)trustManager;
+ authType = appTrustManager.getLastRefusedAuthType();
+ }
OpendsCertificateException oce =
(OpendsCertificateException) e.getRootCause().getCause();
- if (ci.checkServerCertificate(oce.getChain()))
+ if (ci.checkServerCertificate(oce.getChain(), authType,
+ hostName))
{
// If the certificate is trusted, update the trust manager.
trustManager = ci.getTrustManager();
diff --git a/opends/src/server/org/opends/server/util/cli/ConsoleApplication.java b/opends/src/server/org/opends/server/util/cli/ConsoleApplication.java
index 3ea34bb..20bb514 100644
--- a/opends/src/server/org/opends/server/util/cli/ConsoleApplication.java
+++ b/opends/src/server/org/opends/server/util/cli/ConsoleApplication.java
@@ -28,7 +28,9 @@
-import static org.opends.messages.QuickSetupMessages.INFO_ERROR_EMPTY_RESPONSE;
+import static org.opends.messages.AdminToolMessages.*;
+import static org.opends.messages.DSConfigMessages.*;
+import static org.opends.messages.QuickSetupMessages.*;
import static org.opends.messages.UtilityMessages.*;
import static org.opends.server.util.ServerConstants.*;
import static org.opends.server.util.StaticUtils.*;
@@ -41,8 +43,22 @@
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.Reader;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+import javax.naming.NamingException;
+import javax.naming.NoPermissionException;
+import javax.naming.ldap.InitialLdapContext;
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.TrustManager;
+
+import org.opends.admin.ads.util.ApplicationTrustManager;
+import org.opends.admin.ads.util.ConnectionUtils;
+import org.opends.admin.ads.util.OpendsCertificateException;
import org.opends.messages.Message;
+import org.opends.quicksetup.util.Utils;
+import org.opends.server.protocols.ldap.LDAPResultCode;
+import org.opends.server.tools.ClientException;
import org.opends.server.types.NullOutputStream;
import org.opends.server.util.PasswordReader;
@@ -429,7 +445,10 @@
* reason.
*/
public final String readLineOfInput(Message prompt) throws CLIException {
- err.print(wrapText(prompt + " ", MAX_LINE_WIDTH));
+ if (prompt != null)
+ {
+ err.print(wrapText(prompt + " ", MAX_LINE_WIDTH));
+ }
try {
String s = in.readLine();
if (s == null) {
@@ -443,6 +462,7 @@
}
}
+
/**
* Commodity method that interactively prompts (on error output) the user to
* provide a string value. Any non-empty string will be allowed (the empty
@@ -480,7 +500,34 @@
}
}
-
+ /**
+ * Commodity method that interactively prompts (on error output) the user to
+ * provide a string value. Any non-empty string will be allowed (the empty
+ * string will indicate that the default should be used, if there is one).
+ * If an error occurs a message will be logged to the provided logger.
+ *
+ * @param prompt The prompt to present to the user.
+ * @param defaultValue The default value to assume if the user presses ENTER
+ * without typing anything, or <CODE>null</CODE> if
+ * there should not be a default and the user must
+ * explicitly provide a value.
+ *
+ * @param logger the Logger to be used to log the error message.
+ * @return The string value read from the user.
+ */
+ public String readInput(Message prompt, String defaultValue, Logger logger)
+ {
+ String s = defaultValue;
+ try
+ {
+ s = readInput(prompt, defaultValue);
+ }
+ catch (CLIException ce)
+ {
+ logger.log(Level.WARNING, "Error reading input: "+ce, ce);
+ }
+ return s;
+ }
/**
* Interactively retrieves a password from the console.
@@ -503,6 +550,30 @@
}
/**
+ * Commodity method that interactively retrieves a password from the
+ * console. If there is an error an error message is logged to the provided
+ * Logger and <CODE>null</CODE> is returned.
+ *
+ * @param prompt
+ * The password prompt.
+ * @param logger the Logger to be used to log the error message.
+ * @return Returns the password.
+ */
+ protected final String readPassword(Message prompt, Logger logger)
+ {
+ String pwd = null;
+ try
+ {
+ pwd = readPassword(prompt);
+ }
+ catch (CLIException ce)
+ {
+ logger.log(Level.WARNING, "Error reading input: "+ce, ce);
+ }
+ return pwd;
+ }
+
+ /**
* Interactively retrieves a port value from the console.
*
* @param prompt
@@ -585,4 +656,284 @@
}
}
}
+
+ /**
+ * Commodity method that interactively confirms whether a user wishes to
+ * perform an action. If the application is non-interactive, then the provided
+ * default is returned automatically. If there is an error an error message
+ * is logged to the provided Logger and the defaul value is returned.
+ *
+ * @param prompt
+ * The prompt describing the action.
+ * @param defaultValue
+ * The default value for the confirmation message. This
+ * will be returned if the application is non-interactive
+ * or if the user just presses return.
+ * @param logger the Logger to be used to log the error message.
+ * @return Returns <code>true</code> if the user wishes the action
+ * to be performed, or <code>false</code> if they refused.
+ */
+ protected final boolean askConfirmation(Message prompt, boolean defaultValue,
+ Logger logger)
+ {
+ boolean v = defaultValue;
+ try
+ {
+ v = confirmAction(prompt, defaultValue);
+ }
+ catch (CLIException ce)
+ {
+ logger.log(Level.WARNING, "Error reading input: "+ce, ce);
+ }
+ return v;
+ }
+
+ /**
+ * Returns an InitialLdapContext using the provided parameters. We try
+ * to guarantee that the connection is able to read the configuration.
+ * @param host the host name.
+ * @param port the port to connect.
+ * @param useSSL whether to use SSL or not.
+ * @param useStartTLS whether to use StartTLS or not.
+ * @param bindDn the bind dn to be used.
+ * @param pwd the password.
+ * @param trustManager the trust manager.
+ * @return an InitialLdapContext connected.
+ * @throws NamingException if there was an error establishing the connection.
+ */
+ protected InitialLdapContext createAdministrativeContext(String host,
+ int port, boolean useSSL, boolean useStartTLS, String bindDn, String pwd,
+ ApplicationTrustManager trustManager)
+ throws NamingException
+ {
+ InitialLdapContext ctx;
+ String ldapUrl = ConnectionUtils.getLDAPUrl(host, port, useSSL);
+ if (useSSL)
+ {
+ ctx = Utils.createLdapsContext(ldapUrl, bindDn, pwd,
+ Utils.getDefaultLDAPTimeout(), null, trustManager);
+ }
+ else if (useStartTLS)
+ {
+ ctx = Utils.createStartTLSContext(ldapUrl, bindDn, pwd,
+ Utils.getDefaultLDAPTimeout(), null, trustManager,
+ null);
+ }
+ else
+ {
+ ctx = Utils.createLdapContext(ldapUrl, bindDn, pwd,
+ Utils.getDefaultLDAPTimeout(), null);
+ }
+ if (!ConnectionUtils.connectedAsAdministrativeUser(ctx))
+ {
+ throw new NoPermissionException(
+ ERR_NOT_ADMINISTRATIVE_USER.get().toString());
+ }
+ return ctx;
+ }
+
+ /**
+ * Creates an Initial LDAP Context interacting with the user if the
+ * application is interactive.
+ * @param ci the LDAPConnectionConsoleInteraction object that is assumed
+ * to have been already run.
+ * @return the initial LDAP context or <CODE>null</CODE> if the user did
+ * not accept to trust the certificates.
+ * @throws ClientException if there was an error establishing the connection.
+ */
+ protected InitialLdapContext createInitialLdapContextInteracting(
+ LDAPConnectionConsoleInteraction ci) throws ClientException
+ {
+ // Interact with the user though the console to get
+ // LDAP connection information
+ String hostName = ci.getHostName();
+ Integer portNumber = ci.getPortNumber();
+ String bindDN = ci.getBindDN();
+ String bindPassword = ci.getBindPassword();
+ TrustManager trustManager = ci.getTrustManager();
+ KeyManager keyManager = ci.getKeyManager();
+
+ InitialLdapContext ctx;
+
+ if (ci.useSSL())
+ {
+ String ldapsUrl = "ldaps://" + hostName + ":" + portNumber;
+ while (true)
+ {
+ try
+ {
+ ctx = ConnectionUtils.createLdapsContext(ldapsUrl, bindDN,
+ bindPassword, ConnectionUtils.getDefaultLDAPTimeout(), null,
+ trustManager, keyManager);
+ ctx.reconnect(null);
+ break;
+ }
+ catch (NamingException e)
+ {
+ if ( isInteractive() && ci.isTrustStoreInMemory())
+ {
+ if ((e.getRootCause() != null)
+ && (e.getRootCause().getCause()
+ instanceof OpendsCertificateException))
+ {
+ OpendsCertificateException oce =
+ (OpendsCertificateException) e.getRootCause().getCause();
+ String authType = null;
+ if (trustManager instanceof ApplicationTrustManager)
+ {
+ ApplicationTrustManager appTrustManager =
+ (ApplicationTrustManager)trustManager;
+ authType = appTrustManager.getLastRefusedAuthType();
+ }
+ if (ci.checkServerCertificate(oce.getChain(), authType,
+ hostName))
+ {
+ // If the certificate is trusted, update the trust manager.
+ trustManager = ci.getTrustManager();
+
+ // Try to connect again.
+ continue ;
+ }
+ else
+ {
+ // Assume user cancelled.
+ return null;
+ }
+ }
+ else
+ {
+ Message message = ERR_DSCFG_ERROR_LDAP_FAILED_TO_CONNECT.get(
+ hostName, String.valueOf(portNumber));
+ throw new ClientException(
+ LDAPResultCode.CLIENT_SIDE_CONNECT_ERROR, message);
+ }
+ }
+ Message message = ERR_DSCFG_ERROR_LDAP_FAILED_TO_CONNECT.get(
+ hostName, String.valueOf(portNumber));
+ throw new ClientException(
+ LDAPResultCode.CLIENT_SIDE_CONNECT_ERROR, message);
+ }
+ }
+ }
+ else if (ci.useStartTLS())
+ {
+ String ldapUrl = "ldap://" + hostName + ":" + portNumber;
+ while (true)
+ {
+ try
+ {
+ ctx = ConnectionUtils.createStartTLSContext(ldapUrl, bindDN,
+ bindPassword, ConnectionUtils.getDefaultLDAPTimeout(), null,
+ trustManager, keyManager, null);
+ ctx.reconnect(null);
+ break;
+ }
+ catch (NamingException e)
+ {
+ if ( isInteractive() && ci.isTrustStoreInMemory())
+ {
+ if ((e.getRootCause() != null)
+ && (e.getRootCause().getCause()
+ instanceof OpendsCertificateException))
+ {
+ String authType = null;
+ if (trustManager instanceof ApplicationTrustManager)
+ {
+ ApplicationTrustManager appTrustManager =
+ (ApplicationTrustManager)trustManager;
+ authType = appTrustManager.getLastRefusedAuthType();
+ }
+ OpendsCertificateException oce =
+ (OpendsCertificateException) e.getRootCause().getCause();
+ if (ci.checkServerCertificate(oce.getChain(), authType,
+ hostName))
+ {
+ // If the certificate is trusted, update the trust manager.
+ trustManager = ci.getTrustManager();
+
+ // Try to connect again.
+ continue ;
+ }
+ else
+ {
+ // Assume user cancelled.
+ return null;
+ }
+ }
+ else
+ {
+ Message message = ERR_DSCFG_ERROR_LDAP_FAILED_TO_CONNECT.get(
+ hostName, String.valueOf(portNumber));
+ throw new ClientException(
+ LDAPResultCode.CLIENT_SIDE_CONNECT_ERROR, message);
+ }
+ }
+ Message message = ERR_DSCFG_ERROR_LDAP_FAILED_TO_CONNECT.get(
+ hostName, String.valueOf(portNumber));
+ throw new ClientException(
+ LDAPResultCode.CLIENT_SIDE_CONNECT_ERROR, message);
+ }
+ }
+ }
+ else
+ {
+ String ldapUrl = "ldap://" + hostName + ":" + portNumber;
+ while (true)
+ {
+ try
+ {
+ ctx = ConnectionUtils.createLdapContext(ldapUrl, bindDN,
+ bindPassword, ConnectionUtils.getDefaultLDAPTimeout(), null);
+ ctx.reconnect(null);
+ break;
+ }
+ catch (NamingException e)
+ {
+ if ( isInteractive() && ci.isTrustStoreInMemory())
+ {
+ if ((e.getRootCause() != null)
+ && (e.getRootCause().getCause()
+ instanceof OpendsCertificateException))
+ {
+ String authType = null;
+ if (trustManager instanceof ApplicationTrustManager)
+ {
+ ApplicationTrustManager appTrustManager =
+ (ApplicationTrustManager)trustManager;
+ authType = appTrustManager.getLastRefusedAuthType();
+ }
+ OpendsCertificateException oce =
+ (OpendsCertificateException) e.getRootCause().getCause();
+ if (ci.checkServerCertificate(oce.getChain(), authType,
+ hostName))
+ {
+ // If the certificate is trusted, update the trust manager.
+ trustManager = ci.getTrustManager();
+
+ // Try to connect again.
+ continue ;
+ }
+ else
+ {
+ // Assume user cancelled.
+ return null;
+ }
+ }
+ else
+ {
+ Message message = ERR_DSCFG_ERROR_LDAP_FAILED_TO_CONNECT.get(
+ hostName, String.valueOf(portNumber));
+ throw new ClientException(
+ LDAPResultCode.CLIENT_SIDE_CONNECT_ERROR, message);
+ }
+ }
+ Message message = ERR_DSCFG_ERROR_LDAP_FAILED_TO_CONNECT.get(
+ hostName, String.valueOf(portNumber));
+ throw new ClientException(
+ LDAPResultCode.CLIENT_SIDE_CONNECT_ERROR, message);
+ }
+ }
+ }
+ return ctx;
+ }
}
diff --git a/opends/src/server/org/opends/server/util/cli/LDAPConnectionConsoleInteraction.java b/opends/src/server/org/opends/server/util/cli/LDAPConnectionConsoleInteraction.java
index 3951b57..bf47ebf 100644
--- a/opends/src/server/org/opends/server/util/cli/LDAPConnectionConsoleInteraction.java
+++ b/opends/src/server/org/opends/server/util/cli/LDAPConnectionConsoleInteraction.java
@@ -29,7 +29,12 @@
import org.opends.messages.Message;
import static org.opends.messages.UtilityMessages.*;
-import static org.opends.messages.ToolMessages.INFO_LDAPAUTH_PASSWORD_PROMPT;
+import static org.opends.messages.QuickSetupMessages.*;
+import static org.opends.messages.ToolMessages.*;
+
+import org.opends.quicksetup.Step;
+import org.opends.quicksetup.UserDataCertificateException;
+import org.opends.quicksetup.util.Utils;
import org.opends.server.tools.dsconfig.ArgumentExceptionFactory;
import org.opends.server.tools.LDAPConnectionOptions;
import org.opends.server.tools.SSLConnectionFactory;
@@ -37,12 +42,14 @@
import org.opends.server.admin.client.cli.SecureConnectionCliArgs;
import org.opends.server.util.args.ArgumentException;
import org.opends.server.util.SelectableCertificateKeyManager;
+import org.opends.admin.ads.ADSContext;
import org.opends.admin.ads.util.ApplicationTrustManager;
import org.opends.admin.ads.util.ApplicationKeyManager;
import javax.net.ssl.KeyManager;
import javax.net.ssl.TrustManager;
import java.net.InetAddress;
+import java.net.URI;
import java.net.UnknownHostException;
import java.io.File;
import java.io.FileInputStream;
@@ -52,6 +59,8 @@
import java.security.KeyStoreException;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
+import java.util.logging.Level;
+import java.util.logging.Logger;
/**
* Supports interacting with a user through the command line to
@@ -64,9 +73,15 @@
private String hostName;
private int portNumber;
private String bindDN;
+ private String adminUID;
private String bindPassword;
private KeyManager keyManager;
private ApplicationTrustManager trustManager;
+ // Boolean that tells if we ask for bind DN or admin UID in the same prompt.
+ private boolean useAdminOrBindDn = false;
+ // Boolean that tells if we must propose LDAP if it is available even if the
+ // user provided certificate parameters.
+ private boolean displayLdapIfSecureParameters = false;
// The SecureConnectionCliArgsList object.
private SecureConnectionCliArgs secureArgsList = null;
@@ -93,6 +108,8 @@
private String truststorePassword;
+ private Message heading = INFO_LDAP_CONN_HEADING_CONNECTION_PARAMETERS.get();
+
/**
* Enumeration description protocols for interactive CLI choices.
*/
@@ -305,13 +322,7 @@
final String tmpHostName = hostName;
if (app.isInteractive() && !secureArgsList.hostNameArg.isPresent())
{
- if (!isHeadingDisplayed)
- {
- app.println();
- app.println();
- app.println(INFO_LDAP_CONN_HEADING_CONNECTION_PARAMETERS.get());
- isHeadingDisplayed = true;
- }
+ checkHeadingDisplayed();
ValidationCallback<String> callback = new ValidationCallback<String>()
{
@@ -372,13 +383,7 @@
);
if (app.isInteractive() && !connectionTypeIsSet)
{
- if (!isHeadingDisplayed)
- {
- app.println();
- app.println();
- app.println(INFO_LDAP_CONN_HEADING_CONNECTION_PARAMETERS.get());
- isHeadingDisplayed = true;
- }
+ checkHeadingDisplayed();
MenuBuilder<Integer> builder = new MenuBuilder<Integer>(app);
builder.setPrompt(INFO_LDAP_CONN_PROMPT_SECURITY_USE_SECURE_CTX.get());
@@ -394,7 +399,8 @@
}
for (Protocols p : Protocols.values())
{
- if (secureConnection && p.equals(Protocols.LDAP))
+ if (secureConnection && p.equals(Protocols.LDAP) &&
+ !displayLdapIfSecureParameters)
{
continue ;
}
@@ -444,13 +450,9 @@
}
}
- if (useSSL || useStartTLS)
+ if ((useSSL || useStartTLS) && (trustManager == null))
{
- // Get truststore info
- trustManager = getTrustManagerInternal();
-
- // Check if we need client side authentication
- keyManager = getKeyManagerInternal();
+ initializeTrustManager();
}
// Get the LDAP port.
@@ -472,13 +474,7 @@
final int tmpPortNumber = portNumber;
if (app.isInteractive() && !secureArgsList.portArg.isPresent())
{
- if (!isHeadingDisplayed)
- {
- app.println();
- app.println();
- app.println(INFO_LDAP_CONN_HEADING_CONNECTION_PARAMETERS.get());
- isHeadingDisplayed = true;
- }
+ checkHeadingDisplayed();
ValidationCallback<Integer> callback = new ValidationCallback<Integer>()
{
@@ -529,18 +525,18 @@
// Get the LDAP bind credentials.
bindDN = secureArgsList.bindDnArg.getValue();
+ adminUID = secureArgsList.adminUidArg.getValue();
+ final boolean useAdmin = secureArgsList.useAdminUID();
+ boolean argIsPresent = useAdmin ?
+ secureArgsList.adminUidArg.isPresent() :
+ secureArgsList.bindDnArg.isPresent();
final String tmpBindDN = bindDN;
+ final String tmpAdminUID = adminUID;
if (keyManager == null)
{
- if (app.isInteractive() && !secureArgsList.bindDnArg.isPresent())
+ if (app.isInteractive() && !argIsPresent)
{
- if (!isHeadingDisplayed)
- {
- app.println();
- app.println();
- app.println(INFO_LDAP_CONN_HEADING_CONNECTION_PARAMETERS.get());
- isHeadingDisplayed = true;
- }
+ checkHeadingDisplayed();
ValidationCallback<String> callback = new ValidationCallback<String>()
{
@@ -551,7 +547,14 @@
String ninput = input.trim();
if (ninput.length() == 0)
{
- return tmpBindDN;
+ if (useAdmin)
+ {
+ return tmpAdminUID;
+ }
+ else
+ {
+ return tmpBindDN;
+ }
}
else
{
@@ -564,8 +567,34 @@
try
{
app.println();
- bindDN = app.readValidatedInput(INFO_LDAP_CONN_PROMPT_BIND_DN
+ if (useAdminOrBindDn)
+ {
+ String def = (adminUID != null) ? adminUID : bindDN;
+ String v = app.readValidatedInput(
+ INFO_LDAP_CONN_GLOBAL_ADMINISTRATOR_OR_BINDDN_PROMPT.get(def),
+ callback);
+ if (Utils.isDn(v))
+ {
+ bindDN = v;
+ adminUID = null;
+ }
+ else
+ {
+ bindDN = null;
+ adminUID = v;
+ }
+ }
+ else if (useAdmin)
+ {
+ adminUID = app.readValidatedInput(
+ INFO_LDAP_CONN_PROMPT_ADMINISTRATOR_UID.get(adminUID),
+ callback);
+ }
+ else
+ {
+ bindDN = app.readValidatedInput(INFO_LDAP_CONN_PROMPT_BIND_DN
.get(bindDN), callback);
+ }
}
catch (CLIException e)
{
@@ -576,7 +605,8 @@
}
else
{
- bindDN = null ;
+ bindDN = null;
+ adminUID = null;
}
bindPassword = secureArgsList.bindPasswordArg.getValue();
@@ -589,7 +619,14 @@
if (bindPassword == null)
{
- throw ArgumentExceptionFactory.missingBindPassword(bindDN);
+ if (useAdmin)
+ {
+ throw ArgumentExceptionFactory.missingBindPassword(adminUID);
+ }
+ else
+ {
+ throw ArgumentExceptionFactory.missingBindPassword(bindDN);
+ }
}
}
else if (bindPassword == null || bindPassword.equals("-"))
@@ -601,18 +638,31 @@
.unableToReadBindPasswordInteractively();
}
- if (!isHeadingDisplayed)
- {
- app.println();
- app.println();
- app.println(INFO_LDAP_CONN_HEADING_CONNECTION_PARAMETERS.get());
- isHeadingDisplayed = true;
- }
+ checkHeadingDisplayed();
try
{
app.println();
- Message prompt = INFO_LDAPAUTH_PASSWORD_PROMPT.get(bindDN);
+ Message prompt;
+ if (useAdminOrBindDn)
+ {
+ if (adminUID != null)
+ {
+ prompt = INFO_LDAPAUTH_PASSWORD_PROMPT.get(adminUID);
+ }
+ else
+ {
+ prompt = INFO_LDAPAUTH_PASSWORD_PROMPT.get(bindDN);
+ }
+ }
+ else if (useAdmin)
+ {
+ prompt = INFO_LDAPAUTH_PASSWORD_PROMPT.get(adminUID);
+ }
+ else
+ {
+ prompt = INFO_LDAPAUTH_PASSWORD_PROMPT.get(bindDN);
+ }
bindPassword = app.readPassword(prompt);
}
catch (Exception e)
@@ -653,13 +703,7 @@
boolean askForTrustStore = false;
if (app.isInteractive() && weDontKnowTheTrustMethod)
{
- if (!isHeadingDisplayed)
- {
- app.println();
- app.println();
- app.println(INFO_LDAP_CONN_HEADING_CONNECTION_PARAMETERS.get());
- isHeadingDisplayed = true;
- }
+ checkHeadingDisplayed();
app.println();
MenuBuilder<Integer> builder = new MenuBuilder<Integer>(app);
@@ -729,13 +773,7 @@
if (app.isInteractive() && !secureArgsList.trustStorePathArg.isPresent()
&& askForTrustStore)
{
- if (!isHeadingDisplayed)
- {
- app.println();
- app.println();
- app.println(INFO_LDAP_CONN_HEADING_CONNECTION_PARAMETERS.get());
- isHeadingDisplayed = true;
- }
+ checkHeadingDisplayed();
ValidationCallback<String> callback = new ValidationCallback<String>()
{
@@ -800,13 +838,7 @@
}
else
{
- if (!isHeadingDisplayed)
- {
- app.println();
- app.println();
- app.println(INFO_LDAP_CONN_HEADING_CONNECTION_PARAMETERS.get());
- isHeadingDisplayed = true;
- }
+ checkHeadingDisplayed();
try
{
@@ -884,13 +916,7 @@
keystorePath = secureArgsList.keyStorePathArg.getValue();
if (app.isInteractive() && !secureArgsList.keyStorePathArg.isPresent())
{
- if (!isHeadingDisplayed)
- {
- app.println();
- app.println();
- app.println(INFO_LDAP_CONN_HEADING_CONNECTION_PARAMETERS.get());
- isHeadingDisplayed = true;
- }
+ checkHeadingDisplayed();
ValidationCallback<String> callback = new ValidationCallback<String>()
{
@@ -952,13 +978,7 @@
.unableToReadBindPasswordInteractively();
}
- if (!isHeadingDisplayed)
- {
- app.println();
- app.println();
- app.println(INFO_LDAP_CONN_HEADING_CONNECTION_PARAMETERS.get());
- isHeadingDisplayed = true;
- }
+ checkHeadingDisplayed();
try
{
@@ -993,13 +1013,7 @@
if (app.isInteractive() && !secureArgsList.certNicknameArg.isPresent()
&& aliasesEnum.hasMoreElements())
{
- if (!isHeadingDisplayed)
- {
- app.println();
- app.println();
- app.println(INFO_LDAP_CONN_HEADING_CONNECTION_PARAMETERS.get());
- isHeadingDisplayed = true;
- }
+ checkHeadingDisplayed();
try
{
@@ -1123,7 +1137,37 @@
* @return bind DN for connections
*/
public String getBindDN() {
- return this.bindDN;
+ String dn;
+ if (useAdminOrBindDn)
+ {
+ if (this.adminUID != null)
+ {
+ dn = ADSContext.getAdministratorDN(this.adminUID);
+ }
+ else
+ {
+ dn = this.bindDN;
+ }
+ }
+ else if (secureArgsList.useAdminUID())
+ {
+ dn = ADSContext.getAdministratorDN(this.adminUID);
+ }
+ else
+ {
+ dn = this.bindDN;
+ }
+ return dn;
+ }
+
+ /**
+ * Gets the administrator UID name that should be used for connections based
+ * on this interaction.
+ *
+ * @return administrator UID for connections
+ */
+ public String getAdministratorUID() {
+ return this.adminUID;
}
/**
@@ -1198,6 +1242,18 @@
public boolean checkServerCertificate(X509Certificate[] chain,
String authType, String host)
{
+ if (trustManager == null)
+ {
+ try
+ {
+ initializeTrustManager();
+ }
+ catch (ArgumentException ae)
+ {
+ // Should not occur
+ throw new RuntimeException(ae);
+ }
+ }
app.println();
app.println(INFO_LDAP_CONN_PROMPT_SECURITY_SERVER_CERTIFICATE.get());
app.println();
@@ -1278,7 +1334,7 @@
}
catch (KeyStoreException e1)
{
- // What should we do else?
+ // What else should we do?
return false;
}
}
@@ -1438,4 +1494,202 @@
return options;
}
+ /**
+ * Prompts the user to accept the certificate.
+ * @param t the throwable that was generated because the certificate was
+ * not trusted.
+ * @param usedTrustManager the trustManager used when trying to establish the
+ * connection.
+ * @param usedUrl the LDAP URL used to connect to the server.
+ * @param displayErrorMessage whether to display an error message before
+ * asking to accept the certificate or not.
+ * @param logger the Logger used to log messages.
+ * @return <CODE>true</CODE> if the user accepted the certificate and
+ * <CODE>false</CODE> otherwise.
+ */
+ public boolean promptForCertificateConfirmation(Throwable t,
+ ApplicationTrustManager usedTrustManager, String usedUrl,
+ boolean displayErrorMessage, Logger logger)
+ {
+ boolean returnValue = false;
+ ApplicationTrustManager.Cause cause;
+ if (usedTrustManager != null)
+ {
+ cause = usedTrustManager.getLastRefusedCause();
+ }
+ else
+ {
+ cause = null;
+ }
+ if (logger != null)
+ {
+ logger.log(Level.INFO, "Certificate exception cause: "+cause);
+ }
+ UserDataCertificateException.Type excType = null;
+ if (cause == ApplicationTrustManager.Cause.NOT_TRUSTED)
+ {
+ excType = UserDataCertificateException.Type.NOT_TRUSTED;
+ }
+ else if (cause ==
+ ApplicationTrustManager.Cause.HOST_NAME_MISMATCH)
+ {
+ excType = UserDataCertificateException.Type.HOST_NAME_MISMATCH;
+ }
+ else
+ {
+ Message msg = Utils.getThrowableMsg(INFO_ERROR_CONNECTING_TO_LOCAL.get(),
+ t);
+ app.println(msg);
+ }
+
+ if (excType != null)
+ {
+ String h;
+ int p;
+ try
+ {
+ URI uri = new URI(usedUrl);
+ h = uri.getHost();
+ p = uri.getPort();
+ }
+ catch (Throwable t1)
+ {
+ if (logger != null)
+ {
+ logger.log(Level.WARNING, "Error parsing ldap url of ldap url.", t1);
+ }
+ h = INFO_NOT_AVAILABLE_LABEL.get().toString();
+ p = -1;
+ }
+
+
+
+ UserDataCertificateException udce =
+ new UserDataCertificateException(Step.REPLICATION_OPTIONS,
+ INFO_CERTIFICATE_EXCEPTION.get(h, String.valueOf(p)), t, h, p,
+ usedTrustManager.getLastRefusedChain(),
+ usedTrustManager.getLastRefusedAuthType(), excType);
+
+ Message msg;
+ if (udce.getType() == UserDataCertificateException.Type.NOT_TRUSTED)
+ {
+ msg = INFO_CERTIFICATE_NOT_TRUSTED_TEXT_CLI.get(
+ udce.getHost(), String.valueOf(udce.getPort()));
+ }
+ else
+ {
+ msg = INFO_CERTIFICATE_NAME_MISMATCH_TEXT_CLI.get(
+ udce.getHost(), String.valueOf(udce.getPort()),
+ udce.getHost(),
+ udce.getHost(), String.valueOf(udce.getPort()));
+ }
+ if (displayErrorMessage)
+ {
+ app.println(msg);
+ }
+ X509Certificate[] chain = udce.getChain();
+ String authType = udce.getAuthType();
+ String host = udce.getHost();
+ if (logger != null)
+ {
+ if (chain == null)
+ {
+ logger.log(Level.WARNING,
+ "The chain is null for the UserDataCertificateException");
+ }
+ if (authType == null)
+ {
+ logger.log(Level.WARNING,
+ "The auth type is null for the UserDataCertificateException");
+ }
+ if (host == null)
+ {
+ logger.log(Level.WARNING,
+ "The host is null for the UserDataCertificateException");
+ }
+ }
+ if (chain != null)
+ {
+ returnValue = checkServerCertificate(chain, authType, host);
+ }
+ }
+ return returnValue;
+ }
+
+ /**
+ * Sets the heading that is displayed in interactive mode.
+ * @param heading the heading that is displayed in interactive mode.
+ */
+ public void setHeadingMessage(Message heading)
+ {
+ this.heading = heading;
+ }
+
+ /**
+ * Displays the heading if it was not displayed before.
+ *
+ */
+ private void checkHeadingDisplayed()
+ {
+ if (!isHeadingDisplayed)
+ {
+ app.println();
+ app.println();
+ app.println(heading);
+ isHeadingDisplayed = true;
+ }
+ }
+
+ /**
+ * Tells whether during interaction we can ask for both the DN or the admin
+ * UID.
+ * @return <CODE>true</CODE> if during interaction we can ask for both the DN
+ * and the admin UID and <CODE>false</CODE> otherwise.
+ */
+ public boolean isUseAdminOrBindDn()
+ {
+ return useAdminOrBindDn;
+ }
+
+ /**
+ * Tells whether we can ask during interaction for both the DN and the admin
+ * UID or not.
+ * @param useAdminOrBindDn whether we can ask for both the DN and the admin UID
+ * during interaction or not.
+ */
+ public void setUseAdminOrBindDn(boolean useAdminOrBindDn)
+ {
+ this.useAdminOrBindDn = useAdminOrBindDn;
+ }
+
+ /**
+ * Tells whether we propose LDAP as protocol even if the user provided security
+ * parameters. This is required in command-lines that access multiple servers
+ * (like dsreplication).
+ * @param displayLdapIfSecureParameters whether propose LDAP as protocol even
+ * if the user provided security parameters or not.
+ */
+ public void setDisplayLdapIfSecureParameters(
+ boolean displayLdapIfSecureParameters)
+ {
+ this.displayLdapIfSecureParameters = displayLdapIfSecureParameters;
+ }
+
+ /**
+ * Resets the heading displayed flag, so that next time we call run the heading
+ * is displayed.
+ */
+ public void resetHeadingDisplayed()
+ {
+ isHeadingDisplayed = false;
+ }
+
+ private void initializeTrustManager() throws ArgumentException
+ {
+ // Get truststore info
+ trustManager = getTrustManagerInternal();
+
+ // Check if we need client side authentication
+ keyManager = getKeyManagerInternal();
+ }
}
--
Gitblit v1.10.0