The Java Program: Fetch.java

  1 import java.io.IOException;
  2 import java.io.Reader;
  3 import java.io.BufferedReader;
  4 import java.io.InputStreamReader;
  5 import java.net.URL;
  6 import java.net.URLConnection;
  7 import java.util.List;
  8 import java.util.Arrays;
  9 import java.util.ArrayList;
 10 
 11 import javax.swing.text.html.parser.ParserDelegator;
 12 import javax.swing.text.html.HTMLEditorKit.ParserCallback;
 13 import javax.swing.text.html.HTML.Tag;
 14 import javax.swing.text.MutableAttributeSet;
 15 
 16 public final class Fetch {
 17 
 18    private Fetch() {}
 19 
 20    private static String linkName (String cpid) {
 21       return String.format ("http://www.usaco.org/index.php?page=viewproblem&cpid=%s&lang=en", cpid);
 22    }
 23 
 24    public final static void main (String[] args) throws IOException{
 25       final String url = linkName (args[0]);
 26       final URLConnection connection = new URL (url).openConnection();
 27       final Reader r = new BufferedReader (new InputStreamReader (connection.getInputStream()));
 28       extractProblem (r);
 29    }
 30 
 31 
 32    public static void extractProblem (Reader reader) throws IOException {
 33 
 34       final ParserDelegator parserDelegator = new ParserDelegator();
 35       final ParserCallback parserCallback = new ParserCallback() {
 36             int h2=0;
 37             int span=0;
 38             public void handleText(final char[] data, final int pos) {
 39                if (h2==1) {
 40                   System.out.println ("H2");
 41                   System.out.println (data);
 42                } else if (span==1) {
 43                   System.out.println ("SPAN");
 44                   System.out.println (data);
 45                }
 46                System.out.println (data);
 47             }
 48 
 49             public void handleStartTag(Tag tag, MutableAttributeSet attribute, int pos) {
 50                if (tag==Tag.H2) h2++;
 51                else if (tag==Tag.SPAN) span++;
 52             }
 53             public void handleEndTag(Tag t, final int pos) { }
 54             public void handleSimpleTag(Tag t, MutableAttributeSet a, final int pos) { }
 55             public void handleComment(final char[] data, final int pos) { }
 56             public void handleError(final java.lang.String errMsg, final int pos) { }
 57          };
 58       parserDelegator.parse(reader, parserCallback, true);
 59    }
 60 }