import java.net.*;
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;


class MiniBrowser extends Frame{

// Version & Autor
// Vorläufer-Version VersionsDatum 	        = "15.07.2001";"11.08.2003";
private static final String VersionsDatum 	= "29.09.2004";
private static final String Autor		= "Manfred Sommer";

private static String Titel = "Testet HTTP und url ";
private static String newLine = "\r\n";

// TCP/IP Felder
   
   private static int httpPort = 80;
   private static InetAddress hostIPAdr;
   private static Socket hostSocket;
   private static SocketChannel channel = null;

   private static String urlText;
   private static URL hostURL;
   private static String hostName;
   private static String pathName;
   private static String fileName;


// Fonts
    private static final Font FontMono           = new Font("Monospaced", Font.PLAIN, 18);
    private static final Font FontSansSerif 	 = new Font("SansSerif", Font.PLAIN, 14);
    private static final Font BigItalicSansSerif = new Font("SansSerif", Font.ITALIC, 16);

     
// Haupt - Fenstergrösse
    private static int XMax =  650;		
    private static int YMax =  640;
	

// Fenster für Meldungen 
    private static Label    Meld1Label = new Label("Meldungen", Label.LEFT);
    private static TextArea Meldungen1 = new TextArea(5,55);
    private static Label    Meld2Label = new Label("Browser Window", Label.LEFT);
    private static TextArea Meldungen2 = new TextArea(15,55);

// Felder, Label und Fenster für Eingaben
    private static Label     urlLabel = new Label("URL:", Label.LEFT);
    //private static TextField  urlFeld  = new TextField("http://archive.ncsa.uiuc.edu/SDG/Software/Mosaic/Demo/url-primer.html", 75);
    //private static TextField  urlFeld  = new TextField("http://www.ncsa.uiuc.edu/demoweb/url-primer.html", 55);
    //private static TextField  urlFeld  = new TextField("http://archive.ncsa.uiuc.edu/General/Internet/WWW/", 55);
    //private static TextField  urlFeld  = new TextField("http://www.mathematik.uni-marburg.de/index.html", 55);
    private static TextField  urlFeld  = new TextField("http://www.mathematik.uni-marburg.de/index.php", 55);
    //private static  TextField  urlFeld  = new TextField("http://www.mabi.de/index.html", 55);
        
	
// Beginn Menü 
  	
    private static MenuBar  MainMenuBar = new MenuBar();
    private static Menu     DateiMenu 	= new Menu("Datei");
    private static MenuItem DateiOpen	= new MenuItem("Öffnen...");
    private static Menu     BearbeitenMenu = new Menu("Bearbeiten");
    private static MenuItem httpTest  = new MenuItem("HTTP Verbindung testen");
    private static MenuItem urlReaderTest  = new MenuItem("URL Reader testen");

    private static MenuItem LoeMenu  = new MenuItem("Fenster löschen");
    private static MenuItem Beenden	= new MenuItem("Exit");
    private static Menu     HelpMenu 	= new Menu("Hilfe");
    private static MenuItem AboutBox	= new MenuItem("About");
        
// End Menü 

//// Konstruktor.
 
    MiniBrowser () {
	super(Titel);
			
	// Fonts für Menüs
	setFont(FontMono);
	DateiMenu.setFont(FontSansSerif);
	DateiOpen.setFont(FontSansSerif);
	BearbeitenMenu.setFont(FontSansSerif);
	httpTest.setFont(FontSansSerif);
	urlReaderTest.setFont(FontSansSerif);
	LoeMenu.setFont(FontSansSerif);
	Beenden.setFont(FontSansSerif);
	HelpMenu.setFont(FontSansSerif);
	AboutBox.setFont(FontSansSerif);
	// Font für Text Bereich
	setFont(new Font("Monospaced", Font.PLAIN, 18));
	
	setLayout(new FlowLayout(FlowLayout.LEADING));
	
	setMenuBar(MainMenuBar);
		
	MainMenuBar.add(DateiMenu);
	DateiMenu.add(DateiOpen);
	DateiMenu.add(Beenden);
	
	MainMenuBar.add(BearbeitenMenu);
	BearbeitenMenu.add(httpTest);
	BearbeitenMenu.add(urlReaderTest);
	BearbeitenMenu.add(LoeMenu);
		
	MainMenuBar.add(HelpMenu);
	HelpMenu.add(AboutBox);
	
	add(urlLabel);
	add(urlFeld);

	add(Meld1Label);
        Meldungen1.setEditable(false);
        add(Meldungen1);
        add(Meld2Label);
        Meldungen2.setEditable(false);
        add(Meldungen2);
               
        
        DateiOpen.addActionListener(new ActionListener(){
	    public void actionPerformed(ActionEvent e){ doOpenFile();}
	   });
	
	httpTest.addActionListener(new ActionListener(){
	    public void actionPerformed(ActionEvent e){ doHttpTest();}
	    });	
	
	urlReaderTest.addActionListener(new ActionListener(){
	    public void actionPerformed(ActionEvent e){ doUrlReaderTest();}
	    });	
	
	
	LoeMenu.addActionListener(new ActionListener(){
	    public void actionPerformed(ActionEvent e){ 
	    	Meldungen1.setText("");
	    	Meldungen2.setText("");
	    	}
	    });
	
		
	Beenden.addActionListener(new ActionListener(){
	    public void actionPerformed(ActionEvent e){ FensterBeenden(); }
		});
		

	AboutBox.addActionListener(new ActionListener(){
		public void actionPerformed(ActionEvent e){ showAboutBox(); }
		});
	    
		
	addWindowListener(new WindowAdapter() {    
	        public void windowClosing(WindowEvent e) { FensterBeenden(); }
		});
		    
	setBackground(Color.lightGray); 
	setSize(XMax, YMax);   
	setVisible(true);
        }

