HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML
 

"What's Going On With Your Download?"
Volume: 5 Issue: 2, p.30

	

Listing 1: 

package net.fortrel.io; 

import java.io.*; 
import java.net.*; 

/** 
 * This is the Wrapper class for the Input 
 * Stream. 
 */ 
public class DownloadInputStream 
      extends InputStream { 

   // The Input Stream from which to read. 
   private InputStream internalInputStream; 
  
   // The length of the input stream, the 
   // starting time of download and the number 
   // of bytes being read. 
   private int length = -1; 
   private long startTime = -1; 

 private long bytesRead = 0; 
  
   /** 
    * Constructor if we know the length of the 
    * input stream. 
    */ 
   public DownloadInputStream(Input 
   Stream is, 
                        int length) { 
      internalInputStream = is; 
      this.length = length; 
   } 
  
   /** 
    * Constructor if the length is unknown. 
    */ 
   public DownloadInputStream(Input 
   Stream is) { 
      internalInputStream = is; 
   } 

   /** 
    * Special constructor for a URL. 
    */ 
   public DownloadInputStream(URL url) 
         throws IOException { 
      URLConnection connection = 
         url.openConnection(); 
      this.length = connection.getContentLength(); 
  
      internalInputStream = 
         connection.getInputStream(); 
   } 

   /** 
    * Get the current download rate in bytes 
    * per millisecond. 
    */ 
   public float getDownloadRate() { 
      if (startTime != -1) { 
         long currentTime = 
            System.currentTimeMillis(); 
  
         return bytesRead / (float)(currentTime - 
            startTime); 
      } 
      else 
         return -1.0f; 
   } 

   /** 
    * Get the time since the beginning of the 
    * download in milliseconds. 
    */ 
   public long getDownloadTime() { 
      if (startTime != -1) 
         return System.currentTimeMillis() - 
            startTime; 
      else 
         return 0; 
   } 
  
   /** 
    * Get the completion percent. 
    */ 
   public float getDownloadedPercent() { 
      if (startTime == -1 || length == -1) 
         return -1.0f; 
      else { 
         return (float)bytesRead / (float)length; 
      } 
   } 
  
   /** 
    * Get the number of bytes read until now. 
    */ 
   public long getBytesRead() { 
      return bytesRead; 
   } 

   /** 
    * Get the length of the input stream. 
    * Returns -1 if the length is unknown. 
    */ 
   public long getBytesTotal() { 
      return length; 
   } 

   /** 
    * Get the estimated remaining download 
    * time in milliseconds. 
    */ 
   public long getEstimatedDownloadTime() { 
      if (startTime == -1 || length == -1) 
         return -1; 
  
      long currentTime = 
         System.currentTimeMillis(); 
  
      return (long)((length - bytesRead) / 
         getDownloadRate()); 
   } 
 /*************************************** 
 * All other methods are the implemen- 
 * tation of the InputStream methods.    ***************************************/ 
  
   public int available() throws IOException { 
      return internalInputStream.available(); 
   } 

   public void close() throws IOException { 
      internalInputStream.close(); 
   } 

   public void mark(int readlimit) { 
      internalInputStream.mark(readlimit); 
   } 

   public boolean markSupported() { 
      return internalInputStream.markSupported(); 
   } 
  
   public int read() throws IOException { 
      if (startTime == -1) 
         startTime = System.currentTimeMillis(); 
  
      int b = internalInputStream.read(); 
  
      if (b != -1) 
         bytesRead++; 

      return b; 
   } 

   public int read(byte[] b, int off, int len) 
         throws IOException { 
      if (startTime == -1) 
         startTime = System.current- 
         TimeMillis(); 
  
      int read = internalInput- 
      Stream.read(b,off, 
                   len); 
  
      bytesRead += read; 
  
      return read; 
   } 

   public void reset() throws IOException { 
      startTime = -1; 
      bytesRead = 0; 
  
      internalInputStream.reset(); 
   } 

   public long skip(long n) throws 
   IOException { 
      long skipped = internalInput- 
      Stream.skip(n); 
      bytesRead += skipped; 
  
      return skipped; 
   } 
} 

Listing 2: 

package net.fortrel.io; 

import java.io.*; 

/** 
 * This is the Wrapper class for the 
 * Output Stream. 
 */ 
