directory-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From elecha...@apache.org
Subject svn commit: r407090 - in /directory/branches/elecharny/apacheds/server-tools/src/main/java/org/apache/directory/server/tools: BaseCommand.java ImportCommand.java
Date Tue, 16 May 2006 22:04:57 GMT
Author: elecharny
Date: Tue May 16 15:04:52 2006
New Revision: 407090

URL: http://svn.apache.org/viewcvs?rev=407090&view=rev
Log:
Fixed tabs/space mixing

Modified:
    directory/branches/elecharny/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/BaseCommand.java
    directory/branches/elecharny/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/ImportCommand.java

Modified: directory/branches/elecharny/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/BaseCommand.java
URL: http://svn.apache.org/viewcvs/directory/branches/elecharny/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/BaseCommand.java?rev=407090&r1=407089&r2=407090&view=diff
==============================================================================
--- directory/branches/elecharny/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/BaseCommand.java
(original)
+++ directory/branches/elecharny/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/BaseCommand.java
Tue May 16 15:04:52 2006
@@ -16,7 +16,6 @@
  */
 package org.apache.directory.server.tools;
 
-
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.Iterator;
@@ -35,7 +34,6 @@
 import org.apache.commons.cli.PosixParser;
 import org.apache.commons.cli.UnrecognizedOptionException;
 
-
 /**
  * The primary command base class.
  * 
@@ -45,33 +43,38 @@
 public class BaseCommand
 {
     private Map commands = new HashMap();
+
     private List commandsOrdered = new ArrayList();
+
     private Options global = new Options();
+
     private String productCommand;
+
     private String productVersion;
+
     private String productDisplayName;
+
     private String productUrl;
+
     private String productBanner;
-    
-    
+
     public BaseCommand()
     {
         init();
     }
-    
-    
+
     protected void init()
     {
         ToolCommand command;
-        
+
         command = new DiagnosticCommand();
         commands.put( command.getName(), command );
         commandsOrdered.add( command.getName() );
-        
+
         command = new DumpCommand();
         commands.put( command.getName(), command );
         commandsOrdered.add( command.getName() );
-        
+
         command = new GracefulShutdownCommand();
         commands.put( command.getName(), command );
         commandsOrdered.add( command.getName() );
@@ -99,8 +102,7 @@
         op = new Option( "version", false, "print the version information and exit" );
         getGlobal().addOption( op );
     }
-    
-    
+
     public static boolean hasBannerOption( String[] args )
     {
         for ( int ii = 0; ii < args.length; ii++ )
@@ -113,7 +115,6 @@
         return false;
     }
 
-
     public CommandLine getCommandLine( String command, String[] args )
     {
         Options all = allOptions( command );
@@ -123,27 +124,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() );
+            System.err.println( "Command line parsing failed for " + command + ".  Reason:
already selected "
+                    + 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() );
+            System.err.println( "Command line parsing failed for " + command + ".  Reason:
missing argument "
+                    + 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.exit( 1 );
         }
-        catch ( UnrecognizedOptionException uoe )
+        catch (UnrecognizedOptionException uoe)
         {
-            System.err.println( "Command line parsing failed for " + command + ".  Reason:
unrecognized option" + uoe.getMessage() );
+            System.err.println( "Command line parsing failed for " + command + ".  Reason:
unrecognized option"
+                    + 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 );
@@ -152,7 +156,6 @@
         return cmdline;
     }
 
-
     public Options allOptions( String command )
     {
         if ( command.equals( "help" ) )
@@ -161,21 +164,20 @@
         }
 
         Options all = new Options();
-        ToolCommand cmd = ( ToolCommand ) 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 )
@@ -187,7 +189,7 @@
 
         StringBuffer buf = new StringBuffer();
         buf.append( msg ).append( "\n" );
-        
+
         for ( int ii = 0; ii < args.length; ii++ )
         {
             buf.append( "\targs[" + ii + "] = " ).append( args[ii] ).append( "\n" );
@@ -195,7 +197,6 @@
         System.out.println( buf );
     }
 
-
     public void helpOnCommand( String command )
     {
         if ( command.equals( "help" ) )
@@ -203,12 +204,12 @@
             printUsage();
             System.exit( 0 );
         }
-        
+
         if ( getCommands().containsKey( command ) )
         {
-            ToolCommand cmd = ( ToolCommand ) getCommands().get( command );
+            ToolCommand cmd = (ToolCommand) getCommands().get( command );
             HelpFormatter formatter = new HelpFormatter();
-            formatter.printHelp(  getProductCommand() + " " + cmd + " [options]", cmd.getOptions()
);
+            formatter.printHelp( getProductCommand() + " " + cmd + " [options]", cmd.getOptions()
);
         }
         else
         {
@@ -217,17 +218,16 @@
         }
     }
 
-
     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();
         System.out.println( "\thelp" );
-        
+
         while ( it.hasNext() )
         {
             System.out.println( "\t" + it.next() );
@@ -238,96 +238,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 commands )
     {
         this.commands = commands;
     }
 
-
     public Map getCommands()
     {
         return commands;
     }
 
-
     public void setGlobal( Options global )
     {
         this.global = global;
     }
-
 
     public Options getGlobal()
     {

Modified: directory/branches/elecharny/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/ImportCommand.java
URL: http://svn.apache.org/viewcvs/directory/branches/elecharny/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/ImportCommand.java?rev=407090&r1=407089&r2=407090&view=diff
==============================================================================
--- directory/branches/elecharny/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/ImportCommand.java
(original)
+++ directory/branches/elecharny/apacheds/server-tools/src/main/java/org/apache/directory/server/tools/ImportCommand.java
Tue May 16 15:04:52 2006
@@ -65,556 +65,594 @@
  * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
  * @version $Rev: 406112 $
  */
