/** * * @title IndexSearcher * @author James McElvenny * * This class opens the index file, processes it and then searches the entry path for index items. * */ import javax.swing.DefaultListModel; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.w3c.dom.Document; import org.xml.sax.SAXException; import java.io.IOException; public class IndexSearcher { private String server; private String indexFile; private String entryPath; private DocumentBuilder builder; private XPath path; /** * * The constructor sets up all instance variables and the XML parser. * */ public IndexSearcher(String passedServer, String passedIndexFile, String passedEntryPath) throws ParserConfigurationException { server = passedServer; indexFile = passedIndexFile; entryPath = passedEntryPath; DocumentBuilderFactory dbfactory = DocumentBuilderFactory.newInstance(); builder = dbfactory.newDocumentBuilder(); XPathFactory xpfactory = XPathFactory.newInstance(); path = xpfactory.newXPath(); } /** * * The searchIndex method searches through the passed path for strings that match the searchString. * */ public void searchIndex(String index, String searchString, DefaultListModel outputTarget) throws SAXException, IOException, XPathExpressionException { String inputFile = server + indexFile; Document indexDoc = builder.parse(inputFile); int entryCount = Integer.parseInt(path.evaluate("count("+entryPath+")", indexDoc)); for(int i = 1; i <= entryCount; i++) { String indexItem = path.evaluate(entryPath+"["+i+"]/"+index, indexDoc); String indexLink = path.evaluate(entryPath+"["+i+"]/link", indexDoc); if(indexItem.equals(searchString)) { outputTarget.addElement(indexLink); } } if(outputTarget.isEmpty()) outputTarget.addElement(DictSearch.ERROR_MESSAGE); } }