2008年7月3日木曜日

Quick Search API を試す

6.5M1 リリース間近という事で、新機能の Quick Search API を試します
元ネタは Geertjan's Blog の ココやココのエントリー、 NetBeans Zone のココになります
(ほとんど上記のコピーです)

今回の例では Wikipedia の記事を検索します
まずは開発版ビルドをダウンロード、インストールします
次にモジュールプロジェクトを作成します
新規ファイル作成ウィザードの Module Development 中に "Quick Search Provider"という項目がありますので、これを選択します


Wikipedia の検索なので、以下のように入力し、関連ファイルを作成しています


次に実装を行います
ソースコードは以下のようにしました
(取り敢えず作った感じなので、結構適当です)

public class WikipediaSearchProvider implements SearchProvider {
private static final String GOOGLE_API_KEY = ""; // キーは各自で設定を行って下さい
private static final String GOOGLE_APIS_DOMAIN = "ajax.googleapis.com";
private static final String JA_WIKIPEDIA_DOMAIN = "ja.wikipedia.org";
private static final String GOOGLE_SEARCH_SERVICE_PARAMS = "?v=1.0&rsz=small&key=" + GOOGLE_API_KEY + "&q=site%3a" + JA_WIKIPEDIA_DOMAIN + "%20";
private static final String GOOGLE_SEARCH_SERVICE_URL = "http://" + GOOGLE_APIS_DOMAIN + "/ajax/services/search/web" + GOOGLE_SEARCH_SERVICE_PARAMS;
private static final String HTTP_REFERER_URL = "http://snakemanshow.blogspot.com";

/**
* Method is called by infrastructure when search operation was requested.
* Implementors should evaluate given request and fill response object with
* apropriate results
*
* @param request Search request object that contains information what to search for
* @param response Search response object that stores search results. Note that it's important to react to return value of SearchResponse.addResult(...) method and stop computation if false value is returned.
*/
public void evaluate(SearchRequest request, SearchResponse response) {
try {
URL url = new URL(GOOGLE_SEARCH_SERVICE_URL + URLEncoder.encode(request.getText(), "UTF-8"));
URLConnection conn = url.openConnection();
conn.setRequestProperty("Referer", HTTP_REFERER_URL);

JSON json = new JSON();
HttpResponse httpResponse = json.parse(conn.getInputStream(), HttpResponse.class);
List results = httpResponse.getResponseData().getResults();

if(results != null) {
for(GwebSearch search : results) {
if(!response.addResult(new OpenFoundArticle(search.getUnescapedUrl()), search.getTitleNoFormatting()));
}
}
} catch (IOException e) {
Exceptions.printStackTrace(e);
}
}

private static class OpenFoundArticle implements Runnable {

private String article;

public OpenFoundArticle(String article) {
this.article = article;
}

public void run() {
try {
URLDisplayer.getDefault().showURL(new URL(article));
} catch (MalformedURLException e) {
Exceptions.printStackTrace(e);
}
}
}
}

NetBeans API は 作成時に追加される Quick Search API 以外に UI Utilities API、 Utilities API を追加しており、 JSON のパースには JSONIC を使用しています
(JSONIC は依存パッケージもなく、使用方法も直感的とすばらしいライブラリです)

実行すると、以下のように Wikipedia から関連記事のタイトルを表示します


もちろん、日本語でも検索できます


NetBeans ソースコード検索用のモジュールを作成すると、ソースコードリーディングが楽になっていいかも…

1 件のコメント:

Masaki Katakai さんのコメント...

これ面白いよね。いろいろ使えると思うんだけど。