-public class ImportCommand extends ToolCommand {
-	public static final String PORT_RANGE = "("
-			+ AvailablePortFinder.MIN_PORT_NUMBER + ", "
-			+ AvailablePortFinder.MAX_PORT_NUMBER + ")";
+public class ImportCommand extends ToolCommand
+{
+    public static final String PORT_RANGE = "(" + AvailablePortFinder.MIN_PORT_NUMBER + ",
"
+            + AvailablePortFinder.MAX_PORT_NUMBER + ")";
 
-	private int port = 10389;
+    private int port = 10389;
 
-	private String host = "localhost";
+    private String host = "localhost";
 
-	private String password = "secret";
+    private String password = "secret";
 
-	private String user = "uid=admin,ou=system";
+    private String user = "uid=admin,ou=system";
 
-	private String auth = "simple";
+    private String auth = "simple";
 
-	private File ldifFile;
+    private File ldifFile;
 
-	private String logs;
+    private String logs;
 
-	private boolean ignoreErrors = false;
+    private boolean ignoreErrors = false;
+
+    /**
+     * Socket used to connect to the server
+     */
+    private SocketChannel channel;
 
-	/**
-	 * Socket used to connect to the server
-	 */
-	private SocketChannel channel;
     private SocketAddress serverAddress;
-	private IAsn1Container ldapMessageContainer = new LdapMessageContainer();
-	private Asn1Decoder ldapDecoder = new LdapDecoder();
 
-	/**
-	 * The constructor save the command's name into it's super class
-	 * 
-	 */
-	protected ImportCommand() {
-		super( "import" );
-	}
-
-	/**
-	 * Connect to the LDAP server through a socket and establish the Input and
-	 * Output Streams. All the required information for the connection should be
-	 * in the options from the command line, or the default values.
-	 * 
-	 * @throws UnknownHostException
-	 *             The hostname or the Address of server could not be found
-	 * @throws IOException
-	 *             There was a error opening or establishing the socket
-	 */
-	private void connect() throws UnknownHostException, IOException {
-		serverAddress = new InetSocketAddress( host, port );
-		channel = SocketChannel.open( serverAddress ); 
-		channel.configureBlocking( true );
-	}
-
-	private void sendMessage(ByteBuffer bb) throws IOException {
-		channel.write( bb );
-		bb.clear();
-	}
-
-	private LdapMessage readResponse( ByteBuffer bb ) throws IOException, DecoderException {
-		
-		LdapMessage messageResp = null;
-		
-		while (true)
-		{
-			int nbRead = channel.read( bb );
-			
-			if (nbRead == -1)
-			{
-				break;
-			}
-			else
-			{
-				bb.flip();
-				
-		        // Decode the PDU
-		        ldapDecoder.decode( bb, ldapMessageContainer );
-				
-		        if ( ldapMessageContainer.getState() == TLVStateEnum.PDU_DECODED )
-		        {
-		        	messageResp = ((LdapMessageContainer)ldapMessageContainer).getLdapMessage();
-		        	
-		        	if ( messageResp instanceof BindResponse )
-		        	{
-			        	BindResponse resp = ((LdapMessageContainer)ldapMessageContainer).getLdapMessage().getBindResponse();
-
-			        	if (resp.getLdapResult().getResultCode() != 0 )
-			        	{
-			        		System.out.println( "Error : " + resp.getLdapResult().getErrorMessage() );
-			        	}
-		        	}
-		        	else if (messageResp instanceof ExtendedResponse )
-		        	{
-			        	ExtendedResponse resp = ((LdapMessageContainer)ldapMessageContainer).getLdapMessage().getExtendedResponse();
-			        	
-			        	if (resp.getLdapResult().getResultCode() != 0 )
-			        	{
-			        		System.out.println( "Error : " + resp.getLdapResult().getErrorMessage() );
-			        	}
-		        	}
-		        	
-		        	//System.out.println( messageResp.toString() );
-		        	
-		        	//System.out.println( ((LdapMessageContainer)ldapMessageContainer).getLdapMessage()
);
-		        	((LdapMessageContainer)ldapMessageContainer).clean();
-		        	break;
-		        }
-		        else
-		        {
-		        	bb.flip();
-		        }
-			}
-		}
-
-		return messageResp;
-		
-	}
-
-	/**
-	 * Prepare the LDIF entry and send it to the encoder, then wait for a
-	 * reponse from the LDAP server on the results of the operation.
-	 * 
-	 * @param a_buf
-	 *            The string buffer that contain the LDIF entry
-	 * @param msgId
-	 *            message id number
-	 */
-	private void addEntry( Entry entry, int messageId ) throws IOException,
-			DecoderException, InvalidNameException, NamingException,
-			EncoderException 
-	{
-		AddRequest addRequest = new AddRequest();
-
-		String dn = entry.getDn();
-
-		if ( isDebugEnabled() )
-		{
-			System.out.println( "Adding entry " + dn );
-		}
-
-		Attributes attributes = entry.getAttributes();
-
-		addRequest.setEntry( new LdapDN( dn ) );
-
-		addRequest.initAttributes();
-		
-		for (NamingEnumeration attrs = attributes.getAll(); attrs.hasMoreElements();) {
-			Attribute attribute = (Attribute) attrs.nextElement();
-
-			addRequest.addAttributeType( attribute.getID() );
-
-			for (NamingEnumeration values = attribute.getAll(); values.hasMoreElements();) 
-			{
-				Object value = values.nextElement();
-				addRequest.addAttributeValue(value);
-			}
-		}
-
-		LdapMessage message = new LdapMessage();
-
-		message.setProtocolOP(addRequest);
-		message.setMessageId(messageId);
-		ByteBuffer bb = message.encode(null);
-		bb.flip();
-
-		sendMessage(bb);
-		
-		bb.clear();
-		
-		LdapMessage response = readResponse( bb );
-
-		LdapResult result = response.getAddResponse().getLdapResult();
-
-		if (result.getResultCode() == LdapResultEnum.SUCCESS) {
-			if (isDebugEnabled()) {
-				System.out.println("Add of Entry " + entry.getDn()
-						+ " was successful");
-			}
-		} else {
-			System.err
-					.println("Add of entry "
-							+ entry.getDn()
-							+ " failed for the following reasons provided by the server:\n"
-							+ result.getErrorMessage());
-		}
-	}
-
-	private void bind( int messageId ) throws InvalidNameException, EncoderException,
-		DecoderException, IOException
-	{
-		BindRequest bindRequest = new BindRequest();
-		LdapMessage message = new LdapMessage();
-		LdapAuthentication authentication = null; 
-
-		if ( "simple".equals( auth ) )
-		{
-			authentication = new SimpleAuthentication();
-			((SimpleAuthentication)authentication).setSimple( StringTools.getBytesUtf8( password )
);
-		}
-
-		bindRequest.setAuthentication(authentication);
-		bindRequest.setName( new LdapDN( user ) );
-		bindRequest.setVersion( 3 );
-
-		message.setProtocolOP( bindRequest );
-		message.setMessageId( messageId );
-		ByteBuffer bb = message.encode(null);
-		bb.flip();
-
-		connect();
-		sendMessage(bb);
-		
-		bb.clear();
-		
-		LdapMessage response = readResponse( bb );
-
-		LdapResult result = response.getBindResponse().getLdapResult();
-
-		if (result.getResultCode() == LdapResultEnum.SUCCESS) {
-			if (isDebugEnabled()) {
-				System.out.println("Binding of user " + user
-						+ " was successful");
-			}
-		} else {
-			System.err
-					.println("Binding of user "
-							+ user
-							+ " failed for the following reasons provided by the server:\n"
-							+ result.getErrorMessage());
-			System.exit( 1 );
-		}
-	}
-
-	/**
-	 * Unbind from the server
-	 * @param messageId The message Id
-	 * @throws InvalidNameException
-	 * @throws EncoderException
-	 * @throws DecoderException
-	 * @throws IOException
-	 */
-	private void unbind( int messageId ) throws InvalidNameException, EncoderException,
-		DecoderException, IOException
-	{
-		UnBindRequest unbindRequest = new UnBindRequest();
-		LdapMessage message = new LdapMessage();
-	
-		message.setProtocolOP( unbindRequest );
-		message.setMessageId( messageId );
-		ByteBuffer bb = message.encode(null);
-		bb.flip();
-	
-		connect();
-		sendMessage(bb);
-		
-		bb.clear();
-		
-		LdapMessage response = readResponse( bb );
-	
-		LdapResult result = response.getAddResponse().getLdapResult();
-	
-		if (result.getResultCode() == LdapResultEnum.SUCCESS) {
-			if (isDebugEnabled()) {
-				System.out.println("Unbinding of user " + user
-						+ " was successful");
-			}
-		} else {
-			System.err
-					.println("Uninding of user "
-							+ user
-							+ " failed for the following reasons provided by the server:\n"
-							+ result.getErrorMessage());
-			System.exit( 1 );
-		}
-	}
-	
-	/**
-	 * Execute the command
-	 * 
-	 * @param cmd
-	 *            The command to be executed
-	 */
-	public void execute(CommandLine cmd) throws Exception {
-		processOptions(cmd);
-
-		if (isDebugEnabled()) {
-			System.out.println("Parameters for Ldif import request:");
-			System.out.println("port = " + port);
-			System.out.println("host = " + host);
-			System.out.println("user = " + user);
-			System.out.println("auth type = " + auth);
-			System.out.println("file = " + ldifFile);
-			System.out.println("logs = " + logs);
-		}
-
-		int messageId = 0;
-
-		// Login to the server
-		bind( messageId++ );
-
-		if (isDebugEnabled()) {
-			System.out.println("Connection to the server established.\n"
-					+ "Importing data ... ");
-		}
-
-		LdifReader ldifReader = new LdifReader( ldifFile );
-		
-		if ( ldifReader.containsEntries() )
-		{
-			// Parse the file and inject every entri or every modification
-			Iterator entries = ldifReader.iterator();
-			long t0 = System.currentTimeMillis();
-			int nbAdd = 0;
-
-			while ( entries.hasNext() ) {
-				Entry entry = (Entry)entries.next();
-				
-				addEntry( entry, messageId++ );
-				nbAdd++;
-				
-				if ( nbAdd % 10 == 0 )
-				{
-					System.out.print( '.' );
-				}
-				
-				if ( nbAdd % 500 == 0 )
-				{
-					System.out.println( nbAdd );
-				}
-			}
-			
-			long t1 = System.currentTimeMillis();
-
-			System.out.println( "Done!" );
-			System.out.println( nbAdd + " users added in " + ( ( t1 - t0 ) / 1000 ) + " seconds" );
-		}
-		else
-		{
-			// Parse the file and inject every entri or every modification
-			Iterator changes = ldifReader.iterator();
-
-			while ( changes.hasNext() ) {
-				ModificationItem modification = (ModificationItem)changes.next();
-				
-				//addchange( modification, messageId++ );
-			}
-		}
-
-		// Logout to the server
-		unbind( messageId++ );
-
-	}
-
-	/**
-	 * Read the command line and get the options : 'h' : host 'p' : port 'u' :
-	 * user 'w' : password 'a' : authentication type 'i' : ignore errors 'f' :
-	 * ldif file to import
-	 * 
-	 * @param cmd
-	 *            The command line
-	 */
-	private void processOptions(CommandLine cmd) {
-		if (isDebugEnabled()) {
-			System.out
-					.println("Processing options for launching diagnostic UI ...");
-		}
-
-		// -------------------------------------------------------------------
-		// figure out the host value
-		// -------------------------------------------------------------------
-
-		if (cmd.hasOption('h')) {
-			host = cmd.getOptionValue('h');
-
-			if (isDebugEnabled()) {
-				System.out
-						.println("ignore-errors overriden by -i option: true");
-			}
-		} else if (isDebugEnabled()) {
-			System.out.println("ignore-errors set to default: false");
-		}
-
-		// -------------------------------------------------------------------
-		// figure out and error check the port value
-		// -------------------------------------------------------------------
-
-		if (cmd.hasOption('p')) // - user provided port w/ -p takes precedence
-		{
-			String val = cmd.getOptionValue('p');
-
-			try {
-				port = Integer.parseInt(val);
-			} catch (NumberFormatException e) {
-				System.err.println("port value of '" + val
-						+ "' is not a number");
-				System.exit(1);
-			}
-
-			if (port > AvailablePortFinder.MAX_PORT_NUMBER) {
-				System.err.println("port value of '" + val
-						+ "' is larger than max port number: "
-						+ AvailablePortFinder.MAX_PORT_NUMBER);
-				System.exit(1);
-			} else if (port < AvailablePortFinder.MIN_PORT_NUMBER) {
-				System.err.println("port value of '" + val
-						+ "' is smaller than the minimum port number: "
-						+ AvailablePortFinder.MIN_PORT_NUMBER);
-				System.exit(1);
-			}
-
-			if (isDebugEnabled()) {
-				System.out.println("port overriden by -p option: " + port);
-			}
-		} else if (getConfiguration() != null) {
-			port = getConfiguration().getLdapPort();
-
-			if (isDebugEnabled()) {
-				System.out
-						.println("port overriden by server.xml configuration: "
-								+ port);
-			}
-		} else if (isDebugEnabled()) {
-			System.out.println("port set to default: " + port);
-		}
-
-		// -------------------------------------------------------------------
-		// figure out the user value
-		// -------------------------------------------------------------------
-
-		if (cmd.hasOption('u')) {
-			user = cmd.getOptionValue('u');
-
-			if (isDebugEnabled()) {
-				System.out.println("user overriden by -u option: " + user);
-			}
-		} else if (isDebugEnabled()) {
-			System.out.println("user set to default: " + user);
-		}
-
-		// -------------------------------------------------------------------
-		// figure out the password value
-		// -------------------------------------------------------------------
-
-		if (cmd.hasOption('w')) {
-			password = cmd.getOptionValue('w');
-
-			if (isDebugEnabled()) {
-				System.out.println("password overriden by -w option: "
-						+ password);
-			}
-		} else if (isDebugEnabled()) {
-			System.out.println("password set to default: " + password);
-		}
-
-		// -------------------------------------------------------------------
-		// figure out the authentication type
-		// -------------------------------------------------------------------
-
-		if (cmd.hasOption('a')) {
-			auth = cmd.getOptionValue('a');
-
-			if (isDebugEnabled()) {
-				System.out
-						.println("authentication type overriden by -a option: "
-								+ auth);
-			}
-		} else if (isDebugEnabled()) {
-			System.out.println("authentication type set to default: " + auth);
-		}
-
-		// -------------------------------------------------------------------
-		// figure out the 'ignore-errors' flag
-		// -------------------------------------------------------------------
-
-		if (cmd.hasOption('i')) {
-			ignoreErrors = true;
-
-			if (isDebugEnabled()) {
-				System.out
-						.println("authentication type overriden by -a option: "
-								+ auth);
-			}
-		} else if (isDebugEnabled()) {
-			System.out.println("authentication type set to default: " + auth);
-		}
-
-		// -------------------------------------------------------------------
-		// figure out the ldif file to import
-		// -------------------------------------------------------------------
-
-		if (cmd.hasOption('f')) {
-			String ldifFileName = cmd.getOptionValue('f');
-
-			ldifFile = new File(ldifFileName);
-
-			if (ldifFile.exists() == false) {
-				System.err.println("ldif file '" + ldifFileName
-						+ "' does not exist");
-				System.exit(1);
-			}
-
-			if (ldifFile.canRead() == false) {
-				System.err.println("ldif file '" + ldifFileName
-						+ "' can't be read");
-				System.exit(1);
-			}
-
-			if (isDebugEnabled()) {
-				try {
-					System.out.println("ldif file to import: "
-							+ ldifFile.getCanonicalPath());
-				} catch (IOException ioe) {
-					System.out.println("ldif file to import: " + ldifFileName);
-				}
-			}
-		} else {
-			System.err.println("ldif file name must be provided");
-			System.exit(1);
-		}
-	}
-
-	public Options getOptions() {
-		Options opts = new Options();
-		Option op = new Option("h", "host", true,
-				"server host: defaults to localhost");
-		op.setRequired(false);
-		opts.addOption(op);
-		op = new Option("p", "port", true,
-				"server port: defaults to 10389 or server.xml specified port");
-		op.setRequired(false);
-		opts.addOption(op);
-		op = new Option("u", "user", true,
-				"the user: default to uid=admin, ou=system");
-		op.setRequired(false);
-		opts.addOption(op);
-		op = new Option( "w", "password", true,
-				"the apacheds administrator's password: defaults to secret") ;
-		op.setRequired(false);
-		opts.addOption(op);
-		op = new Option( "a", "auth", true,
-				"the authentication mode: defaults to 'simple'" );
-		op.setRequired(false);
-		opts.addOption(op);
-		op = new Option( "f", "file", true, "the ldif file to import" );
-		op.setRequired( true);
-		opts.addOption(op);
-		op = new Option( "i", "ignore", true,
-				"continue to process the file even if errors are encountered " );
-		op.setRequired(false);
-		opts.addOption(op);
+    private IAsn1Container ldapMessageContainer = new LdapMessageContainer();
+
+    private Asn1Decoder ldapDecoder = new LdapDecoder();
+
+    /**
+     * The constructor save the command's name into it's super class
+     * 
+     */
+    protected ImportCommand()
+    {
+        super( "import" );
+    }
+
+    /**
+     * Connect to the LDAP server through a socket and establish the Input and
+     * Output Streams. All the required information for the connection should be
+     * in the options from the command line, or the default values.
+     * 
+     * @throws UnknownHostException
+     *             The hostname or the Address of server could not be found
+     * @throws IOException
+     *             There was a error opening or establishing the socket
+     */
+    private void connect() throws UnknownHostException, IOException
+    {
+        serverAddress = new InetSocketAddress( host, port );
+        channel = SocketChannel.open( serverAddress );
+        channel.configureBlocking( true );
+    }
+
+    private void sendMessage( ByteBuffer bb ) throws IOException
+    {
+        channel.write( bb );
+        bb.clear();
+    }
+
+    private LdapMessage readResponse( ByteBuffer bb ) throws IOException, DecoderException
+    {
+
+        LdapMessage messageResp = null;
+
+        while ( true )
+        {
+            int nbRead = channel.read( bb );
+
+            if ( nbRead == -1 )
+            {
+                break;
+            }
+            else
+            {
+                bb.flip();
+
+                // Decode the PDU
+                ldapDecoder.decode( bb, ldapMessageContainer );
+
+                if ( ldapMessageContainer.getState() == TLVStateEnum.PDU_DECODED )
+                {
+                    messageResp = ( (LdapMessageContainer) ldapMessageContainer ).getLdapMessage();
+
+                    if ( messageResp instanceof BindResponse )
+                    {
+                        BindResponse resp = ( (LdapMessageContainer) ldapMessageContainer
).getLdapMessage().getBindResponse();
+
+                        if ( resp.getLdapResult().getResultCode() != 0 )
+                        {
+                            System.out.println( "Error : " + resp.getLdapResult().getErrorMessage()
);
+                        }
+                    }
+                    else if ( messageResp instanceof ExtendedResponse )
+                    {
+                        ExtendedResponse resp = ( (LdapMessageContainer) ldapMessageContainer
).getLdapMessage()
+                                .getExtendedResponse();
+
+                        if ( resp.getLdapResult().getResultCode() != 0 )
+                        {
+                            System.out.println( "Error : " + resp.getLdapResult().getErrorMessage()
);
+                        }
+                    }
+
+                    // System.out.println( messageResp.toString() );
+
+                    // System.out.println(
+                    // ((LdapMessageContainer)ldapMessageContainer).getLdapMessage()
+                    // );
+                    ( (LdapMessageContainer) ldapMessageContainer ).clean();
+                    break;
+                }
+                else
+                {
+                    bb.flip();
+                }
+            }
+        }
+
+        return messageResp;
+
+    }
+
+    /**
+     * Prepare the LDIF entry and send it to the encoder, then wait for a
+     * reponse from the LDAP server on the results of the operation.
+     * 
+     * @param a_buf
+     *            The string buffer that contain the LDIF entry
+     * @param msgId
+     *            message id number
+     */
+    private void addEntry( Entry entry, int messageId ) throws IOException, DecoderException,
InvalidNameException,
+            NamingException, EncoderException
+    {
+        AddRequest addRequest = new AddRequest();
+
+        String dn = entry.getDn();
+
+        if ( isDebugEnabled() )
+        {
+            System.out.println( "Adding entry " + dn );
+        }
+
+        Attributes attributes = entry.getAttributes();
+
+        addRequest.setEntry( new LdapDN( dn ) );
+
+        addRequest.initAttributes();
+
+        for ( NamingEnumeration attrs = attributes.getAll(); attrs.hasMoreElements(); )
+        {
+            Attribute attribute = (Attribute) attrs.nextElement();
+
+            addRequest.addAttributeType( attribute.getID() );
+
+            for ( NamingEnumeration values = attribute.getAll(); values.hasMoreElements();
)
+            {
+                Object value = values.nextElement();
+                addRequest.addAttributeValue( value );
+            }
+        }
+
+        LdapMessage message = new LdapMessage();
+
+        message.setProtocolOP( addRequest );
+        message.setMessageId( messageId );
+        ByteBuffer bb = message.encode( null );
+        bb.flip();
+
+        sendMessage( bb );
+
+        bb.clear();
+
+        LdapMessage response = readResponse( bb );
+
+        LdapResult result = response.getAddResponse().getLdapResult();
+
+        if ( result.getResultCode() == LdapResultEnum.SUCCESS )
+        {
+            if ( isDebugEnabled() )
+            {
+                System.out.println( "Add of Entry " + entry.getDn() + " was successful" );
+            }
+        }
+        else
+        {
+            System.err.println( "Add of entry " + entry.getDn() + " failed for the following
reasons provided by the server:\n"
+                    + result.getErrorMessage() );
+        }
+    }
+
+    private void bind( int messageId ) throws InvalidNameException, EncoderException, DecoderException,
IOException
+    {
+        BindRequest bindRequest = new BindRequest();
+        LdapMessage message = new LdapMessage();
+        LdapAuthentication authentication = null;
+
+        if ( "simple".equals( auth ) )
+        {
+            authentication = new SimpleAuthentication();
+            ( (SimpleAuthentication) authentication ).setSimple( StringTools.getBytesUtf8(
password ) );
+        }
+
+        bindRequest.setAuthentication( authentication );
+        bindRequest.setName( new LdapDN( user ) );
+        bindRequest.setVersion( 3 );
+
+        message.setProtocolOP( bindRequest );
+        message.setMessageId( messageId );
+        ByteBuffer bb = message.encode( null );
+        bb.flip();
+
+        connect();
+        sendMessage( bb );
+
+        bb.clear();
+
+        LdapMessage response = readResponse( bb );
+
+        LdapResult result = response.getBindResponse().getLdapResult();
+
+        if ( result.getResultCode() == LdapResultEnum.SUCCESS )
+        {
+            if ( isDebugEnabled() )
+            {
+                System.out.println( "Binding of user " + user + " was successful" );
+            }
+        }
+        else
+        {
+            System.err.println( "Binding of user " + user + " failed for the following reasons
provided by the server:\n"
+                    + result.getErrorMessage() );
+            System.exit( 1 );
+        }
+    }
+
+    /**
+     * Unbind from the server
+     * 
+     * @param messageId
+     *            The message Id
+     * @throws InvalidNameException
+     * @throws EncoderException
+     * @throws DecoderException
+     * @throws IOException
+     */
+    private void unbind( int messageId ) throws InvalidNameException, EncoderException, DecoderException,
IOException
+    {
+        UnBindRequest unbindRequest = new UnBindRequest();
+        LdapMessage message = new LdapMessage();
+
+        message.setProtocolOP( unbindRequest );
+        message.setMessageId( messageId );
+        ByteBuffer bb = message.encode( null );
+        bb.flip();
+
+        connect();
+        sendMessage( bb );
+
+        bb.clear();
+
+        LdapMessage response = readResponse( bb );
+
+        LdapResult result = response.getAddResponse().getLdapResult();
+
+        if ( result.getResultCode() == LdapResultEnum.SUCCESS )
+        {
+            if ( isDebugEnabled() )
+            {
+                System.out.println( "Unbinding of user " + user + " was successful" );
+            }
+        }
+        else
+        {
+            System.err.println( "Uninding of user " + user + " failed for the following reasons
provided by the server:\n"
+                    + result.getErrorMessage() );
+            System.exit( 1 );
+        }
+    }
+
+    /**
+     * Execute the command
+     * 
+     * @param cmd
+     *            The command to be executed
+     */
+    public void execute( CommandLine cmd ) throws Exception
+    {
+        processOptions( cmd );
+
+        if ( isDebugEnabled() )
+        {
+            System.out.println( "Parameters for Ldif import request:" );
+            System.out.println( "port = " + port );
+            System.out.println( "host = " + host );
+            System.out.println( "user = " + user );
+            System.out.println( "auth type = " + auth );
+            System.out.println( "file = " + ldifFile );
+            System.out.println( "logs = " + logs );
+        }
+
+        int messageId = 0;
+
+        // Login to the server
+        bind( messageId++ );
+
+        if ( isDebugEnabled() )
+        {
+            System.out.println( "Connection to the server established.\n" + "Importing data
... " );
+        }
+
+        LdifReader ldifReader = new LdifReader( ldifFile );
+
+        if ( ldifReader.containsEntries() )
+        {
+            // Parse the file and inject every entri or every modification
+            Iterator entries = ldifReader.iterator();
+            long t0 = System.currentTimeMillis();
+            int nbAdd = 0;
+
+            while ( entries.hasNext() )
+            {
+                Entry entry = (Entry) entries.next();
+
+                addEntry( entry, messageId++ );
+                nbAdd++;
+
+                if ( nbAdd % 10 == 0 )
+                {
+                    System.out.print( '.' );
+                }
+
+                if ( nbAdd % 500 == 0 )
+                {
+                    System.out.println( nbAdd );
+                }
+            }
+
+            long t1 = System.currentTimeMillis();
+
+            System.out.println( "Done!" );
+            System.out.println( nbAdd + " users added in " + ( ( t1 - t0 ) / 1000 ) + " seconds"
);
+        }
+        else
+        {
+            // Parse the file and inject every entri or every modification
+            Iterator changes = ldifReader.iterator();
+
+            while ( changes.hasNext() )
+            {
+                ModificationItem modification = (ModificationItem) changes.next();
+
+                // addchange( modification, messageId++ );
+            }
+        }
+
+        // Logout to the server
+        unbind( messageId++ );
+
+    }
+
+    /**
+     * Read the command line and get the options : 'h' : host 'p' : port 'u' :
+     * user 'w' : password 'a' : authentication type 'i' : ignore errors 'f' :
+     * ldif file to import
+     * 
+     * @param cmd
+     *            The command line
+     */
+    private void processOptions( CommandLine cmd )
+    {
+        if ( isDebugEnabled() )
+        {
+            System.out.println( "Processing options for launching diagnostic UI ..." );
+        }
+
+        // -------------------------------------------------------------------
+        // figure out the host value
+        // -------------------------------------------------------------------
+
+        if ( cmd.hasOption( 'h' ) )
+        {
+            host = cmd.getOptionValue( 'h' );
+
+            if ( isDebugEnabled() )
+            {
+                System.out.println( "ignore-errors overriden by -i option: true" );
+            }
+        }
+        else if ( isDebugEnabled() )
+        {
+            System.out.println( "ignore-errors set to default: false" );
+        }
+
+        // -------------------------------------------------------------------
+        // figure out and error check the port value
+        // -------------------------------------------------------------------
+
+        if ( cmd.hasOption( 'p' ) ) // - user provided port w/ -p takes
+                                    // precedence
+        {
+            String val = cmd.getOptionValue( 'p' );
+
+            try
+            {
+                port = Integer.parseInt( val );
+            }
+            catch (NumberFormatException e)
+            {
+                System.err.println( "port value of '" + val + "' is not a number" );
+                System.exit( 1 );
+            }
+
+            if ( port > AvailablePortFinder.MAX_PORT_NUMBER )
+            {
+                System.err.println( "port value of '" + val + "' is larger than max port
number: "
+                        + AvailablePortFinder.MAX_PORT_NUMBER );
+                System.exit( 1 );
+            }
+            else if ( port < AvailablePortFinder.MIN_PORT_NUMBER )
+            {
+                System.err.println( "port value of '" + val + "' is smaller than the minimum
port number: "
+                        + AvailablePortFinder.MIN_PORT_NUMBER );
+                System.exit( 1 );
+            }
+
+            if ( isDebugEnabled() )
+            {
+                System.out.println( "port overriden by -p option: " + port );
+            }
+        }
+        else if ( getConfiguration() != null )
+        {
+            port = getConfiguration().getLdapPort();
+
+            if ( isDebugEnabled() )
+            {
+                System.out.println( "port overriden by server.xml configuration: " + port
);
+            }
+        }
+        else if ( isDebugEnabled() )
+        {
+            System.out.println( "port set to default: " + port );
+        }
+
+        // -------------------------------------------------------------------
+        // figure out the user value
+        // -------------------------------------------------------------------
+
+        if ( cmd.hasOption( 'u' ) )
+        {
+            user = cmd.getOptionValue( 'u' );
+
+            if ( isDebugEnabled() )
+            {
+                System.out.println( "user overriden by -u option: " + user );
+            }
+        }
+        else if ( isDebugEnabled() )
+        {
+            System.out.println( "user set to default: " + user );
+        }
+
+        // -------------------------------------------------------------------
+        // figure out the password value
+        // -------------------------------------------------------------------
+
+        if ( cmd.hasOption( 'w' ) )
+        {
+            password = cmd.getOptionValue( 'w' );
+
+            if ( isDebugEnabled() )
+            {
+                System.out.println( "password overriden by -w option: " + password );
+            }
+        }
+        else if ( isDebugEnabled() )
+        {
+            System.out.println( "password set to default: " + password );
+        }
+
+        // -------------------------------------------------------------------
+        // figure out the authentication type
+        // -------------------------------------------------------------------
+
+        if ( cmd.hasOption( 'a' ) )
+        {
+            auth = cmd.getOptionValue( 'a' );
+
+            if ( isDebugEnabled() )
+            {
+                System.out.println( "authentication type overriden by -a option: " + auth
);
+            }
+        }
+        else if ( isDebugEnabled() )
+        {
+            System.out.println( "authentication type set to default: " + auth );
+        }
+
+        // -------------------------------------------------------------------
+        // figure out the 'ignore-errors' flag
+        // -------------------------------------------------------------------
+
+        if ( cmd.hasOption( 'i' ) )
+        {
+            ignoreErrors = true;
+
+            if ( isDebugEnabled() )
+            {
+                System.out.println( "authentication type overriden by -a option: " + auth
);
+            }
+        }
+        else if ( isDebugEnabled() )
+        {
+            System.out.println( "authentication type set to default: " + auth );
+        }
+
+        // -------------------------------------------------------------------
+        // figure out the ldif file to import
+        // -------------------------------------------------------------------
+
+        if ( cmd.hasOption( 'f' ) )
+        {
+            String ldifFileName = cmd.getOptionValue( 'f' );
+
+            ldifFile = new File( ldifFileName );
+
+            if ( ldifFile.exists() == false )
+            {
+                System.err.println( "ldif file '" + ldifFileName + "' does not exist" );
+                System.exit( 1 );
+            }
+
+            if ( ldifFile.canRead() == false )
+            {
+                System.err.println( "ldif file '" + ldifFileName + "' can't be read" );
+                System.exit( 1 );
+            }
+
+            if ( isDebugEnabled() )
+            {
+                try
+                {
+                    System.out.println( "ldif file to import: " + ldifFile.getCanonicalPath()
);
+                }
+                catch (IOException ioe)
+                {
+                    System.out.println( "ldif file to import: " + ldifFileName );
+                }
+            }
+        }
+        else
+        {
+            System.err.println( "ldif file name must be provided" );
+            System.exit( 1 );
+        }
+    }
+
+    public Options getOptions()
+    {
+        Options opts = new Options();
+        Option op = new Option( "h", "host", true, "server host: defaults to localhost" );
+        op.setRequired( false );
+        opts.addOption( op );
+        op = new Option( "p", "port", true, "server port: defaults to 10389 or server.xml
specified port" );
+        op.setRequired( false );
+        opts.addOption( op );
+        op = new Option( "u", "user", true, "the user: default to uid=admin, ou=system" );
+        op.setRequired( false );
+        opts.addOption( op );
+        op = new Option( "w", "password", true, "the apacheds administrator's password: defaults
to secret" );
+        op.setRequired( false );
+        opts.addOption( op );
+        op = new Option( "a", "auth", true, "the authentication mode: defaults to 'simple'"
);
+        op.setRequired( false );
+        opts.addOption( op );
+        op = new Option( "f", "file", true, "the ldif file to import" );
+        op.setRequired( true );
+        opts.addOption( op );
+        op = new Option( "i", "ignore", true, "continue to process the file even if errors
are encountered " );
+        op.setRequired( false );
+        opts.addOption( op );
 
-		return opts;
-	}
+        return opts;
+    }
 }



Mime
View raw message