2011年11月28日月曜日

lime-mvcを使ってみた

久々にWebアプリを作る機会があったのでlime-mvcを使ってみた。
今のところ(2011/11/28現在)あまり知名度がなく、日本語の記事など一切存在していないので
今後の参考にメモ。
lime-mvc - http://code.google.com/p/lime-mvc/

lime-mvcとは

Google Guiceを拡張して作られたMVCパターンのフレームワーク。

セットアップ

lime-mvcはMavenリポジトリから利用可能になっているのでpom.xmlに下記を追加するだけ。
  1. <dependency>  
  2.   <groupId>org.zdevra</groupId>  
  3.   <artifactId>lime-velocity</artifactId>  
  4.   <version>0.2.0.rc2</version>  
  5. </dependency>  
  6. <dependency>  
  7.   <groupId>javax.servlet</groupId>  
  8.   <artifactId>javax.servlet-api</artifactId>  
  9.   <version>3.0.1</version>  
  10.   <scope>provided</scope>  
  11. </dependency>  
  12. <!-- ViewとしてJSPを使う場合は必要 -->  
  13. <!-- Velocity等を使用する場合は不要 -->  
  14. <dependency>  
  15.   <groupId>javax.servlet</groupId>  
  16.   <artifactId>jstl</artifactId>  
  17.   <version>1.2</version>  
  18.   <scope>provided</scope>  
  19. </dependency>  

lime-mvcを使用する場合、MvcModuleのconfigureControllersをオーバーライドして
URLパターンとコントローラーのマッピングを行う。
これはアプリケーション起動時に呼ぶ必要があるため、GuiceServletContextListenerを継承して
デプロイメントディスクリプタ(web.xml)にリスナーとして登録する必要がある。
  1. public class WebAppContextListener extends GuiceServletContextListener {  
  2.   
  3.     @Override  
  4.     protected Injector getInjector() {  
  5.         return Guice.createInjector(new MvcModule() {  
  6.             @Override  
  7.             protected void configureControllers() {  
  8.                 // URLパターンとコントローラーのマッピングを行う  
  9.                 control("/samples/*").withController(WebAppController.class);  
  10.             }  
  11.         });  
  12.     }  
  13. }  

