import java.io.*; import java.net.*; import java.util.*; public class WebSearch { /** * The string which is input by the user to end the search. */ protected static final String QUITSTRING = "quit"; /** * The Vector of URLs initialized by the constructor. */ protected Vector urlWords; /** * Creates a WebSearch object for the specified URLs. * * @param urls is a vector of URL objects. */ public WebSearch(Vector urls) { urlWords = new Vector(); Iterator i = urls.iterator(); while (i.hasNext()) { urlWords.add(new URLWords((URL) i.next())); } } /** * Determines if the user wants to end the web search. * * @param line is a String to be tested. * @return true if the user wants to end the web search, otherwise * false. */ public boolean isStopCondition(String line) { return line.equals(QUITSTRING); } /** * Extracts words from the given string. * * @param line is a String to be processed. * @return a Vector of Strings containing the words in the input * String. */ public Vector parseLine(String line) { StringTokenizer st = new StringTokenizer(line); Vector words = new Vector(); while (st.hasMoreTokens()) words.add(st.nextToken().toLowerCase()); return words; } /** * Prints the URLs in the instance variable urlWords which contain all of * the given words. * * @param searchWords is a Vector of Strings to be searched for. */ public void printURLsContainingWords(Vector searchWords) { Iterator i = urlWords.iterator(); while (i.hasNext()) { URLWords current = (URLWords) i.next(); if (current.containsWords(searchWords)) System.out.println(current.getURL()); } } /** * Until the user types quit, prompts the user to enter words to search for * and then outputs, on separate lines, the URLs of all the web pages in the * instance variable urlWords that contain all of the search words. */ public void start() { if (urlWords.size() == 0) { System.out.println("No valid URLs to search."); return; } String prompt = getClass().getName() +"> "; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); try { System.out.print(prompt); String line = br.readLine(); while (!isStopCondition(line)) { Vector searchWords = parseLine(line); printURLsContainingWords(searchWords); System.out.println(); System.out.print(prompt); line = br.readLine(); } } catch (IOException e) { } } /** * Takes a list of URLs from the command line, attempts to create * corresponding URL objects for them and starts the web search. * * @param args a list URLs as an array of Strings. */ public static void main(String args[]) { Vector urls = new Vector(); int arg = 0; while (arg < args.length) { try { urls.add(new URL(args[arg])); } catch (MalformedURLException e) { System.out.println("Ignoring bad URL: " + args[arg]); } arg++; } WebSearch webSearch = new WebSearch(urls); webSearch.start(); } }