public class UploadOutputStream 
      extends OutputStream { 
  
   // Private internal stream. 
   private OutputStream internalOutputStream; 
  
   // The length of the output stream, the 
   // upload start time and the number of 
   // bytes being writen. 
   private int length=-1; 
   private long startTime=-1; 
   private int bytesWriten=0; 
  
   /** 
    * Constructor to use if the length is 
    * unknown. 
    */ 
   public UploadOutputStream(Output- 
   Stream os) { 
      internalOutputStream = os; 
   } 
  
   /** 
    * Constructor to use when the 
    * length is known. 
    */ 
   public UploadOutputStream(Output- 
   Stream os, 
                        int length) { 
      internalOutputStream = os; 
      this.length = length; 
   } 
  
   /** 
    * Get the upload transfer rate in 
    * bytes per millisecond. 
    */ 
   public float getUploadRate() { 
      if (startTime != -1) { 
         long currentTime = 
            System.currentTimeMillis(); 
  
         return bytesWriten / 
            (float)(currentTime-startTime); 
      } 
      else 
         return -1.0f; 
   } 

   /** 
    * Get the time since the beginning 
    * of the upload in milliseconds. 
    */ 
   public long getUploadTime() { 
      if (startTime != -1) 
         return System.currentTimeMillis() - 
             startTime; 
      else 
         return -0; 
   } 

   /** 
    * Get the completion percent. 
    */ 
   public float getUploadPercent() { 
      if (startTime == -1 || length == -1) 
    return -1.0f; 
      else { 
         return (float)bytesWriten / 
            (float)length; 
      } 
   } 

   /** 
    * Get the number of bytes being 
    * writen by now. 
    */ 
   public long getBytesWriten() { 
      return bytesWriten; 
   } 

   /** 
    * Get the length of the output 
    * stream content to be writen. 
    */ 
   public long getBytesTotal() { 
      return length; 
   } 

   /** 
    * Get the estimated uploading time 
    * in milliseconds. 
    */ 
   public long getEstimatedUploadTime() { 
      if (startTime == -1 || length == -1) 
         return -1; 
  
      long currentTime = 
         System.currentTimeMillis(); 
  
      return (long)((length - 
      bytesWriten) / 
         getUploadRate()); 
   } 
 /*************************************** 
    * All other methods are the imple- 
    * mentation of the OuputStream methods.   ***************************************/ 
   public void close() throws IOException { 
      internalOutputStream.close(); 
   } 
  
   public void flush() throws IOException { 
      internalOutputStream.flush(); 
   } 
  
   public void write(byte[] b, int off, int len) 
         throws IOException { 
      if (startTime == -1) 
         startTime = System.current- 
         TimeMillis(); 
  
      bytesWriten += len; 
              internalOutputStream.write(b,off,len); 
   } 
  
   public void write(int b) throws 
   IOException { 
      if (startTime == -1) 
         startTime = System.current- 
         TimeMillis(); 
      bytesWriten++; 
  
      internalOutputStream.write(b); 
   } 
} 

Listing 3: 

package net.fortrel.io; 

import java.io.*; 
import java.net.*; 
import java.awt.*; 
import javax.swing.*; 

/** 
 * An example on using the DownloadIn- 
 * putStream. 
 */ 
public class DownloadDialog extends JDialog 
      implements Runnable { 
   private JProgressBar bar; 
   private JLabel lTransfertRate, 
               lEstimatedDownloadTime, 
               lBytesRead, 
               lBytesTotal; 
  
   private DownloadInputStream dis; 
   private OutputStream os; 

   private Thread myThread; 

   public DownloadDialog(Frame owner, 
                       URL url, 
                       String outputFile) 
         throws IOException { 
      super(owner, "Download", false); 

      // Build the User Interface. 
      buildUI(url.toString()); 
      pack(); 
  
      // Open every streams. 
      dis = new DownloadInputStream(url); 
      os = new FileOutputStream(outputFile); 
  
      // Start the downloading thread. 
      myThread = new Thread(this); 
      myThread.start(); 
   } 

   /** 
    * A private method to build the 
    * User Interface. 
    */ 
   private void buildUI(String url) { 
      JLabel lFile = new 
      JLabel("File: " + url); 
      lBytesRead = new JLabel("Bytes 
      read:"); 
      lBytesTotal = new 
      JLabel("Size:"); 
      lTransfertRate = new 
         JLabel("Transfer rate:"); 
      lEstimatedDownloadTime = new 
         JLabel("Estimated downloading 
         time:"); 
      bar = new JProgressBar( 
                 JProgressBar.HORIZON 
                 TAL, 0, 100); 

      // Do the layout. 
      getContentPane().setLayout(new 
      GridLayout(0,1)); 
  
      getContentPane().add(lFile); 
      getContentPane().add(lBytesRead); 
      getContentPane().add(lBytesTotal); 
      getContentPane().add(lTransfertRate); 
      getContentPane().add(lEstimated- 
      DownloadTime); 
      getContentPane().add(bar); 
   } 
  
   /** 
    * The downloading thread method. 
    */ 
   public void run() { 
      byte buffer[] = new byte[1024]; 
  
      while(true) { 
         try { 
            int b = dis.read(buffer); 
  
            if (b <= 0) { 
               // The end of the down- 
               // load is reached. 
               os.close(); 
  
               System.exit(0); 
            } 
            else { 
               // Save the data 
               os.write(buffer, 0, b); 
  
               // Update the on-screen 
               // fields. 
               lBytesRead.setText("Bytes read:" + 
                  dis.getBytesRead()); 
               lBytesTotal.setText("Size:" + 
                  dis.getBytesTotal()); 
               lTransfertRate.setText( 
                  "Transfer rate:" + 
                  dis.getDownloadRate() * 
                  (1000f/1024f) + 
                  " kb/s"); 
               lEstimatedDownloadTime.setText( 
                  "Estimated downlaod- 
                   ing time:" + 
                  (int)(dis.getEsti- 
                  matedDownloadTime() 
                  / 1000) + " sec."); 
               bar.setValue( 
                  (int)(dis.getDown- 
                  loadedPercent() * 
                  100)); 
            } 
         } 
         catch(IOException e) { 
            System.err.println("Error: " + e); 
            break; 
         } 
      } 
   } 

   /** 
    * The main method. 
    * Use two parameters: the URL and 
    * the filename to create. 
    */ 
   public static void main(String   args[]) { 
      if (args.length != 2) { 
         System.err.println("Please 
         give the URL"+ 
            " to connect to and the 
              file store"+ 
            " the downloaded data."); 
         System.exit(-1); 
      } 
  
      try { 
         URL url = new URL(args[0]); 
         String filename = args[1]; 
  
         DownloadDialog dd = 
            new DownloadDialog(new 
            JFrame(), 
                           url, 
                           filename); 
  
         dd.show(); 
      } 
      catch(Exception e) { 
         System.err.println("Error:" + e); 
  
         e.printStackTrace(); 
      } 
   } 
} 



 

All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.