2009年2月10日火曜日

GoogleCalenderから予定を取り込んでみる

とあるシステムに「予約」機能を追加したいともくろんでいるのだが、そのシステムでは既に基本的な予約機能は実装されている。「予約時間」と「貸出先ユーザー」と「予約対象物」さえパラメーターで渡してあげればOKなのだ。
しかし、問題はこの3つのパラメータを利用者に入力してもらうためのユーザーインターフェイス部分を作らなければならないのが大変なのだ。理想としては「Googleカレンダー」のようにWebからでも予約でき、タイムチャート表示、説明書無しでも使える直感的なインターフェイス。なのだが・・・
ということで、「Googleカレンダー」に記入した予約データをJavaプログラムで読み込んでみよう!

まずは、「Google Calender API」に関する先人の苦労をパクッてみようと、ググッてみたが日本語のサイトを見つけることが出来ない。しぶしぶ、本家の「Google Calender API」ページを読むことにした。

Google Calendar APIs and Tools - API Developer's Guide: Java


対象読者
この文書は、Googleカレンダーと相互作用することができるGoogleデータAPI Javaクライアントライブラリを使って、クライアントアプリケーションを書きたいプログラマーのために意図されています。

はじめに
クライアントライブラリを設定については、"Getting Started Guide."を見てください。
Javaクライアントライブラリを使うためには,Java1.5実行環境が必要です。
クライアントライブラリをダウンロードすると、「java/lib/gdata-calendar-1.0.jar」と「java/lib/gdataclient-1.0.jar」の二つの jar ファイルが入っています。

1.クライアントライブラリの開発環境をセットアップする
   http://code.google.com/support/bin/answer.py?answer=78455

1.1 依存関係
  • JDK (Java Development Kit) version 1.5+
  • Apache Ant version 1.7+
  • mail.jar in Sun's JavaMail API 1.4+
  • activation.jar in Sun's JavaBeansActivationFramewrok.
    (This is only required for media specific APIs including Document List Data API, Picasa Web Album API, and YouTube Data API.)
  • servlet.jar in Sun's Servlet API version 2.3+.
    (This is required only if executing code samples in 'sample.authsub' or 'sample.gbase.recipe' packages.)
(本家のページにこれらの依存ファイルの入手方法がOSの種類別に解説されています。)

