import java.applet.Applet;
import java.awt.*;
import java.net.*;
import java.io.*;

public class urlFetcher extends Applet {
	 TextField urlField = null;
	 TextArea contentArea = null;
	 TextField contentType = null;
	 TextField contentSize = null;
	 
	 public void init(){
		  makeUI();
		  if(getParameter("URL") != null){
				urlField.setText( getParameter("URL"));
				doFetch();
		  }
	 }
	 
	 public void makeUI(){
		  
		  setLayout( new BorderLayout() );
		  Panel p = new Panel();
		  contentArea = new TextArea(24, 80);
		  Font fCourier = new Font("Courier", Font.PLAIN, 12);
		  contentArea.setFont( fCourier) ;
		  contentArea.setEditable( false );
		  
		  p.add (contentArea);
		  add ("Center", p);
		  p = new Panel();
		  p.add( new Label("Location: "));
		  
		  urlField = new TextField(40 );
		  p.add( urlField );
		  p.add( new Button("Fetch"));
		  p.add( new Button("Clear URL"));
		  
		  add("North", p);
		  p = new Panel();
		  p.add(new Label("Content Type:" ));
		  contentType = new TextField(20);
		  contentType.setEditable( false);
		  p.add (contentType );
		  p.add ( new Label("Content Size: "));
		  
		  contentSize = new TextField(10);
		  contentSize.setEditable(false);
		  p.add( contentSize );
		  
		  add("South", p);
		  
		  repaint();
	 }
	 
	 public void doFetch(){
		  URL target;
		  
		  try {
				target = new URL( urlField.getText());
				showStatus("Fetching \""+target+"\"");	
				
		  } catch( MalformedURLException e) {
				showStatus("Bad URL \""+urlField.getText() +"\":"+ e.getMessage());
				return;
		  } catch( SecurityException e) {
				showStatus( "Security Erro: "+ e.getMessage());
				return;
		  }
		  
		  try {
				String content = "";
				URLConnection con = target.openConnection();
				byte b[] = new byte[ 1024 ];
				int nbytes;
				BufferedInputStream in = new BufferedInputStream( con.getInputStream(), 2048);
		 		contentArea.setText( "");
		  
		  		while ((nbytes = in.read(b,  0,  1024)) != -1 ){
					 content = new String(b, 0, 0, nbytes);
					 contentArea.appendText( content );
				}
		  
				String type = con.getContentType();
				if (type == null ){
					 type = "Unknown";
				}
				contentType.setText( type );
		  
				int size = con.getContentLength();
				if ( size == -1 ){
					 size = content.length();
				}
				contentSize.setText( Integer.toString(size));
				
			} catch ( IOException e ){
				showStatus("Error " +target+e);
				return;
		   }
		  
		  
		  			
	 }
	 
	 public boolean handleEvent(Event e){
		  
		  switch( e.id ){
				case Event.ACTION_EVENT:{
					 if ( e.target instanceof TextField || e.arg.equals("Fetch")) {
						  doFetch();
						  return true;
					 }
					 if (e.arg.equals("Clear URL")){
						  urlField.setText("");
						  return true;
					 }
				}
				default: return false;
		  }
		  
	 }
}
