FTP Implementation


The code for the user interface is shown in Listing 4-1. You'll notice that the FTPConnection class does the bulk of the work, including much of the formatting of the returned listings.

Listing 4-1. FTP Web JSP User Interface
 <%@ page contentType="text/html; charset=iso-8859-1" language="java" import="com.cascadetg.ch04.*"  %><% String directory = request.getParameter("dir"); FTPConnection myConnection = new FTPConnection(); if(directory != null)     myConnection.setWorkingDirectory(directory); myConnection.connect(); %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>FTP Listing : /<%= myConnection.getWorkingDirectory() %></title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <style type="text/css"> <!-- .filelist {     width: 100%; } --> </style> <link href="../ch03/default.css" rel="stylesheet" type="text/css" /> </head> <body> <p><strong>Directory : <%= myConnection.getHTMLFormattedWorkingDirectory("ftp.jsp") %></strong></p> <hr /> <p><%=myConnection.getHTMLFormattedList("ftp.jsp") %> </p> <p><a href="ftp.jsp">Return to default directory</a> </p> </body> </html> 

The FTPConnection object used by the JSP page is fairly straightforward, as shown in Figure 4-3.

Figure 4-3. FTPConnection class.


The code for FTPConnection is shown in Listing 4-2.

Listing 4-2. FTP Connectivity Code
 package com.cascadetg.ch04; import java.util.Date; import java.util.StringTokenizer; import org.apache.commons.net.ftp.*; public class FTPConnection {     /**      * The FTP client implementation. Note that we don't preserve      * the client between executions - doing so would significantly      * improve performance, but would require more effort to ensure      * synchronization. For an example of this, see the      * NNTPConnection class.      *      * @see NNTPConnection      */     FTPClient ftp = new FTPClient();     /** Initially, the connection is considered to be invalid */     boolean valid = false;     /** The file listing as returned by the connection */     private FTPFile[] files;     /**   We don't know the working directory. If the working      * directory is null, we'll assume that the default directory      * as given when the user logs in is to be used.  */     String workingDirectory = null;     public boolean isValid() { return valid; }     /**   Here, we attempt to connect to the specified working      * directory, get the file list, close the connection, and      * return.  */     public void connect()     {         try         {             // Attempt the initial connection. Note that this             // happens before we even log in - here we are just             // trying to establish a connection.             int reply;             ftp.connect(NetConnectionTokens.ftp_server);             // We have to get the reply code to continue - this is             // required by the library.             reply = ftp.getReplyCode();             if (!FTPReply.isPositiveCompletion(reply))             {                 ftp.disconnect();                 return;             }             // Now, we attempt to log in using the FTP username &             // password.             ftp.login(                 NetConnectionTokens.ftp_username,                 NetConnectionTokens.ftp_password);             // If a working directory has been specified, we             // attempt to             // change to that directory             if (this.workingDirectory != null)                 if (this.workingDirectory.length() > 0)                     if (this.workingDirectory.compareTo("null")                         != 0)                         valid =                             ftp.changeWorkingDirectory(                                 this.workingDirectory);             // If no working directory has been specified, we try             // to             // find out what directory we default to and use that.             // Also, if we've followed a link, this might be a more             // accurate report of where we "really" are.             this.workingDirectory = ftp.printWorkingDirectory();             // Get the list of files from the server.             files = ftp.listFiles();             valid = true;         } catch (Exception e) { e.printStackTrace();         } finally         {             // Regardless of any errors, we make an effort to             // disconnect from the server.             if (ftp.isConnected())             {                 try                 { ftp.disconnect();                 } catch (Exception f)                 {  // Silent failure here is fine.                 }             }         }     }     public String getWorkingDirectory() { return workingDirectory; }     public void setWorkingDirectory(String workingDirectory)     { this.workingDirectory = workingDirectory; }     /** A command-line test method */     public static void main(String[] args)     {         FTPConnection myConnection = new FTPConnection();         myConnection.connect();         FTPFile[] files = myConnection.getFiles();         System.out.println(             myConnection.getHTMLFormattedWorkingDirectory(                 "ftp.jsp"));         for (int i = 0; i < files.length; i++)         {             System.out.println(                 myConnection.getHTMLFormattedFile(                     files[i],                     "ftp.jsp"));         }     }     /**   Returns the current working directory nicely formatted for      * display on an HTML page.      *      * @param page      * Specify the page the links should point to      */     public String getHTMLFormattedWorkingDirectory(String page)     {         if (workingDirectory == null)             return "";         StringBuffer result = new StringBuffer();         // Note the use of the built-in JDK tokenizer         StringTokenizer tokenizer =             new StringTokenizer(workingDirectory, "/", false);         String built_path = "";         String current = "";         while (tokenizer.hasMoreTokens())         {             current = tokenizer.nextToken();             built_path = built_path + "/" + current;             result.append("<a href='");             result.append(page);             result.append("?dir=");             result.append(built_path);             result.append("'>");             result.append(current);             result.append("</a>");             result.append("/");         }         result.append("<br />");         return result.toString();     }     /**   Returns the current file list nicely formatted for display      * on an HTML page.      *      * @param page      * Specify the page the links should point to      */     public String getHTMLFormattedList(String page)     {         StringBuffer reply = new StringBuffer();         if (files != null)         {             for (int i = 0; i < files.length; i++)             {                 if (files[i].isDirectory())                     reply.append(                         getHTMLFormattedFile(files[i], page));             }             reply.append("<table class='filelist'>");             for (int i = 0; i < files.length; i++)             {                 if (!files[i].isDirectory())                 {                     reply.append("<tr>");                     reply.append(                         getHTMLFormattedFile(files[i], page));                     reply.append("</tr>");                 }             }             reply.append("</table>");         }         return reply.toString();     }     /**   Returns the current file nicely formatted for display on an      * HTML page. Note that this is used by the      * getHTMLFormattedList function, so this isn't actually used      * in the JSP page.      *      * @param page      * Specify the page the links should point to      */     public String getHTMLFormattedFile(FTPFile file, String page)     {         StringBuffer result = new StringBuffer();         if (file.isDirectory())         {             result.append("<a href='");             result.append(page);             result.append("?dir=");             if (workingDirectory != null)                 result.append(workingDirectory);             result.append("/");             result.append(file.getName());             result.append("'><b>/");             result.append(file.getName());             result.append("</b></a>");             result.append("<br />");         } else         {             result.append("<td>");             result.append(file.getName());             result.append("</td><td>");             result.append((file.getSize() / 1024));             result.append("K</td><td>");             result.append(                 new Date(file.getTimestamp().getTimeInMillis())                     .toLocaleString());             result.append("</td>");         }         return result.toString();     }     public FTPFile[] getFiles() { return files; }     public void setFiles(FTPFile[] files) { this.files = files; } } 

This FTP connectivity code shown in Listing 4-2 suffers from a few obvious limitationsmost significantly, it opens and closes the connection every time the page is requested. Although this might be adequate for extremely light usage, it would be preferable to provide some mechanism for caching the FTP data. If this was the only mechanism provided for interaction with the FTP server, as part of a content publishing framework for example, very aggressive caching might be appropriate.

Additional functionality, such as uploading files, could be added by folding in the code shown in Chapter 2, "FileUpload."



    Apache Jakarta Commons(c) Reusable Java Components
    Real World Web Services
    ISBN: N/A
    EAN: 2147483647
    Year: 2006
    Pages: 137
    Authors: Will Iverson

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net