java实现对Google Calendar API event 事件的添加

参考文档:

参考demo: CalendarSample.java

/*
 * Copyright (c) 2010 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.google.api.services.samples.calendar.cmdline;

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.batch.BatchRequest;
import com.google.api.client.googleapis.batch.json.JsonBatchCallback;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.googleapis.json.GoogleJsonError;
import com.google.api.client.http.HttpHeaders;
import com.google.api.client.http.HttpTransport;
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.Lists;
import com.google.api.client.util.store.DataStoreFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.calendar.CalendarScopes;
import com.google.api.services.calendar.model.Calendar;
import com.google.api.services.calendar.model.CalendarList;
import com.google.api.services.calendar.model.Event;
import com.google.api.services.calendar.model.EventDateTime;
import com.google.api.services.calendar.model.Events;

import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Collections;
import java.util.Date;
import java.util.TimeZone;

/**
 * @author Yaniv Inbar
 */
public class CalendarSample {

  /**
   * Be sure to specify the name of your application. If the application name is {@code null} or
   * blank, the application will log a warning. Suggested format is "MyCompany-ProductName/1.0".
   */
  private static final String APPLICATION_NAME = "";

  /** Directory to store user credentials. */
  private static final java.io.File DATA_STORE_DIR =
      new java.io.File(System.getProperty("user.home"), ".store/calendar_sample");

  /**
   * Global instance of the {@link DataStoreFactory}. The best practice is to make it a single
   * globally shared instance across your application.
   */
  private static FileDataStoreFactory dataStoreFactory;
 
  /** Global instance of the HTTP transport. */
  private static HttpTransport httpTransport;

  /** Global instance of the JSON factory. */
  private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();

  private static com.google.api.services.calendar.Calendar client;

  static final java.util.List<Calendar> addedCalendarsUsingBatch = Lists.newArrayList();

