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

/**
\brief Command line utitlity to download files from the internet.

\par Example
\verbatim
  java DownloadFile url=http://www.jguru.com/images/jguru/logo.gif filename=logo.gif
\endverbatim

If a file can not be downloaded then an error file is created. This communicates
 with the OS that the function failed rather than a return value or any other means.

How can I download files from a URL using HTTP?
 http://www.jguru.com/faq/view.jsp?EID=13198
*/
class DownloadFile
{
  /** Search the string array for targ at start of string. If found
      return the rhs part of the string. */ 
  private static String commandlineGet(String targ, String[] args)
  {
    String s = "";
    for (int i=0; i<args.length; ++i)
    {
      if( args[i].startsWith(targ) )
        s = args[i].substring(targ.length());
    }

    return s;
  }

  /** Given an absolute filepath attempt to save it to filename. */
  private DownloadFile
  (
    String filename,
    String location
  )
  {
    try
    {
      URL url = new URL(location);
      URLConnection connection = url.openConnection();
      InputStream stream = connection.getInputStream();
      BufferedInputStream in = new BufferedInputStream(stream);
      FileOutputStream file = new FileOutputStream(filename);
      BufferedOutputStream out = new BufferedOutputStream(file);
      int i;
      while ((i = in.read()) != -1) 
      {
        out.write(i);
      }
      out.flush();
    }
    catch (Exception e)
    {
      System.out.println("error: can not download file" + location);
      writeerrorfile();
    }
  }

  /** Interface with the OS by creating error.txt file. */
  private static void writeerrorfile()
  {
    try
    {
      FileOutputStream f = new FileOutputStream("error.txt");
      f.close();
    }
    catch( Exception e )
    {
    }
  }

  /** Create the file error.txt if there is an error. 
   */
  public static void main(String[] args)
  {
    String filename = commandlineGet("filename=",args);
    String url = commandlineGet("url=",args);
    
    if ((filename.length()==0) || (url.length()==0))
    {
      writeerrorfile();

      System.out.println("error:  both the filename and url are required.");
      System.out.println("  eg filename=logo.gif url=http://www.jguru.com/images/logo.gif");

      return;
    }

    System.out.println("*" + filename + "*");
    System.out.println("*" + url + "*");


    //DownloadFile app = new DownloadFile
    new DownloadFile
    ( 
      filename,
      url
    );

    return;
  }
}


