import java.net.*; // For URL, MalformedURLException
import java.io.*;  // For DataInputStream

// This appears in Core Web Programming from
// Prentice Hall Publishers, and may be freely used
// or adapted. 1997 Marty Hall, hall@apl.jhu.edu.

/** A small class to demonstrate try/catch blocks. */

public class URLTest {
  public static void main(String[] args) {
    URLTest test = new URLTest();
    test.getURL();
    test.printURL();
  }

  private URL url = null;

  /** Read a string from user and create URL from it.
   *  If reading fails, give up and report error.
   *  If reading succeeds but URL is illegal, try again.
   */
  
  public URL getURL() {
    if (url != null)
      return(url);
    System.out.print("Enter URL: ");
    System.out.flush();
    DataInputStream in = new DataInputStream(System.in);
    String urlString;
    try {
      urlString = in.readLine();
    } catch(IOException ioe) {
      System.out.println("IOError when reading input: " +
                         ioe);
      ioe.printStackTrace(); // Show stack dump
      return(null);
    }
    try {
      url = new URL(urlString);
    } catch(MalformedURLException mue) {
      System.out.println(urlString + " is not valid.\n" +
                         "Try again.");
      getURL();
    }
    return(url);
  }

  /** Print info on URL. */
  
  public void printURL() {
    if (url == null)
      System.out.println("No URL.");
    else {
      String protocol = url.getProtocol();
      String host = url.getHost();
      int port = url.getPort();
      if (protocol.equals("http") && (port == -1))
        port = 80;
      String file = url.getFile();
      System.out.println("Protocol: " + protocol +
                         "\nHost: " + host +
                         "\nPort: " + port +
                         "\nFile: " + file);
    }
  }
}

