女子中高生とTwitter4Jについて発表してきました。#twtr_hack

TwitterAPI勉強会にて、以下のLTをしてきました。
10分の発表なのに、スライド60枚以上作ってしまったので、どうなるかと思いましたが、想定通り1分6枚ペースで時間内に無事?終わりました。
また、タイトルで釣ることを目的にしていたので、中身薄くてゴメンナサイ。

当日のTogetterはこちら
http://togetter.com/li/292726

全体のまとめはこちら
第6回Twitter API勉強会を開催いたしました - ビデオ・スライドまとめ #twtr_hack

発表資料は以下になります。

Ustを録画してくださったので、以下に張っておきます。

TwitterAPIのエラーが多いので、それに対応するコードがカオスになってしまうから、旨いリトライのやり方あったら教えて下さいと言ったら普通にTwitter4Jに実装されていたという恥ずかしいオチでしたが、勉強になりました。リファレンス読めってことですね。ありがとうございました。

関連情報
インフラ構成で軽く触れましたが、AWSのAutoScalingについてはこちらで記事を書いていますので、ご参考になれば。
Amazon WebserviceのAuto Scalingの設定について

Scalaで自動フォロー返し書いたら凄く簡単になった件はこちらに記事を書いています。ご参考になれば。
Javaで書かれたTwitterの自動フォロー返しを、Scalaで書いてみた #twitter4j #twtr_hack

今回MyBatisというORマッパー(HibernateほどなORマップではない)を使いました。某SIerの社内フレームワークiBatisを使っていて、SQL文をxmlに記述していく(またはエクセル方眼紙からそのxmlを自動生成している)と思いますが、MyBatisはxmlを捨ててアノテーションSQLを記述します。
※ちなみにMyBatisはiBatisが大人の事情でApache系列からGoogleCodeProjectに移ることになった際にネーミングが変わっています。
私は、自分でSQLを書きたい派なので、JPA的なインタフェースが少し苦手(笑)で、SQL感が強いMyBatisを採用しました。SpringのTransactionTemplateでもいいじゃんとなるのですが、MyBatisの付属品である、Generatorが便利だったので。
http://code.google.com/p/mybatis/wiki/Generator
データベースにあるテーブル情報から単純なCRUDアクセスパターンはSQL及びそれをラップしたDAOクラスを自動生成してくれます。
例えば、userId、userName、photoUrlのカラムを持つUSERテーブルに対してCRUD生成を行うと以下のようなクラスが生成されます。

