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

/**
 * URLGetFile - getting the stream data referenced from a ftp or http
 * url and save it to disk.
 *
 * Copyright (C) 1999  Shazron Abdullah
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * 
 * @author Shazron Abdullah
 * @version 1999
 */
public class URLGetFile
{

	/**
	 *
	 */
	public static void main(String args[])
	{
		int num_args = args.length;
		
		if (num_args != 2)
			display_help();
		else
			new URLGetFile(args[0], args[1]);
	}
	
	/**
	 *
	 */
	public static void display_help()
	{
		System.out.println("usage: java URLGetFile url dir");
		System.out.println("url : the url of the file to get through HTTP");
		System.out.println("dir : the directory to download the file to");
	}

	/**
	 * This function gets a file from a server location
	 * through a URL connection (http or ftp)
	 *
	 */
	public URLGetFile(String url, String dir)
	{
		URL fileToGetURL=null;
		long total_bytes = 0;
	
		try { fileToGetURL = new URL(url);}
 		catch (MalformedURLException mue) { System.out.println("Error: " + mue); }
 		
 		File test_dir = new File(dir);
 		
 		if (! test_dir.exists() || ! test_dir.isDirectory())
 		{
 			System.out.println("Directory " + dir + " does not exist or is not a directory.");
 			return;
 		}
		
		String filename = fileToGetURL.getFile();

		int index = filename.lastIndexOf('/'); // take out any leading path dirs
		if (index != -1)
			filename = filename.substring(index + 1);
			
		String fileToWrite = new StringBuffer(dir).append(File.separator).append(filename).toString();

		// now try to download the file
		try
		{
			URLConnection conn = fileToGetURL.openConnection();
			int content_length = conn.getContentLength();
 
			DataInputStream fileToGetStream = new DataInputStream(conn.getInputStream());
			BufferedInputStream bis = new BufferedInputStream(fileToGetStream);
			FileOutputStream fos = new FileOutputStream(fileToWrite);

			int N = 1024;
			byte buf[] = new byte[N];
			int ln = 0;
			int int_len = -1;

			System.out.println("File size: " + content_length + " bytes. ");
			System.out.print("Percent downloaded: ");
			
			while ((ln = bis.read(buf, 0, N)) != -1) 
			{
				fos.write(buf, 0, ln);
				total_bytes += ln;
				
				if (int_len != -1)
				{
					System.out.print("\b"); // to get rid of the percentage sign
					for (int i=0; i< int_len; i++)
						System.out.print("\b");
				}
				
				long percentage = (total_bytes * 100) / (long)content_length;
				int_len = Long.toString(percentage).length();
				System.out.print(percentage + "%");
			}

			fos.flush();
			fos.close();
			bis.close();
			fileToGetStream.close();

        	} 
		catch (FileNotFoundException fnfe) { 
			System.out.println("Error " + fnfe + ": file " + filename +  " not found."); 
		}
		catch (IOException ioe) { 
			System.out.println("Error: " + ioe);
		}

		System.out.println("\n" + total_bytes + " bytes of file " + filename +  " downloaded.");
	}
}