
/*
    The applet URLExampleApplet demonstrates how to read data from
    a url over the internet using classes from the packages java.net
    and java.io.  It is assumed that the data in the url is text.
    Up to 10000 characters will be read from the url and displayed
    in a TextArea.  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".
   
*/


import java.awt.*;   // make graphical user interface 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 {

   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

   static String systemEOL = System.getProperty("line.separator");
       // systemEOL is the string that is placed at the end of each line in
       // a text file.  This string can vary from one type of computer to
       // another, but on existing systems is either "\n", "\r" or "\r\n".
       // As the run() method reads text from the url, it translates ends-of-line
       // in the file it is reading into systemEOL, which is the correct end-of-line
       // indicator for the system on which the applet is running.
   
   boolean firstStart = true;  // used in the start() method to determine whether
                               // this is the first time the start method is
                               // being called


   public void init() {
         // lays out the applet when it is first created
      textDisplay = new TextArea();
      loadButton = new Button("Load");
      inputBox = new TextField();
      
      Panel bottom = new Panel();
      bottom.setLayout(new BorderLayout(5,5));
      bottom.add("Center",inputBox);
      bottom.add("East",loadButton);
      
      setLayout(new BorderLayout(5,5));
      add("Center",textDisplay);
      add("South",bottom);
   }

   
   public void start() {
         // When the applet first starts, this checks whether
         // there is an applet parameter named "URL".  If so,
         // it loads that url.
         //     NOTE:  Why isn't this done in init()?  Because
         // the buttons and text components that are set up in
         // the init() method are not really constructred until
         // after that method executes (and before start() is
         // called).
      if (firstStart) {
         firstStart = false;
         String param = getParameter("URL");
         if (param != null) {
            inputBox.setText(param);
            doLoad(param);
         }
      }
   }
      
      
   void doLoad(String urlToLoad) {
        // This method is called by start() and action() to load a url.
        // The interface elements are "turned off" so they can't be used
        // while the url is loading.  Then a separater 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.)  Of course, when you do asynchronous programming,
        // you need to do some thing to keep things synchronized.  In this
        // simple case, turning interface elements on and off is enough.
        // In a more complicated program, "synchronized" methods could be
        // used.
      inputBox.setEditable(false);
      textDisplay.setEditable(false);
      loadButton.disable();
      textDisplay.setText("Loading....");
      urlName = urlToLoad;  // set the urlName which will be used by the thread
      loader = new Thread(this);
      loader.start();
   }
   
   
   public boolean action(Event evt, Object arg) {
         // responds when the user clicks on the load button
      if (evt.target == loadButton) {
         String urlToLoad = inputBox.getText();
         doLoad(urlToLoad);
         return true;
      }
      else
         return super.action(evt,arg);
   }


   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 an input stream
         InputStream in = url.openStream();               //    for reading the data
                                                          //    from the url.

         StringBuffer buffer = new StringBuffer(10010);   // Store input data here until
                                                          //     it has all been read
                                                          
         int input;
         do {
            input = in.read();                 // Read until end-of-data is reached or
            if (input >= 0) {                  // until 10000 characters have been
               char ch = (char)input;          // read.  Translate ends-of-lines in
               if (ch == '\n')                  // the input into the EOL string
                  buffer.append(systemEOL);    // appropriate for the  system the
               else if (ch == '\r') {           // applet is running on.
                  buffer.append(systemEOL);
                  int next = in.read();
                  if (next != '\n') {
                     if (next < 0)
                        input = -1;  // (forces end to do loop)
                     else
                        buffer.append( (char)next );
                  }
               }
               else
                  buffer.append(ch);
            }
         } while (input >= 0 && buffer.length() < 10000);
         
         in.close();  // close the input stream

         textDisplay.setText(buffer.toString());  // set text area to show the data
                                               // read from the URL

      }
      catch (MalformedURLException e) {  // can be thrown when URL is created
         textDisplay.setText("ERROR!  Improper syntax given for the URL to be loaded.");
      }
      catch (SecurityException e) {  // can be thrown when the connection is created
         textDisplay.setText("SECURITY ERROR!  " + e);
      }
      catch (IOException e) {  // can be thrown while data is being read
         textDisplay.setText("INPUT ERROR!  " + e);
      }
      finally {  // This part is done, no matter what, before the thread ends
         loadButton.enable();
         textDisplay.setEditable(true);
         inputBox.setEditable(true);
         inputBox.selectAll();
         inputBox.requestFocus();
      }

   } // end of run() method

} 