/* * WordListFileLoader.java * * Created on January 16, 2005, 8:57 PM */ package com.toy.anagrams.lib; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import org.xml.sax.Attributes; /** * * @author bsuter */ public class WordListFileLoader { /** Creates a new instance of WordListFileLoader */ public WordListFileLoader() { out = System.out; } public String[] loadList(String url) { InputStream is; try { URL u = new URL(url); is = u.openConnection().getInputStream(); } catch (IOException ioe) { report("Unable to open or find the specified wordlist."); is = null; } if (is == null) { report("Unable to load the requested wordlist. An error occurred while opening the file."); return null; } SAXParserFactory parserFactory = SAXParserFactory.newInstance(); SAXParser parser; try { parser = parserFactory.newSAXParser(); } catch ( ParserConfigurationException pce ) { report("Error setting up the XML Parser. The parser is not properly configured. Loading aborted."); return null; } catch ( SAXException saxe ) { report("Error setting up the XML Parser. Loading aborted."); return null; } try { WordListHandler handler = new WordListHandler(); parser.parse(is, handler); } catch ( Exception e ) { report("Unable to load the list, probably while performing SAX parsing."); return null; } return this.list; } public class WordListHandler extends DefaultHandler { protected String nodeType; protected ArrayList al; public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if ( qName == "word" ) { nodeType = "word"; } else if ( qName == "wordlist" ) { al = new ArrayList(); } } public void endElement(String uri, String localName, String qName) throws SAXException { if ( qName == "word" ) { nodeType = null; } else if (qName == "wordlist" ) { /* Cast the ArrayList to a an array of String objects. */ list = (String[]) this.al.toArray(new String[al.size()]); } } public void characters(char[] chars, int start, int length) throws SAXException { if ( this.nodeType == "word" ) { this.al.add(new String(chars, start, length).trim()); } } } protected void report(String message) { this.out.println(message); } protected PrintStream out; protected String[] list; }