commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From rwins...@apache.org
Subject svn commit: r437131 - in /jakarta/commons/proper/net/branches/JDK_1_5_BRANCH/src/main/java: examples/FTPExample.java examples/ftp.java org/apache/commons/net/ftp/FTPSClient.java
Date Sat, 26 Aug 2006 09:17:07 GMT
Author: rwinston
Date: Sat Aug 26 02:17:06 2006
New Revision: 437131

URL: http://svn.apache.org/viewvc?rev=437131&view=rev
Log: (empty)

Added:
    jakarta/commons/proper/net/branches/JDK_1_5_BRANCH/src/main/java/examples/FTPExample.java
Removed:
    jakarta/commons/proper/net/branches/JDK_1_5_BRANCH/src/main/java/examples/ftp.java
Modified:
    jakarta/commons/proper/net/branches/JDK_1_5_BRANCH/src/main/java/org/apache/commons/net/ftp/FTPSClient.java

Added: jakarta/commons/proper/net/branches/JDK_1_5_BRANCH/src/main/java/examples/FTPExample.java
URL: http://svn.apache.org/viewvc/jakarta/commons/proper/net/branches/JDK_1_5_BRANCH/src/main/java/examples/FTPExample.java?rev=437131&view=auto
==============================================================================
--- jakarta/commons/proper/net/branches/JDK_1_5_BRANCH/src/main/java/examples/FTPExample.java
(added)
+++ jakarta/commons/proper/net/branches/JDK_1_5_BRANCH/src/main/java/examples/FTPExample.java
Sat Aug 26 02:17:06 2006
@@ -0,0 +1,188 @@
+/*
+ * Copyright 2001-2005 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 examples;
+
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.PrintWriter;
+import org.apache.commons.net.ftp.FTP;
+import org.apache.commons.net.ftp.FTPClient;
+import org.apache.commons.net.ftp.FTPConnectionClosedException;
+import org.apache.commons.net.ftp.FTPReply;
+
+/***
+ * This is an example program demonstrating how to use the FTPClient class.
+ * This program connects to an FTP server and retrieves the specified
+ * file.  If the -s flag is used, it stores the local file at the FTP server.
+ * Just so you can see what's happening, all reply strings are printed.
+ * If the -b flag is used, a binary transfer is assumed (default is ASCII).
+ * <p>
+ * Usage: ftp [-s] [-b] <hostname> <username> <password> <remote file>
<local file>
+ * <p>
+ ***/
+public final class FTPExample
+{
+
+    public static final String USAGE =
+        "Usage: ftp [-s] [-b] <hostname> <username> <password> <remote
file> <local file>\n" +
+        "\nDefault behavior is to download a file and use ASCII transfer mode.\n" +
+        "\t-s store file on server (upload)\n" +
+        "\t-b use binary transfer mode\n";
+
+    public static final void main(String[] args)
+    {
+        int base = 0;
+        boolean storeFile = false, binaryTransfer = false, error = false;
+        String server, username, password, remote, local;
+        FTPClient ftp;
+
+        for (base = 0; base < args.length; base++)
+        {
+            if (args[base].startsWith("-s"))
+                storeFile = true;
+            else if (args[base].startsWith("-b"))
+                binaryTransfer = true;
+            else
+                break;
+        }
+
+        if ((args.length - base) != 5)
+        {
+            System.err.println(USAGE);
+            System.exit(1);
+        }
+
+        server = args[base++];
+        username = args[base++];
+        password = args[base++];
+        remote = args[base++];
+        local = args[base];
+
+        ftp = new FTPClient();
+        ftp.addProtocolCommandListener(new PrintCommandListener(
+                                           new PrintWriter(System.out)));
+
+        try
+        {
+            int reply;
+            ftp.connect(server);
+            System.out.println("Connected to " + server + ".");
+
+            // After connection attempt, you should check the reply code to verify
+            // success.
+            reply = ftp.getReplyCode();
+
+            if (!FTPReply.isPositiveCompletion(reply))
+            {
+                ftp.disconnect();
+                System.err.println("FTP server refused connection.");
+                System.exit(1);
+            }
+        }
+        catch (IOException e)
+        {
+            if (ftp.isConnected())
+            {
+                try
+                {
+                    ftp.disconnect();
+                }
+                catch (IOException f)
+                {
+                    // do nothing
+                }
+            }
+            System.err.println("Could not connect to server.");
+            e.printStackTrace();
+            System.exit(1);
+        }
+
+__main:
+        try
+        {
+            if (!ftp.login(username, password))
+            {
+                ftp.logout();
+                error = true;
+                break __main;
+            }
+
+            System.out.println("Remote system is " + ftp.getSystemName());
+
+            if (binaryTransfer)
+                ftp.setFileType(FTP.BINARY_FILE_TYPE);
+
+            // Use passive mode as default because most of us are
+            // behind firewalls these days.
+            ftp.enterLocalPassiveMode();
+
+            if (storeFile)
+            {
+                InputStream input;
+
+                input = new FileInputStream(local);
+
+                ftp.storeFile(remote, input);
+
+                input.close();
+            }
+            else
+            {
+                OutputStream output;
+
+                output = new FileOutputStream(local);
+
+                ftp.retrieveFile(remote, output);
+
+                output.close();
+            }
+
+            ftp.logout();
+        }
+        catch (FTPConnectionClosedException e)
+        {
+            error = true;
+            System.err.println("Server closed connection.");
+            e.printStackTrace();
+        }
+        catch (IOException e)
+        {
+            error = true;
+            e.printStackTrace();
+        }
+        finally
+        {
+            if (ftp.isConnected())
+            {
+                try
+                {
+                    ftp.disconnect();
+                }
+                catch (IOException f)
+                {
+                    // do nothing
+                }
+            }
+        }
+
+        System.exit(error ? 1 : 0);
+    } // end main
+
+}
+