  /** Authorizes the installed application to access user‘s protected data. */
  private static Credential authorize() throws Exception {
    // load client secrets
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY,
        new InputStreamReader(CalendarSample.class.getResourceAsStream("/client_secrets.json")));
    if (clientSecrets.getDetails().getClientId().startsWith("Enter")
        || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
      System.out.println(
          "Enter Client ID and Secret from https://code.google.com/apis/console/?api=calendar "
          + "into calendar-cmdline-sample/src/main/resources/client_secrets.json");
      System.exit(1);
    }
    // set up authorization code flow
    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
        httpTransport, JSON_FACTORY, clientSecrets,
        Collections.singleton(CalendarScopes.CALENDAR)).setDataStoreFactory(dataStoreFactory)
        .build();
    // authorize
    return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");
  }

  public static void main(String[] args) {
    try {
      // initialize the transport
      httpTransport = GoogleNetHttpTransport.newTrustedTransport();

      // initialize the data store factory
      dataStoreFactory = new FileDataStoreFactory(DATA_STORE_DIR);

      // authorization
      Credential credential = authorize();

      // set up global Calendar instance
      client = new com.google.api.services.calendar.Calendar.Builder(
          httpTransport, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();

      // run commands
      showCalendars();
      addCalendarsUsingBatch();
      Calendar calendar = addCalendar();
      updateCalendar(calendar);
      addEvent(calendar);
      showEvents(calendar);
      deleteCalendarsUsingBatch();
      deleteCalendar(calendar);

    } catch (IOException e) {
      System.err.println(e.getMessage());
    } catch (Throwable t) {
      t.printStackTrace();
    }
    System.exit(1);
  }

  private static void showCalendars() throws IOException {
    View.header("Show Calendars");
    CalendarList feed = client.calendarList().list().execute();
    View.display(feed);
  }

  private static void addCalendarsUsingBatch() throws IOException {
    View.header("Add Calendars using Batch");
    BatchRequest batch = client.batch();

    // Create the callback.
    JsonBatchCallback<Calendar> callback = new JsonBatchCallback<Calendar>() {

      @Override
      public void onSuccess(Calendar calendar, HttpHeaders responseHeaders) {
        View.display(calendar);
        addedCalendarsUsingBatch.add(calendar);
      }

      @Override
      public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
        System.out.println("Error Message: " + e.getMessage());
      }
    };

    // Create 2 Calendar Entries to insert.
    Calendar entry1 = new Calendar().setSummary("Calendar for Testing 1");
    client.calendars().insert(entry1).queue(batch, callback);

    Calendar entry2 = new Calendar().setSummary("Calendar for Testing 2");
    client.calendars().insert(entry2).queue(batch, callback);

    batch.execute();
  }

  private static Calendar addCalendar() throws IOException {
    View.header("Add Calendar");
    Calendar entry = new Calendar();
    entry.setSummary("Calendar for Testing 3");
    Calendar result = client.calendars().insert(entry).execute();
    View.display(result);
    return result;
  }

  private static Calendar updateCalendar(Calendar calendar) throws IOException {
    View.header("Update Calendar");
    Calendar entry = new Calendar();
    entry.setSummary("Updated Calendar for Testing");
    Calendar result = client.calendars().patch(calendar.getId(), entry).execute();
    View.display(result);
    return result;
  }

  private static void addEvent(Calendar calendar) throws IOException {
    View.header("Add Event");
    Event event = newEvent();
    Event result = client.events().insert(calendar.getId(), event).execute();
    View.display(result);
  }

  private static Event newEvent() {
    Event event = new Event();
    event.setSummary("New Event");
    Date startDate = new Date();
    Date endDate = new Date(startDate.getTime() + 3600000);
    DateTime start = new DateTime(startDate, TimeZone.getTimeZone("UTC"));
    event.setStart(new EventDateTime().setDateTime(start));
    DateTime end = new DateTime(endDate, TimeZone.getTimeZone("UTC"));
    event.setEnd(new EventDateTime().setDateTime(end));
    return event;
  }

  private static void showEvents(Calendar calendar) throws IOException {
    View.header("Show Events");
    Events feed = client.events().list(calendar.getId()).execute();
    View.display(feed);
  }

  private static void deleteCalendarsUsingBatch() throws IOException {
    View.header("Delete Calendars Using Batch");
    BatchRequest batch = client.batch();
    for (Calendar calendar : addedCalendarsUsingBatch) {
      client.calendars().delete(calendar.getId()).queue(batch, new JsonBatchCallback<Void>() {

        @Override
        public void onSuccess(Void content, HttpHeaders responseHeaders) {
          System.out.println("Delete is successful!");
        }

        @Override
        public void onFailure(GoogleJsonError e, HttpHeaders responseHeaders) {
          System.out.println("Error Message: " + e.getMessage());
        }
      });
    }

    batch.execute();
  }

  private static void deleteCalendar(Calendar calendar) throws IOException {
    View.header("Delete Calendar");
    client.calendars().delete(calendar.getId()).execute();
  }
}

参考demo: View.java

/*
 * Copyright (c) 2010 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.google.api.services.samples.calendar.cmdline;

import com.google.api.services.calendar.model.Calendar;
import com.google.api.services.calendar.model.CalendarList;
import com.google.api.services.calendar.model.CalendarListEntry;
import com.google.api.services.calendar.model.Event;
import com.google.api.services.calendar.model.Events;

/**
 * @author Yaniv Inbar
 */
public class View {

  static void header(String name) {
    System.out.println();
    System.out.println("============== " + name + " ==============");
    System.out.println();
  }

  static void display(CalendarList feed) {
    if (feed.getItems() != null) {
      for (CalendarListEntry entry : feed.getItems()) {
        System.out.println();
        System.out.println("-----------------------------------------------");
        display(entry);
      }
    }
  }

