/* 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 displayed The user can specify the url to load by typing it in a JTextField. An initial URL to load can also be specified in an applet parameter with the name "URL". June 2002 */ import java.awt.*; // make graphical user interface classes available import java.awt.event.*; // make event-handling classes available import javax.swing.*; // make Swing GUI classes available import java.io.*; // make I/O classes such as InputStream available import java.net.*; // make networking classes such as URL available public class ReadURLApplet extends JApplet implements Runnable, ActionListener { JTextArea textDisplay; // data loaded from url is displayed here JTextField inputBox; // user enters name of url to be loaded here JButton 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.gray); getContentPane().setBackground(Color.gray); textDisplay = new JTextArea(); textDisplay.setEditable(false); textDisplay.setBackground(Color.white); loadButton = new JButton("Load"); loadButton.addActionListener(this); String url = getParameter("URL"); if (url == null) inputBox = new JTextField(); else inputBox = new JTextField(url); inputBox.setBackground(Color.white); inputBox.addActionListener(this); JPanel bottom = new JPanel(); bottom.setBackground(Color.gray); bottom.setLayout(new BorderLayout(3,3)); bottom.add(inputBox, BorderLayout.CENTER); bottom.add(loadButton, BorderLayout.EAST); bottom.add(new JLabel("Enter URL:"), BorderLayout.WEST); getContentPane().setLayout(new BorderLayout(3,3)); getContentPane().add(new JScrollPane(textDisplay), BorderLayout.CENTER); getContentPane().add(bottom, BorderLayout.SOUTH); inputBox.requestFocus(); } // 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("Connecting..."); 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); } void putText(final String text) { // Called by the thread to set the text in the text area. // This is done using SwingUtilities.invokeLater to avoid // synchronization problems that can occur when Swing // data structures are modified by a thread other than // the event-handling thread. SwingUtilities.invokeLater( new Runnable() { public void run() { textDisplay.setText(text); } } ); } public void run() { // Loads the data in the url specified by an instance 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); /* Open a connection to the URL, and get an input stream for reading data from the URL. */ URLConnection connection = url.openConnection(); InputStream urlData = connection.getInputStream(); /* Check that the content is some type of text. */ String contentType = connection.getContentType(); if (contentType == null || contentType.startsWith("text") == false) throw new IOException("URL does not refer to a text file."); /* Copy lines from the input stream until 10000 characters have been copied or end-of-file is encountered. */ putText("Receiving Data..."); BufferedReader in; // For efficiency, use a buffered reader. in = new BufferedReader(new InputStreamReader(urlData)); int charCt = 0; // Number of characters read. StringBuffer chars; // Store chars here before adding to text area. chars = new StringBuffer(10000); while (true) { int data = in.read(); charCt++; if (data == -1 || charCt > 10000) break; if (data != '\r') chars.append((char)data); else { // Lines can end with \r or \r\n. In these cases, // we want to append \n to indicate end-of-line. chars.append('\n'); data = in.read(); if (data == -1) break; if (data != '\n') { charCt++; chars.append((char)data); } } } in.close(); /* Finally, put the text that has been received into the text area. */ putText(chars.toString()); } catch (MalformedURLException e) { // Can be thrown when URL is created. putText( "\nERROR! Improper syntax given for the URL to be loaded."); } catch (SecurityException e) { // Can be thrown when the connection is created. putText("\nSECURITY ERROR! Can't access that URL."); } catch (IOException e) { // Can be thrown while data is being read. putText( "\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 } // end class ReadURLApplet