directory-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From pamarce...@apache.org
Subject svn commit: r643845 [1/2] - in /directory/apacheds/branches/bigbang/server-tools/src: main/java/org/apache/directory/server/tools/ main/java/org/apache/directory/server/tools/commands/ main/java/org/apache/directory/server/tools/execution/ main/java/or...
Date Wed, 02 Apr 2008 11:03:08 GMT
Author: pamarcelot
Date: Wed Apr  2 04:02:57 2008
New Revision: 643845

URL: http://svn.apache.org/viewvc?rev=643845&view=rev
Log:
Updated Server Tools.
    o Removed the design pattern that was set up for eventual remote invocation
    o Copied the Server Tools implementation from the Apache DS 1.0 branch (with slight modification due to API changes)
This commit includes the Index and CapacityTest commands (that were added in the 1.0 branch).

Added:
    directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/DiagnosticCommand.java
    directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/DisconnectNotificationCommand.java
    directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/DumpCommand.java
    directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/GracefulShutdownCommand.java
    directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/ImportCommand.java
    directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/IndexCommand.java
Removed:
    directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/BaseToolCommand.java
    directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/ToolCommandListener.java
    directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/commands/
    directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/execution/
    directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/listeners/
    directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/request/
    directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/util/
    directory/apacheds/branches/bigbang/server-tools/src/test/java/org/
Modified:
    directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/ApachedsTools.java
    directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/BaseCommand.java
    directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/CapacityTestCommand.java
    directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/ToolCommand.java

Modified: directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/ApachedsTools.java
URL: http://svn.apache.org/viewvc/directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/ApachedsTools.java?rev=643845&r1=643844&r2=643845&view=diff
==============================================================================
--- directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/ApachedsTools.java (original)
+++ directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/ApachedsTools.java Wed Apr  2 04:02:57 2008
@@ -19,17 +19,14 @@
  */
 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.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;
+import org.apache.directory.server.configuration.ApacheDS;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.support.FileSystemXmlApplicationContext;
 
 
 /**
@@ -40,23 +37,10 @@
  */
 public class ApachedsTools
 {
-    public static void main( String[] args )
+    public static void main( String[] args ) throws Exception
     {
-        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 );
-        }
-
+        BaseCommand tools = getInstance();
+        
         if ( !BaseCommand.hasBannerOption( args ) )
         {
             tools.printBanner();
@@ -90,7 +74,7 @@
             System.exit( 0 );
         }
 
-        BaseToolCommandCL cmd = ( BaseToolCommandCL ) tools.getCommands().get( command );
+        ToolCommand cmd = ( ToolCommand ) tools.getCommands().get( command );
         if ( cmd == null )
         {
             System.err.println( "Unknown command: " + args[0] );
@@ -110,30 +94,29 @@
         cmd.setDebugEnabled( cmdline.hasOption( 'd' ) );
         cmd.setVerboseEnabled( cmdline.hasOption( 'v' ) );
         cmd.setVersion( tools.getProductVersion() );
-
-        if ( cmdline.hasOption( 'c' ) && ( cmdline.getOptionValue( 'i' ) == null ) )
+        if ( cmdline.getOptionValue( 'i' ) != null )
         {
-            System.err.println( "forced configuration load (-c) requires the -i option" );
-            System.exit( 1 );
-        }
-
-        try
-        {
-            cmd.execute( cmdline, new ListenerParameter[]
-                { new ListenerParameter( BaseToolCommandExecutor.OUTPUTLISTENER_PARAMETER, outputListener ),
-                    new ListenerParameter( BaseToolCommandExecutor.ERRORLISTENER_PARAMETER, errorListener ),
-                    new ListenerParameter( BaseToolCommandExecutor.EXCEPTIONLISTENER_PARAMETER, exceptionListener ) } );
+            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.setApacheDS( ( ApacheDS ) factory.getBean( "apacheDS" ) );
         }
-        catch ( Exception e )
+        else if ( cmdline.hasOption( 'c' ) )
         {
-            System.err.println( "An error has occurred. Apache DS Tools must quit." + "\nError: " + e.getMessage() );
+            System.err.println( "forced configuration load (-c) requires the -i option" );
             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
@@ -151,7 +134,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 );

Modified: directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/BaseCommand.java
URL: http://svn.apache.org/viewvc/directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/BaseCommand.java?rev=643845&r1=643844&r2=643845&view=diff
==============================================================================
--- directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/BaseCommand.java (original)
+++ directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/BaseCommand.java Wed Apr  2 04:02:57 2008
@@ -19,7 +19,6 @@
  */
 package org.apache.directory.server.tools;
 
-
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.Iterator;
@@ -37,15 +36,6 @@
 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.
@@ -55,9 +45,9 @@
  */
 public class BaseCommand
 {
-    private Map<String, ToolCommand> commands = new HashMap<String, ToolCommand>();
+    private Map commands = new HashMap();
 
-    private List<String> commandsOrdered = new ArrayList<String>();
+    private List commandsOrdered = new ArrayList();
 
     private Options global = new Options();
 
@@ -71,46 +61,40 @@
 
     private String productBanner;
 
-
     public BaseCommand()
     {
         init();
     }
 
-
     protected void init()
     {
-        BaseToolCommandCL command;
- 
-        command = new DiagnosticCommandCL();
-        commands.put( command.getName(), command );
-        commandsOrdered.add( command.getName() );
+        ToolCommand command;
 
-        command = new DumpCommandCL();
+        command = new DiagnosticCommand();
         commands.put( command.getName(), command );
         commandsOrdered.add( command.getName() );
 
-        command = new GracefulShutdownCommandCL();
+        command = new DisconnectNotificationCommand();
         commands.put( command.getName(), command );
         commandsOrdered.add( command.getName() );
 
-        command = new ImportCommandCL();
+        command = new DumpCommand();
         commands.put( command.getName(), command );
         commandsOrdered.add( command.getName() );
 
-        command = new DisconnectNotificationCommandCL();
+        command = new CapacityTestCommand();
         commands.put( command.getName(), command );
         commandsOrdered.add( command.getName() );
 
-        command = new ExportCommandCL();
+        command = new GracefulShutdownCommand();
         commands.put( command.getName(), command );
         commandsOrdered.add( command.getName() );
-        
-        command = new StoredProcedureCommandCL();
+
+        command = new ImportCommand();
         commands.put( command.getName(), command );
         commandsOrdered.add( command.getName() );
 
-//        command = new CapacityTestCommand();
+        command = new IndexCommand();
         commands.put( command.getName(), command );
         commandsOrdered.add( command.getName() );
 
@@ -130,7 +114,6 @@
         getGlobal().addOption( op );
     }
 
-
     public static boolean hasBannerOption( String[] args )
     {
         for ( int ii = 0; ii < args.length; ii++ )
@@ -143,7 +126,6 @@
         return false;
     }
 
-
     public CommandLine getCommandLine( String command, String[] args )
     {
         Options all = allOptions( command );
@@ -153,31 +135,30 @@
         {
             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 );
@@ -186,7 +167,6 @@
         return cmdline;
     }
 
-
     public Options allOptions( String command )
     {
         if ( command.equals( "help" ) )
@@ -195,21 +175,20 @@
         }
 
         Options all = new Options();
-        BaseToolCommandCL cmd = ( BaseToolCommandCL ) getCommands().get( command );
+        ToolCommand cmd = (ToolCommand) 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 )
@@ -229,7 +208,6 @@
         System.out.println( buf );
     }
 
-
     public void helpOnCommand( String command )
     {
         if ( command.equals( "help" ) )
@@ -240,7 +218,7 @@
 
         if ( getCommands().containsKey( command ) )
         {
-            BaseToolCommandCL cmd = ( BaseToolCommandCL ) getCommands().get( command );
+            ToolCommand cmd = (ToolCommand) getCommands().get( command );
             HelpFormatter formatter = new HelpFormatter();
             formatter.printHelp( getProductCommand() + " " + cmd + " [options]", cmd.getOptions() );
         }
@@ -251,12 +229,11 @@
         }
     }
 
-
     public void printUsage()
     {
         HelpFormatter formatter = new HelpFormatter();
-        formatter.printHelp( getProductCommand() + " <command> [options]", "\nGlobal options:", getGlobal(),
-            "\nType \"" + getProductCommand() + " help <command>\" for help on a command." );
+        formatter.printHelp( getProductCommand() + " <command> [options]", "\nGlobal options:", getGlobal(), "\nType \""
+                + getProductCommand() + " help <command>\" for help on a command." );
         System.out.println( "\nAvailable commands:" );
 
         Iterator it = commandsOrdered.iterator();
@@ -272,96 +249,81 @@
     }
 
     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<String, ToolCommand> commands )
+    public void setCommands( Map commands )
     {
         this.commands = commands;
     }
 
-
     public Map getCommands()
     {
         return commands;
     }
 
-
     public void setGlobal( Options global )
     {
         this.global = global;
     }
-
 
     public Options getGlobal()
     {

Modified: directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/CapacityTestCommand.java
URL: http://svn.apache.org/viewvc/directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/CapacityTestCommand.java?rev=643845&r1=643844&r2=643845&view=diff
==============================================================================
--- directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/CapacityTestCommand.java (original)
+++ directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/CapacityTestCommand.java Wed Apr  2 04:02:57 2008
@@ -24,6 +24,8 @@
 import java.io.PrintWriter;
 import java.util.Hashtable;
 
+import javax.naming.NameAlreadyBoundException;
+import javax.naming.NamingException;
 import javax.naming.directory.Attribute;
 import javax.naming.directory.Attributes;
 import javax.naming.ldap.InitialLdapContext;
@@ -34,9 +36,6 @@
 import org.apache.commons.cli.Options;
 import org.apache.commons.lang.RandomStringUtils;
 import org.apache.directory.daemon.AvailablePortFinder;
-import org.apache.directory.server.constants.ServerDNConstants;
-import org.apache.directory.shared.ldap.constants.JndiPropertyConstants;
-import org.apache.directory.shared.ldap.constants.SchemaConstants;
 import org.apache.directory.shared.ldap.message.AttributesImpl;
 
 
@@ -50,27 +49,27 @@
  * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
  * @version $Rev$
  */
-public class CapacityTestCommand extends BaseToolCommand
+public class CapacityTestCommand extends ToolCommand
 {
     public static final String PORT_RANGE = "(" + AvailablePortFinder.MIN_PORT_NUMBER + ", "
         + AvailablePortFinder.MAX_PORT_NUMBER + ")";
 
-    private static final String baseDn = ServerDNConstants.USER_EXAMPLE_COM_DN;
+    private int port = 10389;
+    private String host = "localhost";
+    private String password = "secret";
+    private String baseDn = "ou=users,dc=example,dc=com";
     
     
     public CapacityTestCommand()
     {
         super( "capacity" );
-        port = DEFAULT_PORT;
-        host = DEFAULT_HOST;
-        password = DEFAULT_PASSWORD;
     }
 
 
     public void execute( CommandLine cmdline ) throws Exception
     {
         processOptions( cmdline );
-//        getLayout().verifyInstallation();
+        getLayout().verifyInstallation();
         String outputFile = cmdline.getOptionValue( 'f' );
         PrintWriter out = null;
 
@@ -91,15 +90,18 @@
             out.println( "password = " + password );
         }
 
-        Hashtable<String, Object> env = new Hashtable<String, Object>();
-        env.put( JndiPropertyConstants.JNDI_FACTORY_INITIAL, "com.sun.jndi.ldap.LdapCtxFactory" );
-        env.put( JndiPropertyConstants.JNDI_PROVIDER_URL, "ldap://" + host + ":" + port );
-        env.put( "java.naming.security.principal", ServerDNConstants.ADMIN_SYSTEM_DN );
-        env.put( JndiPropertyConstants.JNDI_SECURITY_CREDENTIALS, password );
-        env.put( JndiPropertyConstants.JNDI_SECURITY_AUTHENTICATION, "simple" );
+        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 );
 
+        // create the base dn if it does not exist
+        createBase( ctx );
+        
         StringBuffer dnBuf = new StringBuffer();
         StringBuffer outBuf = new StringBuffer();
         int counter = 0;
@@ -131,6 +133,23 @@
     }
     
     
+    private boolean createBase( LdapContext ctx ) throws NamingException
+    {
+        Attributes attrs = new AttributesImpl( "objectClass", "organizationalUnit", true );
+        attrs.put( "ou", "users" );
+        
+        try
+        {
+            ctx.createSubcontext( "ou=users,dc=example,dc=com", attrs );
+            return true;
+        }
+        catch( NameAlreadyBoundException e )
+        {
+            return false;
+        }
+    }
+
+
     private Attributes generateLdif( int counter )
     {
         Attributes attrs = new AttributesImpl( "objectClass", "top", true );
@@ -144,7 +163,7 @@
         attrs.put( "cn", RandomStringUtils.randomAlphabetic( 15 ) );
         attrs.put( "initials", RandomStringUtils.randomAlphabetic( 2 ) );
         attrs.put( "mail", RandomStringUtils.randomAlphabetic( 15 ) );
-        attrs.put( SchemaConstants.USER_PASSWORD_AT, "password" );
+        attrs.put( "userPassword", "password" );
         attrs.put( "telephoneNumber", RandomStringUtils.randomNumeric( 10 ) );
         attrs.put( "homePhone", RandomStringUtils.randomNumeric( 10 ) );
         attrs.put( "pager", RandomStringUtils.randomNumeric( 10 ) );
@@ -202,15 +221,15 @@
                 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 ( getApacheDS() != null )
+        {
+            port = getApacheDS().getLdapServer().getIpPort();
+
+            if ( isDebugEnabled() )
+            {
+                System.out.println( "port overriden by server.xml configuration: " + port );
+            }
+        }
         else if ( isDebugEnabled() )
         {
             System.out.println( "port set to default: " + port );

Added: directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/DiagnosticCommand.java
URL: http://svn.apache.org/viewvc/directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/DiagnosticCommand.java?rev=643845&view=auto
==============================================================================
--- directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/DiagnosticCommand.java (added)
+++ directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/DiagnosticCommand.java Wed Apr  2 04:02:57 2008
@@ -0,0 +1,200 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you 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 <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
+ * @version $Rev: 434420 $
+ */
+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 ( getApacheDS() != null )
+        {
+            port = getApacheDS().getLdapServer().getIpPort();
+
+            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;
+    }
+}

Added: directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/DisconnectNotificationCommand.java
URL: http://svn.apache.org/viewvc/directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/DisconnectNotificationCommand.java?rev=643845&view=auto
==============================================================================
--- directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/DisconnectNotificationCommand.java (added)
+++ directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/DisconnectNotificationCommand.java Wed Apr  2 04:02:57 2008
@@ -0,0 +1,319 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you 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.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.UnsolicitedNotificationEvent;
+import javax.naming.ldap.UnsolicitedNotificationListener;
+
+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.codec.DecoderException;
+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 <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
+ * @version $Rev: 434420 $
+ */
+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 ( DecoderException de ) 
+            {
+				// TODO Auto-generated catch block
+				de.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 ( getApacheDS() != null )
+        {
+            port = getApacheDS().getLdapServer().getIpPort();
+
+            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;
+    }
+}

Added: directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/DumpCommand.java
URL: http://svn.apache.org/viewvc/directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/DumpCommand.java?rev=643845&view=auto
==============================================================================
--- directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/DumpCommand.java (added)
+++ directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/DumpCommand.java Wed Apr  2 04:02:57 2008
@@ -0,0 +1,350 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you 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.IOException;
+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.constants.ServerDNConstants;
+import org.apache.directory.server.core.DefaultDirectoryService;
+import org.apache.directory.server.core.DirectoryService;
+import org.apache.directory.server.core.entry.DefaultServerEntry;
+import org.apache.directory.server.core.entry.ServerEntry;
+import org.apache.directory.server.core.partition.impl.btree.Index;
+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.partition.impl.btree.jdbm.JdbmPartition;
+import org.apache.directory.server.core.schema.PartitionSchemaLoader;
+import org.apache.directory.server.schema.SerializableComparator;
+import org.apache.directory.server.schema.bootstrap.ApacheSchema;
+import org.apache.directory.server.schema.bootstrap.ApachemetaSchema;
+import org.apache.directory.server.schema.bootstrap.BootstrapSchemaLoader;
+import org.apache.directory.server.schema.bootstrap.CoreSchema;
+import org.apache.directory.server.schema.bootstrap.Schema;
+import org.apache.directory.server.schema.bootstrap.SystemSchema;
+import org.apache.directory.server.schema.bootstrap.partition.DbFileListing;
+import org.apache.directory.server.schema.registries.AttributeTypeRegistry;
+import org.apache.directory.server.schema.registries.DefaultOidRegistry;
+import org.apache.directory.server.schema.registries.DefaultRegistries;
+import org.apache.directory.server.schema.registries.OidRegistry;
+import org.apache.directory.server.schema.registries.Registries;
+import org.apache.directory.shared.ldap.constants.SchemaConstants;
+import org.apache.directory.shared.ldap.exception.LdapConfigurationException;
+import org.apache.directory.shared.ldap.exception.LdapNamingException;
+import org.apache.directory.shared.ldap.ldif.LdifUtils;
+import org.apache.directory.shared.ldap.message.ResultCodeEnum;
+import org.apache.directory.shared.ldap.name.LdapDN;
+import org.apache.directory.shared.ldap.schema.AttributeType;
+import org.apache.directory.shared.ldap.schema.UsageEnum;
+import org.apache.directory.shared.ldap.util.Base64;
+
+
+/**
+ * Simple tool used to dump the contents of a jdbm based partition.
+ * 
+ * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
+ * @version $Rev: 493916 $
+ */
+public class DumpCommand extends ToolCommand
+{
+	private Registries bootstrapRegistries = new DefaultRegistries( "bootstrap", 
+	        new BootstrapSchemaLoader(), new DefaultOidRegistry() );
+    private Set exclusions = new HashSet();
+    private boolean includeOperational = false;
+
+
+    public DumpCommand()
+    {
+        super( "dump" );
+    }
+    
+    
+    private Registries loadRegistries() throws Exception
+    {
+        // --------------------------------------------------------------------
+        // Load the bootstrap schemas to start up the schema partition
+        // --------------------------------------------------------------------
+
+        // setup temporary loader and temp registry 
+        BootstrapSchemaLoader loader = new BootstrapSchemaLoader();
+        OidRegistry oidRegistry = new DefaultOidRegistry();
+        final Registries registries = new DefaultRegistries( "bootstrap", loader, oidRegistry );
+        
+        // load essential bootstrap schemas 
+        Set<Schema> bootstrapSchemas = new HashSet<Schema>();
+        bootstrapSchemas.add( new ApachemetaSchema() );
+        bootstrapSchemas.add( new ApacheSchema() );
+        bootstrapSchemas.add( new CoreSchema() );
+        bootstrapSchemas.add( new SystemSchema() );
+        loader.loadWithDependencies( bootstrapSchemas, registries );
+
+        // run referential integrity tests
+        List<Throwable> errors = registries.checkRefInteg();
+        
+        if ( !errors.isEmpty() )
+        {
+            NamingException e = new NamingException();
+            e.setRootCause( ( Throwable ) errors.get( 0 ) );
+            throw e;
+        }
+        
+        SerializableComparator.setRegistry( registries.getComparatorRegistry() );
+        
+        // --------------------------------------------------------------------
+        // Initialize schema partition or bomb out if we cannot find it on disk
+        // --------------------------------------------------------------------
+        
+        // If not present then we need to abort 
+        File schemaDirectory = new File( getLayout().getPartitionsDirectory(), "schema" );
+        if ( ! schemaDirectory.exists() )
+        {
+            throw new LdapConfigurationException( "The following schema directory from " +
+                    "the installation layout could not be found:\n\t" + schemaDirectory );
+        }
+        
+        JdbmPartition schemaPartition = new JdbmPartition();
+        schemaPartition.setId( "schema" );
+        schemaPartition.setCacheSize( 1000 );
+        
+        DbFileListing listing;
+        try 
+        {
+            listing = new DbFileListing();
+        }
+        catch( IOException e )
+        {
+            throw new LdapNamingException( "Got IOException while trying to read DBFileListing: " + e.getMessage(), 
+                ResultCodeEnum.OTHER );
+        }
+
+        Set<Index> indexedAttributes = new HashSet<Index>();
+        
+        for ( String attributeId : listing.getIndexedAttributes() )
+        {
+            indexedAttributes.add( new JdbmIndex( attributeId ) );
+        }
+        
+        schemaPartition.setIndexedAttributes( indexedAttributes );
+        schemaPartition.setSuffix( ServerDNConstants.OU_SCHEMA_DN );
+        
+        ServerEntry systemEntry = new DefaultServerEntry( registries, new LdapDN( "ou=schema" ) );
+        systemEntry.put( SchemaConstants.OBJECT_CLASS_AT, 
+            SchemaConstants.TOP_OC,
+            SchemaConstants.ORGANIZATIONAL_UNIT_OC );
+        systemEntry.put( SchemaConstants.OU_AT, "schema" );
+        schemaPartition.setContextEntry( systemEntry );
+
+        DirectoryService directoryService = new DefaultDirectoryService();
+        schemaPartition.init( directoryService );
+
+        // --------------------------------------------------------------------
+        // Initialize schema subsystem and reset registries
+        // --------------------------------------------------------------------
+        
+        PartitionSchemaLoader schemaLoader = new PartitionSchemaLoader( schemaPartition, registries );
+        Registries globalRegistries = new DefaultRegistries( "global", schemaLoader, oidRegistry );
+        schemaLoader.loadEnabled( globalRegistries );
+        SerializableComparator.setRegistry( globalRegistries.getComparatorRegistry() );        
+        return globalRegistries;
+    }
+
+
+    public void execute( CommandLine cmdline ) throws Exception
+    {
+        getLayout().verifyInstallation();
+        bootstrapRegistries = loadRegistries();
+
+        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();
+        idIndex.setAttributeId( attributeType.getName() );
+        idIndex.setWkDirPath( partitionDirectory );
+        idIndex.setCacheSize( 1000 );
+        idIndex.setNumDupLimit( 1000 );
+        idIndex.init( 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 );
+
+            buf.append( "# Entry: " ).append( id ).append( "\n#---------------------\n\n" );
+            if ( !LdifUtils.isLDIFSafe( dn ) )
+            {
+            	// If the DN isn't LdifSafe, it needs to be Base64 encoded.
+
+                buf.append( "dn:: " ).append( new String( Base64.encode( dn.getBytes() ) ) );
+            }
+            else
+            {
+                buf.append( "dn: " ).append( dn );
+            }
+            buf.append( "\n" ).append( LdifUtils.convertToLdif( 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.USER_APPLICATIONS;
+            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;
+    }
+}

Added: directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/GracefulShutdownCommand.java
URL: http://svn.apache.org/viewvc/directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/GracefulShutdownCommand.java?rev=643845&view=auto
==============================================================================
--- directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/GracefulShutdownCommand.java (added)
+++ directory/apacheds/branches/bigbang/server-tools/src/main/java/org/apache/directory/server/tools/GracefulShutdownCommand.java Wed Apr  2 04:02:57 2008
@@ -0,0 +1,376 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you 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 <a href="http://docs.safehaus.org/display/APACHEDS/LDAP+Extensions+for+Graceful+Shutdown">
+ * Graceful Shutdown</a>
+ * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
+ * @version $Rev: 434420 $
+ */
+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 ( getApacheDS() != null )
+        {
+            port = getApacheDS().getLdapServer().getIpPort();
+
+            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;
+    }
+}



Mime
View raw message