directory-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From elecha...@apache.org
Subject svn commit: r426483 [2/5] - in /directory/trunks/apacheds/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/commands/diagnosticcmd/ main/java...
Date Fri, 28 Jul 2006 11:50:43 GMT
Added: directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/dumpcmd/DumpCommandCL.java
URL: http://svn.apache.org/viewvc/directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/dumpcmd/DumpCommandCL.java?rev=426483&view=auto
==============================================================================
--- directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/dumpcmd/DumpCommandCL.java (added)
+++ directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/dumpcmd/DumpCommandCL.java Fri Jul 28 04:50:40 2006
@@ -0,0 +1,149 @@
+/*
+ *   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.commands.dumpcmd;
+
+
+import java.io.File;
+
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
+import org.apache.directory.server.tools.execution.ToolCommandExecutorStub;
+import org.apache.directory.server.tools.request.BaseToolCommandCL;
+import org.apache.directory.server.tools.util.Parameter;
+
+
+/**
+ * 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: 379013 $
+ */
+public class DumpCommandCL extends BaseToolCommandCL
+{
+
+    public DumpCommandCL()
+    {
+        super( "dump" );
+    }
+
+
+    public void processOptions( CommandLine cmd )
+    {
+        // -------------------------------------------------------------------
+        // figure out the 'file' to output the dump to
+        // -------------------------------------------------------------------
+        if ( cmd.hasOption( 'f' ) )
+        {
+            String fileName = cmd.getOptionValue( 'f' );
+
+            parameters.add( new Parameter( DumpCommandExecutor.FILE_PARAMETER, fileName ) );
+        }
+
+        // -------------------------------------------------------------------
+        // figure out the 'partitions' to dump
+        // -------------------------------------------------------------------
+        if ( cmd.hasOption( 'p' ) )
+        {
+            String[] partitions = cmd.getOptionValues( 'p' );
+
+            parameters.add( new Parameter( DumpCommandExecutor.PARTITIONS_PARAMETER, partitions ) );
+        }
+
+        // -------------------------------------------------------------------
+        // figure out the 'attributes' to exclude
+        // -------------------------------------------------------------------
+        if ( cmd.hasOption( 'e' ) )
+        {
+            String[] excludedAttributes = cmd.getOptionValues( 'e' );
+
+            parameters.add( new Parameter( DumpCommandExecutor.EXCLUDEDATTRIBUTES_PARAMETER, excludedAttributes ) );
+        }
+
+        // -------------------------------------------------------------------
+        // figure out the 'include-operational' flag
+        // -------------------------------------------------------------------
+        if ( cmd.hasOption( 'o' ) )
+        {
+            parameters.add( new Parameter( DumpCommandExecutor.INCLUDEOPERATIONAL_PARAMETER, new Boolean( true ) ) );
+        }
+        else
+        {
+            // Default value is false
+            parameters.add( new Parameter( DumpCommandExecutor.INCLUDEOPERATIONAL_PARAMETER, new Boolean( false ) ) );
+        }
+
+        // -------------------------------------------------------------------
+        // figure out the 'install-path'
+        // and verify if the -i option is present when the -c option is used
+        // -------------------------------------------------------------------
+        if ( cmd.hasOption( 'i' ) )
+        {
+            parameters.add( new Parameter( DumpCommandExecutor.INSTALLPATH_PARAMETER, cmd.getOptionValue( 'i' ) ) );
+        }
+        else if ( cmd.hasOption( 'c' ) )
+        {
+            System.err.println( "forced configuration load (-c) requires the -i option" );
+            System.exit( 1 );
+        }
+
+        // -------------------------------------------------------------------
+        // figure out the 'configuration' flag
+        // -------------------------------------------------------------------
+        if ( cmd.hasOption( 'c' ) )
+        {
+            parameters.add( new Parameter( DumpCommandExecutor.CONFIGURATION_PARAMETER, new Boolean( true ) ) );
+        }
+
+        // -------------------------------------------------------------------
+        // Transform other options into params
+        // -------------------------------------------------------------------
+        parameters.add( new Parameter( DumpCommandExecutor.DEBUG_PARAMETER, new Boolean( isDebugEnabled() ) ) );
+        parameters.add( new Parameter( DumpCommandExecutor.QUIET_PARAMETER, new Boolean( isQuietEnabled() ) ) );
+        parameters.add( new Parameter( DumpCommandExecutor.VERBOSE_PARAMETER, new Boolean( isVerboseEnabled() ) ) );
+    }
+
+
+    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;
+    }
+
+
+    public ToolCommandExecutorStub getStub()
+    {
+        return new DumpCommandExecutorStub();
+    }
+}

Added: directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/dumpcmd/DumpCommandExecutor.java
URL: http://svn.apache.org/viewvc/directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/dumpcmd/DumpCommandExecutor.java?rev=426483&view=auto
==============================================================================
--- directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/dumpcmd/DumpCommandExecutor.java (added)
+++ directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/dumpcmd/DumpCommandExecutor.java Fri Jul 28 04:50:40 2006
@@ -0,0 +1,387 @@
+/*
+ *   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.commands.dumpcmd;
+
+
+import java.io.File;
+import java.io.FileWriter;
+import java.io.PrintWriter;
+import java.math.BigInteger;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+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.directory.server.configuration.ServerStartupConfiguration;
+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.server.tools.ToolCommandListener;
+import org.apache.directory.server.tools.execution.BaseToolCommandExecutor;
+import org.apache.directory.server.tools.util.ListenerParameter;
+import org.apache.directory.server.tools.util.Parameter;
+import org.apache.directory.server.tools.util.ToolCommandException;
+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;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.support.FileSystemXmlApplicationContext;
+
+
+/**
+ * This is the Executor Class of the Dump Command.
+ * 
+ * The command can be called using the 'execute' method.
+ */
+public class DumpCommandExecutor extends BaseToolCommandExecutor
+{
+    // Additional Parameters
+    public static final String FILE_PARAMETER = "file";
+    public static final String PARTITIONS_PARAMETER = "partitions";
+    public static final String EXCLUDEDATTRIBUTES_PARAMETER = "excluded-attributes";
+    public static final String INCLUDEOPERATIONAL_PARAMETER = "include-operational";
+
+    private BootstrapRegistries bootstrapRegistries = new BootstrapRegistries();
+    private BootstrapSchemaLoader loader = new BootstrapSchemaLoader();
+    private Set exclusions = new HashSet();
+    private boolean includeOperational = false;
+    private String outputFile;
+    private String[] partitions;
+    private String[] excludedAttributes;
+
+
+    public DumpCommandExecutor()
+    {
+        super( "dump" );
+    }
+
+
+    /**
+     * Executes the command.
+     * <p>
+     * Use the following Parameters and ListenerParameters to call the command.
+     * <p>
+     * Parameters : <ul>
+     *      <li>"FILE_PARAMETER" with a value of type 'String', representing the file to output the dump to</li>
+     *      <li>"PARTITIONS_PARAMETER" with a value of type 'String[]', representing the partitions to dump</li>
+     *      <li>"EXCLUDEDATTRIBUTES_PARAMETER" with a value of type 'String[]', representing the attributes 
+     *          to exclude</li>
+     *      <li>"INCLUDEOPERATIONAL_PARAMETER" with a value of type 'Boolean', to include operational
+     *          attributes</li>
+     *      <li>"DEBUG_PARAMETER" with a value of type 'Boolean', true to enable debug</li>
+     *      <li>"QUIET_PARAMETER" with a value of type 'Boolean', true to enable quiet</li>
+     *      <li>"VERBOSE_PARAMETER" with a value of type 'Boolean', true to enable verbose</li>
+     *      <li>"INSTALLPATH_PARAMETER" with a value of type 'String', representing the path to installation
+     *          directory</li>
+     *      <li>"CONFIGURATION_PARAMETER" with a value of type "Boolean", true to force loading the server.xml
+     *          (requires "install-path")</li>
+     * </ul>
+     * <br />
+     * ListenersParameters : <ul>
+     *      <li>"OUTPUTLISTENER_PARAMETER", a listener that will receive all output messages. It returns
+     *          messages as a String.</li>
+     *      <li>"ERRORLISTENER_PARAMETER", a listener that will receive all error messages. It returns messages
+     *          as a String.</li>
+     *      <li>"EXCEPTIONLISTENER_PARAMETER", a listener that will receive all exception(s) raised. It returns
+     *          Exceptions.</li>
+     * </ul>
+     * <b>Note:</b> "FILE_PARAMETER", "PARTITIONS_PARAMETER" and "INSTALLPATH_PARAMETER" are required.
+     */
+    public void execute( Parameter[] params, ListenerParameter[] listeners )
+    {
+        processParameters( params );
+        processListeners( listeners );
+
+        try
+        {
+            execute();
+        }
+        catch ( Exception e )
+        {
+            notifyExceptionListener( e );
+        }
+    }
+
+
+    private void execute() throws Exception
+    {
+        getLayout().verifyInstallation();
+        loader.load( getConfiguration().getBootstrapSchemas(), bootstrapRegistries );
+
+        PrintWriter out = null;
+        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 processParameters( Parameter[] params )
+    {
+        Map parameters = new HashMap();
+        for ( int i = 0; i < params.length; i++ )
+        {
+            Parameter parameter = params[i];
+            parameters.put( parameter.getName(), parameter.getValue() );
+        }
+
+        // Quiet param
+        Boolean quietParam = ( Boolean ) parameters.get( QUIET_PARAMETER );
+        if ( quietParam != null )
+        {
+            setQuietEnabled( quietParam.booleanValue() );
+        }
+
+        // Debug param
+        Boolean debugParam = ( Boolean ) parameters.get( DEBUG_PARAMETER );
+        if ( debugParam != null )
+        {
+            setDebugEnabled( debugParam.booleanValue() );
+        }
+
+        // Verbose param
+        Boolean verboseParam = ( Boolean ) parameters.get( VERBOSE_PARAMETER );
+        if ( verboseParam != null )
+        {
+            setVerboseEnabled( verboseParam.booleanValue() );
+        }
+
+        // Install-path param
+        String installPathParam = ( String ) parameters.get( INSTALLPATH_PARAMETER );
+        if ( installPathParam != null )
+        {
+            try
+            {
+                setLayout( installPathParam );
+                if ( !isQuietEnabled() )
+                {
+                    notifyOutputListener( "loading settings from: " + getLayout().getConfigurationFile() );
+                }
+                ApplicationContext factory = null;
+                URL configUrl;
+
+                configUrl = getLayout().getConfigurationFile().toURL();
+                factory = new FileSystemXmlApplicationContext( configUrl.toString() );
+                setConfiguration( ( ServerStartupConfiguration ) factory.getBean( "configuration" ) );
+            }
+            catch ( MalformedURLException e )
+            {
+                notifyErrorListener( e.getMessage() );
+                notifyExceptionListener( e );
+            }
+        }
+
+        // File param
+        String fileParam = ( String ) parameters.get( FILE_PARAMETER );
+        if ( fileParam != null )
+        {
+            outputFile = fileParam;
+        }
+
+        // Partitions param
+        String[] partitionsParam = ( String[] ) parameters.get( PARTITIONS_PARAMETER );
+        if ( partitionsParam != null )
+        {
+            partitions = partitionsParam;
+        }
+
+        // Excluded-Attributes param
+        String[] excludedAttributesParam = ( String[] ) parameters.get( EXCLUDEDATTRIBUTES_PARAMETER );
+        if ( excludedAttributesParam != null )
+        {
+            excludedAttributes = excludedAttributesParam;
+        }
+
+        // Include-Operationnal param
+        Boolean includeOperationalParam = ( Boolean ) parameters.get( INCLUDEOPERATIONAL_PARAMETER );
+        if ( includeOperationalParam != null )
+        {
+            includeOperational = includeOperationalParam.booleanValue();
+        }
+    }
+
+
+    private void processListeners( ListenerParameter[] listeners )
+    {
+        Map parameters = new HashMap();
+        for ( int i = 0; i < listeners.length; i++ )
+        {
+            ListenerParameter parameter = listeners[i];
+            parameters.put( parameter.getName(), parameter.getListener() );
+        }
+
+        // OutputListener param
+        ToolCommandListener outputListener = ( ToolCommandListener ) parameters.get( OUTPUTLISTENER_PARAMETER );
+        if ( outputListener != null )
+        {
+            this.outputListener = outputListener;
+        }
+
+        // ErrorListener param
+        ToolCommandListener errorListener = ( ToolCommandListener ) parameters.get( ERRORLISTENER_PARAMETER );
+        if ( errorListener != null )
+        {
+            this.errorListener = errorListener;
+        }
+
+        // ExceptionListener param
+        ToolCommandListener exceptionListener = ( ToolCommandListener ) parameters.get( EXCEPTIONLISTENER_PARAMETER );
+        if ( exceptionListener != null )
+        {
+            this.exceptionListener = exceptionListener;
+        }
+    }
+
+
+    private void dump( File partitionDirectory, PrintWriter out ) throws Exception
+    {
+        if ( !partitionDirectory.exists() )
+        {
+            notifyErrorListener( "Partition directory " + partitionDirectory + " does not exist!" );
+            throw new ToolCommandException( "Partition directory " + partitionDirectory + " does not exist!" );
+        }
+
+        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() )
+                {
+                    notifyOutputListener( "# 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() )
+            {
+                notifyOutputListener( "# Excluding attribute " + id + " in " + dn );
+            }
+        }
+    }
+}

Added: directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/dumpcmd/DumpCommandExecutorSkeleton.java
URL: http://svn.apache.org/viewvc/directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/dumpcmd/DumpCommandExecutorSkeleton.java?rev=426483&view=auto
==============================================================================
--- directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/dumpcmd/DumpCommandExecutorSkeleton.java (added)
+++ directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/dumpcmd/DumpCommandExecutorSkeleton.java Fri Jul 28 04:50:40 2006
@@ -0,0 +1,36 @@
+/*
+ *   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.commands.dumpcmd;
+
+
+import org.apache.directory.server.tools.execution.BaseToolCommandExecutor;
+import org.apache.directory.server.tools.execution.ToolCommandExecutorSkeleton;
+import org.apache.directory.server.tools.util.ListenerParameter;
+import org.apache.directory.server.tools.util.Parameter;
+
+
+public class DumpCommandExecutorSkeleton implements ToolCommandExecutorSkeleton
+{
+
+    public void execute( Parameter[] params, ListenerParameter[] listeners )
+    {
+        BaseToolCommandExecutor executor = new DumpCommandExecutor();
+
+        executor.execute( params, listeners );
+    }
+
+}

Added: directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/dumpcmd/DumpCommandExecutorStub.java
URL: http://svn.apache.org/viewvc/directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/dumpcmd/DumpCommandExecutorStub.java?rev=426483&view=auto
==============================================================================
--- directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/dumpcmd/DumpCommandExecutorStub.java (added)
+++ directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/dumpcmd/DumpCommandExecutorStub.java Fri Jul 28 04:50:40 2006
@@ -0,0 +1,37 @@
+/*
+ *   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.commands.dumpcmd;
+
+
+import org.apache.directory.server.tools.execution.ToolCommandExecutorSkeleton;
+import org.apache.directory.server.tools.execution.ToolCommandExecutorStub;
+import org.apache.directory.server.tools.util.ListenerParameter;
+import org.apache.directory.server.tools.util.Parameter;
+
+
+public class DumpCommandExecutorStub implements ToolCommandExecutorStub
+{
+
+    public void execute( Parameter[] params, ListenerParameter[] listeners ) throws Exception
+    {
+        ToolCommandExecutorSkeleton skeleton = new DumpCommandExecutorSkeleton();
+
+        skeleton.execute( params, listeners );
+
+    }
+
+}

Added: directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/exportcmd/ExportCommandCL.java
URL: http://svn.apache.org/viewvc/directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/exportcmd/ExportCommandCL.java?rev=426483&view=auto
==============================================================================
--- directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/exportcmd/ExportCommandCL.java (added)
+++ directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/exportcmd/ExportCommandCL.java Fri Jul 28 04:50:40 2006
@@ -0,0 +1,294 @@
+/*
+ *   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.commands.exportcmd;
+
+
+import java.io.File;
+import java.io.IOException;
+
+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.server.tools.execution.ToolCommandExecutorStub;
+import org.apache.directory.server.tools.request.BaseToolCommandCL;
+import org.apache.directory.server.tools.util.Parameter;
+
+
+/**
+ * A command to export data from a server.
+ * The data is exported as a Ldif File.
+ */
+public class ExportCommandCL extends BaseToolCommandCL
+{
+    private String ldifFileName;
+    private String baseDN;
+    private String exportPoint;
+    private String scope;
+    private static final String SCOPE_OBJECT = "object";
+    private static final String SCOPE_ONELEVEL = "onelevel";
+    private static final String SCOPE_SUBTREE = "subtree";
+
+
+    public ExportCommandCL()
+    {
+        super( "export" );
+    }
+
+
+    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( "b", "base-dn", true, "the base DN: defaults to ''" );
+        op.setRequired( false );
+        opts.addOption( op );
+        op = new Option( "e", "exportpoint", true, "the export point: defaults to ''" );
+        op.setRequired( false );
+        opts.addOption( op );
+        op = new Option( "s", "scope", true, "the export scope ('" + SCOPE_OBJECT + "', '" + SCOPE_ONELEVEL + "' or '"
+            + SCOPE_SUBTREE + "'): defaults to '" + SCOPE_SUBTREE + "'" );
+        op.setRequired( false );
+        opts.addOption( op );
+        op = new Option( "f", "file", true, "the ldif file to export data to" );
+        op.setRequired( true );
+        opts.addOption( op );
+
+        return opts;
+    }
+
+
+    public ToolCommandExecutorStub getStub()
+    {
+        return new ExportCommandExecutorStub();
+    }
+
+
+    public void processOptions( CommandLine cmd ) throws Exception
+    {
+        if ( isDebugEnabled() )
+        {
+            System.out.println( "Processing options for launching export ..." );
+        }
+
+        // -------------------------------------------------------------------
+        // figure out the host value
+        // -------------------------------------------------------------------
+        if ( cmd.hasOption( 'h' ) )
+        {
+            host = cmd.getOptionValue( 'h' );
+
+            if ( isDebugEnabled() )
+            {
+                System.out.println( "host overriden by -h option: true" );
+            }
+
+            parameters.add( new Parameter( ExportCommandExecutor.HOST_PARAMETER, host ) );
+        }
+
+        // -------------------------------------------------------------------
+        // 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 );
+            }
+
+            parameters.add( new Parameter( ExportCommandExecutor.PORT_PARAMETER, new Integer( 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 );
+            }
+
+            parameters.add( new Parameter( ExportCommandExecutor.USER_PARAMETER, 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 );
+            }
+
+            parameters.add( new Parameter( ExportCommandExecutor.PASSWORD_PARAMETER, 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 );
+            }
+
+            parameters.add( new Parameter( ExportCommandExecutor.AUTH_PARAMETER, auth ) );
+        }
+
+        // -------------------------------------------------------------------
+        // figure out the Base DN value
+        // -------------------------------------------------------------------
+        if ( cmd.hasOption( 'b' ) )
+        {
+            baseDN = cmd.getOptionValue( 'b' );
+
+            if ( isDebugEnabled() )
+            {
+                System.out.println( "base DN overriden by -b option: " + baseDN );
+            }
+
+            parameters.add( new Parameter( ExportCommandExecutor.BASEDN_PARAMETER, baseDN ) );
+        }
+
+        // -------------------------------------------------------------------
+        // figure out the Export Point value
+        // -------------------------------------------------------------------
+        if ( cmd.hasOption( 'e' ) )
+        {
+            exportPoint = cmd.getOptionValue( 'e' );
+
+            if ( isDebugEnabled() )
+            {
+                System.out.println( "export point overriden by -e option: " + exportPoint );
+            }
+
+            parameters.add( new Parameter( ExportCommandExecutor.EXPORTPOINT_PARAMETER, exportPoint ) );
+        }
+
+        // -------------------------------------------------------------------
+        // figure out the scope value
+        // -------------------------------------------------------------------
+        if ( cmd.hasOption( 's' ) )
+        {
+            scope = cmd.getOptionValue( 's' );
+
+            if ( ( scope.equals( SCOPE_OBJECT ) ) || ( scope.equals( SCOPE_ONELEVEL ) )
+                || ( scope.equals( SCOPE_SUBTREE ) ) )
+            {
+                if ( isDebugEnabled() )
+                {
+                    System.out.println( "scope overriden by -s option: " + scope );
+                }
+            }
+            else
+            {
+                System.err.println( "unknown scope. Scope must be '" + SCOPE_OBJECT + "', '" + SCOPE_ONELEVEL
+                    + "' or '" + SCOPE_SUBTREE + "'" );
+                System.exit( 1 );
+            }
+
+            parameters.add( new Parameter( ExportCommandExecutor.SCOPE_PARAMETER, scope ) );
+        }
+
+        // -------------------------------------------------------------------
+        // figure out the ldif file to export entries to
+        // -------------------------------------------------------------------
+        if ( cmd.hasOption( 'f' ) )
+        {
+            ldifFileName = cmd.getOptionValue( 'f' );
+
+            if ( ( ldifFileName == null ) || ( "".equals( ldifFileName ) ) )
+            {
+                System.err.println( "ldif file name must be provided" );
+                System.exit( 1 );
+            }
+
+            File ldifFile = new File( ldifFileName );
+
+            if ( isDebugEnabled() )
+            {
+                try
+                {
+                    System.out.println( "ldif file to export entries to: " + ldifFile.getCanonicalPath() );
+                }
+                catch ( IOException ioe )
+                {
+                    System.out.println( "ldif file to export entries to: " + ldifFile );
+                }
+            }
+        }
+        else
+        {
+            System.err.println( "ldif file name must be provided" );
+            System.exit( 1 );
+        }
+
+        parameters.add( new Parameter( ExportCommandExecutor.FILE_PARAMETER, ldifFileName ) );
+
+        parameters.add( new Parameter( ExportCommandExecutor.DEBUG_PARAMETER, new Boolean( isDebugEnabled() ) ) );
+        parameters.add( new Parameter( ExportCommandExecutor.QUIET_PARAMETER, new Boolean( isQuietEnabled() ) ) );
+        parameters.add( new Parameter( ExportCommandExecutor.VERBOSE_PARAMETER, new Boolean( isVerboseEnabled() ) ) );
+    }
+}

