/* * WebWorm Solution. CSE 341. * * Jason Hartline */ import java.net.*; import java.io.*; import java.util.*; /* * this class reads in web pages and will, when printed, display * the links in the web page. */ class WebWorm { /* * this holds the links that we have found thus far. */ Vector links; /* * this is the URL that we are going to look for links on */ String url; /* * sequences of characters denotes a link. */ static final String linkPrefix = "= 0; index = lower.indexOf(linkPrefix,index+1)) { /* * find the end of the link. */ int endIndex = lower.indexOf(linkSuffix, index); if (endIndex < 0) endIndex = s.length(); /* * add the link to 'links' */ links.addElement(s.substring(index+2,endIndex)); /* * prepare to find the next link. * on this line. */ index = endIndex; } } /* * printing out a WebWorm will either. * 1. if the URL has not been processed, print out * that the WebWorm will process the link. * 2. if there was an error processing the URL, * print out the error message. * 3. if the URL was successfully processed, print * out all of the links. */ public String toString() { /* * oops! there was an error. */ if (hasError()) return("WebWorm error: " + getErrorMessage()); /* * URL has not been processed yet. */ if (links == null) return("WebWorm to load: " + url); /* * print out header. */ StringBuffer out = new StringBuffer("Links found in " + url); /* * print out links. */ for(Enumeration e = links.elements(); e.hasMoreElements(); ) out.append("\n"+e.nextElement()); return(out.toString()); } /* * main program. * * - create a WebWorm. * - have it process the URL. * - print it out. */ public static void main(String [] args) { if (args.length != 1) { System.err.println("USAGE: WebWorm url"); System.exit(-1); } WebWorm worm = new WebWorm(args[0]); worm.process(); System.out.println(worm); } /* * dealing with errors. * * setError, clearError, hasError, and getError */ private String errorMessage = null; private void setError(String error) { errorMessage = error; } private void clearError() { errorMessage = null; } public boolean hasError() { return (errorMessage != null); } public String getErrorMessage() { return errorMessage; } }