1.2 ’Google Data Client Library’のインストール

  1. このサイトに行け! http://code.google.com/p/gdata-java-client/downloads/list

  2. Click on the featured download.(どれをダウンロードすればよいか良くわからないが、とりあえず「gdata-samples.java-1.29.0.java.zip」をダウンロードしてみた

  3. あんたのPCに解凍しなさい.

  4. Navigate to gdata/java/build/build.properties and open the file.

  5. Edit the external dependencies to point to the locations of the .jar files on your local machine.

注意! バックスラッシュは次の例のように2個書いてね
servlet.jar=C:\\Program Files\\Apache Software Foundation\\Tomcat 6.0\\lib\\servlet-api.jar

1.3 サンプルを走らせる
「gdata/java/sample」フォルダに実行できるサンプルがあります。「gdata/java/build/build.properties」ファイルにサンプルの実行に必要なパラメータが定義されています
[sample.credentials.username] と [sample.credentials.password]に適当な値を設定しなさい。
サンプルをビルドするのに Ant を利用できますよ。

ちゃんとインストールされたかどうかテストするために、コマンドプロンプトを開いて、「gdata/java」に移動して、下記のコマンドを打ってみな:
ant sample.calendar.run
たぶん [info]やら[warning] などのわけのわからんメッセージが出るけども、最終的に[BUILD SUCCESSFUL]と表示されればOKです。成功メッセージが出なければ、 troubleshooting section 」を参照してね。

もっとインタラクティブなサンプルも試してください:
ant sample.spreadsheet.guidemo.run

どうやって特定のサンプルを動かすかを知りたければ、[gdata/java/build]ディレクトリに行き、そのサンプルについてBuildファイルをチェックしてください。
samples runセクションを捜してください。

1.4 自作アプリを作る
次の問題はどうすれば自作アプリケーションを作れるかです。カレンダーサービスを利用した "Hello, World!" みたいなプログラムを通じて基本的な機能を見てみましょう。
More detailed information can be found in the Java Client Library's developer guide, as well as the individual product developer guides.

「CalendarTest.java」というファイルを作りなさい。以下のimport文から始めてください。
import com.google.gdata.client.*;
import com.google.gdata.client.calendar.*;
import com.google.gdata.data.*;
import com.google.gdata.data.acl.*;
import com.google.gdata.data.calendar.*;
import com.google.gdata.data.extensions.*;
import com.google.gdata.util.*;

import java.net.*;
import java.io.*;

import sample.util.*;


プログラムはこれです。
public class CalendarTest {

public static void main(String[] args) throws Exception {
CalendarService myService = new CalendarService("exampleCo-exampleApp-1.0");
myService.setUserCredentials("root@gmail.com", "fortytwo");

URL feedUrl = new URL("http://www.google.com/calendar/feeds/default/allcalendars/full");
CalendarFeed resultFeed = myService.getFeed(feedUrl, CalendarFeed.class);

System.out.println("Your calendars:");
System.out.println();

for (int i = 0; i < resultFeed.getEntries().size(); i++) {
CalendarEntry entry = resultFeed.getEntries().get(i);
System.out.println("\t" + entry.getTitle().getPlainText());
}
}

}


この小さなプログラムは、あなたのカレンダーにあるすべての「予定」のタイトルを表示します。
これは本物の "Hello, World!" よりもちょっと長いけれど、冗談抜きにとてもシンプルです。

最初の2、3行はサービスオブジェクトを作成し、ユーザー認証をしています。
CalendarService myService = new CalendarService("exampleCo-exampleApp-1.0");
myService.setUserCredentials("root@gmail.com", "fortytwo");

次に、Googleカレンダー・リソースへのURLを設定します。この例では、認証を許可されたすべてのカレンダーのリストを示しています。
URL feedUrl = new URL("http://www.google.com/calendar/feeds/default/allcalendars/full");

次の行では、指定されたURLへ実際にGETコマンドを実行し、返信された結果はオブジェクトに格納されます。
CalendarFeed resultFeed = myService.getFeed(feedUrl, CalendarFeed.class);

下記のループで、カレンダーのタイトルが表示されます。
タイトルは TextConstruct として表現されます。従って、 プレーンテキストを得るためには特別なファンクションコールが必要です。
for (int i = 0; i < resultFeed.getEntries().size(); i++) {
CalendarEntry entry = resultFeed.getEntries().get(i);
System.out.println("\t" + entry.getTitle().getPlainText());
}

この例はちょっと基本的すぎましたね — もうちょっと実際的な例をやってみましょう。
以下では、オブジェクトの作成と追加の例を示しています。要するに、カレンダーに「新しい予定」を追加する例です。
URL postURL = new URL("http://www.google.com/calendar/feeds/gdata.ops.demo@gmail.com/private/full");
CalendarEventEntry myEvent = new CalendarEventEntry();

//Set the title and description
myEvent.setTitle(new PlainTextConstruct("Pi Day Party"));
myEvent.setContent(new PlainTextConstruct("I am throwing a Pi Day Party!"));

//Create DateTime events and create a When object to hold them, then add
//the When event to the event
DateTime startTime = DateTime.parseDateTime("2007-03-14T15:00:00-08:00");
DateTime endTime = DateTime.parseDateTime("2007-03-14T17:00:00-08:00");
When eventTimes = new When();
eventTimes.setStartTime(startTime);
eventTimes.setEndTime(endTime);
myEvent.addTime(eventTimes);

// POST the request and receive the response:
CalendarEventEntry insertedEntry = myService.insert(postURL, myEvent);

この例では、問い合わせを行います。
//Create a new query object and set the parameters
Query myQuery = new Query(feedURL);
myQuery.setFullTextQuery("Pi");

//Send the request with the built query URL
CalendarEventFeed myResultsFeed = myService.query(myQuery, CalendarEventFeed.class);

//Take the first match and print the title
if (myResultsFeed.getEntries().size() > 0) {
CalendarEventEntry firstMatchEntry = new CalendarEventEntry();
myResultsFeed.getEntries().get(0);
System.out.println(firstMatchEntry.getTitle().getPlainText());
}

While debugging, another useful operation is dumping out the raw XML. There's a handy utility that you can use to do this in the library. Make sure samples.util.* is imported. Then, dump the feed or entry.
CommonUtils.dump(resultFeed, System.out);

For even deeper debugging tools, check out this article about how to turn on logging from within the client library.

This should give you a feel for what building apps using the client library is like. For more detailed information, see the developer guides.





0 件のコメント: