Implementing the Ferret
Because there are no method implementations, you can't just take the Ferret interface and use it to instantiate a Ferret object. Instead, you need to create a class that implements the Ferret interface and instantiate that. Listing 2, for example, shows the GoogleFinder class.
Listing 2 GoogleFinder Class
package org.chase.ferrets; import com.google.soap. search.GoogleSearch; import com.google.soap. search.GoogleSearchResult; import com.google.soap. search.GoogleSearchFault; import com.google.soap.search. GoogleSearchResultElement; import org.chase.research.Ferret; public class GoogleFinder implements Ferret { /* The result object holds the results of any search */ GoogleSearchResult result = null; /* Perform the search and obtain the result, whatever it may be */ public void find(String searchTerm) { try { GoogleSearch search = new GoogleSearch(); search.setKey("00000000000000000000000000000000"); search.setQueryString(searchTerm); result = search.doSearch(); } catch (GoogleSearchFault gsf) { System.out.println("Google Search Fault: "+gsf.getMessage()); } } /* Return the number of hits */ public int getNumResults() { int numResults = result.getEstimatedTotalResultsCount(); return numResults; } /* Return the full set of results */ public String getResults() { return result.toString(); } /* Return only the first hit */ public String getFirstResult() { String resultString = ""; if (result.getEndIndex() > 0) { GoogleSearchResultElement[] resultElements = result.getResultElements(); GoogleSearchResultElement resultElement = resultElements[(0)]; resultString = resultElement.toString(); } else { resultString = "No results found."; } return resultString; } public String getSpelling(String searchTerm) { String suggestion = null; try { GoogleSearch search = new GoogleSearch(); search.setKey("00000000000000000000000000000000"); suggestion = search.doSpellingSuggestion(searchTerm); } catch (GoogleSearchFault gsf) { System.out.println("Google Search Fault: "+gsf.getMessage()); } return suggestion; } }
Here we once again see our four methods, but this time they've got implementations, so we can instantiate the class. More importantly, the class implements the Ferret interface, so we can instantiate this class as a Ferret.
Notice also that this class has an extra method: getSpelling(). Because it's not part of the Ferret interface, we won't be able to call it from the Ferret object, however.
The implementations themselves aren't especially important, but if you're interested, you can get more information on the Google API (and a license key that lets you perform your own searches) at http://www.google.com/apis/.