GoogleCalenderDataAPIの使い方。その1

GoogleカレンダーAPIを使ってみました。
かなり情報が少なくて参った。すんごく簡単なサンプルはあるんだけどその先がない。ちょこちょこつまづきながらもとりあえず一連の操作はできるようになった♪
これで明日ぐらいにはスケジュールボードとの同期が出来そうだ。

準備は凄く簡単でgoogle/gdata-java-client · GitHubから一式落としてきてactivation.jar,mail.jar,servlet-api.jarを適当なところから落としてきたらハイ終わり。後は自分でソース書くだけ。便利だな〜

PJとして使うなら以下の2つのJarだけでも動くはず。

  • data-calendar-1.0.jar
  • gdataclient-1.0.jar

でもソース読みながらの方が断然やりやすいのでDLしたら一色まるっとEclipseにとりこんじゃうといいよ

てなわけで今日つまづいたポイントを纏めてみる。

検索の仕方

Queryクラスだとカレンダー独自の開始時刻とかでの検索が出来ないのでCalendarQueryを使う。*1
その他EntryやFeedなどもすべてカレンダー独自のものが有るのでそれを使うと幸せになれる。

カレンダーのURL

サンプルを見ると「http://www.google.com/calendar/feeds/default/private/full」等と指定してある所が有ります。
これを自分の好きなカレンダーに変えるには、Googleカレンダーの「設定」→「カレンダー」で更新したいカレンダーの「カレンダーID」をコピペしてきて以下のようにアドレスを指定する。
http://www.google.com/calendar/feeds/「カレンダーID」/private/full

CalendarEventEntryのバージョンコンフリクト

CalendarEventEntryは内部にバージョンを保持しているようで、検索して、更新して更新する時など都度更新結果として返却されるCalendarEventEntryを更新の元ネタにしないといけない。
これに違反すると com.google.gdata.util.VersionConflictException が発生する。

時刻のパースが気に食わない

国際化に対応してるとどうしても時刻表記がみずらい。なので自分の気に入った感じにした。

今日の成果物

データを登録して、検索して、変更して、削除してます。
適当に設定して適当に動かすといいよ。
注意。登録したデータを削除してるのでWEBから確認したい時などは適当に削除のところとかをコメントアウトしてみるといいよ

package jp.co.pentasa.googlecalender;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import com.google.gdata.client.calendar.CalendarQuery;
import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.Person;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.calendar.CalendarEventEntry;
import com.google.gdata.data.calendar.CalendarEventFeed;
import com.google.gdata.data.extensions.When;
import com.google.gdata.data.extensions.Where;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;

/**
 * GoogleCalenderUtil
 * @author pentasa 2008/02/28
 * @version 1.0 pentasa 2008/02/28
 */
public class GoogleCalenderUtil {
    // Emailアドレス
    String gLoginAddr = "mailaddress";
    // パスワード
    String gLoginPass = "password";
    // 登録ユーザー名
    String appUserName = "GoogleCalenderUtil";
    // URL
    URL postUrl = new URL("http://www.google.com/calendar/feeds/default/private/full");
    // サービスクラス
    CalendarService service = null;
    // 日付ふぉーまっと
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");

    public static void main(String[] args) throws Exception {
        System.setProperty("http.proxyHost", "proxy");
        System.setProperty("http.proxyPort", "8080");
        System.setProperty("https.proxyHost", "proxy");
        System.setProperty("https.proxyPort", "8080");
        GoogleCalenderUtil gUtil = new GoogleCalenderUtil();
        gUtil.executeSamlple();
    }