Guiceは上記リスナーでマッピングしたデータをGuiceFilterでキャッチしてDispatchするので
ここではすべてのリクエストに対してGuiceFilterを通す設定をweb.xmlに記述する。
  1. <filter>  
  2.   <filter-name>guiceFilter</filter-name>  
  3.   <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>  
  4. </filter>  
  5.   
  6. <filter-mapping>  
  7.   <filter-name>guiceFilter</filter-name>  
  8.   <url-pattern>/*</url-pattern>  
  9. </filter-mapping>  
  10.   
  11. <listener>  
  12.   <listener-class>jp.u1aryz.products.samples.lime.listener.WebAppContextListener  
  13.   </listener-class>  
  14. </listener>  

/helloworld/(.*)というパスに対してリクエストがあった場合にdoActionメソッドを呼び出し
main.jspに転送する場合のコントローラーは下記の通りとなる。
メソッドの戻り値をデータとしてビューに渡すことが出来る。
  1. @Controller  
  2. public class WebAppController {  
  3.   
  4.     @Path("/helloworld/(.*)")  
  5.     @ModelName("msg")  
  6.     @ToView("main.jsp")  
  7.     public String doAction(@UriParameter(1) String name) {  
  8.         return "Hello World " + name + "!";  
  9.     }  
  10. }  

coreタグライブラリでModelNameアノテーションより指定された変数名で出力することにより、
JSPで表示することが出来る。
  1. <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>  
  2. <html>  
  3. <head>  
  4. </head>  
  5. <body>  
  6. <c:out value="${msg}" />  
  7. </body>  
  8. </html>  

コンテキストパスが"/"の場合はhttp://localhost:8080/samples/helloworld/hogeでアクセスすれば
下記のように出力されるはず。
Hello World hoge!

ほかにもlime-mvcはビューとしてJSilverやVelocity、Freemarkerを使えるので
Velocity使いとしてはありがたや〜。

2011年11月20日日曜日

いつからかEclipse上でAndroidプロジェクトのMavenビルドが出来なくなったので…

久々にMavenを使用してAndroidアプリを作成しようと思ったらなぜかビルドが出来ない。。
ADTやらSDKを更新したタイミングで使えなくなったのだろうと思い、いろいろ思考錯誤してみた。
そしてようやくビルドが出来る環境を作成する手順が確立出来たので忘れずメモ。

ちなみに私の環境は以下の通り。
Mac OS X 10.6.8
ADT 15 & SDK15
Maven 3.0.3
Eclipse Indigo

m2eのインストール

[Help] -> [Install New Software...]
プルダウンからIndigoのアップデートサイトを選択しCollaborationを展開する。
「Maven Integration for Eclipse」と「slf4j over logback loggind」にチェックし、-> [Next]
あとは指示通り進んでインストール完了後Eclipseを再起動。

m2e-androidのインストール

[Help] -> [Eclipse Marketplace...]
「m2e-android」と検索すると「Android Configuration for M2E」がヒットするので
Installボタンをクリックし指示通り進んでインストール完了後Eclipseを再起動。

Archetypeの追加

[New] -> [Project...] -> [Maven Project]
Workspace locationに任意の場所を指定 -> [Next] -> [Add Archetype...]
下記のような画面になるので各項目を入力 -> [OK]
Archetype Group Id: de.akquinet.android.archetypes
Archetype Artifact Id : android-quickstart
Archetype Version: 1.0.6
Repository URL: 空白
上記で追加したandroid-quickstartを選択しAndroidプロジェクトを作成する。

m2e connectorのインストール

Androidプロジェクトを作成すると、下記画面のようにpom.xmlにエラーマークがつくので
POMエディターで開く。
pom.xmlを開くと上記に赤くメッセージが表示されるのでその箇所をクリック。
下記のような黄色いウィンドウが表示されるので「Discover new m2e connectors」をクリック。
m2e Marketplaceなるものが開くので「Application」と「Maven」にチェックをし、
「Lifecycle Mappings」と「embedded maven runtimes」をインストールしEclipseを再起動。

pom.xmlの修正

<artifactId>maven-android-plugin</artifactId>
<version>2.8.4</version>
↓
<artifactId>android-maven-plugin</artifactId>
<version>3.0.0-alpha-14</version>
以上でEclipse上でAndroidプロジェクトのMavenビルドが出来るようになるはず。

ちなみにpom.xmlの全体はこんな感じ。
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
  4.   <modelVersion>4.0.0</modelVersion>  
  5.   <groupId>jp.u1aryz.products.hoge</groupId>  
  6.   <artifactId>HogeSample</artifactId>  
  7.   <version>0.0.1-SNAPSHOT</version>  
  8.   <packaging>apk</packaging>  
  9.   <name>HogeSample</name>  
  10.   
  11.   <dependencies>  
  12.     <dependency>  
  13.       <groupId>com.google.android</groupId>  
  14.       <artifactId>android</artifactId>  
  15.       <version>2.1.2</version>  
  16.       <scope>provided</scope>  
  17.     </dependency>  
  18.   </dependencies>  
  19.   
  20.   <build>  
  21.     <finalName>${project.artifactId}</finalName>  
  22.     <sourceDirectory>src/main/java</sourceDirectory>  
  23.     <plugins>  
  24.       <plugin>  
  25.         <groupId>com.jayway.maven.plugins.android.generation2</groupId>  
  26.         <artifactId>android-maven-plugin</artifactId>  
  27.         <version>3.0.0-alpha-14</version>  
  28.         <configuration>  
  29.           <sdk>  
  30.             <!-- SDKのパスはsettings.xmlで定義していれば不要 -->  
  31.             <path>"your ANDROID_HOME"</path>  
  32.             <platform>7</platform>  
  33.           </sdk>  
  34.           <manifest>  
  35.             <debuggable>true</debuggable>  
  36.           </manifest>  
  37.         </configuration>  
  38.         <extensions>true</extensions>  
  39.       </plugin>  
  40.       <plugin>  
  41.         <artifactId>maven-compiler-plugin</artifactId>  
  42.         <version>2.3.2</version>  
  43.         <configuration>  
  44.           <source>1.6</source>  
  45.           <target>1.6</target>  
  46.         </configuration>  
  47.       </plugin>  
  48.     </plugins>  
  49.   </build>  
  50. </project>  

2011年11月18日金曜日

RoboGuiceでAndroidアプリのDI開発

今更ながらRoboGuiceを使ってみたので忘れずメモ。
RoboGuiceについて簡単に触れておくとGoogle GuiceベースのAndroid用のDIコンテナである。
roboguice - Project Hosting on Google Code

細かいViewの制御は抜きにして以下のようなアプリを例としてRoboGuiceを使用して作成してみる。
  • トップ画面より入力された名前を次の画面で文字列を付け足して表示する。




  • まず前エントリーを参考にMavenプロジェクトからAndroidプロジェクトを作成。
    pom.xmlを追記
    1. <dependency>  
    2.   <groupId>org.roboguice</groupId>  
    3.   <artifactId>roboguice</artifactId>  
    4.   <version>1.1.2</version>  
    5. </dependency>  

    TopActivity
    1. public class TopActivity extends RoboActivity {  
    2.   
    3.     @InjectResource(R.string.message)  
    4.     String message;  
    5.   
    6.     @InjectView(R.id.txt_msg)  
    7.     TextView mTextView;  
    8.   
    9.     @InjectView(R.id.edt_name)  
    10.     EditText mEditText;  
    11.   
    12.     @InjectView(R.id.btn_decision)  
    13.     Button mButton;  
    14.   
    15.     @Override  
    16.     protected void onCreate(Bundle savedInstanceState) {  
    17.         super.onCreate(savedInstanceState);  
    18.   
    19. //        mTextView.setText(message); // ここでViewにアクセスするとエラー  
    20.         setContentView(R.layout.top); // ここでViewがInjectされる  
    21.         mTextView.setText(message);  
    22.         mButton.setOnClickListener(new OnClickListener() {  
    23.   
    24.             public void onClick(View v) {  
    25.                 Intent intent = new Intent(TopActivity.this, HelloActivity.class);  
    26.                 intent.putExtra("name", mEditText.getText().toString());  
    27.                 startActivity(intent);  
    28.             }  
    29.         });  
    30.     }  
    31.   
    32. }  
    RoboActivityを継承してアクティビティを作成する。※1.1からGuiceActivityからRoboActivityに変更された
    ListActivityの場合はRoboListActivity、TabActivityの場合はRoboTabActivityなどそれぞれ対応したもの
    が存在する。
    ソースを見るとわかる通り、@InjectView(resouceId)でViewをInjectしてくれる。
    リソースを参照したい場合は@InjectResource(resourceId)を使用すればいい。
    他にもこんなことが可能である。
    Drawable icon = getResources().getDrawable(R.drawable.icon);
    ↓
    @InjectResource(R.drawable.icon)
    Drawable icon;
    
    LocationManager loc = (LocationManager) getSystemService(Activity.LOCATION_SERVICE);
    ↓
    @Inject
    LocationManager loc;
    

    HelloActivityを実装する前にインターフェースと実装クラスを使用して
    少しDIっぽい処理を入れてみる。
    RoboSampleService
    1. public interface RoboSampleService {  
    2.   
    3.     public String hello(String name);  
    4. }  

    RoboSampleServiceImpl
    1. public class RoboSampleServiceImpl implements RoboSampleService {  
    2.   
    3.     public String hello(String name) {  
    4.         return "Hello " + name;  
    5.     }  
    6.   
    7. }  

    続いて上記サービスをバインド
    MyApplication
    1. public class MyApplication extends RoboApplication {  
    2.   
    3.     @Override  
    4.     protected void addApplicationModules(List<Module> modules) {  
    5.         modules.add(new MyModule());  
    6.     }  
    7.   
    8.     static class MyModule extends AbstractAndroidModule {  
    9.   
    10.         @Override  
    11.         protected void configure() {  
    12.             // RoboSampleServiceのInject要求に対してRoboSampleServiceImplを返すようバインドする  
    13.             bind(RoboSampleService.class).to(RoboSampleServiceImpl.class);  
    14.         }  
    15.   
    16.     }  
    17. }  
    ※こちらもGuiceApplicationからRoboApplicationに変更されているので注意

    アプリケーションのエントリポイントとして上記クラスを呼び出す必要があるので
    AndroidManifest.xmlに以下を追加
    <application...
        android:name=".MyApplication"
        ...>
    

    最後にHelloActivityの実装
    HelloActivity
    1. public class HelloActivity extends RoboActivity {  
    2.   
    3.     @InjectExtra("name")  
    4.     String name;  
    5.   
    6.     @InjectView(R.id.hello_msg)  
    7.     TextView textView;  
    8.   
    9.     @Inject  
    10.     RoboSampleService service;  
    11.   
    12.     @Override  
    13.     protected void onCreate(Bundle savedInstanceState) {  
    14.         super.onCreate(savedInstanceState);  
    15.         setContentView(R.layout.hello);  
    16.         textView.setText(service.hello(name));  
    17.     }  
    18.   
    19. }  

    @InjectExtra("name")でTopActivityでputExtraした値が入る。
    また、RoboSampleServiceに@Injectアノテーションをつけることで上記でバインドした
    RoboSampleServiceImplをInjectしてくれるのでインスタンスを生成せず使用することが出来る。

    続いてDIの長所を活かしてHelloActivityのテストを書いてみる。
    テストプロジェクトを作成する前にテスト対象のプロジェクトのクラスパスをエクスポート。

    通常通りAndroidテストプロジェクトを作成する。
    今回作成したサンプルプログラムのhelloメソッドは静的な文字列を付加するだけの
    シンプルな作りであるが、実際は動的であったり、バグが混入していたり、
    決まっていなかったりするので依存するクラスの振る舞いを固定化するモックを作成する。

    MockServiceImpl
    1. public class MockServiceImpl implements RoboSampleService {  
    2.   
    3.     @Override  
    4.     public String hello(String name) {  
    5.         return "test";  
    6.     }  
    7.   
    8. }  

    続いてテストコードの実装
    HelloActivityTest
    1. public class HelloActivityTest extends RoboActivityUnitTestCase<HelloActivity> {  
    2.   
    3.     private Context mContext;  
    4.   
    5.     public HelloActivityTest() {  
    6.         super(HelloActivity.class);  
    7.     }  
    8.   
    9.     class MockApplication extends RoboApplication {  
    10.   
    11.         public MockApplication(Context context) {  
    12.             super();  
    13.             attachBaseContext(context);  
    14.         }  
    15.   
    16.         @Override  
    17.         protected void addApplicationModules(List<Module> modules) {  
    18.             modules.add(new MockModule());  
    19.         }  
    20.   
    21.     }  
    22.   
    23.     class MockModule extends AbstractAndroidModule {  
    24.   
    25.         @Override  
    26.         protected void configure() {  
    27.             // RoboSampleServiceのInject要求に対してMockServiceImplを返すようバインドする  
    28.             bind(RoboSampleService.class).to(MockServiceImpl.class);  
    29.         }  
    30.   
    31.     }  
    32.   
    33.     @Override  
    34.     protected void setUp() throws Exception {  
    35.         super.setUp();  
    36.         mContext = getInstrumentation().getContext();  
    37.         setApplication(new MockApplication(mContext));  
    38.     }  
    39.   
    40.     @MediumTest  
    41.     public void testShouldBeHelloMsg() {  
    42.         Intent intent = new Intent(mContext, HelloActivity.class);  
    43.         intent.putExtra("name""name");  
    44.         HelloActivity a = startActivity(intent, nullnull);  
    45.         assertNotNull(a);  
    46.   
    47.         // Mockで返す文字列を"test"にしているため  
    48.         assertEquals(((TextView)a.findViewById(R.id.hello_msg)).getText(), "test");  
    49.     }  
    50. }  

    RoboActivityUnitTestCase<対象アクティビティ>を継承してテストコードを作成する。
    RoboSampleServiceのInject要求に対してモックを返すようにバインドさせ、
    setApplicationでセットすることで依存したオブジェクトの振る舞いを固定化させることが出来る。

    Run As -> Android JUnit Testで...
    これで一通り完了。案外使いやすいかも?