
/*
    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.
    Slightly modified in April 2000, with no change in functionality.
       
*/


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 an istance variable
          // named urlName.  The data is displayed in a TextArea named
          // textDisplay.  Exception handling is used to detect and respond
          // to errors that might occur.
  
        try {
        
           /* Create a URL object.  This can throw a MalformedURLException. */
        
           URL url = new URL(getDocumentBase(), urlName);
           
           /* Get the object that represents the content of the URL.  This
              can throw an IOException or a SecurityException. */
                                                          
           Object content = url.getContent();
           
           /* Display the content in the TextArea.  If it is not of type
              String, InputStream, or Reader, just display the name of the
              class to which the content belongs.  For an InputStream
              or Reader, at most 10000 characters are read.  For efficiency,
              characters are read from a stream using a BufferedReader. */
                           
           if (content instanceof String) {
                   // Show the text in the TextArea.
               textDisplay.setText((String)content);
           }
           else if (content instanceof InputStream 
                                        || content instanceof Reader) {
                   // Read up to 10000 characters from the stream, and
                   // show them in the TextArea.
               textDisplay.setText("Receiving data...");
               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]; // The characters read.
               int index = 0;                 // Number of chars read.
               while (true) {
                      // Read up to 10000 chars and store them in the array.
                  if (index == 10000)
                     break;
                  int ch = in.read();
                  if (ch == -1)
                     break;
                  data[index] = (char)ch;
                  index++;
               }
               if (index == 0)
                  textDisplay.setText("Couldn't get any data!");
               else
                  textDisplay.setText(new String(data,0,index));
               in.close();
           }
           else {
                  // Set text area to show what type of data was read.
               textDisplay.setText("Loaded data of type\n   " 
                                           + content.getClass().getName());
           }
  
        }
        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:\n"
                       + e.toString());
        }
        finally {  
              // This part is done, no matter what, before the thread ends.
              // Set up the user interface of the applet so the user can
              // enter another URL.
           loadButton.setEnabled(true);
           inputBox.setEditable(true);
           inputBox.selectAll();
           inputBox.requestFocus();
        }
  
     } // end of run() method

} 