Added: directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/exportcmd/ExportCommandExecutor.java
URL: http://svn.apache.org/viewvc/directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/exportcmd/ExportCommandExecutor.java?rev=426483&view=auto
==============================================================================
--- directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/exportcmd/ExportCommandExecutor.java (added)
+++ directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/exportcmd/ExportCommandExecutor.java Fri Jul 28 04:50:40 2006
@@ -0,0 +1,611 @@
+/*
+ *   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.commands.exportcmd;
+
+
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileWriter;
+import java.io.Serializable;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.Map;
+import java.util.Set;
+
+import javax.naming.Context;
+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.InitialDirContext;
+import javax.naming.directory.SearchControls;
+import javax.naming.directory.SearchResult;
+
+import org.apache.commons.collections.MultiHashMap;
+import org.apache.directory.server.configuration.ServerStartupConfiguration;
+import org.apache.directory.server.tools.ToolCommandListener;
+import org.apache.directory.server.tools.execution.BaseToolCommandExecutor;
+import org.apache.directory.server.tools.util.ListenerParameter;
+import org.apache.directory.server.tools.util.Parameter;
+import org.apache.directory.server.tools.util.ToolCommandException;
+import org.apache.directory.shared.ldap.ldif.LdifComposer;
+import org.apache.directory.shared.ldap.ldif.LdifComposerImpl;
+import org.apache.directory.shared.ldap.util.MultiMap;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.support.FileSystemXmlApplicationContext;
+
+
+/**
+ * This is the Executor Class of the Export Command.
+ * 
+ * The command can be called using the 'execute' method.
+ * 
+ */
+public class ExportCommandExecutor extends BaseToolCommandExecutor
+{
+    // Additional Parameters
+    public static final String BASEDN_PARAMETER = "baseDN";
+    public static final String EXPORTPOINT_PARAMETER = "exportPoint";
+    public static final String SCOPE_PARAMETER = "scope";
+    public static final String FILE_PARAMETER = "file";
+
+    // Addutional ListenerParameters
+    public static final String ENTRYWRITTENLISTENER_PARAMETER = "entryWrittenListener";
+
+    public static final String SCOPE_OBJECT = "object";
+    public static final String SCOPE_ONELEVEL = "onelevel";
+    public static final String SCOPE_SUBTREE = "subtree";
+
+    private String baseDN;
+    private static final String DEFAULT_BASEDN = "";
+    private String exportPoint;
+    private static final String DEFAULT_EXPORTPOINT = "";
+    private int scope;
+    private static final int DEFAULT_SCOPE = SearchControls.SUBTREE_SCOPE;
+    private String ldifFileName;
+
+    // The listeners
+    private ToolCommandListener entryWrittenListener;
+
+
+    public ExportCommandExecutor()
+    {
+        super( "export" );
+    }
+
+
+    /**
+     * Executes the command.
+     * <p>
+     * Use the following Parameters and ListenerParameters to call the command.
+     * <p>
+     * Parameters : <ul>
+     *      <li>"HOST_PARAMETER" with a value of type 'String', representing server host</li>
+     *      <li>"PORT_PARAMETER" with a value of type 'Integer', representing server port</li>
+     *      <li>"USER_PARAMETER" with a value of type 'String', representing user DN</li>
+     *      <li>"PASSWORD_PARAMETER" with a value of type 'String', representing user password</li>
+     *      <li>"AUTH_PARAMETER" with a value of type 'String', representing the type of authentication</li>
+     *      <li>"BASEDN_PARAMETER" with a value of type 'String', representing the base DN for the connection
+     *          to server</li>
+     *      <li>"EXPORTPOINT_PARAMETER" with a value of type 'String', representing the DN of the export point</li>
+     *      <li>"SCOPE_PARAMETER" with a value of type 'String', representing the scope of the export, choosing 
+     *          from one of 'object', 'onelevel', 'subtree' values</li>
+     *      <li>"FILE_PARAMETER" with a value of type 'String', representing the path to the file to export 
+     *          entries to</li>
+     *      <li>"DEBUG_PARAMETER" with a value of type 'Boolean', true to enable debug</li>
+     *      <li>"QUIET_PARAMETER" with a value of type 'Boolean', true to enable quiet</li>
+     *      <li>"VERBOSE_PARAMETER" with a value of type 'Boolean', true to enable verbose</li>
+     * </ul>
+     * <br />
+     * ListenersParameters : <ul>
+     *      <li>"OUTPUTLISTENER_PARAMETER", a listener that will receive all output messages. It returns
+     *          messages as a String.</li>
+     *      <li>"ERRORLISTENER_PARAMETER", a listener that will receive all error messages. It returns messages
+     *          as a String.</li>
+     *      <li>"EXCEPTIONLISTENER_PARAMETER", a listener that will receive all exception(s) raised. It returns
+     *          Exceptions.</li>
+     *      <li>"ENTRYWRITTENLISTENER_PARAMETER", a listener that will be notified each time an entry is
+     *          exported. It returns, as a String, the DN of the entry added</li>
+     * </ul>
+     * <b>Note:</b> All Parameters except "DEBUG_PARAMETER", "QUIET_PARAMETER" and "VERBOSE_PARAMETER" are required.
+     */
+    public void execute( Parameter[] params, ListenerParameter[] listeners )
+    {
+        processParameters( params );
+        processListeners( listeners );
+
+        try
+        {
+            execute();
+        }
+        catch ( Exception e )
+        {
+            notifyExceptionListener( e );
+        }
+    }
+
+
+    private void execute() throws Exception
+    {
+        // Connecting to server and retreiving entries
+        NamingEnumeration entries = connectToServerAndGetEntries();
+
+        // Creating destination file
+        File destionationFile = new File( ldifFileName );
+
+        // Deleting the destination file if it already exists
+        if ( destionationFile.exists() )
+        {
+            destionationFile.delete();
+        }
+
+        // Creating the writer to generate the LDIF file
+        FileWriter fw = new FileWriter( ldifFileName, true );
+
+        BufferedWriter writer = new BufferedWriter( fw );
+        LdifComposer composer = new LdifComposerImpl();
+        MultiMap map = new MultiMap()
+        {
+            // FIXME Stop forking commons-collections.
+            private final MultiHashMap map = new MultiHashMap();
+
+
+            public Object remove( Object arg0, Object arg1 )
+            {
+                return map.remove( arg0, arg1 );
+            }
+
+
+            public int size()
+            {
+                return map.size();
+            }
+
+
+            public Object get( Object arg0 )
+            {
+                return map.get( arg0 );
+            }
+
+
+            public boolean containsValue( Object arg0 )
+            {
+                return map.containsValue( arg0 );
+            }
+
+
+            public Object put( Object arg0, Object arg1 )
+            {
+                return map.put( arg0, arg1 );
+            }
+
+
+            public Object remove( Object arg0 )
+            {
+                return map.remove( arg0 );
+            }
+
+
+            public Collection values()
+            {
+                return map.values();
+            }
+
+
+            public boolean isEmpty()
+            {
+                return map.isEmpty();
+            }
+
+
+            public boolean containsKey( Object key )
+            {
+                return map.containsKey( key );
+            }
+
+
+            public void putAll( Map arg0 )
+            {
+                map.putAll( arg0 );
+            }
+
+
+            public void clear()
+            {
+                map.clear();
+            }
+
+
+            public Set keySet()
+            {
+                return map.keySet();
+            }
+
+
+            public Set entrySet()
+            {
+                return map.entrySet();
+            }
+        };
+
+        int entriesCounter = 1;
+        long t0 = System.currentTimeMillis();
+
+        while ( entries.hasMoreElements() )
+        {
+            SearchResult sr = ( SearchResult ) entries.nextElement();
+            Attributes attributes = sr.getAttributes();
+            NamingEnumeration attributesEnumeration = attributes.getAll();
+
+            map.clear();
+
+            while ( attributesEnumeration.hasMoreElements() )
+            {
+                Attribute attr = ( Attribute ) attributesEnumeration.nextElement();
+                NamingEnumeration e2 = null;
+
+                e2 = attr.getAll();
+
+                while ( e2.hasMoreElements() )
+                {
+                    Object value = e2.nextElement();
+                    map.put( attr.getID(), value );
+                }
+            }
+
+            // Writing entry in the file
+            writer.write( "dn: " + sr.getNameInNamespace() + "\n" );
+            writer.write( composer.compose( map ) + "\n" );
+
+            notifyEntryWrittenListener( sr.getNameInNamespace() );
+            entriesCounter++;
+
+            if ( entriesCounter % 10 == 0 )
+            {
+                notifyOutputListener( new Character( '.' ) );
+            }
+
+            if ( entriesCounter % 500 == 0 )
+            {
+                notifyOutputListener( "" + entriesCounter );
+            }
+        }
+
+        writer.flush();
+        writer.close();
+        fw.close();
+
+        long t1 = System.currentTimeMillis();
+
+        notifyOutputListener( "Done!" );
+        notifyOutputListener( entriesCounter + " entries exported in " + ( ( t1 - t0 ) / 1000 ) + " seconds" );
+    }
+
+
+    /**
+     * Gets and returns the entries from the server.
+     * @throws ToolCommandException 
+     * @throws NamingException 
+     */
+    public NamingEnumeration connectToServerAndGetEntries() throws ToolCommandException
+    {
+        // Connecting to the LDAP Server
+        if ( isDebugEnabled() )
+        {
+            notifyOutputListener( "Connecting to LDAP server" );
+            notifyOutputListener( "Host: " + host );
+            notifyOutputListener( "Port: " + port );
+            notifyOutputListener( "User DN: " + user );
+            notifyOutputListener( "Base DN: " + baseDN );
+            notifyOutputListener( "Authentication: " + auth );
+        }
+        Hashtable env = new Hashtable();
+        env.put( Context.SECURITY_PRINCIPAL, user );
+        env.put( Context.SECURITY_CREDENTIALS, password );
+        env.put( Context.SECURITY_AUTHENTICATION, auth );
+        env.put( Context.PROVIDER_URL, "ldap://" + host + ":" + port + "/" + baseDN );
+        env.put( Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory" );
+        DirContext ctx;
+        try
+        {
+            ctx = new InitialDirContext( env );
+        }
+        catch ( NamingException e )
+        {
+            throw new ToolCommandException( "Could not connect to the server.\nError: " + e.getMessage() );
+        }
+
+        // Setting up search scope
+        SearchControls ctls = new SearchControls();
+        ctls.setSearchScope( scope );
+
+        // Fetching entries
+        try
+        {
+            return ctx.search( exportPoint, "(objectClass=*)", ctls );
+        }
+        catch ( NamingException e )
+        {
+            throw new ToolCommandException( "Could not retreive entries" );
+        }
+    }
+
+
+    private void processParameters( Parameter[] params )
+    {
+        Map parameters = new HashMap();
+        for ( int i = 0; i < params.length; i++ )
+        {
+            Parameter parameter = params[i];
+            parameters.put( parameter.getName(), parameter.getValue() );
+        }
+
+        // Quiet param
+        Boolean quietParam = ( Boolean ) parameters.get( QUIET_PARAMETER );
+        if ( quietParam != null )
+        {
+            setQuietEnabled( quietParam.booleanValue() );
+        }
+
+        // Debug param
+        Boolean debugParam = ( Boolean ) parameters.get( DEBUG_PARAMETER );
+        if ( debugParam != null )
+        {
+            setDebugEnabled( debugParam.booleanValue() );
+        }
+
+        // Verbose param
+        Boolean verboseParam = ( Boolean ) parameters.get( VERBOSE_PARAMETER );
+        if ( verboseParam != null )
+        {
+            setVerboseEnabled( verboseParam.booleanValue() );
+        }
+
+        // Install-path param
+        String installPathParam = ( String ) parameters.get( INSTALLPATH_PARAMETER );
+        if ( installPathParam != null )
+        {
+            try
+            {
+                setLayout( installPathParam );
+                if ( !isQuietEnabled() )
+                {
+                    notifyOutputListener( "loading settings from: " + getLayout().getConfigurationFile() );
+                }
+                ApplicationContext factory = null;
+                URL configUrl;
+
+                configUrl = getLayout().getConfigurationFile().toURL();
+                factory = new FileSystemXmlApplicationContext( configUrl.toString() );
+                setConfiguration( ( ServerStartupConfiguration ) factory.getBean( "configuration" ) );
+            }
+            catch ( MalformedURLException e )
+            {
+                notifyErrorListener( e.getMessage() );
+                notifyExceptionListener( e );
+            }
+        }
+
+        // Host param
+        String hostParam = ( String ) parameters.get( HOST_PARAMETER );
+        if ( hostParam != null )
+        {
+            host = hostParam;
+        }
+        else
+        {
+            host = DEFAULT_HOST;
+
+            if ( isDebugEnabled() )
+            {
+                notifyOutputListener( "host set to default: " + host );
+            }
+        }
+
+        // Port param
+        Integer portParam = ( Integer ) parameters.get( PORT_PARAMETER );
+        if ( portParam != null )
+        {
+            port = portParam.intValue();
+        }
+        else if ( getConfiguration() != null )
+        {
+            port = getConfiguration().getLdapPort();
+
+            if ( isDebugEnabled() )
+            {
+                notifyOutputListener( "port overriden by server.xml configuration: " + port );
+            }
+        }
+        else
+        {
+            port = DEFAULT_PORT;
+
+            if ( isDebugEnabled() )
+            {
+                notifyOutputListener( "port set to default: " + port );
+            }
+        }
+
+        // User param
+        String userParam = ( String ) parameters.get( USER_PARAMETER );
+        if ( userParam != null )
+        {
+            user = userParam;
+        }
+        else
+        {
+            user = DEFAULT_USER;
+
+            if ( isDebugEnabled() )
+            {
+                notifyOutputListener( "user set to default: " + user );
+            }
+        }
+
+        // Password param
+        String passwordParam = ( String ) parameters.get( PASSWORD_PARAMETER );
+        if ( passwordParam != null )
+        {
+            password = passwordParam;
+        }
+        else
+        {
+            password = DEFAULT_PASSWORD;
+
+            if ( isDebugEnabled() )
+            {
+                notifyOutputListener( "password set to default: " + password );
+            }
+        }
+
+        // Auth param
+        String authParam = ( String ) parameters.get( AUTH_PARAMETER );
+        if ( authParam != null )
+        {
+            auth = authParam;
+        }
+        else
+        {
+            auth = DEFAULT_AUTH;
+
+            if ( isDebugEnabled() )
+            {
+                notifyOutputListener( "authentication type set to default: " + auth );
+            }
+        }
+
+        // Base DN param
+        String baseDNParam = ( String ) parameters.get( BASEDN_PARAMETER );
+        if ( baseDNParam != null )
+        {
+            baseDN = baseDNParam;
+        }
+        else
+        {
+            baseDN = DEFAULT_BASEDN;
+
+            if ( isDebugEnabled() )
+            {
+                notifyOutputListener( "base DN set to default: " + baseDN );
+            }
+        }
+
+        // Export Point param
+        String exportPointParam = ( String ) parameters.get( EXPORTPOINT_PARAMETER );
+        if ( exportPointParam != null )
+        {
+            exportPoint = exportPointParam;
+        }
+        else
+        {
+            exportPoint = DEFAULT_EXPORTPOINT;
+
+            if ( isDebugEnabled() )
+            {
+                notifyOutputListener( "export point set to default: " + exportPoint );
+            }
+        }
+
+        // scope param
+        String scopeParam = ( String ) parameters.get( SCOPE_PARAMETER );
+        if ( scopeParam != null )
+        {
+            if ( scopeParam.equals( SCOPE_OBJECT ) )
+            {
+                scope = SearchControls.OBJECT_SCOPE;
+            }
+            else if ( scopeParam.equals( SCOPE_ONELEVEL ) )
+            {
+                scope = SearchControls.ONELEVEL_SCOPE;
+            }
+            else if ( scopeParam.equals( SCOPE_SUBTREE ) )
+            {
+                scope = SearchControls.SUBTREE_SCOPE;
+            }
+        }
+        else
+        {
+            scope = DEFAULT_SCOPE;
+
+            if ( isDebugEnabled() )
+            {
+                notifyOutputListener( "scope set to default: " + scope );
+            }
+        }
+
+        // LdifFile param
+        String ldifFileParam = ( String ) parameters.get( FILE_PARAMETER );
+        if ( ldifFileParam != null )
+        {
+            ldifFileName = ldifFileParam;
+        }
+    }
+
+
+    private void processListeners( ListenerParameter[] listeners )
+    {
+        Map parameters = new HashMap();
+        for ( int i = 0; i < listeners.length; i++ )
+        {
+            ListenerParameter parameter = listeners[i];
+            parameters.put( parameter.getName(), parameter.getListener() );
+        }
+
+        // OutputListener param
+        ToolCommandListener outputListener = ( ToolCommandListener ) parameters.get( OUTPUTLISTENER_PARAMETER );
+        if ( outputListener != null )
+        {
+            this.outputListener = outputListener;
+        }
+
+        // ErrorListener param
+        ToolCommandListener errorListener = ( ToolCommandListener ) parameters.get( ERRORLISTENER_PARAMETER );
+        if ( errorListener != null )
+        {
+            this.errorListener = errorListener;
+        }
+
+        // ExceptionListener param
+        ToolCommandListener exceptionListener = ( ToolCommandListener ) parameters.get( EXCEPTIONLISTENER_PARAMETER );
+        if ( exceptionListener != null )
+        {
+            this.exceptionListener = exceptionListener;
+        }
+
+        // EntryAddedListener param
+        ToolCommandListener entryWrittenListener = ( ToolCommandListener ) parameters
+            .get( ENTRYWRITTENLISTENER_PARAMETER );
+        if ( entryWrittenListener != null )
+        {
+            this.entryWrittenListener = entryWrittenListener;
+        }
+    }
+
+
+    private void notifyEntryWrittenListener( Serializable o )
+    {
+        if ( this.entryWrittenListener != null )
+        {
+            this.entryWrittenListener.notify( o );
+        }
+    }
+}

Added: directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/exportcmd/ExportCommandExecutorSkeleton.java
URL: http://svn.apache.org/viewvc/directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/exportcmd/ExportCommandExecutorSkeleton.java?rev=426483&view=auto
==============================================================================
--- directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/exportcmd/ExportCommandExecutorSkeleton.java (added)
+++ directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/exportcmd/ExportCommandExecutorSkeleton.java Fri Jul 28 04:50:40 2006
@@ -0,0 +1,20 @@
+package org.apache.directory.server.tools.commands.exportcmd;
+
+
+import org.apache.directory.server.tools.execution.BaseToolCommandExecutor;
+import org.apache.directory.server.tools.execution.ToolCommandExecutorSkeleton;
+import org.apache.directory.server.tools.util.ListenerParameter;
+import org.apache.directory.server.tools.util.Parameter;
+
+
+public class ExportCommandExecutorSkeleton implements ToolCommandExecutorSkeleton
+{
+
+    public void execute( Parameter[] params, ListenerParameter[] listeners )
+    {
+        BaseToolCommandExecutor executor = new ExportCommandExecutor();
+
+        executor.execute( params, listeners );
+    }
+
+}

Added: directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/exportcmd/ExportCommandExecutorStub.java
URL: http://svn.apache.org/viewvc/directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/exportcmd/ExportCommandExecutorStub.java?rev=426483&view=auto
==============================================================================
--- directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/exportcmd/ExportCommandExecutorStub.java (added)
+++ directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/exportcmd/ExportCommandExecutorStub.java Fri Jul 28 04:50:40 2006
@@ -0,0 +1,20 @@
+package org.apache.directory.server.tools.commands.exportcmd;
+
+
+import org.apache.directory.server.tools.execution.ToolCommandExecutorSkeleton;
+import org.apache.directory.server.tools.execution.ToolCommandExecutorStub;
+import org.apache.directory.server.tools.util.ListenerParameter;
+import org.apache.directory.server.tools.util.Parameter;
+
+
+public class ExportCommandExecutorStub implements ToolCommandExecutorStub
+{
+
+    public void execute( Parameter[] params, ListenerParameter[] listeners ) throws Exception
+    {
+        ToolCommandExecutorSkeleton skeleton = new ExportCommandExecutorSkeleton();
+
+        skeleton.execute( params, listeners );
+    }
+
+}

Added: directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/gracefulshutdowncmd/GracefulShutdownCommandCL.java
URL: http://svn.apache.org/viewvc/directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/gracefulshutdowncmd/GracefulShutdownCommandCL.java?rev=426483&view=auto
==============================================================================
--- directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/gracefulshutdowncmd/GracefulShutdownCommandCL.java (added)
+++ directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/gracefulshutdowncmd/GracefulShutdownCommandCL.java Fri Jul 28 04:50:40 2006
@@ -0,0 +1,267 @@
+/*
+ *   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.commands.gracefulshutdowncmd;
+
+
+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.server.tools.execution.ToolCommandExecutorStub;
+import org.apache.directory.server.tools.request.BaseToolCommandCL;
+import org.apache.directory.server.tools.util.Parameter;
+
+/**
+ * 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: 380697 $
+ */
+public class GracefulShutdownCommandCL extends BaseToolCommandCL
+{
+    private static final int DELAY_MAX = 86400;
+    private int delay;
+
+    private static final int TIME_OFFLINE_MAX = 720;
+    private int timeOffline;
+
+
+    public GracefulShutdownCommandCL()
+    {
+        super( "graceful" );
+    }
+
+
+    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;
+    }
+
+
+    public ToolCommandExecutorStub getStub()
+    {
+        return new GracefulShutdownCommandExecutorStub();
+    }
+
+
+    public void processOptions( CommandLine cmd ) throws Exception
+    {
+        if ( isDebugEnabled() )
+        {
+            System.out.println( "Processing options for launching import ..." );
+        }
+
+        // -------------------------------------------------------------------
+        // figure out the host value
+        // -------------------------------------------------------------------
+        if ( cmd.hasOption( 'h' ) )
+        {
+            host = cmd.getOptionValue( 'h' );
+
+            if ( isDebugEnabled() )
+            {
+                System.out.println( "host overriden by -h option: true" );
+            }
+
+            parameters.add( new Parameter( GracefulShutdownCommandExecutor.HOST_PARAMETER, host ) );
+        }
+
+        // -------------------------------------------------------------------
+        // 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 );
+            }
+
+            parameters.add( new Parameter( GracefulShutdownCommandExecutor.PORT_PARAMETER, new Integer( port ) ) );
+        }
+
+        // -------------------------------------------------------------------
+        // figure out the password value
+        // -------------------------------------------------------------------
+        if ( cmd.hasOption( 'w' ) )
+        {
+            password = cmd.getOptionValue( 'w' );
+
+            if ( isDebugEnabled() )
+            {
+                System.out.println( "password overriden by -w option: " + password );
+            }
+
+            parameters.add( new Parameter( GracefulShutdownCommandExecutor.PASSWORD_PARAMETER, 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 );
+            }
+
+            parameters.add( new Parameter( GracefulShutdownCommandExecutor.DELAY_PARAMETER, new Integer( 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 );
+            }
+
+            parameters.add( new Parameter( GracefulShutdownCommandExecutor.TIMEOFFLINE_PARAMETER, new Integer(
+                timeOffline ) ) );
+        }
+
+        // -------------------------------------------------------------------
+        // figure out the 'install-path'
+        // and verify if the -i option is present when the -c option is used
+        // -------------------------------------------------------------------
+        if ( cmd.hasOption( 'i' ) )
+        {
+            parameters.add( new Parameter( GracefulShutdownCommandExecutor.INSTALLPATH_PARAMETER, cmd
+                .getOptionValue( 'i' ) ) );
+        }
+        else if ( cmd.hasOption( 'c' ) )
+        {
+            System.err.println( "forced configuration load (-c) requires the -i option" );
+            System.exit( 1 );
+        }
+
+        // -------------------------------------------------------------------
+        // figure out the 'configuration' flag
+        // -------------------------------------------------------------------
+        if ( cmd.hasOption( 'c' ) )
+        {
+            parameters
+                .add( new Parameter( GracefulShutdownCommandExecutor.CONFIGURATION_PARAMETER, new Boolean( true ) ) );
+        }
+
+        // -------------------------------------------------------------------
+        // Transform other options into params
+        // -------------------------------------------------------------------
+        parameters
+            .add( new Parameter( GracefulShutdownCommandExecutor.DEBUG_PARAMETER, new Boolean( isDebugEnabled() ) ) );
+        parameters
+            .add( new Parameter( GracefulShutdownCommandExecutor.QUIET_PARAMETER, new Boolean( isQuietEnabled() ) ) );
+        parameters.add( new Parameter( GracefulShutdownCommandExecutor.VERBOSE_PARAMETER, new Boolean(
+            isVerboseEnabled() ) ) );
+    }
+
+}