Modified: jakarta/commons/proper/net/branches/JDK_1_5_BRANCH/src/main/java/org/apache/commons/net/ftp/FTPSClient.java
URL: http://svn.apache.org/viewvc/jakarta/commons/proper/net/branches/JDK_1_5_BRANCH/src/main/java/org/apache/commons/net/ftp/FTPSClient.java?rev=437131&r1=437130&r2=437131&view=diff
==============================================================================
--- jakarta/commons/proper/net/branches/JDK_1_5_BRANCH/src/main/java/org/apache/commons/net/ftp/FTPSClient.java
(original)
+++ jakarta/commons/proper/net/branches/JDK_1_5_BRANCH/src/main/java/org/apache/commons/net/ftp/FTPSClient.java
Sat Aug 26 02:17:06 2006
@@ -30,27 +30,62 @@
 import javax.net.ssl.SSLSocket;
 import javax.net.ssl.TrustManager;
 
-public class FTPSClient extends FTPClient
-{
-	private static final String PASSWORD = "password";
+
+/**
+ * 
+ * This class extends {@link org.apache.commons.net.ftp.FTPClient} to add
+ * the necessary methods that implement SSL/TLS-FTPS.
+ *
+ */
+public class FTPSClient extends FTPClient {
+
+	// Represent the method to the FTP command AUTH...
+	private String sslContext;
 	
+	// Secure context (can be "TLS" or "SSL")
 	private SSLContext context;
 	
-	public FTPSClient()
-	{
-		try
-		{
-			KeyStore keyStore = KeyStore.getInstance("JCEKS");
-			keyStore.load(null, PASSWORD.toCharArray());
+	private String pbsz;
+	private String prot;
+
+	/**
+	 * Default constructor that selects some default options (TLS encryption)
+	 *
+	 */
+	public FTPSClient() {
+		this("JCEKS", "TLS", "password", "0", "P");
+	}
+	
+	
+	/**
+	 * 
+	 * Constructor that initializes the secure connection. 
+	 * 
+	 * @param keyStoreName Type of instance KeyStore, JKS for Java 1.3 y JCEKS for Java 1.4

+	 * @param sslContext Type of the instance SSLContext, can be SSL or TLS.
+	 * @param password The password to access the KeyStore.
+	 */
+	public FTPSClient(String keyStoreName, String sslContext, String password, String pbsz,
String prot) {
+		this.sslContext = sslContext;
+		this.pbsz = pbsz;
+		this.prot = prot;
+		
+		try {
+			KeyStore keyStore = KeyStore.getInstance(keyStoreName);
+			
+			keyStore.load(null, password.toCharArray());
 
 			KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
-			keyManagerFactory.init(keyStore, PASSWORD.toCharArray());
+			
+			keyManagerFactory.init(keyStore, password.toCharArray());
 
-			this.context = SSLContext.getInstance("TLS");
-			this.context.init(keyManagerFactory.getKeyManagers(), new TrustManager[] { new FTPSTrustManager()
}, null);
-		}
-		catch (Exception e)
-		{
+			this.context = SSLContext.getInstance(sslContext);
+
+			this.context.init(
+				keyManagerFactory.getKeyManagers(), 
+				new TrustManager[] { (TrustManager) new FTPSTrustManager() }, null
+			);
+		} catch (Exception e) {
 			e.printStackTrace();
 		}
 	}
@@ -62,7 +97,7 @@
 	{
 		super.connect(address, port, localAddress, localPort);
 		
-		this.secure();
+		this.secure(this.pbsz,this.prot);
 	}
 
 	/**
@@ -72,7 +107,7 @@
 	{
 		super.connect(address, port);
 		
-		this.secure();
+		this.secure(this.pbsz,this.prot);
 	}
 
 	/**
@@ -82,7 +117,7 @@
 	{
 		super.connect(address, port, localAddress, localPort);
 		
-		this.secure();
+		this.secure(this.pbsz,this.prot);
 	}
 
 	/**
@@ -92,39 +127,54 @@
 	{
 		super.connect(address, port);
 		
-		this.secure();
+		this.secure(this.pbsz,this.prot);
 	}
 	
-	public void secure() throws IOException
-	{
-		this.sendCommand("AUTH", "TLS");
+	/**
+	 *
+	 * Initialize the secure connection with the FTP server, throw the AUTH SSL o TLS command.
+	 * Get the socket with the server, starting the "handshake" making the socket, with a layer
of securety,
+	 * and initializing the stream of connection.
+	 * 
+	 * 
+	 * @param pbsz Protection Buffer Size: "0" is a good value
+	 * @param prot Data Channel Protection Level:
+	 * Posible values:
+	 * C - Clear
+	 * S - Safe
+	 * E - Confidential 
+	 * P - PrivateType of secure connection
+	 *  
+	 * @throws IOException If there is any problem with the connection.
+	 */
+	protected void secure(String pbsz, String prot) throws IOException {
+		this.sendCommand("AUTH", sslContext);
 		
-		SSLSocket socket = (SSLSocket) this.context.getSocketFactory().createSocket(this._socket_,
this.getRemoteAddress().getHostAddress(), this.getRemotePort(), true);
+		SSLSocket socket = (SSLSocket)this.context.getSocketFactory().createSocket(this._socket_,
this.getRemoteAddress().getHostAddress(), this.getRemotePort(), true);
 		
 		socket.startHandshake();
-		
+
 		this._socket_ = socket;
+		
 		this._controlInput_ = new BufferedReader(new InputStreamReader(socket.getInputStream(),
getControlEncoding()));
 		this._controlOutput_ = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),
getControlEncoding()));
 
 		this.setSocketFactory(new FTPSSocketFactory(this.context));
-		
-		this.sendCommand("PBSZ", "0");
-		this.sendCommand("PROT", "P");
+
+		this.sendCommand("PBSZ", pbsz);
+		this.sendCommand("PROT", prot);
 	}
 
 	/**
-	 * @see org.apache.commons.net.ftp.FTPClient#_openDataConnection_(int, java.lang.String)
-	 */
-	protected Socket _openDataConnection_(int command, String arg) throws IOException
-	{
+	 * @see org.apache.commons.net.ftp.FTPCliente#_openDataConnection_(java.lang.String, int)
+	 */	
+	protected Socket _openDataConnection_(int command, String arg) throws IOException {
 		Socket socket = super._openDataConnection_(command, arg);
-		
-		if (socket != null)
-		{
-			((SSLSocket) socket).startHandshake();
+		if (socket != null) {
+			((SSLSocket)socket).startHandshake();
 		}
-		
 		return socket;
-	}
+	}	
+
 }
+



---------------------------------------------------------------------
To unsubscribe, e-mail: commons-dev-unsubscribe@jakarta.apache.org
For additional commands, e-mail: commons-dev-help@jakarta.apache.org


Mime
View raw message