  void FensterBeenden() {	
	        
                dispose();
                System.exit(0);
            }
            
  // show about box
	void showAboutBox(){
		final Frame 	f 	= new Frame("About Box");
		final Button 	Ok 	= new Button("Ok");
	
		f.addWindowListener(new WindowAdapter() {
		    public void windowClosing(WindowEvent e) {
				f.dispose();
			}
		});
		    
		Ok.addActionListener(new ActionListener(){
	        public void actionPerformed(ActionEvent e) {
				f.dispose();
			}
		});
		
		f.setFont	(BigItalicSansSerif);
		f.setLayout	(new GridLayout(0, 1));
	
		f.add(new Label(" ", Label.CENTER));
		f.add(new Label(Titel, Label.CENTER));
		f.add(new Label("Datum der letzten Änderung: " + VersionsDatum, Label.CENTER));
		f.add(new Label("Autor: Manfred Sommer", Label.CENTER));
		f.add(new Label(" ", Label.CENTER));
		
		f.add(Ok);
		f.pack(); 
		f.setVisible(true);
	}
	
	

  
    void doOpenFile(){
    Meldungen1.append("Dummy für: Datei - öffnen.\n");
    }    

 void getURL(){
    urlText     = urlFeld.getText();
    hostURL  = null;
    hostName = null;
    fileName = null;
    pathName = null;
    try { hostURL = new URL(urlText);}
    catch (MalformedURLException e) {
      Meldungen1.append(urlText + " ist keine gültige URL");
      return;
      }
    hostName = hostURL.getHost();
    fileName = hostURL.getFile();
    pathName = hostURL.getPath();
    Meldungen1.append("Host-Name: " + hostName + " \n");
    Meldungen1.append("File-Name: " + fileName + " \n");
    Meldungen1.append("Path-Name: " + pathName + " \n");
    }

  void doHttpTest(){
    getURL();
    if (hostName == null) return;
    Meldungen1.append("IP Adresse von " + hostName + " ermitteln...\n");
    try { hostIPAdr = InetAddress.getByName(hostName); }
    catch (UnknownHostException e) {
            Meldungen1.append("IP-Adresse von " + hostName + " nicht gefunden.\n");
            return;
            }
            
    try {         
      InetSocketAddress socketAddress = new InetSocketAddress(hostIPAdr, 80);
      Charset charset = Charset.forName("ISO-8859-1");
      CharsetDecoder decoder = charset.newDecoder();
      CharsetEncoder encoder = charset.newEncoder();

      // Allocate buffers
      ByteBuffer buffer     = ByteBuffer.allocateDirect(1024);
      CharBuffer charBuffer = CharBuffer.allocate(1024);

      // Connect
      channel = SocketChannel.open();
      channel.connect(socketAddress);
      Meldungen1.append("TCP Verbindung steht!\n");

      // Send request
      String request = "GET "   + fileName + " HTTP/1.1" + newLine 
                     + "host: " + hostName + newLine
                     + newLine;
      
      
      channel.write(encoder.encode(CharBuffer.wrap(request)));

      // Read response
      while ((channel.read(buffer)) != -1) {
        buffer.flip();
        // Decode buffer
        decoder.decode(buffer, charBuffer, false);
        // Display
        charBuffer.flip();
        //System.out.println(charBuffer);
        Meldungen2.append(charBuffer.toString());
        buffer.clear();
        charBuffer.clear();
      }
    } 
    catch (UnknownHostException e) { Meldungen1.append(e.toString()); }
    catch (IOException e) { Meldungen1.append("Fehler bei: Socket-Channel verbinden " + e +"\n"); } 
    finally {
      if (channel != null) {
        try {channel.close(); } 
        catch (IOException ignored) {}
        }
      }
    }
	
    
   
    
    void doUrlReaderTest(){
    	getURL();
    	if (hostName == null) return;
    	InputStream is = null;
    	try {
       	   is = hostURL.openStream();  
           Meldungen1.append("ok:Input - Stream von url. \n");
           }
        catch (IOException e) {
           Meldungen1.append("keine Verbindungg zu " + hostName);
           return;
           }
        catch (NullPointerException e) {
           Meldungen1.append("Inhalt war nicht lesbar");
           return;
           }
        BufferedReader streamIn = new BufferedReader(new InputStreamReader(is));
         
	String Gelesen = null;
	try{
	   while (!streamIn.ready());
	   while (streamIn.ready()){ 
	      Gelesen = streamIn.readLine();
	      if (Gelesen != null) Meldungen2.append(Gelesen + "\n");
	      }
	    }
	 catch (IOException e) { 
	     Meldungen2.append("Server - Lese Fehler" + e + "\n");
	    }       
	 finally { if (streamIn != null)
	    try{ 
	     streamIn.close();  streamIn  = null; } 
	     catch (IOException ignored) {}
         }
    }

  public static void main(String args[]) {
    new MiniBrowser();
    }  

}// class MiniBrowser
	
 