public interface UserMapper {
    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbggenerated Mon Oct 03 15:41:07 JST 2011
     */
    @SelectProvider(type=UserSqlProvider.class, method="countByExample")
    int countByExample(UserExample example);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbggenerated Mon Oct 03 15:41:07 JST 2011
     */
    @DeleteProvider(type=UserSqlProvider.class, method="deleteByExample")
    int deleteByExample(UserExample example);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbggenerated Mon Oct 03 15:41:07 JST 2011
     */
    @Delete({
        "delete from user",
        "where userId = #{userId,jdbcType=VARCHAR}"
    })
    int deleteByPrimaryKey(UserKey key);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbggenerated Mon Oct 03 15:41:07 JST 2011
     */
    @Insert({
        "insert into user (userId, userName, ",
        "photoUrl)",
        "values (#{userId,jdbcType=VARCHAR}, #{userName,jdbcType=VARCHAR}, ",
        "#{photoUrl,jdbcType=LONGVARCHAR})"
    })
    int insert(UserWithBLOBs record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbggenerated Mon Oct 03 15:41:07 JST 2011
     */
    @InsertProvider(type=UserSqlProvider.class, method="insertSelective")
    int insertSelective(UserWithBLOBs record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbggenerated Mon Oct 03 15:41:07 JST 2011
     */
    @Select({
        "select",
        "userId, userName, photoUrl",
        "from user",
        "where userId = #{userId,jdbcType=VARCHAR}"
    })
    @Results({
        @Result(column="userId", property="userId", jdbcType=JdbcType.VARCHAR, id=true),
        @Result(column="userName", property="userName", jdbcType=JdbcType.VARCHAR),
        @Result(column="photoUrl", property="photoUrl", jdbcType=JdbcType.LONGVARCHAR)
    })
    UserWithBLOBs selectByPrimaryKey(UserKey key);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbggenerated Mon Oct 03 15:41:07 JST 2011
     */
    @UpdateProvider(type=UserSqlProvider.class, method="updateByExampleSelective")
    int updateByExampleSelective(@Param("record") UserWithBLOBs record, @Param("example") UserExample example);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbggenerated Mon Oct 03 15:41:07 JST 2011
     */
    @UpdateProvider(type=UserSqlProvider.class, method="updateByExampleWithBLOBs")
    int updateByExampleWithBLOBs(@Param("record") UserWithBLOBs record, @Param("example") UserExample example);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbggenerated Mon Oct 03 15:41:07 JST 2011
     */
    @UpdateProvider(type=UserSqlProvider.class, method="updateByExample")
    int updateByExample(@Param("record") User record, @Param("example") UserExample example);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbggenerated Mon Oct 03 15:41:07 JST 2011
     */
    @UpdateProvider(type=UserSqlProvider.class, method="updateByPrimaryKeySelective")
    int updateByPrimaryKeySelective(UserWithBLOBs record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbggenerated Mon Oct 03 15:41:07 JST 2011
     */
    @Update({
        "update user",
        "set userName = #{userName,jdbcType=VARCHAR},",
          "photoUrl = #{photoUrl,jdbcType=LONGVARCHAR}",
        "where userId = #{userId,jdbcType=VARCHAR}"
    })
    int updateByPrimaryKeyWithBLOBs(UserWithBLOBs record);

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbggenerated Mon Oct 03 15:41:07 JST 2011
     */
    @Update({
        "update user",
        "set userName = #{userName,jdbcType=VARCHAR}",
        "where userId = #{userId,jdbcType=VARCHAR}"
    })
    int updateByPrimaryKey(User record);
}

こちらが動的にSQLをつくる必要があるものです。上記クラスからアノテーション経由で利用されます。

public class UserSqlProvider {

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbggenerated Mon Oct 03 15:41:07 JST 2011
     */
    public String countByExample(UserExample example) {
        BEGIN();
        SELECT("count (*)");
        FROM("user");
        applyWhere(example, false);
        return SQL();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbggenerated Mon Oct 03 15:41:07 JST 2011
     */
    public String deleteByExample(UserExample example) {
        BEGIN();
        DELETE_FROM("user");
        applyWhere(example, false);
        return SQL();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbggenerated Mon Oct 03 15:41:07 JST 2011
     */
    public String insertSelective(UserWithBLOBs record) {
        BEGIN();
        INSERT_INTO("user");
        
        if (record.getUserId() != null) {
            VALUES("userId", "#{userId,jdbcType=VARCHAR}");
        }
        
        if (record.getUserName() != null) {
            VALUES("userName", "#{userName,jdbcType=VARCHAR}");
        }
        
        if (record.getPhotoUrl() != null) {
            VALUES("photoUrl", "#{photoUrl,jdbcType=LONGVARCHAR}");
        }
        
        return SQL();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbggenerated Mon Oct 03 15:41:07 JST 2011
     */
    public String updateByExampleSelective(Map<String, Object> parameter) {
        UserWithBLOBs record = (UserWithBLOBs) parameter.get("record");
        UserExample example = (UserExample) parameter.get("example");
        
        BEGIN();
        UPDATE("user");
        
        if (record.getUserId() != null) {
            SET("userId = #{record.userId,jdbcType=VARCHAR}");
        }
        
        if (record.getUserName() != null) {
            SET("userName = #{record.userName,jdbcType=VARCHAR}");
        }
        
        if (record.getPhotoUrl() != null) {
            SET("photoUrl = #{record.photoUrl,jdbcType=LONGVARCHAR}");
        }
        
        applyWhere(example, true);
        return SQL();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbggenerated Mon Oct 03 15:41:07 JST 2011
     */
    public String updateByExampleWithBLOBs(Map<String, Object> parameter) {
        BEGIN();
        UPDATE("user");
        
        SET("userId = #{record.userId,jdbcType=VARCHAR}");
        SET("userName = #{record.userName,jdbcType=VARCHAR}");
        SET("photoUrl = #{record.photoUrl,jdbcType=LONGVARCHAR}");
        
        UserExample example = (UserExample) parameter.get("example");
        applyWhere(example, true);
        return SQL();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbggenerated Mon Oct 03 15:41:07 JST 2011
     */
    public String updateByExample(Map<String, Object> parameter) {
        BEGIN();
        UPDATE("user");
        
        SET("userId = #{record.userId,jdbcType=VARCHAR}");
        SET("userName = #{record.userName,jdbcType=VARCHAR}");
        
        UserExample example = (UserExample) parameter.get("example");
        applyWhere(example, true);
        return SQL();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbggenerated Mon Oct 03 15:41:07 JST 2011
     */
    public String updateByPrimaryKeySelective(UserWithBLOBs record) {
        BEGIN();
        UPDATE("user");
        
        if (record.getUserName() != null) {
            SET("userName = #{userName,jdbcType=VARCHAR}");
        }
        
        if (record.getPhotoUrl() != null) {
            SET("photoUrl = #{photoUrl,jdbcType=LONGVARCHAR}");
        }
        
        WHERE("userId = #{userId,jdbcType=VARCHAR}");
        
        return SQL();
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table user
     *
     * @mbggenerated Mon Oct 03 15:41:07 JST 2011
     */
    protected void applyWhere(UserExample example, boolean includeExamplePhrase) {
        if (example == null) {
            return;
        }
        
        String parmPhrase1;
        String parmPhrase1_th;
        String parmPhrase2;
        String parmPhrase2_th;
        String parmPhrase3;
        String parmPhrase3_th;
        if (includeExamplePhrase) {
            parmPhrase1 = "%s #{example.oredCriteria[%d].allCriteria[%d].value}";
            parmPhrase1_th = "%s #{example.oredCriteria[%d].allCriteria[%d].value,typeHandler=%s}";
            parmPhrase2 = "%s #{example.oredCriteria[%d].allCriteria[%d].value} and #{example.oredCriteria[%d].criteria[%d].secondValue}";
            parmPhrase2_th = "%s #{example.oredCriteria[%d].allCriteria[%d].value,typeHandler=%s} and #{example.oredCriteria[%d].criteria[%d].secondValue,typeHandler=%s}";
            parmPhrase3 = "#{example.oredCriteria[%d].allCriteria[%d].value[%d]}";
            parmPhrase3_th = "#{example.oredCriteria[%d].allCriteria[%d].value[%d],typeHandler=%s}";
        } else {
            parmPhrase1 = "%s #{oredCriteria[%d].allCriteria[%d].value}";
            parmPhrase1_th = "%s #{oredCriteria[%d].allCriteria[%d].value,typeHandler=%s}";
            parmPhrase2 = "%s #{oredCriteria[%d].allCriteria[%d].value} and #{oredCriteria[%d].criteria[%d].secondValue}";
            parmPhrase2_th = "%s #{oredCriteria[%d].allCriteria[%d].value,typeHandler=%s} and #{oredCriteria[%d].criteria[%d].secondValue,typeHandler=%s}";
            parmPhrase3 = "#{oredCriteria[%d].allCriteria[%d].value[%d]}";
            parmPhrase3_th = "#{oredCriteria[%d].allCriteria[%d].value[%d],typeHandler=%s}";
        }
        
        StringBuilder sb = new StringBuilder();
        List<Criteria> oredCriteria = example.getOredCriteria();
        boolean firstCriteria = true;
        for (int i = 0; i < oredCriteria.size(); i++) {
            Criteria criteria = oredCriteria.get(i);
            if (criteria.isValid()) {
                if (firstCriteria) {
                    firstCriteria = false;
                } else {
                    sb.append(" or ");
                }
                
                sb.append('(');
                List<Criterion> criterions = criteria.getAllCriteria();
                boolean firstCriterion = true;
                for (int j = 0; j < criterions.size(); j++) {
                    Criterion criterion = criterions.get(j);
                    if (firstCriterion) {
                        firstCriterion = false;
                    } else {
                        sb.append(" and ");
                    }
                    
                    if (criterion.isNoValue()) {
                        sb.append(criterion.getCondition());
                    } else if (criterion.isSingleValue()) {
                        if (criterion.getTypeHandler() == null) {
                            sb.append(String.format(parmPhrase1, criterion.getCondition(), i, j));
                        } else {
                            sb.append(String.format(parmPhrase1_th, criterion.getCondition(), i, j,criterion.getTypeHandler()));
                        }
                    } else if (criterion.isBetweenValue()) {
                        if (criterion.getTypeHandler() == null) {
                            sb.append(String.format(parmPhrase2, criterion.getCondition(), i, j, i, j));
                        } else {
                            sb.append(String.format(parmPhrase2_th, criterion.getCondition(), i, j, criterion.getTypeHandler(), i, j, criterion.getTypeHandler()));
                        }
                    } else if (criterion.isListValue()) {
                        sb.append(criterion.getCondition());
                        sb.append(" (");
                        List<?> listItems = (List<?>) criterion.getValue();
                        boolean comma = false;
                        for (int k = 0; k < listItems.size(); k++) {
                            if (comma) {
                                sb.append(", ");
                            } else {
                                comma = true;
                            }
                            if (criterion.getTypeHandler() == null) {
                                sb.append(String.format(parmPhrase3, i, j, k));
                            } else {
                                sb.append(String.format(parmPhrase3_th, i, j, k, criterion.getTypeHandler()));
                            }
                        }
                        sb.append(')');
                    }
                }
                sb.append(')');
            }
        }
        
        if (sb.length() > 0) {
            WHERE(sb.toString());
        }
    }
}

使うにはSpringのBean定義に以下を書くだけ

	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="configLocation" value="classpath:MyBatisConfig.xml" />
	</bean>
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
		<property name="basePackage" value= "生成したDAOがおかれるパッケージ" />
	</bean>

生成されたDAOクラスは、当然GenerationGapパターンを適用できるので、自動生成したクラスをスーパークラスとして、個別要件(手動による追記)をextendsした側に記述してあげることで、CRUDの再生成が可能です。

TwitterハッカソンでNFCによるTwitterアイコンチェンジャーを作成しました。#twtr_hack #twitter4j #nfchack

Twitterハッカソンに参加してきました。場所はTwitter Japan!
(場所はアーク森ビルといわれ、勘違いして六本木ヒルズに行き、インフォメーションカウンターのおねーさんにTwitterJapanどこですか?と聞いて、ザワザワしたのは言うまでもない。)

トゥギャッターはこちら → 第0回 Twitterハッカソン #twtr_hack
@yusukeyさんのブログはこちら →第0回Twitterハッカソンを開催しました #twtr_hack
@bina1204さんのブログはこちら →第0回 Twitter Hack に参加した
@makotoworldさんのブログはこちら →第0回Twitterハッカソンに参加して
@johtaniさんのブログはこちら →第0回 Twitter Hack #twtr_hack に遊びに行きました。

私がつくったのはNFC契機によるTwitterのアイコンチェンジャーです。
Twitterのアイコンに現在のステータスを埋め込んだら、MSNメッセンジャーとかでいう現在のステータス(退席中、取り込み中的な)が表現できるのではないかと。
また、ステータスのキーとして、SUICAAndroidにタッチすれば、「電車移動中」とTwitterアイコンに示され、
同様に、社員証をタッチすれば「仕事中!」とアイコンに示されるようにしました。Twitterのアイコンかえるくらい、ボタン操作ではなくワンタッチで済ませたい。

実際の実行結果は以下になります。
これが元のアイコン。
f:id:i2key:20120308032830p:image

これがSUICAタッチ後のアイコン。
f:id:i2key:20120308032831p:image

これが社員証タッチ後のアイコン。
f:id:i2key:20120308032832p:image

遅刻しまくったし時間が無かったので強引なオレオレ実装ですが、ソースはGitHubにアップしておきました。
https://github.com/i2key/NFCxTwitter4J

また、TwitterAPIを使うとかなりの確率でステータスコード4XXや500が返ってくるのだけど、
以下のように何回かリトライさせるような実装で対応するしかないのでしょうか。
皆さんどのように書いているのか非常に気になります。

UpdateProfileImageTask.java

//4XXや5XXでても3回まではリトライする
int continuousErrorCount = 0;
while(true){
	try {
		Log.i(TAG, "START.");
		//やりたいのはこれだけ。アイコン画像のアップロード
		twitter.updateProfileImage(bis);
	} catch (TwitterException e) {
		Integer errorCode = e.getStatusCode();
		if(errorCode.toString().startsWith("5") || errorCode.toString().startsWith("4")){
			continuousErrorCount++;
			if(continuousErrorCount < 4){
				Log.e(TAG, "STATUS CODE is 4XX , 5XX. Try " + continuousErrorCount + "times.");
				continue;
			}else{
				//リトライ4回目で終了(もう無理あきらめる)
				Log.e(TAG, "STATUS CODE is 4XX , 5XX. Try " + continuousErrorCount + "times.");
				return false;
			}
		}else{
			//STATUS CODE = 3XX , 2XXのときはリトライなしで終了
			Log.e(TAG, "STATUS CODE is 3XX , 2XX. Try " + continuousErrorCount + "times.");
			return false;
		}
	}
	//成功したら終了
	Log.i(TAG, "SUCCESS. Try " + continuousErrorCount + "times.");
	break;
}

ハッカソンの雰囲気
f:id:i2key:20120308034112j:image

頂いたノベルティ(ステッカー、ボールペン、クリアファイル、Tシャツ)
f:id:i2key:20120308035803j:image:w360

最後になりましたが、@yusukeyさん、ピザごちそうさまでした!

Javaで書かれたTwitterの自動フォロー返しを、Scalaで書いてみた #twitter4j #twtr_hack

つくっているiOS、AndroidアプリのPRキャンペーンでTwitterの自動フォロー返しが必要になったので、最近勉強をはじめたScalaで書いてみました。
参考にさせていただいたのは以下のJavaソースです。もちろん、Twitter4Jを使います。

http://d.hatena.ne.jp/yoheiM/20100827

import java.util.ArrayList;
import java.util.List;

import twitter4j.IDs;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.User;


public class AutoRefollow {
	protected static Twitter twitter;
	public static void main(String[] args) throws Exception {
		System.out.println("処理開始");
		twitter = new Twitter("yoheiMune", "56909885");
		IDs frends = getFrendIds();
		IDs follower = getFollowerIds();
		List<Integer> notFollowIdList = calcNotFollow(follower, frends);
		doFollow(notFollowIdList);
		System.out.println("処理終了");
	}

	protected static void doFollow(List<Integer> notFollowIdList) throws TwitterException {
		for (Integer userId : notFollowIdList) {
			User user = twitter.createFriendship(userId);
			if(user == null) {
				throw new TwitterException("フォローに失敗しました。対象ID:" + userId);
			}
			System.out.println("フォローしました。対象:" + user.getName());
		}
	}

	protected static List<Integer> calcNotFollow(IDs follower, IDs frends) {
		List<Integer> returnValue = new ArrayList<Integer>();
		for(int id : follower.getIDs()) {
			if(! contains(frends, id)) {
				returnValue.add(Integer.valueOf(id));
			}
		}
		return returnValue;
	}

	private static boolean contains(IDs frends, int id) {
		
		for(int frendId : frends.getIDs()) {
			if(frendId == id) {
				return true;
			}
		}
		return false;
	}

	protected static IDs getFollowerIds() throws TwitterException {
		return twitter.getFollowersIDs();
	}

	protected static IDs getFrendIds() throws TwitterException {
		return twitter.getFriendsIDs();
	}

}

処理は以下のような感じですね。
・自分がフォローしているリストを取得
・自分のフォロワーリストを取得
・自分のフォロワーリストと自分がフォローしているリストを比較し、自分がフォローしていない人をリストにする
・自分がフォローしていない人に対してフォローする。

Scalaで書いたら以下のようになりました。
上記の手順は最後に一行にまとまっています。
また、コンパイルせずにインタプリタとして動作させることを前提でかいています。
ScalaのArrayまわりの使い易さが異常ですね。
エラー処理とかいろいろ抜けていますが、ScalaでかくとJavaで書くよりこんなにシンプルになるよ!というScalaのステマでした。
(むりくり1行にまとめています・・・。)

import twitter4j.Twitter
import twitter4j.TwitterFactory
import twitter4j.TwitterException
import twitter4j.Status
import twitter4j.auth.AccessToken
import twitter4j.IDs

val twitter: Twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer("consumerKey", "consumerSecret");
twitter.setOAuthAccessToken(new AccessToken("accessToken", "accessTokenSecret"));

twitter.getFollowersIDs(twitter.getId(),-1).getIDs().filter(!(twitter.getFriendsIDs(twitter.getId(),-1).getIDs()).contains(_)).foreach(twitter.createFriendship(_));

Android + Twitter4JでHelloWorld2.0 #twitter4j

以前、Twitter API勉強会(#twtr_hack)後の懇親会にて
@yusukeyさんが、「今時はコーディングの勉強はじめるならTwitter4JつかってHelloWorld2.0だよね。」と言っていたので、
そのままその案をパクって採用して、学生向けAndroid勉強会(入門編)のテーマにしました。

やっぱ、Twitterとか普段つかっているものが自分のつくったプログラムで表示されると嬉しいよね。

HelloWorld2.0のサンプルプログラムの仕様(画面遷移)は以下。
f:id:i2key:20120225235028p:image
SreenName(TwitterID)を入力してボタン押下でそのユーザのツイートの一覧を表示します。
詳細チェック無しは、シングルスレッドでゴリゴリ一覧取得&表示でListViewもカスタマイズ無し。
詳細チェック有りは、AsyncTaskで非同期に一覧取得&表示でListViewのカスタマイズ有り。
AsyncTaskLoader使ってなかったり、インジケータ無かったり、いろいろアレですが、HelloWorld的には十分かなと思っております。

資料全体は以下のスライドシェア参考。

サンプルプログラムはGitHubにあげてあります。
https://github.com/i2key/HelloWorld2.0

NFCハッカソンに参加してきました

先日行われましたNFCハッカソンに参加してきました。実は勤務先のブログでも本イベントの報告はしているのですが、個人的な見解等も交えて書きたかったので自分のブログにもポストしました。

NFCについて

技術的なことはWEB上にも沢山あるので(参考:NFCの定義)そちらを見て頂くとして、世界観というかアイディア出しのアプローチとして私なりのNFCの解釈をまとめてみようと思います。
ソニーの鳥居さんの資料がスゴく分かり易かったです。

NFCのイメージ

本ポストではスマフォでのNFC利用前提で言及します。
一般的にNFCというとSUICAFelicaのイメージが強く、どうしてもタッチするというアフォーダンスが働くように思えます。そして何かアイディアを出そうとするとチェックイン系アプリへの発想へと凝り固まる(気がします)
しかしながらNFCは無線通信規格であるため、もっと自由度が高い。

抽象的で申し訳ありませんがNFCリアルとバーチャルを繋ぐゲートウェイになり得るものだと考えています。リアルな世界でNFCで何らかの行為を行うと、バーチャルな世界に何らかの影響を及ぼす、そんなイメージです。なので、チェックインという動作だけに凝り固まるともったいないです(※別にチェックイン系アプリをDisってる訳ではありません)

O2OとNFC

NFCはO2O文脈に非常に向いていると思います。
例えば、GEO情報等でオンライン側から店舗来店のオフライン側に誘導し、店舗内に設置したNFCタグから再びオンライン側に誘導させるとか。しかしながら、NFCタグを各店舗に配るのかというと、それはそれで面倒であり、スタートアップ等では非常にやり難い営業力勝負の所でもある。そして、そこまでまだ浸透していない。まだ、時期尚早感が漂っています。

現段階でのNFC

そこで、現段階ではスマフォユーザがNFCをユーザ体験として学習するフェーズなのかなーとも思ったりします。そういった意味では、SUICAの中身を読み取るだけのアプリでも良いし、Felicaの決済履歴を閲覧でするでも良いと思います。
しかしながら、Androidマーケットを見て驚くのが、「NFCで○○をします!」とか「NFCによってどーのこーの」的な「NFC」を全面に押し出したアプリ説明が多いこと。イノベーターやアーリーアダプターな方々にはNFCという名前で刺さると思うのですが、一般ユーザ目線で言うとNFCという単語は逆に見せない方がいいのではと思います。
SUICAを使っているときも、これはNFCだということは誰も認識していないと思うので。スマートフォンをかざすと何かが起きるというユーザ体験を得ることが出来れば現状十分なのかなーと。

各社のNFC動向

ですが、2013年にはNFC全盛期だという噂もあり、各社いろいろな取り組みが始まっているようです。
しかし、どれもおさいふケータイの延長上な印象。既に使い方を学習済みの用途でスケールさせていくのが正攻法だとは思います。
KDDI が NFC サービスを今春開始、GALAXY SII WiMAX から
モバイルペイメントのアプリケーション開発に力を入れる PayPass、payWaveの発行をカードとモバイルの両輪で展開へ
生活者に受け入れられるNFCサービスの展開を目指す 3キャリア共同で協議会を設立し、歩調を合わせる
資生堂でNFCスマートフォンを使った情報配信実験、凸版印刷が実施

ハッカソンでの自分なりのテーマ

だから、自分としては、そういうお財布ケータイやチェックイン文脈ではないことをやりたかった(全然時間内に終わりませんでしたが)。
そこで今回発表させていただいたドラクエのXボタンの話になりました。

概略としては、
スマートフォンでやることって、時間と場所とかで大体決まるよね?例えば、自分の場合、「ベット」+「夜」の文脈だと、スマートフォンはアラームをセットすることしかしない。このような文脈によって、スマートフォンでの行動が一意に決定できるケースをNFCで更に文脈を与えてあげることで、確度を高め、ワンタッチでアクションするようにしてみようという話。

発表資料をアップしときます。発表ではファミコン時代のドラクエのUI(壷を調べるのに「しらべる」を選択する煩わしさ)とスーパーファミコン以降のドラクエのUI(Xボタンだけで解決)を比較して、文脈により一意に行動が決まる様子を説明しました。

これからもNFCから目が離せないっ!!

自分用Android参考情報まとめ(随時リンク追加中)

Androidを勉強初めて参考にしたページをリストアップしていく。

パフォーマンス

フルGC対策

OutOfMemory発生時に真っ先にメモリを回収させるためのラッパークラス
SoftReference(Android特有の話ではないけど)
http://labs.techfirm.co.jp/android/cho/2142

View

スプラッシュ

スプラッシュを表示させる方法
http://d.hatena.ne.jp/yamamotodaisaku/20100126/1264504434

Activity

透過させる方法
http://techbooster.jpn.org/andriod/ui/4715/

デバイス操作

カメラ

Android のカメラを制御してみた
http://loumo.jp/wp/archive/20110427220305/

カメラを制御する

実用的なカメラの実装
http://kurotofu.sytes.net/kanji/fool/?p=775

処理方式

非同期処理について

メインスレッドとは別にスレッドを立てて、裏でWebAPI等にアクセスし、データを取得したい場合等に、Androidでの非同期処理の実装方法が気になって参考に。
AsyncTask
http://android.keicode.com/basics/async-asynctask.php

現在はAsyncTaskよりもActivityとTask間の結合度が低くなるAsyncTaskLoaderなるものがあるようです。
AsyncTaskLoader
http://archive.guma.jp/2011/11/-asynctask-asynctaskloader.html

Loaderについて
https://sites.google.com/a/techdoctranslator.com/jp/android/guide/activities/loaders

ジョブ

Androidで定期的に処理を実行する方法
http://magpad.jugem.jp/?eid=108

インテント

自作のデータクラス等をインテントで別のActivityに渡したい場合はParcelableな実装にすればよい。
Parcel関連
http://www.adakoda.com/adakoda/2009/01/android-androidosparcelable-parcel.html

データベースアクセス

Android上のデータ格納領域として、SQLiteが入っているため、そうとなるとActivityにSQLガリガリ書くのは気まずいのでDaoパターンで実装したくなります。AndroidアプリでもWEBシステム通りにDaoパターンで実装すればよいと思います。
http://d.hatena.ne.jp/iwata330/20110428/1303988338

HTTP

Android組込みのHttpComponent(HttpClient)の正しい使い方といくつかのtips
http://d.hatena.ne.jp/terurou/20110702/1309541200

データ構造

JSON

Androidで使えるJSONライブラリの比較
http://mstssk.blogspot.com/2011/12/androidjson.html

エラー対処

試しにメインスレッドでHttp通信して色々確認するような場合、AndroidOSがStrictモードによる自己防衛機能で強制クラッシュが発生します。基本的にはそれは有り難いことなのですが、一時的にどうしても外さなきゃならない場合は以下を参考に。
http://d.hatena.ne.jp/miettal/20111108/1320761296
http://d.hatena.ne.jp/Superdry/20101213/1292267620

PlayFrameworkでSpringFrameworkを使う

こんばんは。Play! framework Advent Calendar 2011 jp #play_jaの12月23日の記事になります。よろしくお願いします。

さて、Spring Module知ってますか?

Play!にはSpring Moduleなるものがあります。これによってPlay!でもSpringFrameworkを使うことが可能になります。
Springを使うことのメリットとしては、それなりに大規模な開発において、インタフェースクラスを確実にきって、責務の所在を明らかにした実装を行うケースかと思います。
そして、Springを使うことでフィールドに依存ロジックをhaveする実装になり、外部から依存ロジックを注入可能になることで結果的にテスタビリティが上がるので個人的に好きだったりします。

そもそもPlay!が「そういう面倒なことしなくていいから、ささっと作って動かして確認してしまおうよ」という思想なのは百も承知ですが、AdventCalendarネタがかぶりまくってネタに困っているので、最後の手段でSpringModuleに手を出したわけでPlay!とSpringでなんかできないかなぁと思い試しに使ってみましたので、その情報を共有させていただきます。

例えば以下のような利用シーンはどうでしょうか。
・対外システム接続があり、外部への接続モジュールはスタブと容易に差し替えを可能にしておきたい場合

Springモジュールのインストール

ではやってみましょう。

$play install spring
~        _            _ 
~  _ __ | | __ _ _  _| |
~ | '_ \| |/ _' | || |_|
~ |  __/|_|\____|\__ (_)
~ |_|            |__/   
~
~ play! 1.2.4, http://www.playframework.org
~
~ Will install spring-1.0.2
~ This module is compatible with: 1.2.x
~ Do you want to install this version (y/n)? y
~ Installing module spring-1.0.2...
~
~ Fetching http://www.playframework.org/modules/spring-1.0.2.zip
~ [--------------------------100%-------------------------] 92670.2 KiB/s    
~ Unzipping...
~
~ Module spring-1.0.2 is installed!
~ You can now use it by adding it to the dependencies.yml file:
~
~ require:
~     play -> spring 1.0.2

するとPlay!のフォルダ配下のmodulesにspring-1.0.2が入ります。
そこで、気になるのがSpringのバージョンです。
playルート/modules/spring-1.0.2/lib/META-INF/MANIFEST.MFで中のjarのバージョンを確認してみます。

   :
   :
Spring-Version: 2.5.5
Implementation-Title: Spring Framework
Implementation-Version: 2.5.5
Tool: Bnd-0.0.208
Bundle-Name: spring-core
Created-By: 1.6.0_06 (Sun Microsystems Inc.)
   :
   :

どうやら、Springは2.5系統が組み込まれているようです。しかし、最新のSpringは3ですね。どうせなら、3にバージョンアップしてしまいましょう。
やり方は簡単で、playルート/modules/spring-1.0.2/lib/配下のSpring関連のjarを最新のSpringのjarに入れ替えればよいです。
このlibフォルダにはplay実行時にクラスパスが張られるため、jarのファイル名等は気にしなくて問題ありません。

spring-beans.jar
spring-context.jar
spring-core.jar

元々入っていた上記のjarを以下に置き換えました。

aopalliance-1.0.jar
asm-3.1.jar
aspectjweaver.jar
org.springframework.aop-3.0.4.RELEASE.jar
org.springframework.asm-3.0.4.RELEASE.jar
org.springframework.aspects-3.0.4.RELEASE.jar
org.springframework.beans-3.0.4.RELEASE.jar
org.springframework.context-3.0.4.RELEASE.jar
org.springframework.context.support-3.0.4.RELEASE.jar
org.springframework.core-3.0.4.RELEASE.jar
org.springframework.expression-3.0.4.RELEASE.jar
org.springframework.instrument-3.0.4.RELEASE.jar
org.springframework.instrument.tomcat-3.0.4.RELEASE.jar
org.springframework.jdbc-3.0.4.RELEASE.jar
org.springframework.jms-3.0.4.RELEASE.jar
org.springframework.orm-3.0.4.RELEASE.jar
org.springframework.oxm-3.0.4.RELEASE.jar
org.springframework.test-3.0.4.RELEASE.jar
org.springframework.transaction-3.0.4.RELEASE.jar
org.springframework.web-3.0.4.RELEASE.jar
org.springframework.web.portlet-3.0.4.RELEASE.jar
org.springframework.web.servlet-3.0.4.RELEASE.jar
org.springframework.web.struts-3.0.4.RELEASE.jar

Springのリビジョンがやや古いのは気にしないで下さい。手元にあった一式がこれだったので。
これで、晴れてSpring3.xの機能が使えるようになります。

ControllerにBeanをインジェクション

では、試しに何か適当に実行してみましょう。
確認としてApplicationクラス(Controller)に対して、Twitterに接続するためのクラスTwitterAccessor(実装はTwitterAccessorImpl)をインジェクションしてみます。
@Injectアノテーションをつけることで、application-context.xmlに定義したbeanが自動的にインジェクションされます。

Applicationクラスは以下の通り。

public class Application extends Controller {

	@Inject
	static TwitterAccessor twitterAccessor;

	public static void tweet(String userId, String message) {
		twitterAccessor.tweet(userId, message);
		renderJSON("success");
	}
}

application-context.xml

	<bean id="twitterAccessor" class="models.TwitterAccessorImpl"
		scope="singleton">
	</bean>

TwitterAccessorImpl.java

public class TwitterAccessorImpl implements TwitterAccessor {
	public void tweet(String twitterId, String message) {
		System.out.println("tweet!");
	}
}

実行結果は以下になります。

tweet!

正しくApplicationクラスにTwitterAccessorImplがインジェクションされていることがわかります。

SpringのAOPを動作させる

インジェクションが実現出来るとSpring使い的に次ぎにやりたくなるのがAOPです。そこで、AOP確認用に以下のクラスを用意します。単純にメソッドの実行の前後にログを出力するだけのインターセプターです。

public class LoggingInterceptor implements MethodInterceptor {
	public Object invoke(MethodInvocation invocation) throws Throwable {
		Logger log = Logger.getLogger(invocation.getMethod().getName());
		log.debug(">>>>>proccess_start");

		Object ret = null;
		try {
			ret = invocation.proceed();
		} catch (Exception e) {
			log.error(">>>>>proccess_exception");
			throw e;
		} finally {
			log.debug(">>>>>proccess_finished");
		}

		return ret;
	}
}

application-context.xmlには以下を追記します。TwitterAccessorImplの何らかのメソッドがコールされるタイミングでAOPによるLoggingInterceptorを差し込みます。

	<bean id="logging" class="aop.LoggingInterceptor" />
	<aop:config>
		<aop:advisor
			pointcut="execution(* models.TwitterAccessorImpl.*(..))"
			advice-ref="logging" />
	</aop:config>

実行結果は以下です。

tweet!

実は、@InjectではAOPによるProxyクラスを経由したオブジェクトがインジェクションされるのではなく、そのままのインジェクションになります。そのため、@Injectでは、AOPは効きません。

そこで別の方法でBeanを取得してみます。Play!のSpringモジュールにはSpringクラスというものがあります。

public class Application extends Controller {
                             :
                             :
	public static void tweetWithAOP(String userId, String message) {
		TwitterAccessor ta = (TwitterAccessor) Spring.getBean("twitterAccessor");
		ta.tweet(userId, message);
		renderJSON(result);
	}
}

実行結果は以下です。これでもダメです。

tweet!

しょうがないので、Play!のSpringモジュール内のクラス経由でApplicationContextにアクセスするのではなく、純粋にApplicationContextをインスタンス化して、そこから取り出すことにしました。これなら確実に出来るはず。

public class Application extends Controller {
                             :
                             :
	public static void tweetWithPureSpringAOP(String userId, String message) {
		ApplicationContext ac = new FileSystemXmlApplicationContext("/"
				+ Play.applicationPath + "/conf/application-context.xml");
		TwitterAccessor ta = (TwitterAccessor) ac.getBean("twitterAccessor");
		ta.tweet(userId, message);
	}
}

実行結果は以下になります。想定通りAOPによるログ出力処理が実行出来ました。

2011-12-23 04:12:28,740 DEBUG [play-thread-1](LoggingInterceptor:invoke) >>>>>proccess_start
tweet!
2011-12-23 04:12:28,740 DEBUG [play-thread-1](LoggingInterceptor:invoke) >>>>>proccess_finished

@InjectでSpringのAOPを動作させる(未動作確認)

@InjectでAOPをかけることが出来ないか調べてみました。実際に実行して試してはいないのですが、多分いけると思うのでメモとして残しておきます。

SpringモジュールにはSpringPluginというクラスがあります。PlayPluginはモジュールを作成する際に継承するクラスで、onApplicationStartメソッド等のイベントメソッドがきられていて、アプリケーションの起動時、終了時等様々な契機で処理を実行できます。SpringPluginではアプリケーション起動時の最後にInjector.inject(this);という処理をコールしています。

public class SpringPlugin extends PlayPlugin implements BeanSource {
       :
       :
    @Override
    public void onApplicationStart() {
        URL url = Play.classloader.getResource(Play.id + ".application-context.xml");
        if (url == null) {
            url = Play.classloader.getResource("application-context.xml");
        }
        if (url != null) {
            InputStream is = null;
            try {
                Logger.debug("Starting Spring application context");
                applicationContext = new GenericApplicationContext();
                applicationContext.setClassLoader(Play.classloader);
                XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(applicationContext);
                if (Play.configuration.getProperty(PLAY_SPRING_NAMESPACE_AWARE,
                                                   "false").equals("true")) {
                    xmlReader.setNamespaceAware(true);
                }
                xmlReader.setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE);

                if (Play.configuration.getProperty(PLAY_SPRING_ADD_PLAY_PROPERTIES,
                                                   "true").equals("true")) {
                    Logger.debug("Adding PropertyPlaceholderConfigurer with Play properties");
                    PropertyPlaceholderConfigurer configurer = new PropertyPlaceholderConfigurer();
                    configurer.setProperties(Play.configuration);
                    applicationContext.addBeanFactoryPostProcessor(configurer);
                } else {
                    Logger.debug("PropertyPlaceholderConfigurer with Play properties NOT added");
                }
                //
                //	Check for component scan 
                //
                boolean doComponentScan = Play.configuration.getProperty(PLAY_SPRING_COMPONENT_SCAN_FLAG, "false").equals("true");
                Logger.debug("Spring configuration do component scan: " + doComponentScan);
                if (doComponentScan) {
                    ClassPathBeanDefinitionScanner scanner = new PlayClassPathBeanDefinitionScanner(applicationContext);
                    String scanBasePackage = Play.configuration.getProperty(PLAY_SPRING_COMPONENT_SCAN_BASE_PACKAGES, "");
                    Logger.debug("Base package for scan: " + scanBasePackage);
                    Logger.debug("Scanning...");
                    scanner.scan(scanBasePackage.split(","));
                    Logger.debug("... component scanning complete");
                }

                is = url.openStream();
                xmlReader.loadBeanDefinitions(new InputSource(is));
                ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
                Thread.currentThread().setContextClassLoader(Play.classloader);
                try {
                    applicationContext.refresh();
                    startDate = System.currentTimeMillis();
                } catch (BeanCreationException e) {
                    Throwable ex = e.getCause();
                    if (ex instanceof PlayException) {
                        throw (PlayException) ex;
                    } else {
                        throw e;
                    }
                } finally {
                    Thread.currentThread().setContextClassLoader(originalClassLoader);
                }
            } catch (IOException e) {
                Logger.error(e, "Can't load spring config file");
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        Logger.error(e, "Can't close spring config file stream");
                    }
                }
            }
        }
        Injector.inject(this);
    }

    public <T> T getBeanOfType(Class<T> clazz) {
        Map<String, T> beans = applicationContext.getBeansOfType(clazz);
        if (beans.size() == 0) {
            return null;
        }
        return beans.values().iterator().next();
    }
}

Injectorは以下になります。やっていることは各フィールドをリフレクションでアノテーションを取得し、Injectアノテーションの場合は、SpringPluginのgetBeanOfType()をコールするだけです。

public class Injector {
    /**
     * For now, inject beans in controllers
     */
    public static void inject(BeanSource source) {
        List<Class> classes = Play.classloader.getAssignableClasses(ControllerSupport.class);
        classes.addAll(Play.classloader.getAssignableClasses(Mailer.class));
        classes.addAll(Play.classloader.getAssignableClasses(Job.class));
        for(Class<?> clazz : classes) {
            for(Field field : clazz.getDeclaredFields()) {
                if(Modifier.isStatic(field.getModifiers()) && field.isAnnotationPresent(Inject.class)) {
                    Class<?> type = field.getType();
                    field.setAccessible(true);
                    try {
                        field.set(null, source.getBeanOfType(type));
                    } catch(RuntimeException e) {
                        throw e;
                    } catch(Exception e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
    }
}

つまり、SpringPluginのgetBeanOfTypeメソッドをオーバーライドして型ベースではなくBeanIdをもとにgetBeanするように修正すれば、@InjectでAOPを効かせることも可能だと思われます。(未検証ですみません><)

Play! + Spring + MyBatis連携

Spring3が動くようになったついでに、MyBatisも組み込んでみようと思い試してみました。
MybatisジェネレータでデータベースからORMapperを自動生成して、Spring-Mybatis連携モジュールを使って、正常に動作しました。
Play!でSpring3が動けばあとは単純にSpringとMyBatisの連携をするだけなので、従来通りのやり方で可能でした。
MyBatis-Spring連携の説明

さいごに

まとめると、
・Play!でもSpringが最新バージョンで動く
・@InjectそのままではAOPは効かないけど、やりようによってはAOPもかけれる
・MyBatisも使えるよ

次は@hina0118さんです。よろしくお願いします!