2011年2月18日金曜日

H2 DatabaseとTwitter4Jを使用して接続ユーザーのタイムラインを取得する関数を作成する

H2 DatabaseとTwitter4Jを使用して接続ユーザーのタイムラインを取得する関数を作成するには、以下のスクリプトを実行します。

create alias if not exists twitter_get_user_timeline as $$ 
import java.io.*;
import java.util.*;
import java.sql.*;
import org.h2.tools.*;
import twitter4j.*;
import twitter4j.http.*;
import twitter4j.conf.*;
@CODE
ResultSet twitter_get_user_timeline(String consumerKey,
String consumerSecret, String accessToken,
String accessTokenSecret, Integer page)
throws Exception
{
if( consumerKey == null ){
throw new Exception("consumerKey is not specified.");
}
if( consumerSecret == null ){
throw new Exception("consumerSecret is not specified.");
}
if( accessToken == null ){
throw new Exception("accessToken is not specified.");
}
if( accessTokenSecret == null ){
throw new Exception("accessTokenSecret is not specified.");
}
if( page == null ){
return null;
}

SimpleResultSet rs = new SimpleResultSet();
rs.addColumn("ID", Types.NUMERIC, 20, 0);
rs.addColumn("CREATEDAT", Types.TIMESTAMP, 0, 0);
rs.addColumn("NAME", Types.VARCHAR, 100, 0);
rs.addColumn("TWEET", Types.VARCHAR, 140, 0);

Properties prop = new Properties();
prop.put("oauth.consumerKey", consumerKey);
prop.put("oauth.consumerSecret", consumerSecret);
prop.put("oauth.accessToken", accessToken);
prop.put("oauth.accessTokenSecret", accessTokenSecret);
PropertyConfiguration pc =
new PropertyConfiguration(prop);

OAuthAuthorization oauth = new OAuthAuthorization(pc);
TwitterFactory tf = new TwitterFactory();
Twitter twitter = tf.getInstance(oauth);
ResponseList<Status> rl = twitter.getUserTimeline(new Paging(page));
for(Status status : rl){
rs.addRow(status.getId(),
new Timestamp(status.getCreatedAt().getTime()),
status.getUser().getScreenName(),
status.getText());
}
return rs;
}
$$

実行例
select * from twitter_get_user_timeline('xxxx',
'xxxx',
'xxxx',
'xxxx', 1);

※以下のjarをCLASSPATH環境変数に追加
twitter4j-core-2.1.12-SNAPSHOT.jar

○動作環境
JDK6 Update23, H2 Database 1.2.149 (2011-01-07), twitter4j-2.1.12-SNAPSHOT

○関連情報
H2 Database上でTwitter4Jを使用するユーザー定義関数のまとめ
・H2 Databaseに関する他の記事はこちらを参照してください。

0 件のコメント:

コメントを投稿