
/*
    The applet URLExampleApplet demonstrates how to read data from
    a url over the internet using classes from the packages java.net
    and java.io.  If the data from the url is of type String, then
    the string is displayed.  Otherwise, if the type of the data is
    known, then the type is displyed
        The user can specify the url to load by typing
    it in a TextField.  An initial URL to load can also be specified
    in an applet parameter with the name "URL".

    Originally written 1996; modified August 1998 to use Java 1.1 sytle
    event handling and to use the getContent() method of the URL class.
       
*/


import java.awt.*;       // make graphical user interface classes available
import java.awt.event.*; // make event-handling classes available
import java.io.*;        // make I/O classes such as InputStream avaialable
import java.net.*;       // make networking classes such as URL available

import java.applet.Applet;

public class URLExampleApplet extends Applet implements Runnable, ActionListener {

   TextArea textDisplay;  // data loaded from url is displayed here
   TextField inputBox;    // user enters name of url to be loaded here
   Button loadButton;     // user clicks on this button to load the url
   
   String urlName;  // the name of the url to be loaded by the run() method.
       // Note:  this url can be specified relative to the location of the
       //        HTML document that contains the applet.
   
   Thread loader;   // thread for reading data from the url

   
   public void init() {
         // Lays out the applet when it is first created.
         // If there is an applet parameter named "URL", then
         // that parameter is read and loaded into the input box.
         // the user can then load the url by clicking on load.
         
      setBackground(Color.lightGray);
      
      textDisplay = new TextArea();
      textDisplay.setEditable(false);
      textDisplay.setBackground(Color.white);
      
      loadButton = new Button("Load");
      loadButton.addActionListener(this);
      loadButton.setBackground(Color.white);
      
      String url = getParameter("URL");
      if (url == null) 
         inputBox = new TextField();
      else
         inputBox = new TextField(url);
      inputBox.setBackground(Color.white);
      inputBox.addActionListener(this);
      
      Panel bottom = new Panel();
      bottom.setLayout(new BorderLayout(3,3));
      bottom.add("Center",inputBox);
      bottom.add("East",loadButton);
      
      setLayout(new BorderLayout(3,3));
      add("Center",textDisplay);
      add("South",bottom);

   }  // end init()
   
   
   public Insets getInsets() {
      return new Insets(3,3,3,3);
   }

   
   void doLoad(String urlToLoad) {
        // This method is called by actionPerformed() to load a url.
        // The interface elements are "turned off" so they can't be used
        // while the url is loading.  Then a separate thread is started
        // to do the loading.  The interface elements will be turned
        // back on when that thread finishes its execution.
        //   NOTE:  I use a thread to do the loading so that the loading
        // can take place asynchronously, while other things are going
        // on in the applet.  (For this simple example, there really
        // isn't anything else to do anyway, but the technique is
        // useful to know.)
      inputBox.setEditable(false);
      loadButton.setEnabled(false);
      textDisplay.setText("Loading....");
      urlName = urlToLoad;  // set the urlName which will be used by the thread
      loader = new Thread(this);
      loader.start();
   }
   
   
   public void actionPerformed(ActionEvent evt) {
         // responds when the user clicks on the load button or
         // presses return in the input box
      String urlToLoad = inputBox.getText().trim();
      if (urlToLoad.equals("")) {
         textDisplay.setText("No URL found in text-input box");
         textDisplay.requestFocus();
      }
      else
         doLoad(urlToLoad);
   }
   
   
   public void destroy() {
         // If the thread is still running when the applet is destroyed,
         // take the drastic step of stopping it.
      if (loader != null && loader.isAlive())
          loader.stop();
   }


   public void run() {
        // Loads the data in the url specified by urlName into the text display.
        // Exception handling is used to detect and respond to errors that
        // might occur.

      try {
      
         URL url = new URL(getDocumentBase(), urlName); // Create a URL object.
                                                        // (Can throw MalformedURLException)
                                                        
         Object content = url.getContent();  // Read data from the URL.  Can throw
                                             // SecurityException and MalformedURLExceprion
                                             
         if (content instanceof String) {
             textDisplay.setText((String)content);  // set text area to show the data
                                                    // read from the URL
         }
         else if (content instanceof InputStream || content instanceof Reader) {
                 // I don't think this sould happen, but it does on my Macintosh
             BufferedReader in;  // for reading from the URL stream
             if (content instanceof InputStream)
                in = new BufferedReader(new InputStreamReader( (InputStream)content ));
             else if (content instanceof BufferedReader)
                in = (BufferedReader)content;
             else
                in = new BufferedReader( (Reader)content );
             char[] data = new char[10000]; // buffer into which characters are read
             int index = 0;               // number of chars already read
             while (index < 10000) { // try to read up to 10000 characters
                int charCt = in.read(data,index,10000-index);
                if (charCt == -1)
                   break;
                index += charCt;
             }
             if (index == 0)
                textDisplay.setText("Couln't get any data from the input stream.");
             else
                textDisplay.setText(new String(data,0,index));
             in.close();
         }
         else {
             textDisplay.setText("Loaded data of type\n   " + content.getClass().getName());
                     // set text area to show what type of non-string data was read
         }

      }
      catch (MalformedURLException e) {  // can be thrown when URL is created
         textDisplay.setText("\nERROR!  Improper syntax given for the URL to be loaded.");
      }
      catch (SecurityException e) {  // can be thrown when the connection is created
         textDisplay.setText("\nSECURITY ERROR!  Can't access that URL.");
      }
      catch (IOException e) {  // can be thrown while data is being read
         textDisplay.setText("\nINPUT ERROR! Problem reading data from that URL");
      }
      finally {  // This part is done, no matter what, before the thread ends
         loadButton.setEnabled(true);
         inputBox.setEditable(true);
         inputBox.selectAll();
         inputBox.requestFocus();
         loader = null;
      }

   } // end of run() method

} 