  static void display(Events feed) {
    if (feed.getItems() != null) {
      for (Event entry : feed.getItems()) {
        System.out.println();
        System.out.println("-----------------------------------------------");
        display(entry);
      }
    }
  }

  static void display(CalendarListEntry entry) {
    System.out.println("ID: " + entry.getId());
    System.out.println("Summary: " + entry.getSummary());
    if (entry.getDescription() != null) {
      System.out.println("Description: " + entry.getDescription());
    }
  }

  static void display(Calendar entry) {
    System.out.println("ID: " + entry.getId());
    System.out.println("Summary: " + entry.getSummary());
    if (entry.getDescription() != null) {
      System.out.println("Description: " + entry.getDescription());
    }
  }

  static void display(Event event) {
    if (event.getStart() != null) {
      System.out.println("Start Time: " + event.getStart());
    }
    if (event.getEnd() != null) {
      System.out.println("End Time: " + event.getEnd());
    }
  }
}

地址:https://code.google.com/p/google-api-java-client/source/browse/calendar-cmdline-sample/src/main/java/com/google/api/services/samples/calendar/cmdline/?repo=samples

java实现Google Calendar API event 事件的添加:(需要的jar包在blog里)

import java.io.File;
import java.util.Collections;
import java.util.Date;
import java.util.TimeZone;

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.calendar.CalendarScopes;
import com.google.api.services.calendar.model.Event;
import com.google.api.services.calendar.model.EventDateTime;

public class TestCalendar2 {
    private static HttpTransport httpTransport;
    private static com.google.api.services.calendar.Calendar client;
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    private static Credential authorize() throws Exception{
        JsonFactory JSON_FACTORY =JacksonFactory.getDefaultInstance();
        HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
//        File file = new File(TestCalendar2.class.getResource("/eb2e54acd629.p12").getFile());
        File file = new File("G:/eb2e54acd629.p12");
        GoogleCredential credential = new GoogleCredential.Builder()
        .setTransport(httpTransport)
        .setServiceAccountId("[email protected]account.com")
        .setServiceAccountScopes(Collections.singleton(CalendarScopes.CALENDAR))
        .setJsonFactory(JSON_FACTORY).setServiceAccountPrivateKeyFromP12File(file)
        .build();
        return credential;
    }
    
    public static void main(String[] args) {
        try {
            httpTransport = GoogleNetHttpTransport.newTrustedTransport();
            Credential credential = authorize();
            credential.refreshToken();
            
            client = new com.google.api.services.calendar.Calendar.Builder(
                      httpTransport, JSON_FACTORY, credential).setApplicationName("test").build();
            com.google.api.services.calendar.model.Events events = client.events().list("primary").execute();
            //System.out.println(events.getDescription());
            try {
                Event event = new Event();
                event.setSummary("vincentlinnnnnnn");
                event.setLocation("myhomeeeeeeeeee");
                System.out.println("----------");
                Date startDate = new Date();
                Date endDate = new Date(startDate.getTime() + 3600000);
                com.google.api.client.util.DateTime start = new com.google.api.client.util.DateTime(startDate, TimeZone.getTimeZone("UTC"));
                event.setStart(new EventDateTime().setDateTime(start));
                com.google.api.client.util.DateTime end = new com.google.api.client.util.DateTime(endDate, TimeZone.getTimeZone("UTC"));
                event.setEnd(new EventDateTime().setDateTime(end));
                System.out.println("------=====");
                Event result = client.events().insert("[email protected]", event).execute();
                System.out.println(result.getId());
            } catch (Exception e) {
                e.printStackTrace();
            }
            
            com.google.api.services.calendar.model.Events showEvents = client.events().list("").execute();
            for (Event e : showEvents.getItems()) {
                System.out.println(e.getSummary());
            }
            System.out.println("======");
        } catch (Exception e) {

        }
        
    }

}

实现思路:

参考文档:

1、https://developers.google.com/google-apps/calendar/

