2011年6月3日金曜日

Evernoteにアクセスする その3 サンプルをシンプル編


サンプルはJSPでOAuthを分かりやすく記述していますが
手数が多く記述してあるので、実装としてはわかりずらいので
一旦整理してみましょう。

Google for Eclipse Plugin[更新サイト:http://dl.google.com/eclipse/plugin/3.6] と
Slim3 Plugin[更新サイト:http://slim3.googlecode.com/svn/updates/]をインストールします。

Slim3はGoogleAppEngineに最適化されたMVCフレームワークです。
非常に簡単なので説明は省きます。

indexを作成して

  1.         SimpleOAuthRequest oauthRequestor =  
  2.             new SimpleOAuthRequest(requestTokenUrl,consumerKey,consumerSecret,null);  
  3.   
  4.         //現在のURLからコールバックURLを作成  
  5.         String thisUrl = request.getRequestURL().toString();  
  6.         String cbUrl = thisUrl.substring(0, thisUrl.lastIndexOf('/') + 1);  
  7.         cbUrl = cbUrl + "callback";  
  8.   
  9.         oauthRequestor.setParameter("oauth_callback", cbUrl);  
  10.         Map<string, string=""> reply = oauthRequestor.sendRequest();  
  11.   
  12.         String requestToken = reply.get("oauth_token");  
  13.         String authorizationUrl = authorizationUrlBase + "?oauth_token=" + requestToken;  
  14.   
  15.         //認証にリダイレクトを行う  
  16.         return redirect(authorizationUrl);  
  17. </string,>  


設定値などはコールバックURL以外はそのままです。
SimpleOAuthRequestを利用して認証用のURLを作成してそのままリダイレクトをかけてます。
※もちろんログインボタンとか作りたいなら別ですけど。

これにより/indexにアクセスするとEvernoteの認可画面が表示されるはずです。
それではコールバックURLを指定してみましょう。
callbackを作成して

  1.  SimpleOAuthRequest oauthRequestor = new SimpleOAuthRequest( requestTokenUrl, consumerKey, consumerSecret, null);  
  2.   
  3.  String requestToken = requestScope("oauth_token");  
  4.  String verifier     = requestScope("oauth_verifier");  
  5.  oauthRequestor.setParameter( "oauth_token", requestToken);  
  6.  oauthRequestor.setParameter( "oauth_verifier", verifier);  
  7.   
  8.  Map<string, string=""> reply = oauthRequestor.sendRequest();  
  9.   
  10.  String accessToken = reply.get("oauth_token");   
  11.  String shardId     = reply.get("edam_shard");  
  12.  String noteStoreUrl = noteStoreUrlBase + shardId;  
  13.   
  14. THttpClient noteStoreTrans    = new THttpClient(noteStoreUrl);  
  15. TBinaryProtocol noteStoreProt = new TBinaryProtocol(noteStoreTrans);  
  16. NoteStore.Client noteStore =  
  17.   new NoteStore.Client(noteStoreProt, noteStoreProt);  
  18.   
  19. List<notebook> notebooks = noteStore.listNotebooks(accessToken);  
  20. for (Notebook notebook : notebooks) {  
  21.   logger.info("Notebook: " + notebook.getName());  
  22. }  
  23. ook></string,>  


これもサンプルと同じ実装ですね。
もちろん認証してなかったら~とかの処理は必要ですが、
何やっているかを分かりやすくするため、2つのURLだけで実装してみました。

ListのところはNotebookを返してたので?じゃなくしました。
THttpClient はライブラリに存在するthriftのAPIですね。
それらを利用してEvernoteのAPIを利用するイメージです。

SimpleOAuthRequestの実装を説明しないと何やってるかわかりずらいですね。
次回はSimpleOAuthRequestについて記述してみましょう。

0 件のコメント: