Java Reference
In-Depth Information
So let's say you were making a system and wanted to give your users the ability
to do Google searches from within your application. The Google API for calling
their web service is simple enough to use, but because other search engines are pro-
viding similar API s now, we are going to create a more generic search API that will
be used to wrap the Google implementation, and call that API from our application.
First we need to come up with a search interface and structure for returning
search results, so let's start with a simple bean and an interface:
public class SearchResult {
private String url;
private String summary;
private String title;
// getters and setters omitted...
}
public interface WebSearchDao {
List<SearchResult> getSearchResults(String text);
}
Our bean has three properties, and our interface has one method that returns a
typed list. Here is the implementation of that search API , using the Google API :
public class GoogleDaoImpl implements WebSearchDao {
private String googleKey;
public GoogleDaoImpl(){
this("insert-your-key-value-here");
}
public GoogleDaoImpl(String key){
this.googleKey = key;
}
public List<SearchResult> getSearchResults(String text){
List<SearchResult> returnValue = new
ArrayList<SearchResult>();
GoogleSearch s = new GoogleSearch();
s.setKey(googleKey);
s.setQueryString(text);
try {
GoogleSearchResult gsr = s.doSearch();
for (int i = 0; i < gsr.getResultElements().length;
i++){
GoogleSearchResultElement sre =
gsr.getResultElements()[i];
SearchResult sr = new SearchResult();
sr.setSummary(sre.getSummary());
sr.setTitle(sre.getTitle());
sr.setUrl(sre.getURL());
Search WWH ::




Custom Search