2、https://developers.google.com/google-apps/calendar/firstapp

3、https://developers.google.com/console/help/new/

4、https://developers.google.com/accounts/docs/OAuth2#serviceaccount

5、https://developers.google.com/google-apps/calendar/downloads

时间: 2024-07-29 05:47:09

java实现对Google Calendar API event 事件的添加的相关文章

Google Map API Version3 :代码添加和删除marker标记

转自:http://blog.sina.com.cn/s/blog_4cdc44df0100u80h.html Google Map API Version3 教程:在地图 通过代添加和删除mark标记 lat = 23.14746; lng = 113.34175376; var myLatLng = new google.maps.LatLng(lat, lng); var myOptions = { zoom: 15, center: myLatLng, mapTypeId: google

用JAVA实现对txt文件文本增删改查

package com.qiqiao.test; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Arrays; import java.util

Java实现对Mysql的图片存取操作

1.MySQL中的BLOB类型 Mysql中可以存储大文件数据,一般使用的BLOB对象.如图片,视频等等. BLOB是一个二进制大对象,可以容纳可变数量的数据.因为是二进制对象,所以与编码方式无关.有4种BLOB类型:TINYBLOB.BLOB.MEDIUMBLOB和LONGBLOB.它们只是可容纳值的最大长度不同. 四种字段类型保存的最大长度如下: TINYBLOB - 255 bytes BLOB - 65535 bytes(64KB) MEDIUMBLOB - 16,777,215 byt

windows下搭建LDAP并利用Java实现对LDAP的操作

什么是LDAP,百度百科一堆专业术语的描述. 我总结为一句话:轻量级目录访问协议,有数据库的数据存储功能,以树状层次型存储方式,就好像你的电话薄那样. 在一次项目中,由于该项目是教育性管理项目,客户要求项目必须部署在内网.那么在内网的话,就代表用户需要去拨VPN才能进行内网的访问. 其实当时我想到的是,单独开个注册映射到外网,让用户自己注册,管理员进行审核,然后用VPN去读数据库中的账号和密码就行了.这样,我们的系统和vpn就 相当于统一账号.但是当我确认需求的时候,那个老师告诉我们,他不会读什

Java实现对MongoDB的AND、OR和IN操作 ,大于、小于等判断

本文转自http://blog.csdn.net/mydeman/article/details/6652387 在MongoDB的官方文档中关于Java操作的介绍,只给出了很简单的几个例子.这些例子虽然可以满足一定的需求,但是还并不是太完全.下面是我根据网页中的提示写的几个例子. 1.背景.用JUnit4.8.2实现的单元测试的形式.测试数据: [plain] view plaincopyprint? {uid:10,username:"Jim",age:23,agender:&qu

Java实现对cookie的增删改查

原文:http://blog.csdn.net/k21325/article/details/54377830 1.springMVC框架:           [java] view plain copy /** * 读取所有cookie * 注意二.从客户端读取Cookie时,包括maxAge在内的其他属性都是不可读的,也不会被提交.浏览器提交Cookie时只会提交name与value属性.maxAge属性只被浏览器用来判断Cookie是否过期 * @param request * @par

Java实现对xml文件的增删改查

package com.HeiBeiEDU.test2; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import org.junit.Test; import org.w3c.dom.*; import org.xml.sax.SAXException; import javax.xml.parser

Java实现对zip和rar文件的解压缩

package com.svse.test; import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.Enumeration; import org.apache.tools.zip.ZipEntry;import org.apache.tools.zi

Java实现对MongoDB的增删改查

一.连接数据库 连接数据库,你需要指定数据库名称,如果指定的数据库不存在,mongo会自动创建数据库. 连接数据库的Java代码如下(无需密码的连接): public class MongTest { public static void main(String[] args) { try { MongoClient mongoClient = new MongoClient("localhost",27017);//连接到 mongodb 服务 MongoDatabase mongo