    public void executeSamlple() throws Exception {
        System.out.println("GoogleCalenderUtil Sample <Start>");
        String startDate = "2008/02/29 10:00";
        String endDate = "2008/02/29 15:00";
        String title = "適当な予定";

        // スケジュールを追加する
        CalendarEventEntry insertEntry = makeCalendarEventEntry(title, startDate, endDate);
        CalendarEventEntry insertedEntry = getCalService().insert(postUrl, insertEntry);

        // スケジュールを検索する。
        List<CalendarEventEntry> feeds = selectCalendarEventEntry(startDate, endDate, title);
        for (CalendarEventEntry entry : feeds) {
            System.out.println("Titie: " + entry.getTitle().getPlainText() + " 開始 :"
                    + entry.getTimes().get(0).getStartTime());

            // 検索結果の予定を変更
            CalendarEventEntry updatedEntry = editCalendarEventEntryTitle(entry, entry.getTitle()
                    .getPlainText() + "だね♪");

            System.out.println("Titie: " + updatedEntry.getTitle().getPlainText() + " 開始 :"
                    + updatedEntry.getTimes().get(0).getStartTime());

            // スケジュールを削除
            URL deleteURL = new URL(updatedEntry.getEditLink().getHref());
            getCalService().delete(deleteURL);
        }
        System.out.println("GoogleCalenderUtil Sample <END>");
    }

    public CalendarEventEntry editCalendarEventEntryTitle(CalendarEventEntry entry, String newTitle)
            throws MalformedURLException, IOException, ServiceException, AuthenticationException {
        URL entryUrl = new URL(entry.getSelfLink().getHref());
        CalendarEventEntry retrievedEntry = getCalService().getEntry(entryUrl,
                CalendarEventEntry.class);
        retrievedEntry.setTitle(new PlainTextConstruct(newTitle));
        URL retrievedUrl = new URL(retrievedEntry.getEditLink().getHref());
        return getCalService().update(retrievedUrl, retrievedEntry);
    }

    public List<CalendarEventEntry> selectCalendarEventEntry(String startDate, String endDate,
            String title) throws IOException, ServiceException, AuthenticationException {
        CalendarQuery calQuery = new CalendarQuery(postUrl);
        calQuery.setFullTextQuery(title);
        calQuery.setMinimumStartTime(convDateTime(startDate));
        calQuery.setMaximumStartTime(convDateTime(endDate));
        CalendarEventFeed myResultsFeed = getCalService().query(calQuery, CalendarEventFeed.class);
        List<CalendarEventEntry> feeds = myResultsFeed.getEntries();
        return feeds;
    }

    private CalendarService getCalService() throws AuthenticationException {
        if (service == null) {
            service = new CalendarService(appUserName);
            service.setUserCredentials(gLoginAddr, gLoginPass);
            System.out.println("CalendarService is created");
        }
        return service;
    }

    public CalendarEventEntry makeCalendarEventEntry(String title, String startDate, String endDate) {
        return makeCalendarEventEntry(title, startDate, endDate, "", "");
    }

    public CalendarEventEntry makeCalendarEventEntry(String title, String startDate,
            String endDate, String place, String memo) {
        CalendarEventEntry entry = new CalendarEventEntry();
        // タイトル
        entry.setTitle(new PlainTextConstruct(title));
        // 詳細情報
        entry.setContent(new PlainTextConstruct(memo));
        Person author = new Person(appUserName);
        entry.getAuthors().add(author);
        // 開始終了日時
        DateTime startTime = convDateTime(startDate);
        DateTime endTime = convDateTime(endDate);
        // 開始終了日時
        When eventTimes = new When();
        eventTimes.setStartTime(startTime);
        eventTimes.setEndTime(endTime);
        entry.addTime(eventTimes);
        // 場所
        Where evLocation = new Where();
        evLocation.setValueString(place);
        entry.addLocation(evLocation);
        return entry;
    }

    private DateTime convDateTime(String date) {
        DateTime dateTime = null;
        try {
            dateTime = new DateTime(dateFormat.parse(date));
            dateTime.setTzShift(9);
        } catch (ParseException e) {
            new Exception("日付は「2008/02/28 12:00」形式で指定してください。");
        }
        return dateTime;
    }
}

*1:これが分からず1時間ぐらいなやんだ。。