Added: directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/gracefulshutdowncmd/GracefulShutdownCommandExecutor.java
URL: http://svn.apache.org/viewvc/directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/gracefulshutdowncmd/GracefulShutdownCommandExecutor.java?rev=426483&view=auto
==============================================================================
--- directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/gracefulshutdowncmd/GracefulShutdownCommandExecutor.java (added)
+++ directory/trunks/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/commands/gracefulshutdowncmd/GracefulShutdownCommandExecutor.java Fri Jul 28 04:50:40 2006
@@ -0,0 +1,398 @@
+/*
+ *   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.commands.gracefulshutdowncmd;
+
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.Map;
+
+import javax.naming.CommunicationException;
+import javax.naming.ldap.InitialLdapContext;
+import javax.naming.ldap.LdapContext;
+
+import org.apache.directory.server.configuration.ServerStartupConfiguration;
+import org.apache.directory.server.tools.ToolCommandListener;
+import org.apache.directory.server.tools.execution.BaseToolCommandExecutor;
+import org.apache.directory.server.tools.util.ListenerParameter;
+import org.apache.directory.server.tools.util.Parameter;
+import org.apache.directory.server.tools.util.ToolCommandException;
+import org.apache.directory.shared.ldap.message.extended.GracefulShutdownRequest;
+import org.springframework.context.ApplicationContext;
+import org.springframework.context.support.FileSystemXmlApplicationContext;
+
+
+/**
+ * This is the Executor Class of the GracefulShutdown Command.
+ * 
+ * The command can be called using the 'execute' method.
+ */
+public class GracefulShutdownCommandExecutor extends BaseToolCommandExecutor
+{
+    // Additional Parameters
+    public static final String DELAY_PARAMETER = "delay";
+    public static final String TIMEOFFLINE_PARAMETER = "time-offline";
+
+    private int delay;
+
+    private int timeOffline;
+
+    private boolean isWaiting;
+    private boolean isSuccess = false;
+    private Thread executeThread = null;
+
+
+    public GracefulShutdownCommandExecutor()
+    {
+        super( "graceful" );
+    }
+
+
+    /**
+     * Executes the command.
+     * <p>
+     * Use the following Parameters and ListenerParameters to call the command.
+     * <p>
+     * Parameters : <ul>
+     *      <li>"HOST_PARAMETER" with a value of type 'String', representing server host</li>
+     *      <li>"PORT_PARAMETER" with a value of type 'Integer', representing server port</li>
+     *      <li>"PASSWORD_PARAMETER" with a value of type 'String', representing user password</li>
+     *      <li>"DELAY_PARAMETER" with a value of type 'Integer', representing the delay (seconds) before shutdown</li>
+     *      <li>"TIMEOFFLINE_PARAMETER" with a value of type 'Integer', representing the server offline time (minutes)</li>
+     *      <li>"DEBUG_PARAMETER" with a value of type 'Boolean', true to enable debug</li>
+     *      <li>"QUIET_PARAMETER" with a value of type 'Boolean', true to enable quiet</li>
+     *      <li>"VERBOSE_PARAMETER" with a value of type 'Boolean', true to enable verbose</li>
+     *      <li>"INSTALLPATH_PARAMETER" with a value of type 'String', representing the path to installation
+     *          directory</li>
+     *      <li>"CONFIGURATION_PARAMETER" with a value of type "Boolean", true to force loading the server.xml
+     *          (requires "install-path")</li>
+     * </ul>
+     * <br />
+     * ListenersParameters : <ul>
+     *      <li>"OUTPUTLISTENER_PARAMETER", a listener that will receive all output messages. It returns
+     *          messages as a String.</li>
+     *      <li>"ERRORLISTENER_PARAMETER", a listener that will receive all error messages. It returns messages
+     *          as a String.</li>
+     *      <li>"EXCEPTIONLISTENER_PARAMETER", a listener that will receive all exception(s) raised. It returns
+     *          Exceptions.</li>
+     * </ul>
+     * <b>Note:</b> "HOST_PARAMETER", "PORT_PARAMETER", "PASSWORD_PARAMETER", "DELAY_PARAMETER" and "TIMEOFFLINE_PARAMETER" are required.
+     */
+    public void execute( Parameter[] params, ListenerParameter[] listeners )
+    {
+        processParameters( params );
+        processListeners( listeners );
+
+        try
+        {
+            execute();
+        }
+        catch ( Exception e )
+        {
+            notifyExceptionListener( e );
+        }
+    }
+
+
+    private void execute() throws Exception
+    {
+        executeThread = Thread.currentThread();
+
+        if ( isDebugEnabled() )
+        {
+            notifyOutputListener( "Parameters for GracefulShutdown extended request:" );
+            notifyOutputListener( "port = " + port );
+            notifyOutputListener( "host = " + host );
+            notifyOutputListener( "password = " + password );
+            notifyOutputListener( "delay = " + delay );
+            notifyOutputListener( "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() )
+        {
+            notifyOutputListener( "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;
+                notifyErrorListener( "shutdown request failed with error: " + t.getMessage() );
+            }
+            catch ( CommunicationException e )
+            {
+                isSuccess = true;
+            }
+        }
+        isWaiting = false;
+        ctx.close();
+    }
+
+
+    private void processParameters( Parameter[] params )
+    {
+        Map parameters = new HashMap();
+        for ( int i = 0; i < params.length; i++ )
+        {
+            Parameter parameter = params[i];
+            parameters.put( parameter.getName(), parameter.getValue() );
+        }
+
+        // Quiet param
+        Boolean quietParam = ( Boolean ) parameters.get( QUIET_PARAMETER );
+        if ( quietParam != null )
+        {
+            setQuietEnabled( quietParam.booleanValue() );
+        }
+
+        // Debug param
+        Boolean debugParam = ( Boolean ) parameters.get( DEBUG_PARAMETER );
+        if ( debugParam != null )
+        {
+            setDebugEnabled( debugParam.booleanValue() );
+        }
+
+        // Verbose param
+        Boolean verboseParam = ( Boolean ) parameters.get( VERBOSE_PARAMETER );
+        if ( verboseParam != null )
+        {
+            setVerboseEnabled( verboseParam.booleanValue() );
+        }
+
+        // Install-path param
+        String installPathParam = ( String ) parameters.get( INSTALLPATH_PARAMETER );
+        if ( installPathParam != null )
+        {
+            try
+            {
+                setLayout( installPathParam );
+                if ( !isQuietEnabled() )
+                {
+                    notifyOutputListener( "loading settings from: " + getLayout().getConfigurationFile() );
+                }
+                ApplicationContext factory = null;
+                URL configUrl;
+
+                configUrl = getLayout().getConfigurationFile().toURL();
+                factory = new FileSystemXmlApplicationContext( configUrl.toString() );
+                setConfiguration( ( ServerStartupConfiguration ) factory.getBean( "configuration" ) );
+            }
+            catch ( MalformedURLException e )
+            {
+                notifyErrorListener( e.getMessage() );
+                notifyExceptionListener( e );
+            }
+        }
+
+        // Host param
+        String hostParam = ( String ) parameters.get( HOST_PARAMETER );
+        if ( hostParam != null )
+        {
+            host = hostParam;
+        }
+        else
+        {
+            host = DEFAULT_HOST;
+
+            if ( isDebugEnabled() )
+            {
+                notifyOutputListener( "host set to default: " + host );
+            }
+        }
+
+        // Port param
+        Integer portParam = ( Integer ) parameters.get( PORT_PARAMETER );
+        if ( portParam != null )
+        {
+            port = portParam.intValue();
+        }
+        else if ( getConfiguration() != null )
+        {
+            port = getConfiguration().getLdapPort();
+
+            if ( isDebugEnabled() )
+            {
+                notifyOutputListener( "port overriden by server.xml configuration: " + port );
+            }
+        }
+        else
+        {
+            port = DEFAULT_PORT;
+
+            if ( isDebugEnabled() )
+            {
+                notifyOutputListener( "port set to default: " + port );
+            }
+        }
+
+        // Password param
+        String passwordParam = ( String ) parameters.get( PASSWORD_PARAMETER );
+        if ( passwordParam != null )
+        {
+            password = passwordParam;
+        }
+        else
+        {
+            password = DEFAULT_PASSWORD;
+
+            if ( isDebugEnabled() )
+            {
+                notifyOutputListener( "password set to default: " + password );
+            }
+        }
+
+        // Delay param
+        Integer delayParam = ( Integer ) parameters.get( DELAY_PARAMETER );
+        if ( delayParam != null )
+        {
+            delay = delayParam.intValue();
+        }
+        else
+        {
+            delay = 0;
+
+            if ( isDebugEnabled() )
+            {
+                notifyOutputListener( "Using default delay value of " + delay );
+            }
+        }
+
+        // Time-Offline param
+        Integer timeOfflineParam = ( Integer ) parameters.get( TIMEOFFLINE_PARAMETER );
+        if ( timeOfflineParam != null )
+        {
+            timeOffline = timeOfflineParam.intValue();
+        }
+        else
+        {
+            timeOffline = 0;
+
+            if ( isDebugEnabled() )
+            {
+                notifyOutputListener( "Using default timeOffline value of " + timeOffline );
+            }
+        }
+    }
+
+
+    private void processListeners( ListenerParameter[] listeners )
+    {
+        Map parameters = new HashMap();
+        for ( int i = 0; i < listeners.length; i++ )
+        {
+            ListenerParameter parameter = listeners[i];
+            parameters.put( parameter.getName(), parameter.getListener() );
+        }
+
+        // OutputListener param
+        ToolCommandListener outputListener = ( ToolCommandListener ) parameters.get( OUTPUTLISTENER_PARAMETER );
+        if ( outputListener != null )
+        {
+            this.outputListener = outputListener;
+        }
+
+        // ErrorListener param
+        ToolCommandListener errorListener = ( ToolCommandListener ) parameters.get( ERRORLISTENER_PARAMETER );
+        if ( errorListener != null )
+        {
+            this.errorListener = errorListener;
+        }
+
+        // ExceptionListener param
+        ToolCommandListener exceptionListener = ( ToolCommandListener ) parameters.get( EXCEPTIONLISTENER_PARAMETER );
+        if ( exceptionListener != null )
+        {
+            this.exceptionListener = exceptionListener;
+        }
+    }
+
+    class Ticker implements Runnable
+    {
+        public void run()
+        {
+            if ( !isQuietEnabled() )
+                notifyOutputListener( "[waiting for shutdown] " );
+            while ( isWaiting )
+            {
+                try
+                {
+                    Thread.sleep( 1000 );
+                }
+                catch ( InterruptedException e )
+                {
+                    e.printStackTrace();
+                }
+                if ( !isQuietEnabled() )
+                    notifyOutputListener( "." );
+            }
+            if ( isSuccess )
+            {
+                if ( !isQuietEnabled() )
+                    notifyOutputListener( "\n[shutdown complete]" );
+                try
+                {
+                    executeThread.join( 1000 );
+                }
+                catch ( InterruptedException e )
+                {
+                    e.printStackTrace();
+                }
+                return;
+            }
+            else
+            {
+                if ( !isQuietEnabled() )
+                    notifyOutputListener( "\n[shutdown failed]" );
+                try
+                {
+                    executeThread.join( 1000 );
+                }
+                catch ( InterruptedException e )
+                {
+                    e.printStackTrace();
+                }
+                notifyExceptionListener( new ToolCommandException( "Shutdown failed" ) );
+                return;
+            }
+        }
+    }
+}



Mime
View raw message