Index: apacheds/server-tools/src/main/java/org/apache/directory/server/tools/DisconnectNotificationCommand.java =================================================================== --- apacheds/server-tools/src/main/java/org/apache/directory/server/tools/DisconnectNotificationCommand.java (revision 423936) +++ apacheds/server-tools/src/main/java/org/apache/directory/server/tools/DisconnectNotificationCommand.java (working copy) @@ -1,316 +0,0 @@ -/* - * Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.apache.directory.server.tools; - - -import java.util.Hashtable; - -import javax.naming.NamingException; -import javax.naming.directory.SearchControls; -import javax.naming.event.EventContext; -import javax.naming.event.NamingExceptionEvent; -import javax.naming.ldap.InitialLdapContext; -import javax.naming.ldap.LdapContext; -import javax.naming.ldap.UnsolicitedNotification; -import javax.naming.ldap.UnsolicitedNotificationListener; -import javax.naming.ldap.UnsolicitedNotificationEvent; - -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.Option; -import org.apache.commons.cli.Options; -import org.apache.directory.daemon.AvailablePortFinder; -import org.apache.directory.shared.ldap.message.extended.GracefulDisconnect; -import org.apache.directory.shared.ldap.message.extended.NoticeOfDisconnect; - - -/** - * Responds to unsolicited notifications by launching an external process. Also - * reconnects to the server an launches another process to notify that the server - * is back up. - * - * @author Apache Directory Project - * @version $Rev$ - */ -public class DisconnectNotificationCommand extends ToolCommand implements UnsolicitedNotificationListener -{ - UnsolicitedNotification notification; - boolean canceled = false; - private String host = "localhost"; - private int port = 10389; - private String bindDn = "uid=admin,ou=system"; - private String password = "secret"; - - - // private String shutdownCommand = "echo"; - // private String[] shutdownCommandArgs = new String[] { - // "server $HOST:$PORT will shutdown for $OFFLINE minutes in $DELAY seconds" }; - - protected DisconnectNotificationCommand() - { - super( "notifications" ); - } - - - public void notificationReceived( UnsolicitedNotificationEvent evt ) - { - notification = evt.getNotification(); - - if ( notification.getID().equals( NoticeOfDisconnect.EXTENSION_OID ) ) - { - System.out.println( "\nRecieved NoticeOfDisconnect: " + NoticeOfDisconnect.EXTENSION_OID ); - System.out.println( "Expect to loose this connection without further information." ); - canceled = true; - } - else if ( notification.getID().equals( GracefulDisconnect.EXTENSION_OID ) ) - { - System.out.println( "Recieved GracefulDisconnect: " + GracefulDisconnect.EXTENSION_OID ); - GracefulDisconnect gd = null; - - try - { - gd = new GracefulDisconnect( notification.getEncodedValue() ); - } - catch ( NamingException e ) - { - // TODO Auto-generated catch block - e.printStackTrace(); - } - - System.out.println( "LDAP server will shutdown in " + gd.getDelay() + " seconds." ); - System.out.println( "LDAP server will be back online in " + gd.getTimeOffline() + " minutes." ); - - if ( gd.getDelay() > 0 ) - { - Thread t = new Thread( new Counter( gd.getDelay() ) ); - t.start(); - } - } - else - { - System.out.println( "Unknown event recieved with OID: " + evt.getNotification().getID() ); - } - } - - - public void namingExceptionThrown( NamingExceptionEvent evt ) - { - canceled = true; - System.out.println( "Got an excption event: " + evt.getException().getMessage() ); - System.out.println( "Process shutting down abruptly." ); - System.exit( 1 ); - } - - class Counter implements Runnable - { - int delay; - - - Counter(int delay) - { - this.delay = delay; - } - - - public void run() - { - System.out.println( "Starting countdown until server shutdown:" ); - System.out.print( "[" ); - long delayMillis = delay * 1000 - 1000; // 1000 is for setup costs - long startTime = System.currentTimeMillis(); - while ( System.currentTimeMillis() - startTime < delayMillis && !canceled ) - { - try - { - Thread.sleep( 1000 ); - } - catch ( InterruptedException e ) - { - } - System.out.print( "." ); - } - - if ( canceled ) - { - System.out.println( " -- countdown canceled -- " ); - } - else - { - System.out.println( "]" ); - System.out.println( "Client shutting down gracefully." ); - System.exit( 0 ); - } - } - } - - - public void execute( CommandLine cmd ) throws Exception - { - processOptions( cmd ); - - Hashtable env = new Hashtable(); - env.put( "java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory" ); - env.put( "java.naming.provider.url", "ldap://" + host + ":" + port ); - env.put( "java.naming.security.principal", bindDn ); - env.put( "java.naming.security.credentials", password ); - env.put( "java.naming.security.authentication", "simple" ); - - LdapContext ctx = new InitialLdapContext( env, null ); - ctx = ctx.newInstance( null ); - UnsolicitedNotificationListener listener = new DisconnectNotificationCommand(); - ( ( EventContext ) ctx ).addNamingListener( "", SearchControls.SUBTREE_SCOPE, listener ); - - System.out.println( "Listening for notifications." ); - System.out.println( "Press any key to terminate." ); - System.in.read(); - ctx.close(); - System.out.println( "Process terminated!!!" ); - } - - - private void processOptions( CommandLine cmd ) - { - if ( isDebugEnabled() ) - { - System.out.println( "Processing options for disconnect notifications ..." ); - } - - // ------------------------------------------------------------------- - // figure out and error check the port value - // ------------------------------------------------------------------- - - if ( cmd.hasOption( 'p' ) ) // - user provided port w/ -p takes precedence - { - String val = cmd.getOptionValue( 'p' ); - try - { - port = Integer.parseInt( val ); - } - catch ( NumberFormatException e ) - { - System.err.println( "port value of '" + val + "' is not a number" ); - System.exit( 1 ); - } - - if ( port > AvailablePortFinder.MAX_PORT_NUMBER ) - { - System.err.println( "port value of '" + val + "' is larger than max port number: " - + AvailablePortFinder.MAX_PORT_NUMBER ); - System.exit( 1 ); - } - else if ( port < AvailablePortFinder.MIN_PORT_NUMBER ) - { - System.err.println( "port value of '" + val + "' is smaller than the minimum port number: " - + AvailablePortFinder.MIN_PORT_NUMBER ); - System.exit( 1 ); - } - - if ( isDebugEnabled() ) - { - System.out.println( "port overriden by -p option: " + port ); - } - } - else if ( getConfiguration() != null ) - { - port = getConfiguration().getLdapPort(); - - if ( isDebugEnabled() ) - { - System.out.println( "port overriden by server.xml configuration: " + port ); - } - } - else if ( isDebugEnabled() ) - { - System.out.println( "port set to default: " + port ); - } - - // ------------------------------------------------------------------- - // figure out the host value - // ------------------------------------------------------------------- - - if ( cmd.hasOption( 'h' ) ) - { - host = cmd.getOptionValue( 'h' ); - - if ( isDebugEnabled() ) - { - System.out.println( "host overriden by -h option: " + host ); - } - } - else if ( isDebugEnabled() ) - { - System.out.println( "host set to default: " + host ); - } - - // ------------------------------------------------------------------- - // figure out the password value - // ------------------------------------------------------------------- - - if ( cmd.hasOption( 'w' ) ) - { - password = cmd.getOptionValue( 'w' ); - - if ( isDebugEnabled() ) - { - System.out.println( "password overriden by -w option: " + password ); - } - } - else if ( isDebugEnabled() ) - { - System.out.println( "password set to default: " + password ); - } - - // ------------------------------------------------------------------- - // figure out the binddn value - // ------------------------------------------------------------------- - - if ( cmd.hasOption( 'u' ) ) - { - bindDn = cmd.getOptionValue( 'u' ); - - if ( isDebugEnabled() ) - { - System.out.println( "binddn overriden by -u option: " + bindDn ); - } - } - else if ( isDebugEnabled() ) - { - System.out.println( "binddn set to default: " + bindDn ); - } - } - - - public Options getOptions() - { - Options opts = new Options(); - Option op = new Option( "h", "host", true, "server host: defaults to localhost" ); - op.setRequired( false ); - opts.addOption( op ); - op = new Option( "p", "port", true, "server port: defaults to 10389 or server.xml specified port" ); - op.setRequired( false ); - opts.addOption( op ); - op = new Option( "w", "password", true, "the apacheds administrator's password: defaults to secret" ); - op.setRequired( false ); - opts.addOption( op ); - op = new Option( "u", "binddn", true, "an apacheds user's dn: defaults to " + bindDn ); - op.setRequired( false ); - opts.addOption( op ); - op = new Option( "i", "install-path", true, "path to apacheds installation directory" ); - op.setRequired( false ); - opts.addOption( op ); - return opts; - } -} Index: apacheds/server-tools/src/main/java/org/apache/directory/server/tools/DiagnosticCommand.java =================================================================== --- apacheds/server-tools/src/main/java/org/apache/directory/server/tools/DiagnosticCommand.java (revision 423936) +++ apacheds/server-tools/src/main/java/org/apache/directory/server/tools/DiagnosticCommand.java (working copy) @@ -1,197 +0,0 @@ -/* - * Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.apache.directory.server.tools; - - -import java.util.Hashtable; -import javax.naming.ldap.InitialLdapContext; -import javax.naming.ldap.LdapContext; - -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.Option; -import org.apache.commons.cli.Options; -import org.apache.directory.daemon.AvailablePortFinder; -import org.apache.directory.shared.ldap.message.extended.LaunchDiagnosticUiRequest; - - -/** - * A command to send an extened request which launches a diagnostic UI - * on the server's console. This may not work unless the display is set - * and access is granted to the display (via xhost +). This is especially - * the case when running the server in daemon mode. Usually when running - * the server in debug mode is when you want the diagnostics turned on. - * - * @author Apache Directory Project - * @version $Rev$ - */ -public class DiagnosticCommand extends ToolCommand -{ - public static final String PORT_RANGE = "(" + AvailablePortFinder.MIN_PORT_NUMBER + ", " - + AvailablePortFinder.MAX_PORT_NUMBER + ")"; - - private int port = 10389; - private String host = "localhost"; - private String password = "secret"; - - - protected DiagnosticCommand() - { - super( "diagnostic" ); - } - - - public void execute( CommandLine cmd ) throws Exception - { - processOptions( cmd ); - - if ( isDebugEnabled() ) - { - System.out.println( "Parameters for LaunchDiagnosticUI extended request:" ); - System.out.println( "port = " + port ); - System.out.println( "host = " + host ); - System.out.println( "password = " + password ); - } - - Hashtable env = new Hashtable(); - env.put( "java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory" ); - env.put( "java.naming.provider.url", "ldap://" + host + ":" + port ); - env.put( "java.naming.security.principal", "uid=admin,ou=system" ); - env.put( "java.naming.security.credentials", password ); - env.put( "java.naming.security.authentication", "simple" ); - - LdapContext ctx = new InitialLdapContext( env, null ); - if ( isDebugEnabled() ) - { - System.out.println( "Connection to the server established.\n" + "Sending extended request ... " ); - } - ctx.extendedOperation( new LaunchDiagnosticUiRequest( 3 ) ); - ctx.close(); - } - - - private void processOptions( CommandLine cmd ) - { - if ( isDebugEnabled() ) - { - System.out.println( "Processing options for launching diagnostic UI ..." ); - } - - // ------------------------------------------------------------------- - // figure out and error check the port value - // ------------------------------------------------------------------- - - if ( cmd.hasOption( 'p' ) ) // - user provided port w/ -p takes precedence - { - String val = cmd.getOptionValue( 'p' ); - try - { - port = Integer.parseInt( val ); - } - catch ( NumberFormatException e ) - { - System.err.println( "port value of '" + val + "' is not a number" ); - System.exit( 1 ); - } - - if ( port > AvailablePortFinder.MAX_PORT_NUMBER ) - { - System.err.println( "port value of '" + val + "' is larger than max port number: " - + AvailablePortFinder.MAX_PORT_NUMBER ); - System.exit( 1 ); - } - else if ( port < AvailablePortFinder.MIN_PORT_NUMBER ) - { - System.err.println( "port value of '" + val + "' is smaller than the minimum port number: " - + AvailablePortFinder.MIN_PORT_NUMBER ); - System.exit( 1 ); - } - - if ( isDebugEnabled() ) - { - System.out.println( "port overriden by -p option: " + port ); - } - } - else if ( getConfiguration() != null ) - { - port = getConfiguration().getLdapPort(); - - if ( isDebugEnabled() ) - { - System.out.println( "port overriden by server.xml configuration: " + port ); - } - } - else if ( isDebugEnabled() ) - { - System.out.println( "port set to default: " + port ); - } - - // ------------------------------------------------------------------- - // figure out the host value - // ------------------------------------------------------------------- - - if ( cmd.hasOption( 'h' ) ) - { - host = cmd.getOptionValue( 'h' ); - - if ( isDebugEnabled() ) - { - System.out.println( "host overriden by -h option: " + host ); - } - } - else if ( isDebugEnabled() ) - { - System.out.println( "host set to default: " + host ); - } - - // ------------------------------------------------------------------- - // figure out the password value - // ------------------------------------------------------------------- - - if ( cmd.hasOption( 'w' ) ) - { - password = cmd.getOptionValue( 'w' ); - - if ( isDebugEnabled() ) - { - System.out.println( "password overriden by -w option: " + password ); - } - } - else if ( isDebugEnabled() ) - { - System.out.println( "password set to default: " + password ); - } - } - - - public Options getOptions() - { - Options opts = new Options(); - Option op = new Option( "h", "host", true, "server host: defaults to localhost" ); - op.setRequired( false ); - opts.addOption( op ); - op = new Option( "p", "port", true, "server port: defaults to 10389 or server.xml specified port" ); - op.setRequired( false ); - opts.addOption( op ); - op = new Option( "w", "password", true, "the apacheds administrator's password: defaults to secret" ); - op.setRequired( false ); - opts.addOption( op ); - op = new Option( "i", "install-path", true, "path to apacheds installation directory" ); - op.setRequired( false ); - opts.addOption( op ); - return opts; - } -} Index: apacheds/server-tools/src/main/java/org/apache/directory/server/tools/GracefulShutdownCommand.java =================================================================== --- apacheds/server-tools/src/main/java/org/apache/directory/server/tools/GracefulShutdownCommand.java (revision 423936) +++ apacheds/server-tools/src/main/java/org/apache/directory/server/tools/GracefulShutdownCommand.java (working copy) @@ -1,373 +0,0 @@ -/* - * Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.apache.directory.server.tools; - - -import java.util.Hashtable; - -import javax.naming.CommunicationException; -import javax.naming.ldap.InitialLdapContext; -import javax.naming.ldap.LdapContext; - -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.Option; -import org.apache.commons.cli.Options; -import org.apache.directory.daemon.AvailablePortFinder; -import org.apache.directory.shared.ldap.message.extended.GracefulShutdownRequest; - - -/** - * A command used to send a graceful disconnect to established clients - * while allowing them time to complete operations already in progress. - * - * @see - * Graceful Shutdown - * @author Apache Directory Project - * @version $Rev$ - */ -public class GracefulShutdownCommand extends ToolCommand -{ - public static final String PORT_RANGE = "(" + AvailablePortFinder.MIN_PORT_NUMBER + ", " - + AvailablePortFinder.MAX_PORT_NUMBER + ")"; - - private static final int DELAY_MAX = 86400; - - private static final int TIME_OFFLINE_MAX = 720; - - private int port = 10389; - private String host = "localhost"; - private String password = "secret"; - private int delay; - private int timeOffline; - - - protected GracefulShutdownCommand() - { - super( "graceful" ); - } - - private boolean isWaiting; - private boolean isSuccess = false; - private Thread executeThread = null; - - - public void execute( CommandLine cmd ) throws Exception - { - executeThread = Thread.currentThread(); - processOptions( cmd ); - - if ( isDebugEnabled() ) - { - System.out.println( "Parameters for GracefulShutdown extended request:" ); - System.out.println( "port = " + port ); - System.out.println( "host = " + host ); - System.out.println( "password = " + password ); - System.out.println( "delay = " + delay ); - System.out.println( "timeOffline = " + timeOffline ); - } - - Hashtable env = new Hashtable(); - env.put( "java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory" ); - env.put( "java.naming.provider.url", "ldap://" + host + ":" + port ); - env.put( "java.naming.security.principal", "uid=admin,ou=system" ); - env.put( "java.naming.security.credentials", password ); - env.put( "java.naming.security.authentication", "simple" ); - - LdapContext ctx = new InitialLdapContext( env, null ); - if ( !isQuietEnabled() ) - { - System.out.println( "Connection to the server established.\n" - + "Sending extended request and blocking for shutdown:" ); - isWaiting = true; - Thread t = new Thread( new Ticker() ); - t.start(); - } - try - { - ctx.extendedOperation( new GracefulShutdownRequest( 0, timeOffline, delay ) ); - isSuccess = true; - } - catch ( Throwable t ) - { - /* - * Sometimes because of timing issues we show a failure when the - * shutdown has succeeded so we should check if the server is up - * before we set success to false. - */ - try - { - new InitialLdapContext( env, null ); - isSuccess = false; - System.err.print( "shutdown request failed with error: " + t.getMessage() ); - } - catch( CommunicationException e ) - { - isSuccess = true; - } - } - isWaiting = false; - ctx.close(); - } - - class Ticker implements Runnable - { - public void run() - { - if ( !isQuietEnabled() ) - System.out.print( "[waiting for shutdown] " ); - while ( isWaiting ) - { - try - { - Thread.sleep( 1000 ); - } - catch ( InterruptedException e ) - { - // TODO Auto-generated catch block - e.printStackTrace(); - } - if ( !isQuietEnabled() ) - System.out.print( "." ); - } - if ( isSuccess ) - { - if ( !isQuietEnabled() ) - System.out.println( "\n[shutdown complete]" ); - try - { - executeThread.join( 1000 ); - } - catch ( InterruptedException e ) - { - e.printStackTrace(); - } - System.exit( 0 ); - } - else - { - if ( !isQuietEnabled() ) - System.out.println( "\n[shutdown failed]" ); - try - { - executeThread.join( 1000 ); - } - catch ( InterruptedException e ) - { - e.printStackTrace(); - } - System.exit( 1 ); - } - } - } - - - private void processOptions( CommandLine cmd ) - { - if ( isDebugEnabled() ) - { - System.out.println( "Processing options for graceful shutdown ..." ); - } - - // ------------------------------------------------------------------- - // figure out and error check the port value - // ------------------------------------------------------------------- - - if ( cmd.hasOption( 'p' ) ) // - user provided port w/ -p takes precedence - { - String val = cmd.getOptionValue( 'p' ); - try - { - port = Integer.parseInt( val ); - } - catch ( NumberFormatException e ) - { - System.err.println( "port value of '" + val + "' is not a number" ); - System.exit( 1 ); - } - - if ( port > AvailablePortFinder.MAX_PORT_NUMBER ) - { - System.err.println( "port value of '" + val + "' is larger than max port number: " - + AvailablePortFinder.MAX_PORT_NUMBER ); - System.exit( 1 ); - } - else if ( port < AvailablePortFinder.MIN_PORT_NUMBER ) - { - System.err.println( "port value of '" + val + "' is smaller than the minimum port number: " - + AvailablePortFinder.MIN_PORT_NUMBER ); - System.exit( 1 ); - } - - if ( isDebugEnabled() ) - { - System.out.println( "port overriden by -p option: " + port ); - } - } - else if ( getConfiguration() != null ) - { - port = getConfiguration().getLdapPort(); - - if ( isDebugEnabled() ) - { - System.out.println( "port overriden by server.xml configuration: " + port ); - } - } - else if ( isDebugEnabled() ) - { - System.out.println( "port set to default: " + port ); - } - - // ------------------------------------------------------------------- - // figure out the host value - // ------------------------------------------------------------------- - - if ( cmd.hasOption( 'h' ) ) - { - host = cmd.getOptionValue( 'h' ); - - if ( isDebugEnabled() ) - { - System.out.println( "host overriden by -h option: " + host ); - } - } - else if ( isDebugEnabled() ) - { - System.out.println( "host set to default: " + host ); - } - - // ------------------------------------------------------------------- - // figure out the password value - // ------------------------------------------------------------------- - - if ( cmd.hasOption( 'w' ) ) - { - password = cmd.getOptionValue( 'w' ); - - if ( isDebugEnabled() ) - { - System.out.println( "password overriden by -w option: " + password ); - } - } - else if ( isDebugEnabled() ) - { - System.out.println( "password set to default: " + password ); - } - - // ------------------------------------------------------------------- - // figure out the delay value - // ------------------------------------------------------------------- - - if ( cmd.hasOption( 'e' ) ) - { - String val = cmd.getOptionValue( 'e' ); - try - { - delay = Integer.parseInt( val ); - } - catch ( NumberFormatException e ) - { - System.err.println( "delay value of '" + val + "' is not a number" ); - System.exit( 1 ); - } - - if ( delay > DELAY_MAX ) - { - System.err.println( "delay value of '" + val + "' is larger than max delay (seconds) allowed: " - + DELAY_MAX ); - System.exit( 1 ); - } - else if ( delay < 0 ) - { - System.err.println( "delay value of '" + val + "' is less than zero and makes no sense" ); - System.exit( 1 ); - } - - if ( isDebugEnabled() ) - { - System.out.println( "delay seconds overriden by -e option: " + delay ); - } - } - else if ( isDebugEnabled() ) - { - System.out.println( "Using default delay value of " + delay ); - } - - // ------------------------------------------------------------------- - // figure out the timeOffline value - // ------------------------------------------------------------------- - - if ( cmd.hasOption( 't' ) ) - { - String val = cmd.getOptionValue( 't' ); - try - { - timeOffline = Integer.parseInt( val ); - } - catch ( NumberFormatException e ) - { - System.err.println( "timeOffline value of '" + val + "' is not a number" ); - System.exit( 1 ); - } - - if ( timeOffline > TIME_OFFLINE_MAX ) - { - System.err.println( "timeOffline value of '" + val - + "' is larger than max timeOffline (minutes) allowed: " + TIME_OFFLINE_MAX ); - System.exit( 1 ); - } - else if ( timeOffline < 0 ) - { - System.err.println( "timeOffline value of '" + val + "' is less than zero and makes no sense" ); - System.exit( 1 ); - } - - if ( isDebugEnabled() ) - { - System.out.println( "timeOffline seconds overriden by -t option: " + timeOffline ); - } - } - else if ( isDebugEnabled() ) - { - System.out.println( "Using default timeOffline value of " + delay ); - } - } - - - public Options getOptions() - { - Options opts = new Options(); - Option op = new Option( "h", "host", true, "server host: defaults to localhost" ); - op.setRequired( false ); - opts.addOption( op ); - op = new Option( "p", "port", true, "server port: defaults to 10389 or server.xml specified port" ); - op.setRequired( false ); - opts.addOption( op ); - op = new Option( "e", "delay", true, "delay (seconds) before shutdown: defaults to 0" ); - op.setRequired( false ); - opts.addOption( op ); - op = new Option( "w", "password", true, "the apacheds administrator's password: defaults to secret" ); - op.setRequired( false ); - opts.addOption( op ); - op = new Option( "t", "time-offline", true, "server offline time (minutes): defaults to 0 (indefinate)" ); - op.setRequired( false ); - opts.addOption( op ); - op = new Option( "i", "install-path", true, "path to apacheds installation directory" ); - op.setRequired( false ); - opts.addOption( op ); - return opts; - } -} Index: apacheds/server-tools/src/main/java/org/apache/directory/server/tools/DumpCommand.java =================================================================== --- apacheds/server-tools/src/main/java/org/apache/directory/server/tools/DumpCommand.java (revision 423936) +++ apacheds/server-tools/src/main/java/org/apache/directory/server/tools/DumpCommand.java (working copy) @@ -1,235 +0,0 @@ -/* - * Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.apache.directory.server.tools; - - -import java.io.File; -import java.io.FileWriter; -import java.io.PrintWriter; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import javax.naming.NamingEnumeration; -import javax.naming.NamingException; -import javax.naming.directory.Attribute; -import javax.naming.directory.Attributes; - -import jdbm.helper.MRU; -import jdbm.recman.BaseRecordManager; -import jdbm.recman.CacheRecordManager; - -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.Option; -import org.apache.commons.cli.Options; -import org.apache.directory.server.core.partition.impl.btree.Tuple; -import org.apache.directory.server.core.partition.impl.btree.jdbm.JdbmIndex; -import org.apache.directory.server.core.partition.impl.btree.jdbm.JdbmMasterTable; -import org.apache.directory.server.core.schema.AttributeTypeRegistry; -import org.apache.directory.server.core.schema.bootstrap.BootstrapRegistries; -import org.apache.directory.server.core.schema.bootstrap.BootstrapSchemaLoader; -import org.apache.directory.shared.ldap.message.LockableAttributeImpl; -import org.apache.directory.shared.ldap.message.LockableAttributesImpl; -import org.apache.directory.shared.ldap.schema.AttributeType; -import org.apache.directory.shared.ldap.schema.UsageEnum; - - -/** - * Simple tool used to dump the contents of a jdbm based partition. - * - * @author Apache Directory Project - * @version $Rev$ - */ -public class DumpCommand extends ToolCommand -{ - private BootstrapRegistries bootstrapRegistries = new BootstrapRegistries(); - private BootstrapSchemaLoader loader = new BootstrapSchemaLoader(); - private Set exclusions = new HashSet(); - private boolean includeOperational = false; - - - public DumpCommand() - { - super( "dump" ); - } - - - public void execute( CommandLine cmdline ) throws Exception - { - getLayout().verifyInstallation(); - loader.load( getConfiguration().getBootstrapSchemas(), bootstrapRegistries ); - - includeOperational = cmdline.hasOption( 'o' ); - String[] partitions = cmdline.getOptionValues( 'p' ); - String outputFile = cmdline.getOptionValue( 'f' ); - PrintWriter out = null; - - String[] excludedAttributes = cmdline.getOptionValues( 'e' ); - if ( excludedAttributes != null ) - { - AttributeTypeRegistry registry = bootstrapRegistries.getAttributeTypeRegistry(); - for ( int ii = 0; ii < excludedAttributes.length; ii++ ) - { - AttributeType type = registry.lookup( excludedAttributes[ii] ); - exclusions.add( type.getName() ); - } - } - - if ( outputFile == null ) - { - out = new PrintWriter( System.out ); - } - else - { - out = new PrintWriter( new FileWriter( outputFile ) ); - } - - for ( int ii = 0; ii < partitions.length; ii++ ) - { - File partitionDirectory = new File( getLayout().getPartitionsDirectory(), partitions[ii] ); - out.println( "\n\n" ); - dump( partitionDirectory, out ); - } - } - - - private void dump( File partitionDirectory, PrintWriter out ) throws Exception - { - if ( !partitionDirectory.exists() ) - { - System.err.println( "Partition directory " + partitionDirectory + " does not exist!" ); - System.exit( 1 ); - } - - out.println( "# ========================================================================" ); - out.println( "# ApacheDS Tools Version: " + getVersion() ); - out.println( "# Partition Directory: " + partitionDirectory ); - out.println( "# ========================================================================\n\n" ); - - String path = partitionDirectory.getPath() + File.separator + "master"; - BaseRecordManager base = new BaseRecordManager( path ); - base.disableTransactions(); - CacheRecordManager recMan = new CacheRecordManager( base, new MRU( 1000 ) ); - - JdbmMasterTable master = new JdbmMasterTable( recMan ); - AttributeType attributeType = bootstrapRegistries.getAttributeTypeRegistry().lookup( "apacheUpdn" ); - JdbmIndex idIndex = new JdbmIndex( attributeType, partitionDirectory ); - - out.println( "#---------------------" ); - NamingEnumeration list = master.listTuples(); - StringBuffer buf = new StringBuffer(); - while ( list.hasMore() ) - { - Tuple tuple = ( Tuple ) list.next(); - BigInteger id = ( BigInteger ) tuple.getKey(); - String dn = ( String ) idIndex.reverseLookup( id ); - Attributes entry = ( Attributes ) tuple.getValue(); - - filterAttributes( dn, entry ); - - if ( !( entry instanceof LockableAttributesImpl ) ) - { - Attributes tmp = entry; - entry = new LockableAttributesImpl(); - NamingEnumeration attrs = tmp.getAll(); - while ( attrs.hasMore() ) - { - Attribute attr = ( Attribute ) attrs.next(); - LockableAttributeImpl myattr = new LockableAttributeImpl( attr.getID() ); - entry.put( myattr ); - for ( int ii = 0; ii < attr.size(); ii++ ) - { - myattr.add( attr.get( ii ) ); - } - } - } - - buf.append( "# Entry: " ).append( id ).append( "\n#---------------------\n\n" ); - buf.append( "dn: " ).append( dn ).append( "\n" ).append( entry ); - if ( list.hasMore() ) - { - buf.append( "\n\n#---------------------\n" ); - } - out.print( buf.toString() ); - out.flush(); - buf.setLength( 0 ); - } - } - - - private void filterAttributes( String dn, Attributes entry ) throws NamingException - { - List toRemove = new ArrayList(); - AttributeTypeRegistry registry = bootstrapRegistries.getAttributeTypeRegistry(); - NamingEnumeration attrs = entry.getAll(); - while ( attrs.hasMore() ) - { - Attribute attr = ( Attribute ) attrs.next(); - if ( !registry.hasAttributeType( attr.getID() ) ) - { - if ( !isQuietEnabled() ) - { - System.out - .println( "# Cannot properly filter unrecognized attribute " + attr.getID() + " in " + dn ); - } - continue; - } - - AttributeType type = registry.lookup( attr.getID() ); - boolean isOperational = type.getUsage() != UsageEnum.USERAPPLICATIONS; - if ( exclusions.contains( attr.getID() ) || ( isOperational && ( !includeOperational ) ) ) - { - toRemove.add( attr.getID() ); - } - } - for ( int ii = 0; ii < toRemove.size(); ii++ ) - { - String id = ( String ) toRemove.get( ii ); - entry.remove( id ); - if ( isDebugEnabled() ) - { - System.out.println( "# Excluding attribute " + id + " in " + dn ); - } - } - } - - - public Options getOptions() - { - Options opts = new Options(); - Option op = new Option( "f", "file", true, "file to output the dump to" ); - op.setRequired( false ); - opts.addOption( op ); - op = new Option( "p", "partitions", true, "the partitions to dump" ); - op.setRequired( true ); - op.setValueSeparator( File.pathSeparatorChar ); - opts.addOption( op ); - op = new Option( "e", "excluded-attributes", true, "the attributes to exclude" ); - op.setRequired( false ); - op.setValueSeparator( File.pathSeparatorChar ); - opts.addOption( op ); - op = new Option( "o", "include-operational", false, "include operational attributes: defaults to false" ); - op.setRequired( false ); - opts.addOption( op ); - op = new Option( "i", "install-path", true, "path to apacheds installation directory" ); - op.setRequired( true ); - opts.addOption( op ); - return opts; - } -} Index: apacheds/server-tools/src/main/java/org/apache/directory/server/tools/StoredProcedureCommand.java =================================================================== --- apacheds/server-tools/src/main/java/org/apache/directory/server/tools/StoredProcedureCommand.java (revision 423936) +++ apacheds/server-tools/src/main/java/org/apache/directory/server/tools/StoredProcedureCommand.java (working copy) @@ -1,205 +0,0 @@ -/* - * Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.apache.directory.server.tools; - - -import java.util.Hashtable; - -import javax.naming.ldap.InitialLdapContext; -import javax.naming.ldap.LdapContext; - -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.Option; -import org.apache.commons.cli.Options; -import org.apache.directory.daemon.AvailablePortFinder; -import org.apache.directory.shared.ldap.message.extended.StoredProcedureRequest; - - -/** - * A command used to send a command to execute a stored procedure on the server. - * - * @author Apache Directory Project - * @version $Rev$ - */ -public class StoredProcedureCommand extends ToolCommand -{ - public static final String PORT_RANGE = "(" + AvailablePortFinder.MIN_PORT_NUMBER + ", " - + AvailablePortFinder.MAX_PORT_NUMBER + ")"; - - private int port = 10389; - private String host = "localhost"; - private String password = "secret"; - - - protected StoredProcedureCommand() - { - super( "proc" ); - } - - - public void execute( CommandLine cmd ) throws Exception - { - processOptions( cmd ); - - if ( isDebugEnabled() ) - { - System.out.println( "Parameters for StoredProcedure extended request:" ); - System.out.println( "port = " + port ); - System.out.println( "host = " + host ); - System.out.println( "password = " + password ); - } - - Hashtable env = new Hashtable(); - env.put( "java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory" ); - env.put( "java.naming.provider.url", "ldap://" + host + ":" + port ); - env.put( "java.naming.security.principal", "uid=admin,ou=system" ); - env.put( "java.naming.security.credentials", password ); - env.put( "java.naming.security.authentication", "simple" ); - - LdapContext ctx = new InitialLdapContext( env, null ); - if ( !isQuietEnabled() ) - { - System.out.println( "Connection to the server established.\n" - + "Sending extended request and blocking for shutdown:" ); - } - - String language = "java"; - String procedure = "HelloWorldProcedure.sayHello"; - StoredProcedureRequest req = new StoredProcedureRequest( 0, procedure, language ); - ctx.extendedOperation( req ); - ctx.close(); - } - - - private void processOptions( CommandLine cmd ) - { - if ( isDebugEnabled() ) - { - System.out.println( "Processing options for graceful shutdown ..." ); - } - - // ------------------------------------------------------------------- - // figure out and error check the port value - // ------------------------------------------------------------------- - - if ( cmd.hasOption( 'p' ) ) // - user provided port w/ -p takes precedence - { - String val = cmd.getOptionValue( 'p' ); - try - { - port = Integer.parseInt( val ); - } - catch ( NumberFormatException e ) - { - System.err.println( "port value of '" + val + "' is not a number" ); - System.exit( 1 ); - } - - if ( port > AvailablePortFinder.MAX_PORT_NUMBER ) - { - System.err.println( "port value of '" + val + "' is larger than max port number: " - + AvailablePortFinder.MAX_PORT_NUMBER ); - System.exit( 1 ); - } - else if ( port < AvailablePortFinder.MIN_PORT_NUMBER ) - { - System.err.println( "port value of '" + val + "' is smaller than the minimum port number: " - + AvailablePortFinder.MIN_PORT_NUMBER ); - System.exit( 1 ); - } - - if ( isDebugEnabled() ) - { - System.out.println( "port overriden by -p option: " + port ); - } - } - else if ( getConfiguration() != null ) - { - port = getConfiguration().getLdapPort(); - - if ( isDebugEnabled() ) - { - System.out.println( "port overriden by server.xml configuration: " + port ); - } - } - else if ( isDebugEnabled() ) - { - System.out.println( "port set to default: " + port ); - } - - // ------------------------------------------------------------------- - // figure out the host value - // ------------------------------------------------------------------- - - if ( cmd.hasOption( 'h' ) ) - { - host = cmd.getOptionValue( 'h' ); - - if ( isDebugEnabled() ) - { - System.out.println( "host overriden by -h option: " + host ); - } - } - else if ( isDebugEnabled() ) - { - System.out.println( "host set to default: " + host ); - } - - // ------------------------------------------------------------------- - // figure out the password value - // ------------------------------------------------------------------- - - if ( cmd.hasOption( 'w' ) ) - { - password = cmd.getOptionValue( 'w' ); - - if ( isDebugEnabled() ) - { - System.out.println( "password overriden by -w option: " + password ); - } - } - else if ( isDebugEnabled() ) - { - System.out.println( "password set to default: " + password ); - } - } - - - public Options getOptions() - { - Options opts = new Options(); - Option op = new Option( "h", "host", true, "server host: defaults to localhost" ); - op.setRequired( false ); - opts.addOption( op ); - op = new Option( "p", "port", true, "server port: defaults to 10389 or server.xml specified port" ); - op.setRequired( false ); - opts.addOption( op ); - op = new Option( "e", "delay", true, "delay (seconds) before shutdown: defaults to 0" ); - op.setRequired( false ); - opts.addOption( op ); - op = new Option( "w", "password", true, "the apacheds administrator's password: defaults to secret" ); - op.setRequired( false ); - opts.addOption( op ); - op = new Option( "t", "time-offline", true, "server offline time (minutes): defaults to 0 (indefinate)" ); - op.setRequired( false ); - opts.addOption( op ); - op = new Option( "i", "install-path", true, "path to apacheds installation directory" ); - op.setRequired( false ); - opts.addOption( op ); - return opts; - } -} Index: apacheds/server-tools/src/main/java/org/apache/directory/server/tools/ApachedsTools.java =================================================================== --- apacheds/server-tools/src/main/java/org/apache/directory/server/tools/ApachedsTools.java (revision 423936) +++ apacheds/server-tools/src/main/java/org/apache/directory/server/tools/ApachedsTools.java (working copy) @@ -16,14 +16,17 @@ */ package org.apache.directory.server.tools; + import java.io.IOException; -import java.net.URL; import java.util.Properties; import org.apache.commons.cli.CommandLine; -import org.apache.directory.server.configuration.ServerStartupConfiguration; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.FileSystemXmlApplicationContext; +import org.apache.directory.server.tools.execution.BaseToolCommandExecutor; +import org.apache.directory.server.tools.listeners.ExceptionListener; +import org.apache.directory.server.tools.listeners.SysErrListener; +import org.apache.directory.server.tools.listeners.SysOutListener; +import org.apache.directory.server.tools.request.BaseToolCommandCL; +import org.apache.directory.server.tools.util.ListenerParameter; /** @@ -34,10 +37,23 @@ */ public class ApachedsTools { - public static void main( String[] args ) throws Exception + public static void main( String[] args ) { - BaseCommand tools = getInstance(); - + ToolCommandListener outputListener = new SysOutListener(); + ToolCommandListener errorListener = new SysErrListener(); + ToolCommandListener exceptionListener = new ExceptionListener(); + + BaseCommand tools = null; + try + { + tools = getInstance(); + } + catch ( Exception e ) + { + System.err.println( "An error has occurred. Apache DS Tools must quit." + "\nError: " + e.getMessage() ); + System.exit( 1 ); + } + if ( !BaseCommand.hasBannerOption( args ) ) { tools.printBanner(); @@ -71,7 +87,7 @@ System.exit( 0 ); } - ToolCommand cmd = ( ToolCommand ) tools.getCommands().get( command ); + BaseToolCommandCL cmd = ( BaseToolCommandCL ) tools.getCommands().get( command ); if ( cmd == null ) { System.err.println( "Unknown command: " + args[0] ); @@ -91,29 +107,30 @@ cmd.setDebugEnabled( cmdline.hasOption( 'd' ) ); cmd.setVerboseEnabled( cmdline.hasOption( 'v' ) ); cmd.setVersion( tools.getProductVersion() ); - if ( cmdline.getOptionValue( 'i' ) != null ) + + if ( cmdline.hasOption( 'c' ) && ( cmdline.getOptionValue( 'i' ) == null ) ) { - cmd.setLayout( cmdline.getOptionValue( 'i' ) ); - if ( !cmd.isQuietEnabled() ) - { - System.out.println( "loading settings from: " + cmd.getLayout().getConfigurationFile() ); - } - ApplicationContext factory = null; - URL configUrl = cmd.getLayout().getConfigurationFile().toURL(); - factory = new FileSystemXmlApplicationContext( configUrl.toString() ); - cmd.setConfiguration( ( ServerStartupConfiguration ) factory.getBean( "configuration" ) ); + System.err.println( "forced configuration load (-c) requires the -i option" ); + System.exit( 1 ); } - else if ( cmdline.hasOption( 'c' ) ) + + try { - System.err.println( "forced configuration load (-c) requires the -i option" ); + cmd.execute( cmdline, new ListenerParameter[] + { new ListenerParameter( BaseToolCommandExecutor.OUTPUTLISTENER_PARAMETER, outputListener ), + new ListenerParameter( BaseToolCommandExecutor.ERRORLISTENER_PARAMETER, errorListener ), + new ListenerParameter( BaseToolCommandExecutor.EXCEPTIONLISTENER_PARAMETER, exceptionListener ) } ); + } + catch ( Exception e ) + { + System.err.println( "An error has occurred. Apache DS Tools must quit." + "\nError: " + e.getMessage() ); System.exit( 1 ); } - - cmd.execute( cmdline ); } - public static BaseCommand getInstance() throws InstantiationException, IllegalAccessException, ClassNotFoundException + public static BaseCommand getInstance() throws InstantiationException, IllegalAccessException, + ClassNotFoundException { Properties props = new Properties(); try @@ -131,7 +148,7 @@ String productCommand = props.getProperty( "product.command", "apacheds-tools" ); String productBanner = props.getProperty( "product.banner", BaseCommand.BANNER ); String productClass = props.getProperty( "product.class", "org.apache.directory.server.tools.BaseCommand" ); - + BaseCommand baseCommand = ( BaseCommand ) Class.forName( productClass ).newInstance(); baseCommand.setProductBanner( productBanner ); baseCommand.setProductDisplayName( productDisplayName ); Index: apacheds/server-tools/src/main/java/org/apache/directory/server/tools/BaseCommand.java =================================================================== --- apacheds/server-tools/src/main/java/org/apache/directory/server/tools/BaseCommand.java (revision 423936) +++ apacheds/server-tools/src/main/java/org/apache/directory/server/tools/BaseCommand.java (working copy) @@ -16,6 +16,7 @@ */ package org.apache.directory.server.tools; + import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; @@ -33,7 +34,16 @@ import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.apache.commons.cli.UnrecognizedOptionException; +import org.apache.directory.server.tools.commands.diagnosticcmd.DiagnosticCommandCL; +import org.apache.directory.server.tools.commands.disconnectnotificationcmd.DisconnectNotificationCommandCL; +import org.apache.directory.server.tools.commands.dumpcmd.DumpCommandCL; +import org.apache.directory.server.tools.commands.exportcmd.ExportCommandCL; +import org.apache.directory.server.tools.commands.gracefulshutdowncmd.GracefulShutdownCommandCL; +import org.apache.directory.server.tools.commands.importcmd.ImportCommandCL; +import org.apache.directory.server.tools.commands.storedprocedurecmd.StoredProcedureCommandCL; +import org.apache.directory.server.tools.request.BaseToolCommandCL; + /** * The primary command base class. * @@ -58,35 +68,45 @@ private String productBanner; + public BaseCommand() { init(); } + protected void init() { - ToolCommand command; + BaseToolCommandCL command; - command = new DiagnosticCommand(); + command = new DiagnosticCommandCL(); commands.put( command.getName(), command ); commandsOrdered.add( command.getName() ); - command = new DumpCommand(); + command = new DumpCommandCL(); commands.put( command.getName(), command ); commandsOrdered.add( command.getName() ); - command = new GracefulShutdownCommand(); + command = new GracefulShutdownCommandCL(); commands.put( command.getName(), command ); commandsOrdered.add( command.getName() ); - command = new ImportCommand(); + command = new ImportCommandCL(); commands.put( command.getName(), command ); commandsOrdered.add( command.getName() ); - command = new DisconnectNotificationCommand(); + command = new DisconnectNotificationCommandCL(); commands.put( command.getName(), command ); commandsOrdered.add( command.getName() ); + command = new ExportCommandCL(); + commands.put( command.getName(), command ); + commandsOrdered.add( command.getName() ); + + command = new StoredProcedureCommandCL(); + commands.put( command.getName(), command ); + commandsOrdered.add( command.getName() ); + Option op = new Option( "i", "install-path", true, "path to installation directory" ); getGlobal().addOption( op ); op = new Option( "b", "banner", false, "suppress banner print outs" ); @@ -103,6 +123,7 @@ getGlobal().addOption( op ); } + public static boolean hasBannerOption( String[] args ) { for ( int ii = 0; ii < args.length; ii++ ) @@ -115,6 +136,7 @@ return false; } + public CommandLine getCommandLine( String command, String[] args ) { Options all = allOptions( command ); @@ -124,30 +146,31 @@ { cmdline = parser.parse( all, args ); } - catch (AlreadySelectedException ase) + catch ( AlreadySelectedException ase ) { System.err.println( "Command line parsing failed for " + command + ". Reason: already selected " - + ase.getMessage() ); + + ase.getMessage() ); System.exit( 1 ); } - catch (MissingArgumentException mae) + catch ( MissingArgumentException mae ) { System.err.println( "Command line parsing failed for " + command + ". Reason: missing argument " - + mae.getMessage() ); + + mae.getMessage() ); System.exit( 1 ); } - catch (MissingOptionException moe) + catch ( MissingOptionException moe ) { - System.err.println( "Command line parsing failed for " + command + ". Reason: missing option " + moe.getMessage() ); + System.err.println( "Command line parsing failed for " + command + ". Reason: missing option " + + moe.getMessage() ); System.exit( 1 ); } - catch (UnrecognizedOptionException uoe) + catch ( UnrecognizedOptionException uoe ) { System.err.println( "Command line parsing failed for " + command + ". Reason: unrecognized option" - + uoe.getMessage() ); + + uoe.getMessage() ); System.exit( 1 ); } - catch (ParseException pe) + catch ( ParseException pe ) { System.err.println( "Command line parsing failed for " + command + ". Reason: " + pe.getClass() ); System.exit( 1 ); @@ -156,6 +179,7 @@ return cmdline; } + public Options allOptions( String command ) { if ( command.equals( "help" ) ) @@ -164,20 +188,21 @@ } Options all = new Options(); - ToolCommand cmd = (ToolCommand) getCommands().get( command ); + BaseToolCommandCL cmd = ( BaseToolCommandCL ) getCommands().get( command ); for ( Iterator ii = getGlobal().getOptions().iterator(); ii.hasNext(); ) { - all.addOption( (Option) ii.next() ); + all.addOption( ( Option ) ii.next() ); } for ( Iterator ii = cmd.getOptions().getOptions().iterator(); ii.hasNext(); ) { - all.addOption( (Option) ii.next() ); + all.addOption( ( Option ) ii.next() ); } return all; } + public static void dumpArgs( String msg, String[] args ) { if ( args.length == 0 ) @@ -197,6 +222,7 @@ System.out.println( buf ); } + public void helpOnCommand( String command ) { if ( command.equals( "help" ) ) @@ -207,7 +233,7 @@ if ( getCommands().containsKey( command ) ) { - ToolCommand cmd = (ToolCommand) getCommands().get( command ); + BaseToolCommandCL cmd = ( BaseToolCommandCL ) getCommands().get( command ); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp( getProductCommand() + " " + cmd + " [options]", cmd.getOptions() ); } @@ -218,11 +244,12 @@ } } + public void printUsage() { HelpFormatter formatter = new HelpFormatter(); - formatter.printHelp( getProductCommand() + " [options]", "\nGlobal options:", getGlobal(), "\nType \"" - + getProductCommand() + " help \" for help on a command." ); + formatter.printHelp( getProductCommand() + " [options]", "\nGlobal options:", getGlobal(), + "\nType \"" + getProductCommand() + " help \" for help on a command." ); System.out.println( "\nAvailable commands:" ); Iterator it = commandsOrdered.iterator(); @@ -238,82 +265,97 @@ } static final String BANNER = " _ _ ____ ____ _____ _ \n" - + " / \\ _ __ __ _ ___| |__ ___| _ \\/ ___| |_ _|__ ___ | |___ \n" - + " / _ \\ | '_ \\ / _` |/ __| '_ \\ / _ \\ | | \\___ \\ | |/ _ \\ / _ \\| / __| \n" - + " / ___ \\| |_) | (_| | (__| | | | __/ |_| |___) | | | (_) | (_) | \\__ \\ \n" - + " /_/ \\_\\ .__/ \\__,_|\\___|_| |_|\\___|____/|____/ |_|\\___/ \\___/|_|___/ \n" - + " |_| \n"; + + " / \\ _ __ __ _ ___| |__ ___| _ \\/ ___| |_ _|__ ___ | |___ \n" + + " / _ \\ | '_ \\ / _` |/ __| '_ \\ / _ \\ | | \\___ \\ | |/ _ \\ / _ \\| / __| \n" + + " / ___ \\| |_) | (_| | (__| | | | __/ |_| |___) | | | (_) | (_) | \\__ \\ \n" + + " /_/ \\_\\ .__/ \\__,_|\\___|_| |_|\\___|____/|____/ |_|\\___/ \\___/|_|___/ \n" + + " |_| \n"; + public void printBanner() { System.out.println( getProductBanner() ); } + public void setProductCommand( String productCommand ) { this.productCommand = productCommand; } + public String getProductCommand() { return productCommand; } + public void setProductVersion( String productVersion ) { this.productVersion = productVersion; } + public String getProductVersion() { return productVersion; } + public void setProductDisplayName( String productDisplayName ) { this.productDisplayName = productDisplayName; } + public String getProductDisplayName() { return productDisplayName; } + public void setProductUrl( String productUrl ) { this.productUrl = productUrl; } + public String getProductUrl() { return productUrl; } + public void setProductBanner( String productBanner ) { this.productBanner = productBanner; } + public String getProductBanner() { return productBanner; } + public void setCommands( Map commands ) { this.commands = commands; } + public Map getCommands() { return commands; } + public void setGlobal( Options global ) { this.global = global; } + public Options getGlobal() { return global; Index: apacheds/server-tools/src/main/java/org/apache/directory/server/tools/ImportCommand.java =================================================================== --- apacheds/server-tools/src/main/java/org/apache/directory/server/tools/ImportCommand.java (revision 423936) +++ apacheds/server-tools/src/main/java/org/apache/directory/server/tools/ImportCommand.java (working copy) @@ -1,972 +0,0 @@ -/* - * Copyright 2004 The Apache Software Foundation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package org.apache.directory.server.tools; - -import java.io.File; -import java.io.IOException; -import java.net.InetSocketAddress; -import java.net.SocketAddress; -import java.net.UnknownHostException; -import java.nio.ByteBuffer; -import java.nio.channels.SocketChannel; -import java.util.Iterator; - -import javax.naming.InvalidNameException; -import javax.naming.NamingEnumeration; -import javax.naming.NamingException; -import javax.naming.directory.Attribute; -import javax.naming.directory.Attributes; -import javax.naming.directory.DirContext; -import javax.naming.directory.ModificationItem; - -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.Option; -import org.apache.commons.cli.Options; -import org.apache.directory.daemon.AvailablePortFinder; -import org.apache.directory.shared.asn1.ber.Asn1Decoder; -import org.apache.directory.shared.asn1.ber.IAsn1Container; -import org.apache.directory.shared.asn1.ber.tlv.TLVStateEnum; -import org.apache.directory.shared.asn1.codec.DecoderException; -import org.apache.directory.shared.asn1.codec.EncoderException; -import org.apache.directory.shared.ldap.ldif.Entry; -import org.apache.directory.shared.ldap.ldif.LdifReader; -import org.apache.directory.shared.ldap.name.LdapDN; -import org.apache.directory.shared.ldap.name.Rdn; -import org.apache.directory.shared.ldap.util.StringTools; -import org.apache.directory.shared.ldap.codec.LdapConstants; -import org.apache.directory.shared.ldap.codec.LdapDecoder; -import org.apache.directory.shared.ldap.codec.LdapMessage; -import org.apache.directory.shared.ldap.codec.LdapMessageContainer; -import org.apache.directory.shared.ldap.codec.LdapResult; -import org.apache.directory.shared.ldap.codec.add.AddRequest; -import org.apache.directory.shared.ldap.codec.bind.BindRequest; -import org.apache.directory.shared.ldap.codec.bind.BindResponse; -import org.apache.directory.shared.ldap.codec.bind.LdapAuthentication; -import org.apache.directory.shared.ldap.codec.bind.SimpleAuthentication; -import org.apache.directory.shared.ldap.codec.del.DelRequest; -import org.apache.directory.shared.ldap.codec.extended.ExtendedResponse; -import org.apache.directory.shared.ldap.codec.modify.ModifyRequest; -import org.apache.directory.shared.ldap.codec.modifyDn.ModifyDNRequest; -import org.apache.directory.shared.ldap.codec.unbind.UnBindRequest; -import org.apache.directory.shared.ldap.codec.util.LdapResultEnum; - -/** - * A command to import data into a server. The data to be imported must be - * stored in a Ldif File, and they could be added entries or modified entries. - * - * @author Apache Directory Project - * @version $Rev: 406112 $ - */ -public class ImportCommand extends ToolCommand -{ - public static final String PORT_RANGE = "(" + AvailablePortFinder.MIN_PORT_NUMBER + ", " - + AvailablePortFinder.MAX_PORT_NUMBER + ")"; - - private int port = 10389; - - private String host = "localhost"; - - private String password = "secret"; - - private String user = "uid=admin,ou=system"; - - private String auth = "simple"; - - private File ldifFile; - - private String logs; - - private boolean ignoreErrors = false; - - private static final int IMPORT_ERROR = -1; - private static final int IMPORT_SUCCESS= 0; - - /** - * Socket used to connect to the server - */ - private SocketChannel channel; - - private SocketAddress serverAddress; - - private IAsn1Container ldapMessageContainer = new LdapMessageContainer(); - - private Asn1Decoder ldapDecoder = new LdapDecoder(); - - /** - * The constructor save the command's name into it's super class - * - */ - protected ImportCommand() - { - super( "import" ); - } - - /** - * Connect to the LDAP server through a socket and establish the Input and - * Output Streams. All the required information for the connection should be - * in the options from the command line, or the default values. - * - * @throws UnknownHostException - * The hostname or the Address of server could not be found - * @throws IOException - * There was a error opening or establishing the socket - */ - private void connect() throws UnknownHostException, IOException - { - serverAddress = new InetSocketAddress( host, port ); - channel = SocketChannel.open( serverAddress ); - channel.configureBlocking( true ); - } - - private void sendMessage( ByteBuffer bb ) throws IOException - { - channel.write( bb ); - bb.clear(); - } - - private LdapMessage readResponse( ByteBuffer bb ) throws IOException, DecoderException, NamingException - { - - LdapMessage messageResp = null; - - while ( true ) - { - int nbRead = channel.read( bb ); - - if ( nbRead == -1 ) - { - break; - } - else - { - bb.flip(); - - // Decode the PDU - ldapDecoder.decode( bb, ldapMessageContainer ); - - if ( ldapMessageContainer.getState() == TLVStateEnum.PDU_DECODED ) - { - messageResp = ( (LdapMessageContainer) ldapMessageContainer ).getLdapMessage(); - - if ( messageResp instanceof BindResponse ) - { - BindResponse resp = ( (LdapMessageContainer) ldapMessageContainer ).getLdapMessage().getBindResponse(); - - if ( resp.getLdapResult().getResultCode() != 0 ) - { - System.out.println( "Error : " + resp.getLdapResult().getErrorMessage() ); - } - } - else if ( messageResp instanceof ExtendedResponse ) - { - ExtendedResponse resp = ( (LdapMessageContainer) ldapMessageContainer ).getLdapMessage() - .getExtendedResponse(); - - if ( resp.getLdapResult().getResultCode() != 0 ) - { - System.out.println( "Error : " + resp.getLdapResult().getErrorMessage() ); - } - } - - ( (LdapMessageContainer) ldapMessageContainer ).clean(); - break; - } - else - { - bb.flip(); - } - } - } - - return messageResp; - - } - - /** - * Send the entry to the encoder, then wait for a - * reponse from the LDAP server on the results of the operation. - * - * @param entry - * The entry to add - * @param msgId - * message id number - */ - private int addEntry( Entry entry, int messageId ) throws IOException, DecoderException, InvalidNameException, - NamingException, EncoderException - { - AddRequest addRequest = new AddRequest(); - - String dn = entry.getDn(); - - if ( isDebugEnabled() ) - { - System.out.println( "Adding entry " + dn ); - } - - Attributes attributes = entry.getAttributes(); - - addRequest.setEntry( new LdapDN( dn ) ); - - // Copy the attributes - addRequest.initAttributes(); - - for ( NamingEnumeration attrs = attributes.getAll(); attrs.hasMoreElements(); ) - { - Attribute attribute = (Attribute) attrs.nextElement(); - - addRequest.addAttributeType( attribute.getID() ); - - for ( NamingEnumeration values = attribute.getAll(); values.hasMoreElements(); ) - { - Object value = values.nextElement(); - addRequest.addAttributeValue( value ); - } - } - - LdapMessage message = new LdapMessage(); - - message.setProtocolOP( addRequest ); - message.setMessageId( messageId ); - - // Encode and send the addRequest message - ByteBuffer bb = message.encode( null ); - bb.flip(); - - sendMessage( bb ); - - bb.clear(); - - // Get the response - LdapMessage response = readResponse( bb ); - - LdapResult result = response.getAddResponse().getLdapResult(); - - if ( result.getResultCode() == LdapResultEnum.SUCCESS ) - { - if ( isDebugEnabled() ) - { - System.out.println( "Add of Entry " + entry.getDn() + " was successful" ); - } - - return IMPORT_SUCCESS; - } - else - { - System.err.println( "Add of entry " + entry.getDn() + " failed for the following reasons provided by the server:\n" - + result.getErrorMessage() ); - - return IMPORT_ERROR; - } - } - - /** - * Send the entry to the encoder, then wait for a - * reponse from the LDAP server on the results of the operation. - * - * @param entry - * The entry to delete - * @param msgId - * message id number - */ - private int deleteEntry( Entry entry, int messageId ) throws IOException, DecoderException, InvalidNameException, - NamingException, EncoderException - { - DelRequest delRequest = new DelRequest(); - - String dn = entry.getDn(); - - if ( isDebugEnabled() ) - { - System.out.println( "Deleting entry " + dn ); - } - - delRequest.setEntry( new LdapDN( dn ) ); - - LdapMessage message = new LdapMessage(); - - message.setProtocolOP( delRequest ); - message.setMessageId( messageId ); - - // Encode and send the delete request - ByteBuffer bb = message.encode( null ); - bb.flip(); - - sendMessage( bb ); - - bb.clear(); - - // Get the response - LdapMessage response = readResponse( bb ); - - LdapResult result = response.getDelResponse().getLdapResult(); - - if ( result.getResultCode() == LdapResultEnum.SUCCESS ) - { - if ( isDebugEnabled() ) - { - System.out.println( "Delete of Entry " + entry.getDn() + " was successful" ); - } - - return IMPORT_SUCCESS; - } - else - { - System.err.println( "Delete of entry " + entry.getDn() + " failed for the following reasons provided by the server:\n" - + result.getErrorMessage() ); - return IMPORT_ERROR; - } - } - - /** - * Send the entry to the encoder, then wait for a - * reponse from the LDAP server on the results of the operation. - * - * @param entry - * The entry to modify - * @param msgId - * message id number - */ - private int changeModRDNEntry( Entry entry, int messageId ) throws IOException, DecoderException, InvalidNameException, - NamingException, EncoderException - { - ModifyDNRequest modifyDNRequest = new ModifyDNRequest(); - - String dn = entry.getDn(); - - if ( isDebugEnabled() ) - { - System.out.println( "Modify DN of entry " + dn ); - } - - modifyDNRequest.setEntry( new LdapDN( dn ) ); - modifyDNRequest.setDeleteOldRDN( entry.isDeleteOldRdn() ); - modifyDNRequest.setNewRDN( new Rdn( entry.getNewRdn() ) ); - - if ( StringTools.isEmpty( entry.getNewSuperior() ) == false ) - { - modifyDNRequest.setNewSuperior( new LdapDN( entry.getNewSuperior() ) ); - } - - LdapMessage message = new LdapMessage(); - - message.setProtocolOP( modifyDNRequest ); - message.setMessageId( messageId ); - - // Encode and send the delete request - ByteBuffer bb = message.encode( null ); - bb.flip(); - - sendMessage( bb ); - - bb.clear(); - - // Get the response - LdapMessage response = readResponse( bb ); - - LdapResult result = response.getModifyDNResponse().getLdapResult(); - - if ( result.getResultCode() == LdapResultEnum.SUCCESS ) - { - if ( isDebugEnabled() ) - { - System.out.println( "ModifyDn of Entry " + entry.getDn() + " was successful" ); - } - - return IMPORT_SUCCESS; - } - else - { - System.err.println( "ModifyDn of entry " + entry.getDn() + " failed for the following reasons provided by the server:\n" - + result.getErrorMessage() ); - return IMPORT_ERROR; - } - } - - /** - * Send the entry to the encoder, then wait for a - * reponse from the LDAP server on the results of the operation. - * - * @param entry - * The entry to modify - * @param msgId - * message id number - */ - private int changeModifyEntry( Entry entry, int messageId ) throws IOException, DecoderException, InvalidNameException, - NamingException, EncoderException - { - ModifyRequest modifyRequest = new ModifyRequest(); - - String dn = entry.getDn(); - - if ( isDebugEnabled() ) - { - System.out.println( "Modify of entry " + dn ); - } - - modifyRequest.setObject( new LdapDN( dn ) ); - modifyRequest.initModifications(); - - Iterator modifications = entry.getModificationItems().iterator(); - - while ( modifications.hasNext() ) - { - ModificationItem modification = (ModificationItem)modifications.next(); - - switch ( modification.getModificationOp() ) - { - case DirContext.ADD_ATTRIBUTE : - modifyRequest.setCurrentOperation( LdapConstants.OPERATION_ADD ); - break; - - case DirContext.REMOVE_ATTRIBUTE : - modifyRequest.setCurrentOperation( LdapConstants.OPERATION_DELETE ); - break; - - case DirContext.REPLACE_ATTRIBUTE : - modifyRequest.setCurrentOperation( LdapConstants.OPERATION_REPLACE ); - break; - - default : - System.err.println( "Unknown modify operation for DN " + dn ); - } - - modifyRequest.addAttributeTypeAndValues( modification.getAttribute().getID() ); - - for ( NamingEnumeration values = modification.getAttribute().getAll(); values.hasMoreElements(); ) - { - Object value = values.nextElement(); - modifyRequest.addAttributeValue( value ); - } - } - - LdapMessage message = new LdapMessage(); - - message.setProtocolOP( modifyRequest ); - message.setMessageId( messageId ); - - // Encode and send the delete request - ByteBuffer bb = message.encode( null ); - bb.flip(); - - sendMessage( bb ); - - bb.clear(); - - // Get the response - LdapMessage response = readResponse( bb ); - - LdapResult result = response.getModifyResponse().getLdapResult(); - - if ( result.getResultCode() == LdapResultEnum.SUCCESS ) - { - if ( isDebugEnabled() ) - { - System.out.println( "Modify of Entry " + entry.getDn() + " was successful" ); - } - - return IMPORT_SUCCESS; - } - else - { - System.err.println( "Modify of entry " + entry.getDn() + " failed for the following reasons provided by the server:\n" - + result.getErrorMessage() ); - return IMPORT_ERROR; - } - } - - /** - * Send the change operation to the encoder, then wait for a - * reponse from the LDAP server on the results of the operation. - * - * @param entry - * The entry to add - * @param msgId - * message id number - */ - private int changeEntry( Entry entry, int messageId ) throws IOException, DecoderException, InvalidNameException, - NamingException, EncoderException - { - switch ( entry.getChangeType() ) - { - case Entry.ADD : - // No difference with the injection of new entries - return addEntry( entry, messageId ); - - case Entry.DELETE : - return deleteEntry( entry, messageId ); - - case Entry.MODIFY : - return changeModifyEntry( entry, messageId ); - - case Entry.MODDN : - case Entry.MODRDN : - return changeModRDNEntry( entry, messageId ); - - default : - return IMPORT_ERROR; - } - } - - /** - * Bind to the ldap server - * - * @param messageId The message Id - */ - private void bind( int messageId ) throws NamingException, EncoderException, DecoderException, IOException - { - BindRequest bindRequest = new BindRequest(); - LdapMessage message = new LdapMessage(); - LdapAuthentication authentication = null; - - if ( "simple".equals( auth ) ) - { - authentication = new SimpleAuthentication(); - ( (SimpleAuthentication) authentication ).setSimple( StringTools.getBytesUtf8( password ) ); - } - - bindRequest.setAuthentication( authentication ); - bindRequest.setName( new LdapDN( user ) ); - bindRequest.setVersion( 3 ); - - message.setProtocolOP( bindRequest ); - message.setMessageId( messageId ); - - // Encode and send the bind request - ByteBuffer bb = message.encode( null ); - bb.flip(); - - connect(); - sendMessage( bb ); - - bb.clear(); - - // Get the bind response - LdapMessage response = readResponse( bb ); - - LdapResult result = response.getBindResponse().getLdapResult(); - - if ( result.getResultCode() == LdapResultEnum.SUCCESS ) - { - if ( isDebugEnabled() ) - { - System.out.println( "Binding of user " + user + " was successful" ); - } - } - else - { - System.err.println( "Binding of user " + user + " failed for the following reasons provided by the server:\n" - + result.getErrorMessage() ); - System.exit( 1 ); - } - } - - /** - * Unbind from the server - * - * @param messageId - * The message Id - * @throws InvalidNameException - * @throws EncoderException - * @throws DecoderException - * @throws IOException - */ - private void unbind( int messageId ) throws InvalidNameException, EncoderException, DecoderException, IOException - { - UnBindRequest unbindRequest = new UnBindRequest(); - LdapMessage message = new LdapMessage(); - - message.setProtocolOP( unbindRequest ); - message.setMessageId( messageId ); - ByteBuffer bb = message.encode( null ); - bb.flip(); - - sendMessage( bb ); - - if ( isDebugEnabled() ) - { - System.out.println( "Unbinding of user " + user + " was successful" ); - } - } - - /** - * Execute the command - * - * @param cmd - * The command to be executed - */ - public void execute( CommandLine cmd ) throws Exception - { - processOptions( cmd ); - - if ( isDebugEnabled() ) - { - System.out.println( "Parameters for Ldif import request:" ); - System.out.println( "port = " + port ); - System.out.println( "host = " + host ); - System.out.println( "user = " + user ); - System.out.println( "auth type = " + auth ); - System.out.println( "file = " + ldifFile ); - System.out.println( "logs = " + logs ); - } - - int messageId = 0; - - // Login to the server - bind( messageId++ ); - - if ( isDebugEnabled() ) - { - System.out.println( "Connection to the server established.\n" + "Importing data ... " ); - } - - LdifReader ldifReader = new LdifReader( ldifFile ); - - if ( ldifReader.containsEntries() ) - { - // Parse the file and inject every entry - Iterator entries = ldifReader.iterator(); - long t0 = System.currentTimeMillis(); - int nbAdd = 0; - - while ( entries.hasNext() ) - { - Entry entry = (Entry) entries.next(); - - // Check if we have had some error, has next() does not throw any exception - if ( ldifReader.hasError() ) - { - System.err.println( "Found an error while persing an entry : " + ldifReader.getError().getMessage() ); - - if ( ignoreErrors == false ) - { - unbind( messageId ); - - System.err.println( "Import failed..." ); - System.exit( 1 ); - } - } - - if ( ( addEntry( entry, messageId++ ) == IMPORT_ERROR ) && - ( ignoreErrors == false ) ) - { - unbind( messageId ); - - System.err.println( "Import failed..." ); - System.exit( 1 ); - } - - nbAdd++; - - if ( nbAdd % 10 == 0 ) - { - System.out.print( '.' ); - } - - if ( nbAdd % 500 == 0 ) - { - System.out.println( nbAdd ); - } - } - - long t1 = System.currentTimeMillis(); - - System.out.println( "Done!" ); - System.out.println( nbAdd + " users added in " + ( ( t1 - t0 ) / 1000 ) + " seconds" ); - } - else - { - // Parse the file and inject every modification - Iterator entries = ldifReader.iterator(); - long t0 = System.currentTimeMillis(); - int nbMod = 0; - - while ( entries.hasNext() ) - { - Entry entry = (Entry) entries.next(); - - // Check if we have had some error, has next() does not throw any exception - if ( ldifReader.hasError() ) - { - System.err.println( "Found an error while persing an entry : " + ldifReader.getError().getMessage() ); - - if ( ignoreErrors == false ) - { - unbind( messageId ); - - System.err.println( "Import failed..." ); - System.exit( 1 ); - } - } - - if ( ( changeEntry( entry, messageId++ ) == IMPORT_ERROR ) && - ( ignoreErrors == false ) ) - { - unbind( messageId ); - - System.err.println( "Import failed..." ); - System.exit( 1 ); - } - - nbMod++; - - if ( nbMod % 10 == 0 ) - { - System.out.print( '.' ); - } - - if ( nbMod % 500 == 0 ) - { - System.out.println( nbMod ); - } - } - - long t1 = System.currentTimeMillis(); - - System.out.println( "Done!" ); - System.out.println( nbMod + " users changed in " + ( ( t1 - t0 ) / 1000 ) + " seconds" ); - } - - // Logout to the server - unbind( messageId++ ); - - } - - /** - * Read the command line and get the options : 'h' : host 'p' : port 'u' : - * user 'w' : password 'a' : authentication type 'i' : ignore errors 'f' : - * ldif file to import - * - * @param cmd - * The command line - */ - private void processOptions( CommandLine cmd ) - { - if ( isDebugEnabled() ) - { - System.out.println( "Processing options for launching diagnostic UI ..." ); - } - - // ------------------------------------------------------------------- - // figure out the host value - // ------------------------------------------------------------------- - - if ( cmd.hasOption( 'h' ) ) - { - host = cmd.getOptionValue( 'h' ); - - if ( isDebugEnabled() ) - { - System.out.println( "ignore-errors overriden by -i option: true" ); - } - } - else if ( isDebugEnabled() ) - { - System.out.println( "ignore-errors set to default: false" ); - } - - // ------------------------------------------------------------------- - // figure out and error check the port value - // ------------------------------------------------------------------- - - if ( cmd.hasOption( 'p' ) ) // - user provided port w/ -p takes - // precedence - { - String val = cmd.getOptionValue( 'p' ); - - try - { - port = Integer.parseInt( val ); - } - catch (NumberFormatException e) - { - System.err.println( "port value of '" + val + "' is not a number" ); - System.exit( 1 ); - } - - if ( port > AvailablePortFinder.MAX_PORT_NUMBER ) - { - System.err.println( "port value of '" + val + "' is larger than max port number: " - + AvailablePortFinder.MAX_PORT_NUMBER ); - System.exit( 1 ); - } - else if ( port < AvailablePortFinder.MIN_PORT_NUMBER ) - { - System.err.println( "port value of '" + val + "' is smaller than the minimum port number: " - + AvailablePortFinder.MIN_PORT_NUMBER ); - System.exit( 1 ); - } - - if ( isDebugEnabled() ) - { - System.out.println( "port overriden by -p option: " + port ); - } - } - else if ( getConfiguration() != null ) - { - port = getConfiguration().getLdapPort(); - - if ( isDebugEnabled() ) - { - System.out.println( "port overriden by server.xml configuration: " + port ); - } - } - else if ( isDebugEnabled() ) - { - System.out.println( "port set to default: " + port ); - } - - // ------------------------------------------------------------------- - // figure out the user value - // ------------------------------------------------------------------- - - if ( cmd.hasOption( 'u' ) ) - { - user = cmd.getOptionValue( 'u' ); - - if ( isDebugEnabled() ) - { - System.out.println( "user overriden by -u option: " + user ); - } - } - else if ( isDebugEnabled() ) - { - System.out.println( "user set to default: " + user ); - } - - // ------------------------------------------------------------------- - // figure out the password value - // ------------------------------------------------------------------- - - if ( cmd.hasOption( 'w' ) ) - { - password = cmd.getOptionValue( 'w' ); - - if ( isDebugEnabled() ) - { - System.out.println( "password overriden by -w option: " + password ); - } - } - else if ( isDebugEnabled() ) - { - System.out.println( "password set to default: " + password ); - } - - // ------------------------------------------------------------------- - // figure out the authentication type - // ------------------------------------------------------------------- - - if ( cmd.hasOption( 'a' ) ) - { - auth = cmd.getOptionValue( 'a' ); - - if ( isDebugEnabled() ) - { - System.out.println( "authentication type overriden by -a option: " + auth ); - } - } - else if ( isDebugEnabled() ) - { - System.out.println( "authentication type set to default: " + auth ); - } - - // ------------------------------------------------------------------- - // figure out the 'ignore-errors' flag - // ------------------------------------------------------------------- - - if ( cmd.hasOption( 'e' ) ) - { - ignoreErrors = true; - - if ( isDebugEnabled() ) - { - System.out.println( "authentication type overriden by -a option: " + auth ); - } - } - else if ( isDebugEnabled() ) - { - System.out.println( "authentication type set to default: " + auth ); - } - - // ------------------------------------------------------------------- - // figure out the ldif file to import - // ------------------------------------------------------------------- - - if ( cmd.hasOption( 'f' ) ) - { - String ldifFileName = cmd.getOptionValue( 'f' ); - - ldifFile = new File( ldifFileName ); - - if ( ldifFile.exists() == false ) - { - System.err.println( "ldif file '" + ldifFileName + "' does not exist" ); - System.exit( 1 ); - } - - if ( ldifFile.canRead() == false ) - { - System.err.println( "ldif file '" + ldifFileName + "' can't be read" ); - System.exit( 1 ); - } - - if ( isDebugEnabled() ) - { - try - { - System.out.println( "ldif file to import: " + ldifFile.getCanonicalPath() ); - } - catch (IOException ioe) - { - System.out.println( "ldif file to import: " + ldifFileName ); - } - } - } - else - { - System.err.println( "ldif file name must be provided" ); - System.exit( 1 ); - } - } - - public Options getOptions() - { - Options opts = new Options(); - Option op = new Option( "h", "host", true, "server host: defaults to localhost" ); - op.setRequired( false ); - opts.addOption( op ); - op = new Option( "p", "port", true, "server port: defaults to 10389 or server.xml specified port" ); - op.setRequired( false ); - opts.addOption( op ); - op = new Option( "u", "user", true, "the user: default to uid=admin, ou=system" ); - op.setRequired( false ); - opts.addOption( op ); - op = new Option( "w", "password", true, "the apacheds administrator's password: defaults to secret" ); - op.setRequired( false ); - opts.addOption( op ); - op = new Option( "a", "auth", true, "the authentication mode: defaults to 'simple'" ); - op.setRequired( false ); - opts.addOption( op ); - op = new Option( "f", "file", true, "the ldif file to import" ); - op.setRequired( true ); - opts.addOption( op ); - op = new Option( "e", "ignore", false, "continue to process the file even if errors are encountered " ); - op.setRequired( false ); - opts.addOption( op ); - - return opts; - } -} Index: apacheds/server-tools/src/main/java/org/apache/directory/server/tools/ToolCommand.java =================================================================== --- apacheds/server-tools/src/main/java/org/apache/directory/server/tools/ToolCommand.java (revision 423936) +++ apacheds/server-tools/src/main/java/org/apache/directory/server/tools/ToolCommand.java (working copy) @@ -17,135 +17,15 @@ package org.apache.directory.server.tools; -import java.io.File; - -import org.apache.commons.cli.CommandLine; -import org.apache.commons.cli.Options; -import org.apache.directory.daemon.InstallationLayout; -import org.apache.directory.server.configuration.ServerStartupConfiguration; - - /** - * Simple base class for tool commands. - * - * @author Apache Directory Project - * @version $Rev$ + * Interface that must be extended by every type of command. */ -public abstract class ToolCommand +public interface ToolCommand { - private final String name; - private boolean debugEnabled = false; - private boolean verboseEnabled = false; - private boolean quietEnabled = false; - private String version; - private InstallationLayout layout; - private ServerStartupConfiguration configuration; - - - protected ToolCommand(String name) - { - this.name = name; - } - - - public abstract void execute( CommandLine cmd ) throws Exception; - - - public abstract Options getOptions(); - - - public String getName() - { - return this.name; - } - - - public void setLayout( File installationDirectory ) - { - this.layout = new InstallationLayout( installationDirectory ); - } - - - public void setLayout( String installationPath ) - { - this.layout = new InstallationLayout( installationPath ); - } - - - public void setLayout( InstallationLayout layout ) - { - this.layout = layout; - } - - - public InstallationLayout getLayout() - { - return layout; - } - - - public void setConfiguration( ServerStartupConfiguration configuration ) - { - this.configuration = configuration; - } - - - public ServerStartupConfiguration getConfiguration() - { - return configuration; - } - - - public void setVersion( String version ) - { - this.version = version; - } - - - public String getVersion() - { - return version; - } - - - public String toString() - { - return getName(); - } - - - public void setDebugEnabled( boolean debugEnabled ) - { - this.debugEnabled = debugEnabled; - } - - - public boolean isDebugEnabled() - { - return debugEnabled; - } - - - public void setVerboseEnabled( boolean verboseEnabled ) - { - this.verboseEnabled = verboseEnabled; - } - - - public boolean isVerboseEnabled() - { - return verboseEnabled; - } - - - public void setQuietEnabled( boolean quietEnabled ) - { - this.quietEnabled = quietEnabled; - } - - - public boolean isQuietEnabled() - { - return quietEnabled; - } + // Default values + public final static int DEFAULT_PORT = 10389; + public final static String DEFAULT_HOST = "localhost"; + public final static String DEFAULT_PASSWORD = "secret"; + public final static String DEFAULT_USER = "uid=admin,ou=system"; + public final static String DEFAULT_AUTH = "simple"; }