【Java】Java で Google Calendar API を使う

■ はじめに

https://developers.google.com/calendar/quickstart/java
を参考にすればできた

■ 前提条件

 * Googleアカウントを作成しておく
https://accounts.google.com/SignUp

■ 手順

Step 1: Turn on the Google Calendar API (Google Calendar APIを有効にする)
Step 2: Prepare the project (プロジェクトを準備する)
Step 3: Set up the sample (サンプルの設定する)
Step 4: Run the sample (サンプルを実行する)

Step 1: Google Calendar APIを有効にする

 * 以下のサイトからアクセスする
https://console.developers.google.com/flows/enableapi?apiid=calendar
 * 認証情報「client_secret_<your_client_id>.json」をダウンロード
  => 「client_secret.json」にリネームしておく

Step 2: プロジェクトを準備する

 * 以下の「■ プロジェクトの設定」を参照

Step 3: サンプルの設定する

 * 以下の「■ サンプル」を参照

Step 4: サンプルを実行する

 * Eclipseとかで実行

■ プロジェクトの設定

ポイント

【1】 EclipseでGradleプロジェクトを選択
【2】 build.gradleを修正(以下の「build.gradle」参照)
【3】「src/main/resources」に「client_secret.json」を置く

build.gradle

// Apply the java-library plugin to add support for Java Library
apply plugin: 'java-library'
apply plugin: 'application'

repositories {
    mavenCentral()
}

dependencies {
    compile 'com.google.api-client:google-api-client:1.23.0'
    compile 'com.google.oauth-client:google-oauth-client-jetty:1.23.0'
    compile 'com.google.apis:google-api-services-calendar:v3-rev305-1.23.0'
}

■ サンプル

CalendarQuickstart.java

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.DateTime;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.calendar.Calendar;
import com.google.api.services.calendar.CalendarScopes;
import com.google.api.services.calendar.model.Event;
import com.google.api.services.calendar.model.Events;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;

public class CalendarQuickstart {
  private static final String APPLICATION_NAME = "Google Calendar API Java Quickstart";
  private static final JsonFactory JSON_FACTORY = JacksonFactory
      .getDefaultInstance();
  private static final String CREDENTIALS_FOLDER = "credentials";

  /**
   * Global instance of the scopes required by this quickstart. If modifying
   * these scopes, delete your previously saved credentials/ folder.
   */
  private static final List<String> SCOPES = Collections
      .singletonList(CalendarScopes.CALENDAR_READONLY);
  private static final String CLIENT_SECRET_DIR = "client_secret.json";

  /**
   * Creates an authorized Credential object.
   * 
   * @param HTTP_TRANSPORT
   *          The network HTTP Transport.
   * @return An authorized Credential object.
   * @throws IOException
   *           If there is no client_secret.
   */
  private static Credential getCredentials(
      final NetHttpTransport HTTP_TRANSPORT) throws IOException {
    // Load client secrets.
    URL url = ClassLoader.getSystemResource(CLIENT_SECRET_DIR);
    URI uri = URI.create(url.toString());
    Path path = Paths.get(uri);
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
        new InputStreamReader(new FileInputStream(path.toString())));

    // Build flow and trigger user authorization request.
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
        HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(
                new FileDataStoreFactory(new java.io.File(CREDENTIALS_FOLDER)))
            .setAccessType("offline").build();
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver())
        .authorize("user");
  }

  public static void main(String... args)
      throws IOException, GeneralSecurityException {
    // Build a new authorized API client service.
    final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport
        .newTrustedTransport();
    Calendar service = new Calendar.Builder(HTTP_TRANSPORT, JSON_FACTORY,
        getCredentials(HTTP_TRANSPORT)).setApplicationName(APPLICATION_NAME)
            .build();

    // List the next 10 events from the primary calendar.
    DateTime now = new DateTime(System.currentTimeMillis());
    Events events = service.events().list("primary").setMaxResults(10)
        .setTimeMin(now).setOrderBy("startTime").setSingleEvents(true)
        .execute();
    List<Event> items = events.getItems();
    if (items.isEmpty()) {
      System.out.println("No upcoming events found.");
    } else {
      System.out.println("Upcoming events");
      for (Event event : items) {
        DateTime start = event.getStart().getDateTime();
        if (start == null) {
          start = event.getStart().getDate();
        }
        System.out.printf("%s (%s)\n", event.getSummary(), start);
      }
    }
  }
}


関連記事

JavaGoogle/Outlook Calendar の iCal形式のURLからデータを取得する

https://blogs.yahoo.co.jp/dk521123/37536957.html

Java】iCalendar ライブラリ ~ biweekly ~

https://blogs.yahoo.co.jp/dk521123/37532480.html